text
stringlengths
8
4.13M
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { failure::{Error, ResultExt}, fidl::endpoints::ClientEnd, fidl_fuchsia_io::FileMarker, fidl_fuchsia_netemul_guest::{ CommandListenerMarker, EnvironmentVariable, GuestDiscoveryMarker, GuestInteractionMarker, }, fuchsia_async as fasync, fuchsia_component::client, fuchsia_zircon as zx, futures::io::AsyncReadExt, netemul_guest_lib::wait_for_command_completion, rand::distributions::Alphanumeric, rand::{thread_rng, Rng}, std::fs::File, std::io::prelude::*, std::io::Read, }; fn create_test_data(file_path: String, file_size: usize) -> Result<(), Error> { let file_contents: String = thread_rng().sample_iter(&Alphanumeric).take(file_size).collect(); let mut test_file = File::create(file_path)?; test_file.write_all(file_contents.as_bytes())?; return Ok(()); } fn file_to_client(file: &File) -> Result<ClientEnd<FileMarker>, Error> { let channel = fdio::clone_channel(file)?; return Ok(ClientEnd::new(channel)); } async fn test_file_transfer() -> Result<(), Error> { let local_test_data = "/data/test_data.txt"; let guest_destination = "/root/input/test_data.txt"; let verification_copy = "/data/test_data_copy.txt"; let guest_discovery_service = client::connect_to_service::<GuestDiscoveryMarker>()?; let (gis, gis_ch) = fidl::endpoints::create_proxy::<GuestInteractionMarker>()?; let () = guest_discovery_service.get_guest(None, "debian_guest", gis_ch)?; create_test_data(local_test_data.to_string(), 4096)?; // Push the file to the guest let put_file = file_to_client(&File::open(local_test_data)?)?; let put_status = gis.put_file(put_file, guest_destination).await.context("Failed to put file")?; zx::ok(put_status)?; // Retrieve the file from the guest let get_file = file_to_client(&File::create(verification_copy)?)?; let get_status = gis.get_file(guest_destination, get_file).await.context("Failed to get file")?; zx::ok(get_status)?; // Compare the original file to the one copied back from the guest. let mut original_contents = String::new(); let mut copy_contents = String::new(); let mut original_file = File::open(local_test_data)?; original_file.read_to_string(&mut original_contents)?; let mut verification_file = File::open(verification_copy)?; verification_file.read_to_string(&mut copy_contents)?; assert_eq!(original_contents, copy_contents); return Ok(()); } async fn test_exec_script() -> Result<(), Error> { // Command to run, environment variable definitions, and stdin to input. let command_to_run = "/bin/sh -c \"/root/input/test_script.sh\""; let stdin_input = "hello\n"; let stdout_env_var = "STDOUT_STRING"; let stderr_env_var = "STDERR_STRING"; let stdout_expected_string = "stdout"; let stderr_expected_string = "stderr"; let mut env = vec![ EnvironmentVariable { key: stdout_env_var.to_string(), value: stdout_expected_string.to_string(), }, EnvironmentVariable { key: stderr_env_var.to_string(), value: stderr_expected_string.to_string(), }, ]; // Request that the guest interaction service run the command. let guest_discovery_service = client::connect_to_service::<GuestDiscoveryMarker>()?; let (gis, gis_ch) = fidl::endpoints::create_proxy::<GuestInteractionMarker>()?; let () = guest_discovery_service.get_guest(None, "debian_guest", gis_ch)?; let (stdin_0, stdin_1) = zx::Socket::create(zx::SocketOpts::STREAM).unwrap(); let (stdout_0, stdout_1) = zx::Socket::create(zx::SocketOpts::STREAM).unwrap(); let (stderr_0, stderr_1) = zx::Socket::create(zx::SocketOpts::STREAM).unwrap(); let (client_proxy, server_end) = fidl::endpoints::create_proxy::<CommandListenerMarker>() .context("Failed to create CommandListener ends")?; gis.execute_command( command_to_run, &mut env.iter_mut(), Some(stdin_1), Some(stdout_1), Some(stderr_1), server_end, )?; // Ensure that the process completes normally. wait_for_command_completion(client_proxy.take_event_stream(), Some((stdin_0, &stdin_input))) .await?; // Validate the stdout and stderr. let mut guest_stdout = Vec::new(); let mut stdout_socket = fasync::Socket::from_socket(stdout_0)?; stdout_socket.read_to_end(&mut guest_stdout).await?; assert_eq!(std::str::from_utf8(&guest_stdout)?.trim(), stdout_expected_string); let mut guest_stderr = Vec::new(); let mut stderr_socket = fasync::Socket::from_socket(stderr_0)?; stderr_socket.read_to_end(&mut guest_stderr).await?; assert_eq!(std::str::from_utf8(&guest_stderr)?.trim(), stderr_expected_string); // Pull the file that was created by the script and validate its contents. let local_copy = "/data/script_output_copy.txt"; let outfile_location = "/root/output/script_output.txt"; let get_file = file_to_client(&File::create(local_copy)?)?; let get_status = gis .get_file(outfile_location, get_file) .await .context("Failed waiting for file transfer.")?; zx::ok(get_status).context("Failed to get requested file.")?; let mut file_contents = String::new(); let mut stdin_file = File::open(local_copy)?; stdin_file.read_to_string(&mut file_contents)?; assert_eq!(file_contents, stdin_input.to_string()); return Ok(()); } async fn do_run() -> Result<(), Error> { test_file_transfer().await?; test_exec_script().await?; return Ok(()); } fn main() -> Result<(), Error> { let mut executor = fasync::Executor::new().context("Error creating executor")?; executor.run_singlethreaded(do_run())?; return Ok(()); }
use serde::{ Deserialize, Serialize, }; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Basic { pub length: usize, pub md5: String, }
use std::{os}; fn main() { let args: ~[~str] = os::args(); let mut it = args.iter().skip(1); for it.advance() |e| { print(*e+" "); } println(""); }
use crate::prelude::*; #[repr(C)] #[derive(Debug)] pub struct VkPipelineColorBlendAttachmentState { pub blendEnable: VkBool32, pub srcColorBlendFactor: VkBlendFactor, pub dstColorBlendFactor: VkBlendFactor, pub colorBlendOp: VkBlendOp, pub srcAlphaBlendFactor: VkBlendFactor, pub dstAlphaBlendFactor: VkBlendFactor, pub alphaBlendOp: VkBlendOp, pub colorWriteMask: VkColorComponentFlagBits, } impl Default for VkPipelineColorBlendAttachmentState { fn default() -> Self { VkPipelineColorBlendAttachmentState { blendEnable: VK_TRUE, srcColorBlendFactor: VK_BLEND_FACTOR_SRC_ALPHA, dstColorBlendFactor: VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, colorBlendOp: VK_BLEND_OP_ADD, srcAlphaBlendFactor: VK_BLEND_FACTOR_ONE, dstAlphaBlendFactor: VK_BLEND_FACTOR_ZERO, alphaBlendOp: VK_BLEND_OP_ADD, colorWriteMask: VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, } } }
/* Copyright 2020 Timo Saarinen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use super::*; // ------------------------------------------------------------------------------------------------- /// Type 23: Group Assignment Command #[derive(Default, Clone, Debug, PartialEq)] pub struct GroupAssignmentCommand { /// True if the data is about own vessel, false if about other. pub own_vessel: bool, /// AIS station type. pub station: Station, /// User ID (30 bits) pub mmsi: u32, /// Northeast latitude to 0.1 minutes. pub ne_lat: Option<f64>, /// Northeast longitude to 0.1 minutes. pub ne_lon: Option<f64>, /// Southwest latitude to 0.1 minutes. pub sw_lat: Option<f64>, /// Southwest longitude to 0.1 minutes. pub sw_lon: Option<f64>, /// AIS station type. pub station_type: StationType, /// Ship type pub ship_type: ShipType, /// Cargo type pub cargo_type: CargoType, /// TxRx mode: /// 0 = TxA/TxB, RxA/RxB (default) /// 1 = TxA, RxA/RxB /// 2 = TxB, RxA/RxB /// 3 = Reserved for future use pub txrx: u8, /// Report interval. pub interval: StationInterval, /// Quiet time specifies how many minutes the affected stations are to remain silent. /// None = none /// 1-15 = quiet time in minutes pub quiet: Option<u8>, } /// Station Type (for message type 23). #[derive(Clone, Copy, Debug, PartialEq)] pub enum StationType { /// All types of mobiles (default) AllTypes, /// Reserved for future use Reserved1, /// All types of Class B mobile stations AllTypesOfClassBMobile, /// SAR airborne mobile station SarAirborneMobile, /// Aid to Navigation station AidToNavigation, /// Class B shopborne mobile station (IEC62287 only) ClassBShipBorneMobile, /// Regional use and inland waterways Regional6, /// Regional use and inland waterways Regional7, /// Regional use and inland waterways Regional8, /// Regional use and inland waterways Regional9, /// Reserved for future use Reserved10, /// Reserved for future use Reserved11, /// Reserved for future use Reserved12, /// Reserved for future use Reserved13, /// Reserved for future use Reserved14, /// Reserved for future use Reserved15, } impl Default for StationType { fn default() -> Self { StationType::AllTypes } } impl StationType { fn new(val: u8) -> Result<StationType, String> { match val { 0 => Ok(StationType::AllTypes), 1 => Ok(StationType::Reserved1), 2 => Ok(StationType::AllTypesOfClassBMobile), 3 => Ok(StationType::SarAirborneMobile), 4 => Ok(StationType::AidToNavigation), 5 => Ok(StationType::ClassBShipBorneMobile), 6 => Ok(StationType::Regional6), 7 => Ok(StationType::Regional7), 8 => Ok(StationType::Regional8), 9 => Ok(StationType::Regional9), 10 => Ok(StationType::Reserved10), 11 => Ok(StationType::Reserved11), 12 => Ok(StationType::Reserved12), 13 => Ok(StationType::Reserved13), 14 => Ok(StationType::Reserved14), 15 => Ok(StationType::Reserved15), _ => Err(format!("Station type value out of range: {}", val)), } } } /// Station interval (for message type 23) #[derive(Clone, Copy, Debug, PartialEq)] pub enum StationInterval { /// As given by the autonomous mode Autonomous, /// 10 minutes Time10min, /// 6 minutes Time6min, /// 3 minutes Time3min, /// 1 minute Time1min, /// 30 seconds Time30sec, /// 15 seconds Time15sec, /// 10 seconds Time10sec, /// 5 seconds Time5sec, /// Next shorter reporting interval NextShorterReportingInverval, /// Next longer reporting interval NextLongerReportingInverval, /// Reserved for future use Reserved11, /// Reserved for future use Reserved12, /// Reserved for future use Reserved13, /// Reserved for future use Reserved14, /// Reserved for future use Reserved15, } impl StationInterval { fn new(val: u8) -> Result<StationInterval, String> { match val { 0 => Ok(StationInterval::Autonomous), 1 => Ok(StationInterval::Time10min), 2 => Ok(StationInterval::Time6min), 3 => Ok(StationInterval::Time3min), 4 => Ok(StationInterval::Time1min), 5 => Ok(StationInterval::Time30sec), 6 => Ok(StationInterval::Time15sec), 7 => Ok(StationInterval::Time10sec), 8 => Ok(StationInterval::Time5sec), 9 => Ok(StationInterval::NextShorterReportingInverval), 10 => Ok(StationInterval::NextLongerReportingInverval), 11 => Ok(StationInterval::Reserved11), 12 => Ok(StationInterval::Reserved12), 13 => Ok(StationInterval::Reserved13), 14 => Ok(StationInterval::Reserved14), 15 => Ok(StationInterval::Reserved15), _ => Err(format!("Station interval value out of range: {}", val)), } } } impl Default for StationInterval { fn default() -> Self { StationInterval::Autonomous } } // ------------------------------------------------------------------------------------------------- /// AIS VDM/VDO type 23: Group Assignment Command pub(crate) fn handle( bv: &BitVec, station: Station, own_vessel: bool, ) -> Result<ParsedMessage, ParseError> { Ok(ParsedMessage::GroupAssignmentCommand( GroupAssignmentCommand { own_vessel: { own_vessel }, station: { station }, mmsi: { pick_u64(&bv, 8, 30) as u32 }, ne_lat: { Some(pick_i64(&bv, 58, 17) as f64 / 600.0) }, ne_lon: { Some(pick_i64(&bv, 40, 18) as f64 / 600.0) }, sw_lat: { Some(pick_i64(&bv, 93, 17) as f64 / 600.0) }, sw_lon: { Some(pick_i64(&bv, 75, 18) as f64 / 600.0) }, station_type: StationType::new(pick_u64(&bv, 110, 4) as u8)?, ship_type: ShipType::new(pick_u64(&bv, 114, 8) as u8), cargo_type: CargoType::new(pick_u64(&bv, 114, 8) as u8), txrx: { let val = pick_u64(&bv, 144, 2) as u8; if val < 4 { val } else { return Err(format!("Tx/Tr mode field out of range: {}", val).into()); } }, interval: StationInterval::new(pick_u64(&bv, 146, 4) as u8)?, quiet: { let val = pick_u64(&bv, 150, 4) as u8; match val { 0 => None, 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 => Some(val), _ => { unreachable!("This should never be reached as all four bit cases are covered (value: {})", val); } } }, }, )) } // ------------------------------------------------------------------------------------------------- #[cfg(test)] mod test { use super::*; #[test] fn test_parse_vdm_type23() { let mut p = NmeaParser::new(); match p.parse_sentence("!AIVDM,1,1,,B,G02:Kn01R`sn@291nj600000900,2*12") { Ok(ps) => { match ps { // The expected result ParsedMessage::GroupAssignmentCommand(gac) => { assert_eq!(gac.mmsi, 2268120); assert::close(gac.ne_lat.unwrap_or(0.0), 30642.0 / 600.0, 0.1); assert::close(gac.ne_lon.unwrap_or(0.0), 1578.0 / 600.0, 0.1); assert::close(gac.sw_lat.unwrap_or(0.0), 30408.0 / 600.0, 0.1); assert::close(gac.sw_lon.unwrap_or(0.0), 1096.0 / 600.0, 0.1); assert_eq!(gac.station_type, StationType::Regional6); assert_eq!(gac.ship_type, ShipType::NotAvailable); assert_eq!(gac.cargo_type, CargoType::Undefined); assert_eq!(gac.txrx, 0); assert_eq!(gac.interval, StationInterval::NextShorterReportingInverval); assert_eq!(gac.quiet, None); } ParsedMessage::Incomplete => { assert!(false); } _ => { assert!(false); } } } Err(e) => { assert_eq!(e.to_string(), "OK"); } } } }
use course4::week4::solution::solve; fn main() { solve(); }
extern crate chrono; extern crate hyper; extern crate retry_after; use chrono::{Duration, UTC}; use hyper::header::Headers; use retry_after::RetryAfter; fn retry_after_delay() { let mut headers = Headers::new(); headers.set(RetryAfter::Delay(Duration::seconds(300))); // Should print "Retry-After: 300" println!("{}", headers); } fn retry_after_datetime() { let mut headers = Headers::new(); headers.set(RetryAfter::DateTime(UTC::now() + Duration::seconds(300))); // Should print "Retry-After: ..." println!("{}", headers); } fn main() { retry_after_delay(); retry_after_datetime(); }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashMap; use std::sync::Arc; use common_exception::ErrorCode; use common_exception::Result; use headers::authorization::Basic; use headers::authorization::Bearer; use headers::authorization::Credentials; use http::header::AUTHORIZATION; use http::HeaderValue; use poem::error::Error as PoemError; use poem::error::Result as PoemResult; use poem::http::StatusCode; use poem::Addr; use poem::Body; use poem::Endpoint; use poem::IntoResponse; use poem::Middleware; use poem::Request; use poem::Response; use tracing::error; use tracing::info; use super::v1::HttpQueryContext; use crate::auth::AuthMgr; use crate::auth::Credential; use crate::servers::HttpHandlerKind; use crate::sessions::SessionManager; use crate::sessions::SessionType; pub struct HTTPSessionMiddleware { pub kind: HttpHandlerKind, pub auth_manager: Arc<AuthMgr>, } impl HTTPSessionMiddleware { pub fn create(kind: HttpHandlerKind, auth_manager: Arc<AuthMgr>) -> HTTPSessionMiddleware { HTTPSessionMiddleware { kind, auth_manager } } } fn get_credential(req: &Request, kind: HttpHandlerKind) -> Result<Credential> { let std_auth_headers: Vec<_> = req.headers().get_all(AUTHORIZATION).iter().collect(); if std_auth_headers.len() > 1 { let msg = &format!("Multiple {} headers detected", AUTHORIZATION); return Err(ErrorCode::AuthenticateFailure(msg)); } let client_ip = match req.remote_addr().0 { Addr::SocketAddr(addr) => Some(addr.ip().to_string()), Addr::Custom(..) => Some("127.0.0.1".to_string()), _ => None, }; if std_auth_headers.is_empty() { if matches!(kind, HttpHandlerKind::Clickhouse) { auth_clickhouse_name_password(req, client_ip) } else { Err(ErrorCode::AuthenticateFailure( "No authorization header detected", )) } } else { auth_by_header(&std_auth_headers, client_ip) } } fn auth_by_header( std_auth_headers: &[&HeaderValue], client_ip: Option<String>, ) -> Result<Credential> { let value = &std_auth_headers[0]; if value.as_bytes().starts_with(b"Basic ") { match Basic::decode(value) { Some(basic) => { let name = basic.username().to_string(); let password = basic.password().to_owned().as_bytes().to_vec(); let password = (!password.is_empty()).then_some(password); let c = Credential::Password { name, password, hostname: client_ip, }; Ok(c) } None => Err(ErrorCode::AuthenticateFailure("bad Basic auth header")), } } else if value.as_bytes().starts_with(b"Bearer ") { match Bearer::decode(value) { Some(bearer) => Ok(Credential::Jwt { token: bearer.token().to_string(), hostname: client_ip, }), None => Err(ErrorCode::AuthenticateFailure("bad Bearer auth header")), } } else { Err(ErrorCode::AuthenticateFailure("bad auth header")) } } fn auth_clickhouse_name_password(req: &Request, client_ip: Option<String>) -> Result<Credential> { let (user, key) = ( req.headers().get("X-CLICKHOUSE-USER"), req.headers().get("X-CLICKHOUSE-KEY"), ); if let (Some(name), Some(password)) = (user, key) { let c = Credential::Password { name: String::from_utf8(name.as_bytes().to_vec()).unwrap(), password: Some(password.as_bytes().to_vec()), hostname: client_ip, }; Ok(c) } else { let query_str = req.uri().query().unwrap_or_default(); let query_params = serde_urlencoded::from_str::<HashMap<String, String>>(query_str) .map_err(|e| ErrorCode::BadArguments(format!("{}", e)))?; let (user, key) = (query_params.get("user"), query_params.get("password")); if let (Some(name), Some(password)) = (user, key) { Ok(Credential::Password { name: name.clone(), password: Some(password.as_bytes().to_vec()), hostname: client_ip, }) } else { Err(ErrorCode::AuthenticateFailure( "No header or query parameters for authorization detected", )) } } } impl<E: Endpoint> Middleware<E> for HTTPSessionMiddleware { type Output = HTTPSessionEndpoint<E>; fn transform(&self, ep: E) -> Self::Output { HTTPSessionEndpoint { ep, kind: self.kind, auth_manager: self.auth_manager.clone(), } } } pub struct HTTPSessionEndpoint<E> { ep: E, pub kind: HttpHandlerKind, pub auth_manager: Arc<AuthMgr>, } impl<E> HTTPSessionEndpoint<E> { async fn auth(&self, req: &Request) -> Result<HttpQueryContext> { let credential = get_credential(req, self.kind)?; let session_manager = SessionManager::instance(); let session = session_manager.create_session(SessionType::Dummy).await?; let ctx = session.create_query_context().await?; if let Some(tenant_id) = req.headers().get("X-DATABEND-TENANT") { let tenant_id = tenant_id.to_str().unwrap().to_string(); session.set_current_tenant(tenant_id); } self.auth_manager .auth(ctx.get_current_session(), &credential) .await?; Ok(HttpQueryContext::new(session)) } } #[poem::async_trait] impl<E: Endpoint> Endpoint for HTTPSessionEndpoint<E> { type Output = Response; async fn call(&self, mut req: Request) -> PoemResult<Self::Output> { // method, url, version, header info!("receive http handler request: {req:?},"); let res = match self.auth(&req).await { Ok(ctx) => { req.extensions_mut().insert(ctx); self.ep.call(req).await } Err(err) => Err(PoemError::from_string( err.message(), StatusCode::UNAUTHORIZED, )), }; match res { Err(err) => { error!("http request error: {}", err); let body = Body::from_json(serde_json::json!({ "error": { "code": err.status().as_str(), "message": err.to_string(), } })) .unwrap(); Ok(Response::builder().status(err.status()).body(body)) } Ok(res) => Ok(res.into_response()), } } }
//! Optimize query routing. use std::collections::HashMap; // use crate::{Error, Result}; use lp_modeler::dsl::{lp_sum, BoundableLp, LpContinuous, LpObjective, LpOperations, LpProblem}; use lp_modeler::solvers::{CbcSolver, SolverTrait}; use ndarray::{Array2, ArrayView2}; /// Represents techniques optimizing routing probabilities. pub trait Optimizer { /// Optimize routing policy. fn optimize(&self, weights: ArrayView2<'_, f32>) -> Array2<f32>; } /// No optimization: returns the same weights as given on input. pub struct IdentityOptimizer {} impl Optimizer for IdentityOptimizer { fn optimize(&self, weights: ArrayView2<'_, f32>) -> Array2<f32> { weights.to_owned() } } /// Balances load with an LP program. pub struct LpOptimizer; fn format_dispatch_variable(shard: usize, node: usize) -> String { format!("d({},{})", shard, node) } fn parse_dispatch_variable(name: &str) -> Option<(usize, usize)> { match (name.find('('), name.find(','), name.find(')')) { (Some(open_bracket), Some(comma), Some(close_bracket)) => { if name.get(..open_bracket).unwrap() == "d" && name.get(close_bracket..).unwrap() == ")" { let shard = name .get(open_bracket + 1..comma) .and_then(|n| n.parse::<usize>().ok())?; let node = name .get(comma + 1..close_bracket) .and_then(|n| n.parse::<usize>().ok())?; Some((shard, node)) } else { None } } _ => None, } } fn result_to_array(dim: (usize, usize), result: &HashMap<String, f32>) -> Array2<f32> { let mut array = Array2::<f32>::from_elem(dim, 0.0); for (variable, value) in result { if let Some((shard, node)) = parse_dispatch_variable(variable) { *array .get_mut((node, shard)) .expect("variable points out of bounds") = *value; } } array } impl Optimizer for LpOptimizer { fn optimize(&self, weights: ArrayView2<'_, f32>) -> Array2<f32> { let mut problem = LpProblem::new("Balance routing", LpObjective::Minimize); let z = LpContinuous::new("Z"); problem += &z; let dispatch_variables: Vec<Vec<_>> = weights .gencolumns() .into_iter() .enumerate() .map(|(shard_id, weights)| { let shard_vars: Vec<_> = weights .iter() .enumerate() .map(|(node_id, weight)| { LpContinuous::new(&format_dispatch_variable(shard_id, node_id)) .lower_bound(0.0) .upper_bound(if *weight == 0.0 { 0.0 } else { 1.0 }) }) .collect(); problem += lp_sum(&shard_vars).equal(1.0); shard_vars }) .collect(); for (node, weights) in weights.genrows().into_iter().enumerate() { let node_vars: Vec<_> = dispatch_variables .iter() .zip(weights) .map(|(shard_vars, &w)| &shard_vars[node] * w) .collect(); problem += lp_sum(&node_vars).le(&z); } let solver = CbcSolver::new(); let solution = solver.run(&problem).expect("Failed to run the CBC solver"); match solution.status { lp_modeler::solvers::Status::Optimal => { result_to_array(weights.dim(), &solution.results) } status => { log::error!("CBC solver failed: {:?}", status); log::error!( "Input: {:?}", weights .genrows() .into_iter() .map(|row| row.iter().copied().collect::<Vec<_>>()) .collect::<Vec<_>>() ); panic!(); } } } } #[cfg(test)] mod test { use super::*; use proptest::prelude::*; #[test] fn test_easy_dispatch() { let weights: Array2<f32> = Array2::from_shape_vec( (3, 6), vec![ 1.0, 1.0, 0.0, // Shard 1 0.0, 1.0, 1.0, // Shard 2 1.0, 0.0, 1.0, // Shard 3 1.0, 1.0, 0.0, // Shard 4 0.0, 1.0, 1.0, // Shard 5 1.0, 0.0, 1.0, // Shard 6 ], ) .expect("unable to create array"); let dispatch = LpOptimizer.optimize(weights.view()); println!("{}", &dispatch); for (sid, sum) in dispatch .gencolumns() .into_iter() .map(|col| col.iter().sum::<f32>()) .enumerate() { assert_eq!(sum, 1.0, "prob sum for shard {} is {}", sid, sum); } } fn test_dispatch(weights: ArrayView2<'_, f32>) { let optimizer = LpOptimizer; let dispatch = optimizer.optimize(weights); assert!(dispatch.iter().all(|&v| v >= 0.0 && v <= 1.0)); for (sid, sum) in dispatch .gencolumns() .into_iter() .map(|row| row.iter().sum::<f32>()) .enumerate() { assert!( approx::ulps_eq!(sum, 1.0, max_ulps = 4, epsilon = f32::EPSILON), "prob sum for shard {} is {}", sid, sum ); } } fn assignment(length: usize, replicas: usize) -> impl Strategy<Value = Vec<bool>> { let v = std::iter::repeat(true) .take(replicas) .chain(std::iter::repeat(false)) .take(length) .collect::<Vec<_>>(); Just(v).prop_shuffle() } fn distr(length: usize, replicas: usize) -> impl Strategy<Value = Vec<f32>> { ( assignment(length, replicas), prop::collection::vec(0.1_f32..1.0, replicas..=replicas), ) .prop_map(|(assignment, mut probs)| { let norm: f32 = probs.iter().sum(); for prob in probs.iter_mut() { *prob /= norm; } let mut v = assignment .into_iter() .map(|a| if a { 1.0 } else { 0.0 }) .collect::<Vec<_>>(); for (r, prob) in v.iter_mut().filter(|x| **x > 0.0).zip(probs) { *r = prob; } v }) } fn weights() -> impl Strategy<Value = Array2<f32>> { (2..10_usize, 2..10_usize, 2..=3_usize) .prop_flat_map(|(nodes, shards, replicas)| { ( Just(nodes), Just(shards), prop::collection::vec(distr(nodes, replicas), shards..=shards), ) }) .prop_map(|(nodes, shards, vecs)| { Array2::from_shape_vec((shards, nodes), vecs.into_iter().flatten().collect()) .expect("unable to create array") .reversed_axes() }) } proptest! { #[test] fn test_probabilistic_dispatch(weights in weights()) { test_dispatch(weights.view()); } } }
#![feature(custom_attribute)] #[cfg(target_family = "unix")] #[macro_use] extern crate diesel; #[cfg(target_family = "unix")] #[macro_use] extern crate diesel_codegen; #[cfg(target_family = "unix")] extern crate dotenv; #[cfg(target_family = "unix")] use diesel::prelude::*; #[cfg(target_family = "unix")] use diesel::pg::PgConnection; #[cfg(target_family = "unix")] use diesel::expression::sql_literal::sql; #[cfg(target_family = "unix")] use std::env; #[cfg(target_family = "unix")] mod schema { infer_schema!("dotenv:DATABASE_URL"); } #[cfg(target_family = "unix")] use schema::*; #[cfg(target_family = "unix")] #[derive(Debug, Queryable, Identifiable, Associations, AsChangeset)] pub struct User { pub id: i32, pub username: String, pub avatar: Option<String>, } #[cfg(target_family = "unix")] #[derive(Debug, Queryable, Identifiable, Associations, AsChangeset)] #[belongs_to(User)] pub struct Photo { pub id: i32, pub user_id: i32, pub url: String, pub tags: Vec<String>, } #[cfg(target_family = "unix")] #[derive(Debug, Insertable)] #[table_name = "photos"] pub struct NewPhoto { pub user_id: i32, pub url: String, } #[cfg(target_family = "unix")] impl User { fn new_photo(&self, url: &str) -> NewPhoto { NewPhoto { user_id: self.id, url: url.to_string(), } } } #[cfg(target_family = "windows")] fn main() { println!("TODO"); } #[cfg(target_family = "unix")] fn main() { println!("24 Days of Rust vol. 2 - diesel"); dotenv::dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let conn = PgConnection::establish(&database_url).expect("Couldn't connect to DB"); let me = users::table.find(1).first::<User>(&conn).expect( "Error loading user", ); println!("{:?}", me); let deleted_count = diesel::delete(photos::table.filter(photos::id.gt(1))) .execute(&conn) .expect("Failed to clean up photos"); println!("Deleted {} photo(s)", deleted_count); let photo_count: i64 = Photo::belonging_to(&me).count().first(&conn).expect( "Error counting photos", ); println!("User {} has {} photo(s)", me.username, photo_count); print_sql!(Photo::belonging_to(&me).count()); let my_photos = Photo::belonging_to(&me).load::<Photo>(&conn).expect( "Error loading photos", ); println!("{:?}", my_photos); let photos: Vec<(Photo, User)> = photos::table.inner_join(users::table).load(&conn).expect( "Error loading photos", ); for (photo, user) in photos { println!("Photo #{} by {}", photo.id, user.username); } let users_with_cat_photos: Vec<String> = users::table .select(users::username) .inner_join(photos::table) .filter(photos::url.like("%cat%")) .group_by(users::id) .load(&conn) .expect("Error loading users"); println!("{:?}", users_with_cat_photos); let photo = me.new_photo("http://lorempixel.com/output/cats-q-c-640-480-8.jpg"); let mut inserted_photo = diesel::insert(&photo) .into(photos::table) .get_result::<Photo>(&conn) .expect("Failed to insert photo"); println!("{:?}", inserted_photo); inserted_photo.tags = vec!["cute".to_string(), "kitten".to_string()]; let updated_photo: Photo = inserted_photo.save_changes(&conn).expect( "Error updating photo", ); println!("{:?}", updated_photo); let cute_cat_count: i64 = photos::table .filter(photos::tags.contains(vec!["cute", "kitten"])) .count() .get_result(&conn) .expect("Error counting cute kittens"); println!("There's {} photos of cute cats", cute_cat_count); let cute_cat_count: i64 = sql( "select count(*) from photos \ where tags @> array['cute', 'kitten']", ).get_result(&conn) .expect("Error executing raw SQL"); println!("There's {} photos of cute cats", cute_cat_count); }
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Note: We ignore the is_* functions for coverage as they effectively are // only lists use crate::errors::{Error, ErrorKind, Result, ResultExt, UnfinishedToken}; #[cfg_attr(feature = "cargo-clippy", allow(clippy::all, clippy::unwrap_used))] use crate::parser::g::__ToTriple; use crate::path::ModulePath; use crate::pos; pub use crate::pos::*; use crate::Value; use beef::Cow; use simd_json::Writable; use std::ffi::OsStr; use std::fmt; use std::io::Read; use std::iter::Peekable; use std::path::{Path, PathBuf}; use std::str::Chars; use std::{collections::VecDeque, mem}; use tremor_common::file; use unicode_xid::UnicodeXID; /// Source for a parser pub trait ParserSource { /// The source as a str fn src(&self) -> &str; /// the initial index fn start_index(&self) -> pos::Byte; } impl ParserSource for str { fn src(&self) -> &str { self } fn start_index(&self) -> pos::Byte { pos::Byte::from(0) } } /// A token with a span to indicate its location pub type TokenSpan<'input> = Spanned<'input>; fn is_ws(ch: char) -> bool { ch.is_whitespace() && ch != '\n' } fn is_ident_start(ch: char) -> bool { UnicodeXID::is_xid_start(ch) || ch == '_' || ch == '-' } fn is_ident_continue(ch: char) -> bool { let ch = ch as char; UnicodeXID::is_xid_continue(ch) || ch == '_' || ch == '-' } fn is_test_start(ch: char) -> bool { ch == '|' } fn is_dec_digit(ch: char) -> bool { ch.is_digit(10) } fn is_hex(ch: char) -> bool { ch.is_digit(16) } pub(crate) fn ident_to_token(ident: &str) -> Token { match ident { "intrinsic" => Token::Intrinsic, "mod" => Token::Module, "const" => Token::Const, "let" => Token::Let, "match" => Token::Match, "end" => Token::End, "fn" => Token::Fun, "null" => Token::Nil, "case" => Token::Case, "of" => Token::Of, "when" => Token::When, "default" => Token::Default, "patch" => Token::Patch, "insert" => Token::Insert, "upsert" => Token::Upsert, "update" => Token::Update, "erase" => Token::Erase, "move" => Token::Move, "copy" => Token::Copy, "merge" => Token::Merge, "for" => Token::For, "event" => Token::Event, "state" => Token::State, "present" => Token::Present, "absent" => Token::Absent, "true" => Token::BoolLiteral(true), "false" => Token::BoolLiteral(false), "and" => Token::And, "or" => Token::Or, "xor" => Token::Xor, "not" => Token::Not, "drop" => Token::Drop, "emit" => Token::Emit, "select" => Token::Select, "from" => Token::From, "where" => Token::Where, "with" => Token::With, // "order" => Token::Order, "group" => Token::Group, "by" => Token::By, "having" => Token::Having, "into" => Token::Into, "create" => Token::Create, "tumbling" => Token::Tumbling, "sliding" => Token::Sliding, "window" => Token::Window, "stream" => Token::Stream, "operator" => Token::Operator, "script" => Token::Script, "set" => Token::Set, "each" => Token::Each, "define" => Token::Define, "args" => Token::Args, "use" => Token::Use, "as" => Token::As, "recur" => Token::Recur, src => Token::Ident(src.into(), false), } } /// A token in the source ( file, byte stream ), to be emitted by the `Lexer` /// The LALRPOP grammar uses these tokens and this custom lexer /// as it does not have a facility to ignore special tokens, to /// easily disambiguate tokens ( eg: ':' vs '::' vs ':=' ), nor /// to inject magic tokens ( bad token ) or support lexical streams /// ( different token streams drive by users, eg: emit ignorable tokens when /// syntax highlighting or error highlighting #[derive(Clone, Debug, PartialEq)] pub enum Token<'input> { /// Ignorable when parsing, significant when highlighting Whitespace(&'input str), /// a new line NewLine, /// a singe line comment SingleLineComment(&'input str), /// a mod comment ModComment(&'input str), /// a doc comment DocComment(&'input str), /// a BAD TOKEN Bad(String), // Mark bad tokens in lexical stream /// an ident Ident(Cow<'input, str>, bool), // bool marks whether the ident is surrounded by '`' (escape notation) /// the `$` sign Dollar, /// a `.` Dot, /// null Nil, /// a boolean BoolLiteral(bool), /// an integer IntLiteral(i64), /// an float FloatLiteral(f64, String), /// a test literal TestLiteral(usize, Vec<String>), /// a heredoc start token `"""` HereDocStart, /// a heredoc end token `"""` HereDocEnd, /// a heredoc literal, within triple quotes with special newline handling HereDocLiteral(Cow<'input, str>), /// a double quote `"` DQuote, /// a string literal StringLiteral(Cow<'input, str>), // Keywords /// the `let` keyword Let, /// the `const` keyword Const, /// the `match` keyword Match, /// the `case` keyword Case, /// the `of` keyword Of, /// the `when` keyword When, /// the `end` keyword End, /// the `patch` keyword Patch, /// the `insert` keyword Insert, /// the `upsert` keyword Upsert, /// the `update` keyword Update, /// the `erase` keyword Erase, /// the `move` keyword Move, /// the `copy` keyword Copy, /// the `merge` keyword Merge, /// the `drop` keyword Drop, /// the `default` keyword Default, /// the `emit` keyword Emit, /// the `for` keyword For, /// the `event` keyword Event, /// the `state` keyword State, /// the `present` keyword Present, /// the `absent` keyword Absent, /// the `fun` keyword Fun, /// the `intrinsic` keyword Intrinsic, /// the `mod` keyword Module, /// the `_` token DontCare, /// the `recur` token Recur, // Symbols /// the `\` backslash BSlash, /// the `,` comma Comma, // Op /// the `not` keyword Not, /// bitwise not `!` BitNot, /// the `and` keyword And, /// the `or` keyword Or, /// the `xor` keyword Xor, /// bitwise and `&` BitAnd, /// bitwise or `|` // BitOr, /// bitwise xor `^` BitXor, /// equal `=` Eq, /// double equal `==` EqEq, /// not equal `!=` NotEq, /// tilde equal `~=` TildeEq, /// tilde `~` Tilde, /// greater than equal `>=` Gte, /// grater than `>` Gt, /// lower than equal `<=` Lte, /// lower then `<` Lt, /// Right bit shift signed `>>` RBitShiftSigned, /// Right bit shift unsigned `>>>` RBitShiftUnsigned, /// Left bit shift `<<` LBitShift, /// Add `+` Add, /// Substract `-` Sub, /// Multiply `*` Mul, /// Divide `/` Div, /// Moduly `%` Mod, // Symbols /// Colon `:` Colon, /// Double coilon `::` ColonColon, /// Effector array `=>` EqArrow, /// Semicolon `;` Semi, /// Left Paren `%(` LPatParen, /// Left Paren `(` LParen, /// Right Paren `)` RParen, /// Left brace `{` LBrace, /// Interpolation Start `#{` Interpol, /// Escaped Hash `\#` EscapedHash, /// Left pattern Bracket `%{` LPatBrace, /// Right Brace `}` RBrace, /// Left Bracket `[` LBracket, /// Left pattern Bracket `%[` LPatBracket, /// Right bracket `]` RBracket, /// End of stream token EndOfStream, // Query /// The `select` keyword Select, /// The `from` keyword From, /// The `where` keyword Where, /// The `with` keyword With, /// The `order` keyword // Order, /// the `group` keyword Group, /// The `by` keyword By, /// The `having` keyword Having, /// The `into` keyword Into, /// The `create` keyword Create, /// The `tumbling` keyword Tumbling, /// The `sliding` keyword Sliding, /// The `window` keyword Window, /// The `stream` keyword Stream, /// The `operator` keyword Operator, /// The `script` keyword Script, /// The `set` keyword Set, /// The `each` keyword Each, /// The `define` keyword Define, /// The `args` keyword Args, /// The `use` keyword Use, /// The `as` keyword As, /// Preprocessor directives LineDirective(Location, Cow<'input, str>), /// Config Directive ConfigDirective, } impl<'input> Default for Token<'input> { fn default() -> Self { Self::EndOfStream } } impl<'input> Token<'input> { /// Is the token ignorable except when syntax or error highlighting. /// Is the token insignificant when parsing ( a correct ... ) source. #[cfg(not(tarpaulin_include))] // matches is not supported pub(crate) fn is_ignorable(&self) -> bool { matches!( *self, Token::SingleLineComment(_) | Token::Whitespace(_) | Token::NewLine | Token::LineDirective(_, _) ) } /// Is the token a keyword, excluding keyword literals ( eg: true, nil ) #[cfg(not(tarpaulin_include))] // matches is not supported pub(crate) fn is_keyword(&self) -> bool { matches!( *self, Token::Absent | Token::Args | Token::By | Token::Case | Token::Const | Token::Copy | Token::Create | Token::Default | Token::Define | Token::Drop | Token::Each | Token::Emit | Token::End | Token::Erase | Token::Event | Token::For | Token::From | Token::Fun | Token::Group | Token::Having | Token::Insert | Token::Into | Token::Intrinsic | Token::Let | Token::Match | Token::Merge | Token::Module | Token::Move | Token::Of | Token::Operator // | Token::Order | Token::Patch | Token::Present | Token::Script | Token::Select | Token::Set | Token::Use | Token::As | Token::Sliding | Token::State | Token::Stream | Token::Tumbling | Token::Update | Token::Upsert | Token::When | Token::Where | Token::Window | Token::With ) } /// Is the token a literal, excluding list and record literals #[cfg(not(tarpaulin_include))] // matches is not supported pub(crate) fn is_literal(&self) -> bool { matches!( *self, Token::DontCare | Token::Nil | Token::BoolLiteral(_) | Token::IntLiteral(_) | Token::FloatLiteral(_, _) ) } // It's text-like or string-like notation such as String, char, regex ... #[cfg(not(tarpaulin_include))] // matches is not supported pub(crate) fn is_string_like(&self) -> bool { matches!( *self, Token::StringLiteral(_) | Token::DQuote | Token::TestLiteral(_, _) | Token::HereDocStart | Token::HereDocEnd | Token::HereDocLiteral(_) ) } /// Is the token a builtin delimiter symbol #[cfg(not(tarpaulin_include))] // matches is not supported pub(crate) fn is_symbol(&self) -> bool { matches!( *self, Token::BSlash | Token::Colon | Token::ColonColon | Token::Comma | Token::Eq | Token::EqArrow | Token::LBrace | Token::LBracket | Token::LineDirective(_, _) | Token::ConfigDirective | Token::LParen | Token::LPatBrace | Token::LPatBracket | Token::RBrace | Token::RBracket | Token::RParen | Token::Semi | Token::TildeEq ) } /// Is the token a builtin expression operator ( excludes forms such as 'match', 'let' #[cfg(not(tarpaulin_include))] // matches is not supported pub(crate) fn is_operator(&self) -> bool { matches!( *self, Token::Not | Token::BitNot | Token::Or | Token::Xor | Token::And // | Token::BitOr | Token::BitXor | Token::BitAnd | Token::Eq | Token::EqEq | Token::NotEq | Token::TildeEq | Token::Tilde | Token::Gte | Token::Gt | Token::Lte | Token::Lt | Token::RBitShiftSigned | Token::RBitShiftUnsigned | Token::LBitShift | Token::Add | Token::Sub | Token::Mul | Token::Div | Token::Mod | Token::Dollar | Token::Dot ) } } // LALRPOP requires a means to convert spanned tokens to triple form #[allow(clippy::wrong_self_convention)] impl<'input> __ToTriple<'input> for Spanned<'input> { fn to_triple( value: Self, ) -> std::result::Result< (Location, Token<'input>, Location), lalrpop_util::ParseError<Location, Token<'input>, Error>, > { Ok((value.span.start(), value.value, value.span.end())) } } // Format a token for display // impl<'input> fmt::Display for Token<'input> { #[allow(clippy::too_many_lines)] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Token::Whitespace(ws) => write!(f, "{}", &ws), Token::NewLine => writeln!(f), Token::Ident(ref name, true) => write!(f, "`{}`", name), Token::Ident(ref name, false) => write!(f, "{}", name), Token::ModComment(comment) => write!(f, "### {}", &comment), Token::DocComment(comment) => write!(f, "## {}", &comment), Token::SingleLineComment(comment) => write!(f, "# {}", &comment), Token::IntLiteral(value) => write!(f, "{}", value), Token::FloatLiteral(_, txt) => write!(f, "{}", txt), Token::DQuote => write!(f, "\""), Token::Interpol => write!(f, "#{{"), Token::EscapedHash => write!(f, "\\#"), Token::StringLiteral(value) => { // We do those to ensure proper escaping let value: &str = value; let s = Value::from(value).encode(); // Strip the quotes write!(f, "{}", s.get(1..s.len() - 1).unwrap_or_default()) } Token::HereDocStart => { // here we write the following linebreak writeln!(f, r#"""""#) } Token::HereDocEnd => { // here we do not write!(f, r#"""""#) } Token::HereDocLiteral(value) => { // do not escape linebreaks let (value, add_linebreak) = value .strip_suffix('\n') .map_or_else(|| (value as &str, false), |stripped| (stripped, true)); let s = Value::from(value).encode(); // Strip the quotes if let Some(s) = s.get(1..s.len() - 1) { write!(f, "{}", s)?; } if add_linebreak { writeln!(f)?; } Ok(()) } Token::TestLiteral(indent, values) => { let mut first = true; write!(f, "|")?; if let [v] = values.as_slice() { write!(f, "{}", v.replace('\\', "\\\\").replace('|', "\\|"))?; } else { for l in values { if first { first = false; } else { write!(f, "\\\n{}", " ".repeat(*indent))?; }; write!(f, "{}", l.replace('\\', "\\\\").replace('|', "\\|"))?; } } write!(f, "|") } Token::BoolLiteral(true) => write!(f, "true"), Token::BoolLiteral(false) => write!(f, "false"), Token::Bad(value) => write!(f, "{}", value), Token::Let => write!(f, "let"), Token::Const => write!(f, "const"), Token::Match => write!(f, "match"), Token::Patch => write!(f, "patch"), Token::Insert => write!(f, "insert"), Token::Upsert => write!(f, "upsert"), Token::Update => write!(f, "update"), Token::Erase => write!(f, "erase"), Token::Move => write!(f, "move"), Token::Copy => write!(f, "copy"), Token::Merge => write!(f, "merge"), Token::For => write!(f, "for"), Token::Event => write!(f, "event"), Token::State => write!(f, "state"), Token::Present => write!(f, "present"), Token::Absent => write!(f, "absent"), // Token::Return => write!(f, "return"), // Token::Todo => write!(f, "todo"), Token::Drop => write!(f, "drop"), Token::Emit => write!(f, "emit"), Token::Fun => write!(f, "fn"), Token::End => write!(f, "end"), Token::Nil => write!(f, "null"), Token::Case => write!(f, "case"), Token::Of => write!(f, "of"), Token::When => write!(f, "when"), Token::Default => write!(f, "default"), Token::Intrinsic => write!(f, "intrinsic"), Token::Module => write!(f, "mod"), Token::BSlash => write!(f, "\\"), Token::Colon => write!(f, ":"), Token::ColonColon => write!(f, "::"), Token::Comma => write!(f, ","), // Token::DotDotDot => write!(f, "..."), // Token::DotDot => write!(f, ".."), Token::Dot => write!(f, "."), Token::Dollar => write!(f, "$"), // Token::Question => write!(f, "?"), // Token::Pipe => write!(f, "|"), Token::Not => write!(f, "not"), Token::BitNot => write!(f, "!"), // Token::Tilde => write!(f, "~"), Token::DontCare => write!(f, "_"), Token::EqArrow => write!(f, "=>"), Token::Semi => write!(f, ";"), Token::LPatParen => write!(f, "%("), Token::LParen => write!(f, "("), Token::RParen => write!(f, ")"), Token::LPatBrace => write!(f, "%{{"), Token::LBrace => write!(f, "{{"), Token::RBrace => write!(f, "}}"), Token::LBracket => write!(f, "["), Token::LPatBracket => write!(f, "%["), Token::RBracket => write!(f, "]"), Token::And => write!(f, "and"), Token::Or => write!(f, "or"), Token::Xor => write!(f, "xor"), Token::BitAnd => write!(f, "&"), // Token::BitOr => write!(f, "|"), Token::BitXor => write!(f, "^"), Token::Eq => write!(f, "="), Token::EqEq => write!(f, "=="), Token::NotEq => write!(f, "!="), Token::TildeEq => write!(f, "~="), Token::Tilde => write!(f, "~"), Token::Gte => write!(f, ">="), Token::Gt => write!(f, ">"), Token::Lte => write!(f, "<="), Token::Lt => write!(f, "<"), Token::RBitShiftSigned => write!(f, ">>"), Token::RBitShiftUnsigned => write!(f, ">>>"), Token::LBitShift => write!(f, "<<"), Token::Mul => write!(f, "*"), Token::Div => write!(f, "/"), Token::Add => write!(f, "+"), Token::Sub => write!(f, "-"), Token::Mod => write!(f, "%"), Token::EndOfStream => write!(f, ""), // Query Token::Select => write!(f, "select"), Token::From => write!(f, "from"), Token::Where => write!(f, "where"), Token::With => write!(f, "with"), // Token::Order => write!(f, "order"), Token::Group => write!(f, "group"), Token::By => write!(f, "by"), Token::Having => write!(f, "having"), Token::Into => write!(f, "into"), Token::Create => write!(f, "create"), Token::Tumbling => write!(f, "tumbling"), Token::Sliding => write!(f, "sliding"), Token::Window => write!(f, "window"), Token::Stream => write!(f, "stream"), Token::Operator => write!(f, "operator"), Token::Script => write!(f, "script"), Token::Set => write!(f, "set"), Token::Each => write!(f, "each"), Token::Define => write!(f, "define"), Token::Args => write!(f, "args"), Token::Use => write!(f, "use"), Token::As => write!(f, "as"), Token::Recur => write!(f, "recur"), Token::ConfigDirective => write!(f, "#!config "), Token::LineDirective(l, file) => write!( f, "#!line {} {} {} {} {}", l.absolute(), l.line(), l.column(), l.unit_id, file ), } } } struct CharLocations<'input> { location: Location, chars: Peekable<Chars<'input>>, } impl<'input> CharLocations<'input> { pub(crate) fn new<S>(input: &'input S) -> CharLocations<'input> where S: ?Sized + ParserSource, { CharLocations { location: Location::new(1, 1, input.start_index().to_usize(), 0), chars: input.src().chars().peekable(), } } pub(crate) fn current(&self) -> &Location { &self.location } } impl<'input> Iterator for CharLocations<'input> { type Item = (Location, char); fn next(&mut self) -> Option<(Location, char)> { self.chars.next().map(|ch| { let location = self.location; self.location.shift(ch); (location, ch) }) } } /// A Tremor tokeniser pub struct Tokenizer<'input> { //cu: usize, eos: bool, pos: Span, iter: Peekable<Lexer<'input>>, } impl<'input> Tokenizer<'input> { /// Creates a new tokeniser #[must_use] pub fn new(input: &'input str) -> Self { let lexer = Lexer::new(input); let start = Location::default(); let end = Location::default(); Tokenizer { //cu: 0, eos: false, iter: lexer.peekable(), pos: span(start, end, start, end), } } /// Turn this Tokenizer into an `Iterator` of tokens that are produced until the first error is hit /// /// The purpose of this method is to not accidentally consume tokens after an error, /// which might be completely incorrect, but would still show up in the resulting iterator if /// used with `filter_map(Result::ok)` for example. pub fn tokenize_until_err(self) -> impl Iterator<Item = Spanned<'input>> { // i wanna use map_while here, but it is still unstable :( self.scan((), |_, item| item.ok()).fuse() } } impl<'input> Iterator for Tokenizer<'input> { type Item = Result<TokenSpan<'input>>; fn next(&mut self) -> Option<Self::Item> { let token = self.iter.next(); match (self.eos, token) { (false, None) => { self.eos = true; Some(Ok(Spanned { value: Token::EndOfStream, span: self.pos, })) } (true, _) => None, (_, Some(Err(x))) => Some(Err(x)), (_, Some(Ok(t))) => { self.pos = t.clone().span; Some(Ok(t)) } } } } /// A lexical preprocessor in the spirit of cpp /// pub struct Preprocessor {} macro_rules! take_while { ($let:ident, $token:pat, $iter:expr) => { $let = $iter.next().ok_or(ErrorKind::UnexpectedEndOfStream)??; loop { if let Spanned { value: $token, .. } = $let { $let = $iter.next().ok_or(ErrorKind::UnexpectedEndOfStream)??; continue; } break; } }; } /// A compilation unit #[derive(Clone, Debug)] pub struct CompilationUnit { file_path: Box<Path>, } impl CompilationUnit { fn from_file(file: &Path) -> Self { let mut p = PathBuf::new(); p.push(file); Self { file_path: p.into_boxed_path(), } } /// Returns the path of the file for this #[must_use] pub fn file_path(&self) -> &Path { &self.file_path } } impl PartialEq for CompilationUnit { fn eq(&self, other: &Self) -> bool { self.file_path == other.file_path } } impl fmt::Display for CompilationUnit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.file_path.to_string_lossy()) } } /// Tracks set of included files in a given logical compilation unit pub struct IncludeStack { elements: Vec<CompilationUnit>, pub(crate) cus: Vec<CompilationUnit>, } impl Default for IncludeStack { fn default() -> Self { Self { elements: Vec::new(), cus: Vec::new(), } } } impl IncludeStack { fn pop(&mut self) { self.elements.pop(); } /// Returns set of compilation units #[must_use] pub fn into_cus(self) -> Vec<CompilationUnit> { self.cus } /// Pushes a a compilation unit onto the include stack /// /// # Errors /// if a cyclic dependency is detected pub fn push<S: AsRef<OsStr> + ?Sized>(&mut self, file: &S) -> Result<usize> { let e = CompilationUnit::from_file(Path::new(file)); if self.contains(&e) { let es = self .elements .iter() .map(ToString::to_string) .collect::<Vec<_>>() .join(" -> "); Err(format!("Cyclic dependency detected: {} -> {}", es, e.to_string()).into()) } else { let cu = self.cus.len(); self.cus.push(e.clone()); self.elements.push(e); Ok(cu) } } fn contains(&self, e: &CompilationUnit) -> bool { self.elements.contains(e) } } fn urt(next: &Spanned<'_>, alt: &[&'static str]) -> Error { ErrorKind::UnrecognizedToken( Range::from(next.span).expand_lines(2), Range::from(next.span), next.value.to_string(), alt.iter().map(ToString::to_string).collect(), ) .into() } fn as_ident(next: Spanned<'_>) -> Result<Cow<'_, str>> { if let Token::Ident(id, _) = next.value { Ok(id) } else { Err(urt(&next, &["`<ident>`"])) } } impl<'input> Preprocessor { pub(crate) fn resolve( module_path: &ModulePath, use_span: Span, span2: Span, rel_module_path: &Path, include_stack: &mut IncludeStack, ) -> Result<(usize, Box<Path>)> { let mut file = PathBuf::from(rel_module_path); file.set_extension("tremor"); if let Some(path) = module_path.resolve(&file) { if path.is_file() { let cu = include_stack.push(path.as_os_str())?; return Ok((cu, path)); } } file.set_extension("trickle"); if let Some(path) = module_path.resolve(&file) { if path.is_file() { let cu = include_stack.push(path.as_os_str())?; return Ok((cu, path)); } } let outer = Range::from((use_span.start, use_span.end)).expand_lines(2); let inner = Range::from((span2.start, span2.end)); let path = rel_module_path.to_string_lossy().to_string(); Err(ErrorKind::ModuleNotFound(outer, inner, path, module_path.mounts.clone()).into()) } #[allow(clippy::too_many_lines)] /// Preprocess a possibly nested set of related sources into a single compilation unit /// /// # Errors /// on preprocessor failreus pub fn preprocess<S: AsRef<OsStr> + ?Sized>( module_path: &ModulePath, file_name: &S, input: &'input mut std::string::String, cu: usize, include_stack: &mut IncludeStack, ) -> Result<Vec<Result<TokenSpan<'input>>>> { let file_name = Path::new(file_name); let top = input.clone(); input.clear(); let mut iter = Tokenizer::new(top.as_str()); let mut next; loop { next = iter.next().ok_or(ErrorKind::UnexpectedEndOfStream)??; match next { // // use <module_path> [as <alias>] ; // Spanned { value: Token::Use, span: use_span, .. } => { let mut rel_module_path = PathBuf::new(); let mut alias; take_while!(next, Token::Whitespace(_), iter); let id = as_ident(next)?; alias = id.to_string(); rel_module_path.push(&alias); take_while!(next, Token::Whitespace(_), iter); loop { if next.value == Token::ColonColon { // module path of the form: // <ident> [ :: <ident> ]*; // take_while!(next, Token::Whitespace(_), iter); let id = as_ident(next)?; alias = id.to_string(); rel_module_path.push(&alias); take_while!(next, Token::Whitespace(_), iter); match next.value { Token::As => (), Token::ColonColon => continue, Token::Semi => break, _ => { return Err(urt(&next, &["`as`", "`::`", "`;`"])); } } } else if next.value == Token::As || next.value == Token::Semi { break; } else { return Err(urt(&next, &["`as`", "`::`", "`;`"])); } } // // As <alias:ident> // if next.value == Token::As { take_while!(next, Token::Whitespace(_), iter); alias = as_ident(next)?.to_string(); // ';' take_while!(next, Token::Whitespace(_), iter); // Semi take_while!(next, Token::Whitespace(_), iter); } if next.value == Token::Semi { take_while!(next, Token::Whitespace(_), iter); } if next.value == Token::NewLine { //let file_path = rel_module_path.clone(); let (inner_cu, file_path) = Preprocessor::resolve( module_path, use_span, next.span, &rel_module_path, include_stack, )?; let file_path2 = file_path.clone(); let mut file = file::open(&file_path)?; let mut s = String::new(); file.read_to_string(&mut s)?; s.push(' '); let s = Preprocessor::preprocess( module_path, file_path.as_os_str(), &mut s, inner_cu, include_stack, )?; let y = s .into_iter() .filter_map(|x| x.map(|x| format!("{}", x.value)).ok()) .collect::<Vec<String>>() .join(""); input.push_str(&format!( "#!line 0 0 0 {} {}\n", inner_cu, &file_path2.to_string_lossy() )); input.push_str(&format!("mod {} with\n", &alias)); input.push_str(&format!( "#!line 0 0 0 {} {}\n", inner_cu, &file_path2.to_string_lossy() )); input.push_str(&format!("{}\n", y.trim())); input.push_str("end;\n"); input.push_str(&format!( "#!line {} {} {} {} {}\n", next.span.end.absolute(), next.span.end.line() + 1, 0, cu, file_name.to_string_lossy(), )); include_stack.pop(); } else { return Err(urt(&next, &["`<newline>`"])); } } Spanned { value: Token::EndOfStream, .. } => break, other => { input.push_str(&format!("{}", other.value)); } } } //input.push_str(" "); let tokens = Tokenizer::new(input).collect(); Ok(tokens) } } /// An iterator over a source string that yeilds `Token`s for subsequent use by /// the parser pub struct Lexer<'input> { input: &'input str, chars: CharLocations<'input>, start_index: pos::Byte, file_offset: Location, cu: usize, stored_tokens: VecDeque<TokenSpan<'input>>, } type Lexeme = Option<(Location, char)>; impl<'input> Lexer<'input> { pub(crate) fn spanned2( &self, mut start: Location, mut end: Location, value: Token<'input>, ) -> Spanned<'input> { start.unit_id = self.cu; end.unit_id = self.cu; Spanned { span: span(start - self.file_offset, end - self.file_offset, start, end), value, } } /// Create a new lexer from the source string pub(crate) fn new<S>(input: &'input S) -> Self where S: ?Sized + ParserSource, { let chars = CharLocations::new(input); Lexer { input: input.src(), chars, start_index: input.start_index(), file_offset: Location::default(), cu: 0, stored_tokens: VecDeque::new(), } } /// Return the next character in the source string fn lookahead(&mut self) -> Lexeme { let loc = self.chars.location; self.chars.chars.peek().map(|b| (loc, *b)) } fn starts_with(&mut self, start: Location, s: &str) -> Option<(Location, &'input str)> { let mut end = start; for c in s.chars() { end.shift(c); } if let Some(head) = self.slice(start, end) { if head == s { for _ in 0..s.len() - 1 { self.bump(); } Some((end, head)) } else { None } } else { None } } fn bump(&mut self) -> Lexeme { self.chars.next() } /// Return a slice of the source string fn slice(&self, start: Location, end: Location) -> Option<&'input str> { let start = start.absolute() - self.start_index.to_usize(); let end = end.absolute() - self.start_index.to_usize(); // Our indexes are in characters as we are iterating over codepoints // string indexes however are in bytes and might lead to either // invalid regions or even invalid strings // That is terrible, what are you thinking rust! // But at lease we can work around it using `indices` self.input.get(start..end) } /// return a slice from `start` to eol of the line `end` is on fn slice_full_lines(&self, start: &Location, end: &Location) -> Option<String> { let start_idx = start.absolute() - self.start_index.to_usize(); let take_lines = end.line().saturating_sub(start.line()) + 1; self.input.get(start_idx..).map(|f| { f.split('\n') .take(take_lines) .collect::<Vec<&'input str>>() .join("\n") }) } /// return a slice from start to the end of the line fn slice_until_eol(&self, start: &Location) -> Option<&'input str> { let start = start.absolute() - self.start_index.to_usize(); self.input.get(start..).and_then(|f| f.split('\n').next()) } // return a slice from start to the end of the input fn slice_until_eof(&self, start: &Location) -> Option<&'input str> { let start = start.absolute() - self.start_index.to_usize(); self.input.get(start..) } // return a String without any seperators fn extract_number<F>(&mut self, start: Location, mut is_valid: F) -> (Location, String) where F: FnMut(char) -> bool, { let seperator = '_'; let (end, number) = self.take_while(start, |c| is_valid(c) || c == seperator); // Remove seperators from number (end, number.replace(seperator, "")) } fn take_while<F>(&mut self, start: Location, mut keep_going: F) -> (Location, &'input str) where F: FnMut(char) -> bool, { self.take_until(start, |c| !keep_going(c)) } fn take_until<F>(&mut self, start: Location, mut terminate: F) -> (Location, &'input str) where F: FnMut(char) -> bool, { let mut e = start; while let Some((end, ch)) = self.lookahead() { e = end; if terminate(ch) { if let Some(slice) = self.slice(start, e) { return (end, slice); } // Invalid start end case :( return (end, "<ERROR>"); } self.bump(); } // EOF // we need to shift by 1, otherwise we take the location of the previous char. e.shift(0 as char); self.slice(start, e) .map_or((e, "<ERROR>"), |slice| (e, slice)) } /// handle comments fn cx(&mut self, start: Location) -> Result<TokenSpan<'input>> { if let Some((end, _)) = self.starts_with(start, "#!config ") { Ok(self.spanned2(start, end, Token::ConfigDirective)) } else { let (end, lexeme) = self.take_until(start, |ch| ch == '\n'); if let Some(l) = lexeme.strip_prefix("###") { let doc = Token::ModComment(l); Ok(self.spanned2(start, end, doc)) } else if let Some(l) = lexeme.strip_prefix("##") { let doc = Token::DocComment(l); Ok(self.spanned2(start, end, doc)) } else if let Some(directive) = lexeme.strip_prefix("#!line") { let directive = directive.trim(); let splitted: Vec<_> = directive.split(' ').collect(); if let Some(&[absolute, line, column, cu, file]) = splitted.get(0..5) { let cu = cu.parse()?; // we need to move up 1 line as the line directive itself occupies its own line let l = Location::new(line.parse()?, column.parse()?, absolute.parse()?, cu) .move_up_lines(1); let line_directive = Token::LineDirective(l, file.into()); // set the file offset to the difference between the included file (line directive) // and the current position in the source so we point to the correct location // in the included file self.file_offset = (start - l).start_of_line(); // update the cu to the included file self.file_offset.unit_id = cu; self.cu = cu; Ok(self.spanned2(start, end, line_directive)) } else { Err("failed to parse line directive!".into()) } } else { Ok(self.spanned2( start, end, Token::SingleLineComment(lexeme.trim_start_matches('#')), )) } } } /// handle equals fn eq(&mut self, start: Location) -> TokenSpan<'input> { match self.lookahead() { Some((end, '>')) => { self.bump(); self.spanned2(start, end + '>', Token::EqArrow) } Some((end, '=')) => { self.bump(); self.spanned2(start, end + '=', Token::EqEq) } _ => self.spanned2(start, start + '=', Token::Eq), } } /// handle colons fn cn(&mut self, start: Location) -> TokenSpan<'input> { let (end, lexeme) = self.take_while(start, |ch| ch == ':'); match lexeme { "::" => self.spanned2(start, end, Token::ColonColon), ":" => self.spanned2(start, end, Token::Colon), _ => self.spanned2(start, end, Token::Bad(lexeme.to_string())), } } fn gt(&mut self, start: Location) -> TokenSpan<'input> { match self.lookahead() { Some((end, '>')) => { self.bump(); if let Some((end, '>')) = self.lookahead() { self.bump(); self.spanned2(start, end + '>', Token::RBitShiftUnsigned) } else { self.spanned2(start, end + '>', Token::RBitShiftSigned) } } Some((end, '=')) => { self.bump(); self.spanned2(start, end + '=', Token::Gte) } Some((end, _)) => self.spanned2(start, end, Token::Gt), None => self.spanned2(start, start, Token::Bad(">".to_string())), } } fn lt(&mut self, start: Location) -> TokenSpan<'input> { match self.lookahead() { Some((end, '<')) => { self.bump(); self.spanned2(start, end + '<', Token::LBitShift) } Some((end, '=')) => { self.bump(); self.spanned2(start, end + '=', Token::Lte) } Some((end, _)) => self.spanned2(start, end, Token::Lt), None => self.spanned2(start, start, Token::Bad("<".to_string())), } } /// handle pattern begin fn pb(&mut self, start: Location) -> Result<TokenSpan<'input>> { match self.lookahead().ok_or(ErrorKind::UnexpectedEndOfStream)? { (end, '[') => { self.bump(); Ok(self.spanned2(start, end + '[', Token::LPatBracket)) } (end, '(') => { self.bump(); Ok(self.spanned2(start, end + '(', Token::LPatParen)) } (end, '{') => { self.bump(); Ok(self.spanned2(start, end + '{', Token::LPatBrace)) } (end, _) => Ok(self.spanned2(start, end, Token::Mod)), } } /// handle pattern end fn pe(&mut self, start: Location) -> Result<TokenSpan<'input>> { match self.lookahead().ok_or(ErrorKind::UnexpectedEndOfStream)? { (end, '=') => { self.bump(); Ok(self.spanned2(start, end + '=', Token::NotEq)) } (end, _ch) => Ok(self.spanned2(start, end, Token::BitNot)), } } /// handle tilde fn tl(&mut self, start: Location) -> Result<TokenSpan<'input>> { match self.lookahead().ok_or(ErrorKind::UnexpectedEndOfStream)? { (end, '=') => { self.bump(); Ok(self.spanned2(start, end + '=', Token::TildeEq)) } (end, _) => Ok(self.spanned2(start, end, Token::Tilde)), } } fn id(&mut self, start: Location) -> TokenSpan<'input> { let (end, ident) = self.take_while(start, is_ident_continue); let token = ident_to_token(ident); self.spanned2(start, end, token) } fn next_index(&mut self) -> Result<Location> { let (loc, _) = self.chars.next().ok_or(ErrorKind::UnexpectedEndOfStream)?; Ok(loc) } fn escape_code( &mut self, string_start: &Location, start: Location, ) -> Result<(Location, char)> { match self.bump().ok_or(ErrorKind::UnexpectedEndOfStream)? { (e, '\'') => Ok((e, '\'')), (e, '"') => Ok((e, '"')), (e, '\\') => Ok((e, '\\')), // Some((e, '{')) => Ok((e, '{')), // Some((e, '}')) => Ok((e, '}')), (e, '#') => Ok((e, '#')), (e, '/') => Ok((e, '/')), (e, 'b') => Ok((e, '\u{8}')), // Backspace (e, 'f') => Ok((e, '\u{c}')), // Form Feed (e, 'n') => Ok((e, '\n')), (e, 'r') => Ok((e, '\r')), (e, 't') => Ok((e, '\t')), // TODO: Unicode escape codes (mut end, 'u') => { let mut escape_start = end; escape_start.extend_left('u'); let mut digits = String::with_capacity(4); for _i in 0..4 { if let Some((mut e, c)) = self.bump() { digits.push(c); if u32::from_str_radix(&format!("{}", c), 16).is_err() { e.shift(' '); let token_str = self.slice_full_lines(string_start, &e).unwrap_or_default(); let range = Range::from((escape_start, e)); return Err(ErrorKind::InvalidUtf8Sequence( Range::from((start, e)).expand_lines(2), range, UnfinishedToken::new(range, token_str), ) .into()); } end = e; } else { end.shift(' '); let token_str = self .slice_full_lines(string_start, &end) .unwrap_or_default(); let range = Range::from((escape_start, end)); return Err(ErrorKind::InvalidUtf8Sequence( Range::from((escape_start, end)).expand_lines(2), range, UnfinishedToken::new(range, token_str), ) .into()); } } if let Ok(Some(c)) = u32::from_str_radix(&digits, 16).map(std::char::from_u32) { Ok((end, c)) } else { let token_str = self .slice_full_lines(string_start, &end) .unwrap_or_default(); end.shift(' '); let range = Range::from((escape_start, end)); Err(ErrorKind::InvalidUtf8Sequence( Range::from((escape_start, end)).expand_lines(2), range, UnfinishedToken::new(range, token_str), ) .into()) } } (mut end, ch) => { let token_str = self .slice_full_lines(string_start, &end) .unwrap_or_default(); end.shift(' '); let range = Range::from((start, end)); Err(ErrorKind::UnexpectedEscapeCode( Range::from((start, end)).expand_lines(2), range, UnfinishedToken::new(range, token_str), ch, ) .into()) } } } /// handle quoted idents `\` ... fn id2(&mut self, start: Location) -> Result<TokenSpan<'input>> { let mut string = String::new(); let mut end = start; loop { match self.bump().ok_or_else(|| { let range = Range::from((start, end)); ErrorKind::UnterminatedIdentLiteral( range.expand_lines(2), range, UnfinishedToken::new(range, format!("`{}", string)), ) })? { (mut end, '`') => { // we got to bump end by one so we claim the tailing `"` let e = end; let mut s = start; s.shift('`'); end.shift('`'); if let Some(slice) = self.slice(s, e) { let token = Token::Ident(slice.into(), true); return Ok(self.spanned2(start, end, token)); } // Invalid start end case :( let token = Token::Ident(string.into(), true); return Ok(self.spanned2(start, end, token)); } (end, '\n') => { let range = Range::from((start, end)); return Err(ErrorKind::UnterminatedIdentLiteral( range.expand_lines(2), range, UnfinishedToken::new(range, format!("`{}", string)), ) .into()); } (e, other) => { string.push(other as char); end = e; continue; } } } } /// handle quoted strings or heredoc strings fn qs_or_hd(&mut self, start: Location) -> Result<Vec<TokenSpan<'input>>> { let mut end = start; let heredoc_start = start; end.shift('"'); let q1 = self.spanned2(start, end, Token::DQuote); let mut res = vec![q1]; let mut string = String::new(); if let (mut end, '"') = self.lookahead().ok_or_else(|| { let range = Range::from((start, start)); ErrorKind::UnterminatedStringLiteral( range.expand_lines(2), range, UnfinishedToken::new(range, format!("\"{}", string)), ) })? { // This would be the second quote self.bump(); if let Some((end, '"')) = self.lookahead() { self.bump(); // We don't allow anything tailing the initial `"""` match self.bump().ok_or_else(|| { let token_str = self .slice_until_eol(&start) .map_or_else(|| r#"""""#.to_string(), ToString::to_string); let range = Range::from((start, end)); ErrorKind::UnterminatedHereDoc( range.expand_lines(2), range, UnfinishedToken::new(range, token_str), ) })? { (mut newline_loc, '\n') => { res = vec![self.spanned2(start, end + '"', Token::HereDocStart)]; // (0, vec![]))]; string = String::new(); newline_loc.shift('\n'); // content starts after newline self.hd(heredoc_start, newline_loc, end, false, &string, res) } (end, ch) => { let token_str = self .slice_until_eol(&start) .map_or_else(|| format!(r#""""{}"#, ch), ToString::to_string); let range = Range::from((start, end)); Err(ErrorKind::TailingHereDoc( range.expand_lines(2), range, UnfinishedToken::new(range, token_str), ch, ) .into()) } } } else { // We had two quotes followed by something not a quote so // it is an empty string. //TODO :make slice let start = end; end.shift('"'); res.push(self.spanned2(start, end, Token::DQuote)); Ok(res) } } else { self.qs(heredoc_start, end, end, false, string, res) } } #[allow(clippy::too_many_arguments)] fn intercept_heredoc_error( &self, is_hd: bool, error_prefix: &str, total_start: Location, segment_start: &mut Location, end: &mut Location, res: &mut Vec<TokenSpan<'input>>, content: &mut String, error: Error, ) -> ErrorKind { // intercept error and extend the token to match this outer heredoc // with interpolation // otherwise we will not get the whole heredoc in error messages let end_location = error.context().1.map_or_else( || res.last().map_or(*end, |last| last.span.end), |inner_error_range| inner_error_range.1, ); let Error(kind, ..) = error; let token_str = self .slice_full_lines(&total_start, &end_location) .unwrap_or_else(|| format!("{}{}", error_prefix, content)); let mut end = total_start; end.shift_str(&token_str); let unfinished_token = UnfinishedToken::new(Range::from((total_start, end_location)), token_str); match kind { ErrorKind::UnterminatedExtractor(outer, location, _) => { // expand to start line of heredoc, so we get a proper context let outer = outer.expand_lines(outer.0.line().saturating_sub(total_start.line())); ErrorKind::UnterminatedExtractor(outer, location, unfinished_token) } ErrorKind::UnterminatedIdentLiteral(outer, location, _) => { // expand to start line of heredoc, so we get a proper context let outer = outer.expand_lines(outer.0.line().saturating_sub(total_start.line())); ErrorKind::UnterminatedIdentLiteral(outer, location, unfinished_token) } ErrorKind::UnterminatedHereDoc(outer, location, _) | ErrorKind::TailingHereDoc(outer, location, _, _) => { if is_hd { // unterminated heredocs within interpolation are better reported // as unterminated interpolation ErrorKind::UnterminatedInterpolation( Range::from((total_start, end.move_down_lines(2))), Range::from((total_start, end)), unfinished_token, ) } else { let outer = outer.expand_lines(outer.0.line().saturating_sub(total_start.line())); ErrorKind::UnterminatedHereDoc(outer, location, unfinished_token) } } ErrorKind::UnterminatedInterpolation(outer, location, _) => { // expand to start line of heredoc, so we get a proper context let outer = outer.expand_lines(outer.0.line().saturating_sub(total_start.line())); ErrorKind::UnterminatedInterpolation(outer, location, unfinished_token) } ErrorKind::UnexpectedEscapeCode(outer, location, _, found) => { // expand to start line of heredoc, so we get a proper context let outer = outer.expand_lines(outer.0.line().saturating_sub(total_start.line())); ErrorKind::UnexpectedEscapeCode(outer, location, unfinished_token, found) } ErrorKind::UnterminatedStringLiteral(outer, location, _) => { // expand to start line of heredoc, so we get a proper context let outer = outer.expand_lines(outer.0.line().saturating_sub(total_start.line())); if is_hd { ErrorKind::UnterminatedStringLiteral(outer, location, unfinished_token) } else { let mut toekn_end = *segment_start; toekn_end.shift('#'); toekn_end.shift('{'); ErrorKind::UnterminatedInterpolation( outer, Range::from((*segment_start, toekn_end)), unfinished_token, ) } } ErrorKind::InvalidUtf8Sequence(outer, location, _) => { // expand to start line of heredoc, so we get a proper context let outer = outer.expand_lines(outer.0.line().saturating_sub(total_start.line())); ErrorKind::InvalidUtf8Sequence(outer, location, unfinished_token) } e => e, } } #[allow(clippy::too_many_arguments)] fn handle_interpol<F>( &mut self, is_hd: bool, error_prefix: &str, has_escapes: &mut bool, total_start: Location, end_inner: Location, segment_start: &mut Location, end: &mut Location, res: &mut Vec<TokenSpan<'input>>, content: &mut String, token_constructor: F, ) -> Result<()> where F: Fn(Cow<'input, str>) -> Token, { end.shift('{'); self.bump(); if !content.is_empty() { let mut c = String::new(); mem::swap(&mut c, content); let token = if *has_escapes { // The string was modified so we can't use the slice token_constructor(c.into()) } else { token_constructor( self.slice(*segment_start, end_inner) .map_or_else(|| Cow::from(c), Cow::from), ) }; res.push(self.spanned2(*segment_start, end_inner, token)); *has_escapes = false; } *segment_start = end_inner; res.push(self.spanned2(*segment_start, *end, Token::Interpol)); let mut pcount = 0; let mut first = true; loop { let next = self.next().ok_or_else(|| { let end_location = self.chars.current(); let token_str = self .slice_full_lines(&total_start, end_location) .unwrap_or_else(|| format!("{}{}", error_prefix, content)); ErrorKind::UnterminatedInterpolation( Range::from((total_start, end.move_down_lines(2))), Range::from((*segment_start, *end)), UnfinishedToken::new(Range::from((total_start, *end_location)), token_str), ) })?; let s = next.map_err(|error| { self.intercept_heredoc_error( is_hd, error_prefix, total_start, segment_start, end, res, content, error, ) })?; match &s.value { Token::RBrace if pcount == 0 => { let start = *segment_start; *segment_start = s.span.pp_end; res.push(s); if first { let end_location = *segment_start; let token_str = self .slice_full_lines(&total_start, &end_location) .unwrap_or_else(|| format!("{}{}", error_prefix, content)); let unfinished_token = UnfinishedToken::new(Range::from((start, end_location)), token_str); return Err(ErrorKind::EmptyInterpolation( Range::from((total_start, end_location)), Range::from((start, end_location)), unfinished_token, ) .into()); } break; } Token::RBrace => { pcount -= 1; } Token::LBrace | Token::Interpol => { pcount += 1; } _ => {} }; res.push(s); first = false; } Ok(()) } #[allow(clippy::too_many_arguments)] fn handle_qs_hd_generic<F>( &mut self, is_hd: bool, error_prefix: &str, has_escapes: &mut bool, total_start: Location, segment_start: &mut Location, end: &mut Location, res: &mut Vec<TokenSpan<'input>>, content: &mut String, lc: (Location, char), token_constructor: F, ) -> Result<()> where F: Fn(Cow<'input, str>) -> Token, { match lc { (end_inner, '\\') => { let (mut e, c) = self.escape_code(&total_start, end_inner)?; if c == '#' { if !content.is_empty() { let mut c = String::new(); mem::swap(&mut c, content); let token = if *has_escapes { // The string was modified so we can't use the slice token_constructor(c.into()) } else { self.slice(*segment_start, end_inner).map_or_else( || token_constructor(c.into()), |slice| token_constructor(slice.into()), ) }; res.push(self.spanned2(*segment_start, end_inner, token)); *has_escapes = false; } res.push(self.spanned2(end_inner, e, Token::EscapedHash)); e.shift(c); *segment_start = e; } else { *has_escapes = true; content.push(c); } *end = e; } (end_inner, '#') => { if let Some((e, '{')) = self.lookahead() { *end = e; self.handle_interpol( is_hd, error_prefix, has_escapes, total_start, end_inner, segment_start, end, res, content, token_constructor, )?; } else { content.push('#'); *end = end_inner; } } (e, other) => { content.push(other); *end = e; end.shift(other); } } Ok(()) } /// Handle heredoc strings `"""` ... fn hd( &mut self, heredoc_start: Location, mut segment_start: Location, mut end: Location, mut has_escapes: bool, _string: &str, mut res: Vec<TokenSpan<'input>>, ) -> Result<Vec<TokenSpan<'input>>> { // TODO: deduplicate by encapsulating all state in a struct and have some common operations on it let mut content = String::new(); loop { let next = self.bump().ok_or_else(|| { // We reached EOF let token_str = self .slice_until_eof(&heredoc_start) .map_or_else(|| format!(r#""""\n{}"#, content), ToString::to_string); let range = Range::from((heredoc_start, end)); ErrorKind::UnterminatedHereDoc( range.expand_lines(2), range, UnfinishedToken::new(range, token_str), ) })?; match next { (e, '"') => { // If the current line is just a `"""` then we are at the end of the heredoc res.push(self.spanned2( segment_start, e, Token::HereDocLiteral(content.into()), )); segment_start = e; content = String::new(); content.push('"'); end = if let Some((e, '"')) = self.lookahead() { self.bump(); content.push('"'); if let Some((e, '"')) = self.lookahead() { self.bump(); let mut heredoc_end = e; heredoc_end.shift('"'); res.push(self.spanned2(segment_start, heredoc_end, Token::HereDocEnd)); return Ok(res); } e } else { e }; end.shift('"'); } (e, '\n') => { end = e; content.push('\n'); res.push(self.spanned2( segment_start, end, Token::HereDocLiteral(content.into()), )); end.shift('\n'); segment_start = end; content = String::new(); } lc => { self.handle_qs_hd_generic( true, "\"\"\"\n", &mut has_escapes, heredoc_start, &mut segment_start, &mut end, &mut res, &mut content, lc, Token::HereDocLiteral, )?; } } } } /// Handle quote strings `"` ... fn qs( &mut self, total_start: Location, mut segment_start: Location, mut end: Location, mut has_escapes: bool, mut string: String, mut res: Vec<TokenSpan<'input>>, ) -> Result<Vec<TokenSpan<'input>>> { loop { let next = self .bump() .ok_or_else(|| self.unfinished_token("\"", &string, total_start))?; match next { (mut end, '"') => { // If the string is empty we kind of don't need it. if !string.is_empty() { let token = if has_escapes { // The string was modified so we can't use the slice Token::StringLiteral(string.into()) } else { self.slice(segment_start, end).map_or_else( || Token::StringLiteral(string.into()), |slice| Token::StringLiteral(slice.into()), ) }; res.push(self.spanned2(segment_start, end, token)); } let start = end; end.shift('"'); res.push(self.spanned2(start, end, Token::DQuote)); return Ok(res); } (end, '\n') => { let token_str = self .slice_until_eol(&total_start) .map_or_else(|| format!("\"{}", string), ToString::to_string); let mut token_end = total_start; token_end.shift_str(&token_str); let range = Range::from((total_start, end)); return Err(ErrorKind::UnterminatedStringLiteral( range.expand_lines(2), range, UnfinishedToken::new(Range::from((total_start, token_end)), token_str), ) .into()); } lc => { self.handle_qs_hd_generic( false, "\"", &mut has_escapes, total_start, &mut segment_start, &mut end, &mut res, &mut string, lc, Token::StringLiteral, )?; } } } } fn test_escape_code(&mut self, start: &Location, s: &str) -> Result<Option<char>> { match self.bump().ok_or(ErrorKind::UnexpectedEndOfStream)? { (_, '\\') => Ok(Some('\\')), (_, '|') => Ok(Some('|')), (_end, '\n') => Ok(None), (end, ch) => { let token_str = format!("|{}\\{}", s, ch); let mut token_end = end; token_end.shift(ch); let range = Range::from((end, end)); Err(ErrorKind::UnexpectedEscapeCode( range.expand_lines(2), range, UnfinishedToken::new(Range::from((*start, token_end)), token_str), ch, ) .into()) } } } fn unfinished_token(&self, pfx: &str, string: &str, start: Location) -> ErrorKind { let token_str = self .slice_until_eol(&start) .map_or_else(|| format!("{}{}", pfx, string), ToString::to_string); let mut token_end = start; token_end.shift_str(&token_str); let range = Range::from((start, token_end)); ErrorKind::UnterminatedExtractor( range.expand_lines(2), range, UnfinishedToken::new(Range::from((start, token_end)), token_str), ) } /// handle test/extractor '|...' fn pl(&mut self, total_start: Location) -> Result<TokenSpan<'input>> { let mut string = String::new(); let mut strings = Vec::new(); loop { let next = self .bump() .ok_or_else(|| self.unfinished_token("|", &string, total_start))?; match next { (_e, '\\') => { if let Some(ch) = self.test_escape_code(&total_start, &string)? { string.push(ch); } else { strings.push(string); string = String::new(); } } (mut end, '|') => { strings.push(string); end.shift('|'); let indent = indentation(&strings); let strings = strings .iter() .map(|s| { if s.is_empty() { s.clone() } else { s.split_at(indent).1.to_string() } }) .collect(); let token = Token::TestLiteral(indent, strings); return Ok(self.spanned2(total_start, end, token)); } (end, '\n') => { let token_str = self .slice_until_eol(&total_start) .map_or_else(|| format!("|{}", string), ToString::to_string); let range = Range::from((total_start, end)); return Err(ErrorKind::UnterminatedExtractor( range.expand_lines(2), range, UnfinishedToken::new(range, token_str), ) .into()); } (_e, other) => { string.push(other as char); continue; } } } } fn nm_float(&mut self, start: Location, int: &str) -> Result<TokenSpan<'input>> { self.bump(); // Skip '.' let (end, float) = self.extract_number(start, is_dec_digit); match self.lookahead() { Some((_, 'e')) => { self.bump(); if let Some((exp_location, _)) = self.bump() { // handle sign let (exp_location, sign) = match self.lookahead() { Some((loc, '+' | '-')) => { self.bump(); self.slice(exp_location, loc).map(|s| (loc, s)) } _ => Some((exp_location, "")), } .unwrap_or((exp_location, "")); let (end, exp) = self.extract_number(exp_location, is_dec_digit); let float = &format!("{}e{}{}", float, sign, exp); Ok(self.spanned2( start, end, Token::FloatLiteral( float.parse().chain_err(|| { ErrorKind::InvalidFloatLiteral( Range::from((start, end)).expand_lines(2), Range::from((start, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| float.to_string(), ToString::to_string), ), ) })?, float.to_string(), ), )) } else { Err(ErrorKind::InvalidFloatLiteral( Range::from((start, end)).expand_lines(2), Range::from((start, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| float.to_string(), ToString::to_string), ), ) .into()) } } Some((end, ch)) if is_ident_start(ch) => Err(ErrorKind::UnexpectedCharacter( Range::from((start, end)).expand_lines(2), Range::from((end, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| int.to_string(), ToString::to_string), ), ch, ) .into()), _ => Ok(self.spanned2( start, end, Token::FloatLiteral( float.parse().chain_err(|| { ErrorKind::InvalidFloatLiteral( Range::from((start, end)).expand_lines(2), Range::from((start, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| float.to_string(), ToString::to_string), ), ) })?, float.to_string(), ), )), } } fn nm_hex(&mut self, start: Location, int: &str) -> Result<TokenSpan<'input>> { self.bump(); // Skip 'x' let int_start = self.next_index()?; let (end, hex) = self.extract_number(int_start, is_hex); // ALLOW: this takes the whole string and can not panic match int { "0" | "-0" => match self.lookahead() { Some((_, ch)) if is_ident_start(ch) => Err(ErrorKind::UnexpectedCharacter( Range::from((start, end)).expand_lines(2), Range::from((start, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| hex.to_string(), ToString::to_string), ), ch, ) .into()), _ => { if hex.is_empty() { Err(ErrorKind::InvalidHexLiteral( Range::from((start, end)).expand_lines(2), Range::from((start, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| hex.to_string(), ToString::to_string), ), ) .into()) } else { let is_positive = int == "0"; // ALLOW: this takes the whole string and can not panic match i64_from_hex(&hex[..], is_positive) { Ok(val) => Ok(self.spanned2(start, end, Token::IntLiteral(val))), Err(_err) => Err(ErrorKind::InvalidHexLiteral( Range::from((start, end)).expand_lines(2), Range::from((start, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| hex.to_string(), ToString::to_string), ), ) .into()), } } } }, _ => Err(ErrorKind::InvalidHexLiteral( Range::from((start, end)).expand_lines(2), Range::from((start, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| int.to_string(), ToString::to_string), ), ) .into()), } } /// handle numbers (with or without leading '-') #[allow(clippy::too_many_lines)] fn nm(&mut self, start: Location) -> Result<TokenSpan<'input>> { let (end, int) = self.extract_number(start, is_dec_digit); match self.lookahead() { Some((_, '.')) => self.nm_float(start, &int), Some((_, 'x')) => self.nm_hex(start, &int), Some((char_loc, ch)) if is_ident_start(ch) => Err(ErrorKind::UnexpectedCharacter( Range::from((start, end)).expand_lines(2), Range::from((char_loc, char_loc)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| int.to_string(), ToString::to_string), ), ch, ) .into()), None | Some(_) => int .parse() .map(|val| self.spanned2(start, end, Token::IntLiteral(val))) .map_err(|_| { Error::from(ErrorKind::InvalidIntLiteral( Range::from((start, end)).expand_lines(2), Range::from((start, end)), UnfinishedToken::new( Range::from((start, end)), self.slice_until_eol(&start) .map_or_else(|| int.to_string(), ToString::to_string), ), )) }), } } /// Consume whitespace fn ws(&mut self, start: Location) -> TokenSpan<'input> { let (end, src) = self.take_while(start, is_ws); self.spanned2(start, end, Token::Whitespace(src)) } } /// Converts partial hex literal (i.e. part after `0x` or `-0x`) to 64 bit signed integer. /// /// This is basically a copy and adaptation of `std::num::from_str_radix`. fn i64_from_hex(hex: &str, is_positive: bool) -> Result<i64> { let r = i64::from_str_radix(hex, 16)?; Ok(if is_positive { r } else { -r }) } impl<'input> Iterator for Lexer<'input> { type Item = Result<TokenSpan<'input>>; fn next(&mut self) -> Option<Self::Item> { if let Some(next) = self.stored_tokens.pop_front() { return Some(Ok(next)); } let (start, ch) = self.bump()?; match ch as char { // '...' => Some(Ok(self.spanned2(start, self.next_index(), Token::DotDotDot))), // ".." => Some(Ok(self.spanned2(start, self.next_index(), Token::DotDot))), ',' => Some(Ok(self.spanned2(start, start + ch, Token::Comma))), '$' => Some(Ok(self.spanned2(start, start + ch, Token::Dollar))), '.' => Some(Ok(self.spanned2(start, start + ch, Token::Dot))), // '?' => Some(Ok(self.spanned2(start, start, Token::Question))), '_' => Some(Ok(self.spanned2(start, start + ch, Token::DontCare))), ';' => Some(Ok(self.spanned2(start, start + ch, Token::Semi))), '+' => Some(Ok(self.spanned2(start, start + ch, Token::Add))), '*' => Some(Ok(self.spanned2(start, start + ch, Token::Mul))), '\\' => Some(Ok(self.spanned2(start, start + ch, Token::BSlash))), '(' => Some(Ok(self.spanned2(start, start + ch, Token::LParen))), ')' => Some(Ok(self.spanned2(start, start + ch, Token::RParen))), '{' => Some(Ok(self.spanned2(start, start + ch, Token::LBrace))), '}' => Some(Ok(self.spanned2(start, start + ch, Token::RBrace))), '[' => Some(Ok(self.spanned2(start, start + ch, Token::LBracket))), ']' => Some(Ok(self.spanned2(start, start + ch, Token::RBracket))), '/' => Some(Ok(self.spanned2(start, start + ch, Token::Div))), // TODO account for extractors which use | to mark format boundaries //'|' => Some(Ok(self.spanned2(start, start, Token::BitOr))), '^' => Some(Ok(self.spanned2(start, start + ch, Token::BitXor))), '&' => Some(Ok(self.spanned2(start, start + ch, Token::BitAnd))), ':' => Some(Ok(self.cn(start))), '-' => match self.lookahead() { Some((_loc, c)) if is_dec_digit(c) => Some(self.nm(start)), _ => Some(Ok(self.spanned2(start, start + ch, Token::Sub))), }, '#' => Some(self.cx(start)), '=' => Some(Ok(self.eq(start))), '<' => Some(Ok(self.lt(start))), '>' => Some(Ok(self.gt(start))), '%' => Some(self.pb(start)), '~' => Some(self.tl(start)), '`' => Some(self.id2(start)), // TODO account for bitwise not operator '!' => Some(self.pe(start)), '\n' => Some(Ok(self.spanned2(start, start, Token::NewLine))), ch if is_ident_start(ch) => Some(Ok(self.id(start))), '"' => match self.qs_or_hd(start) { Ok(mut tokens) => { for t in tokens.drain(..) { self.stored_tokens.push_back(t); } self.next() } Err(e) => Some(Err(e)), }, ch if is_test_start(ch) => Some(self.pl(start)), ch if is_dec_digit(ch) => Some(self.nm(start)), ch if ch.is_whitespace() => Some(Ok(self.ws(start))), _ => { let str = format!("{}", ch); Some(Ok(self.spanned2(start, start, Token::Bad(str)))) } } } } fn indentation(strings: &[String]) -> usize { let mut indent = None; for s in strings { if !s.is_empty() { let l = s.len() - s.trim_start().len(); if let Some(i) = indent { if i > l { indent = Some(l); } } else { indent = Some(l); } } } indent.unwrap_or(0) } #[cfg(test)] mod tests { use super::*; macro_rules! lex_ok { ($src:expr, $($span:expr => $token:expr,)*) => {{ let lexed_tokens: Vec<_> = Tokenizer::new($src).filter(|t| match t { Ok(Spanned { value: Token::EndOfStream, .. }) => false, Ok(Spanned { value: t, .. }) => !t.is_ignorable(), Err(_) => true }).map(|t| match t { Ok(Spanned { value: t, span: tspan }) => Ok((t, tspan.start.column(), tspan.end.column())), Err(e) => Err(e) }).collect(); // locations are 1-based, so we need to add 1 to every loc, end position needs another +1 let expected_tokens = vec![$({ Ok(($token, $span.find("~").unwrap() + 1, $span.rfind("~").unwrap() + 2)) }),*]; assert_eq!(lexed_tokens, expected_tokens); }}; } #[rustfmt::skip] #[test] fn interpolate() -> Result<()> { lex_ok! { r#" "" "#, r#" ~ "# => Token::DQuote, r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "hello" "#, r#" ~ "# => Token::DQuote, r#" ~~~~~ "# => Token::StringLiteral("hello".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "hello #{7}" "#, r#" ~ "# => Token::DQuote, r#" ~~~~~~ "# => Token::StringLiteral("hello ".into()), r#" ~~ "# => Token::Interpol, r#" ~ "# => Token::IntLiteral(7), r#" ~ "# => Token::RBrace, r#" ~ "# => Token::DQuote, }; // We can't use `r#""#` for the string since we got a a `"#` in it lex_ok! { " \"#{7} hello\" ", r#" ~ "# => Token::DQuote, r#" ~~ "# => Token::Interpol, r#" ~ "# => Token::IntLiteral(7), r#" ~ "# => Token::RBrace, r#" ~~~~~~ "# => Token::StringLiteral(" hello".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "hello #{ "snot #{7}" }" "#, r#" ~ "# => Token::DQuote, r#" ~~~~~~ "# => Token::StringLiteral("hello ".into()), r#" ~~ "# => Token::Interpol, r#" ~ "# => Token::DQuote, r#" ~~~~~ "# => Token::StringLiteral("snot ".into()), r#" ~~ "# => Token::Interpol, r#" ~ "# => Token::IntLiteral(7), r#" ~ "# => Token::RBrace, r#" ~ "# => Token::DQuote, r#" ~ "# => Token::RBrace, r#" ~ "# => Token::DQuote, }; Ok(()) } #[rustfmt::skip] #[test] fn number_parsing() -> Result<()> { lex_ok! { "1_000_000", "~~~~~~~~~" => Token::IntLiteral(1_000_000), }; lex_ok! { "1_000_000_", "~~~~~~~~~~" => Token::IntLiteral(1_000_000), }; lex_ok! { "100.0000", "~~~~~~~~" => Token::FloatLiteral(100.0000, "100.0000".to_string()), }; lex_ok! { "1_00.0_000_", "~~~~~~~~~~~" => Token::FloatLiteral(100.0000, "100.0000".to_string()), }; lex_ok! { "0xFFAA00", "~~~~~~~~" => Token::IntLiteral(16_755_200), }; lex_ok! { "0xFF_AA_00", "~~~~~~~~~~" => Token::IntLiteral(16_755_200), }; Ok(()) } #[rustfmt::skip] #[test] fn paths() -> Result<()> { lex_ok! { " hello-hahaha8ABC ", " ~~~~~~~~~~~~~~~~ " => Token::Ident("hello-hahaha8ABC".into(), false), }; lex_ok! { " .florp ", " ~ " => Token::Dot, " ~~~~~ " => Token::Ident("florp".into(), false), }; lex_ok! { " $borp ", " ~ " => Token::Dollar, " ~~~~ " => Token::Ident("borp".into(), false), }; lex_ok! { " $`borp`", " ~ " => Token::Dollar, " ~~~~~~ " => Token::Ident("borp".into(), true), }; Ok(()) } #[rustfmt::skip] #[test] fn keywords() -> Result<()> { lex_ok! { " let ", " ~~~ " => Token::Let, }; lex_ok! { " match ", " ~~~~~ " => Token::Match, }; lex_ok! { " case ", " ~~~~ " => Token::Case, }; lex_ok! { " of ", " ~~ " => Token::Of, }; lex_ok! { " end ", " ~~~ " => Token::End, }; lex_ok! { " drop ", " ~~~~ " => Token::Drop, }; lex_ok! { " emit ", " ~~~~ " => Token::Emit, }; lex_ok! { " event ", " ~~~~~ " => Token::Event, }; lex_ok! { " state ", " ~~~~~ " => Token::State, }; lex_ok! { " set ", " ~~~ " => Token::Set, }; lex_ok! { " each ", " ~~~~ " => Token::Each, }; lex_ok! { " intrinsic ", " ~~~~~~~~~ " => Token::Intrinsic, }; Ok(()) } #[rustfmt::skip] #[test] fn operators() -> Result<()> { lex_ok! { " not null ", " ~~~ " => Token::Not, " ~~~~ " => Token::Nil, }; lex_ok! { " != null ", " ~~ " => Token::NotEq, " ~~~~ " => Token::Nil, }; lex_ok! { " !1 ", " ~ " => Token::BitNot, " ~ " => Token::IntLiteral(1), }; lex_ok! { " ! ", " ~ " => Token::BitNot, }; lex_ok! { " and ", " ~~~ " => Token::And, }; lex_ok! { " or ", " ~~ " => Token::Or, }; lex_ok! { " xor ", " ~~~ " => Token::Xor, }; lex_ok! { " & ", " ~ " => Token::BitAnd, }; /* TODO: enable lex_ok! { " | ", " ~ " => Token::BitOr, };*/ lex_ok! { " ^ ", " ~ " => Token::BitXor, }; lex_ok! { " = ", " ~ " => Token::Eq, }; lex_ok! { " == ", " ~~ " => Token::EqEq, }; lex_ok! { " != ", " ~~ " => Token::NotEq, }; lex_ok! { " >= ", " ~~ " => Token::Gte, }; lex_ok! { " > ", " ~ " => Token::Gt, }; lex_ok! { " <= ", " ~~ " => Token::Lte, }; lex_ok! { " < ", " ~ " => Token::Lt, }; lex_ok! { " >> ", " ~~ " => Token::RBitShiftSigned, }; lex_ok! { " >>> ", " ~~~ " => Token::RBitShiftUnsigned, }; lex_ok! { " << ", " ~~ " => Token::LBitShift, }; lex_ok! { " + ", " ~ " => Token::Add, }; lex_ok! { " - ", " ~ " => Token::Sub, }; lex_ok! { " * ", " ~ " => Token::Mul, }; lex_ok! { " / ", " ~ " => Token::Div, }; lex_ok! { " % ", " ~ " => Token::Mod, }; Ok(()) } #[test] fn should_disambiguate() -> Result<()> { // Starts with ':' lex_ok! { " : ", " ~ " => Token::Colon, }; lex_ok! { " :: ", " ~~ " => Token::ColonColon, }; // Starts with '-' lex_ok! { " - ", " ~ " => Token::Sub, }; // Starts with '=' lex_ok! { " = ", " ~ " => Token::Eq, }; lex_ok! { " == ", " ~~ " => Token::EqEq, }; lex_ok! { " => ", " ~~ " => Token::EqArrow, }; // Starts with '%' lex_ok! { " % ", " ~ " => Token::Mod, } lex_ok! { " %{ ", " ~~ " => Token::LPatBrace, } lex_ok! { " %[ ", " ~~ " => Token::LPatBracket, } lex_ok! { " %( ", " ~~ " => Token::LPatParen, } // Starts with '.' lex_ok! { " . ", " ~ " => Token::Dot, }; Ok(()) } #[test] fn delimiters() -> Result<()> { lex_ok! { " ( ) { } [ ] ", " ~ " => Token::LParen, " ~ " => Token::RParen, " ~ " => Token::LBrace, " ~ " => Token::RBrace, " ~ " => Token::LBracket, " ~ " => Token::RBracket, }; Ok(()) } #[test] fn string() -> Result<()> { lex_ok! { r#" "\n" "#, r#" ~ "# => Token::DQuote, r#" ~~ "# => Token::StringLiteral("\n".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "\r" "#, r#" ~ "# => Token::DQuote, r#" ~~ "# => Token::StringLiteral("\r".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "\t" "#, r#" ~ "# => Token::DQuote, r#" ~~ "# => Token::StringLiteral("\t".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "\\" "#, r#" ~ "# => Token::DQuote, r#" ~~ "# => Token::StringLiteral("\\".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "\"" "#, r#" ~ "# => Token::DQuote, r#" ~~ "# => Token::StringLiteral("\"".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "{" "#, r#" ~ "# => Token::DQuote, r#" ~ "# => Token::StringLiteral("{".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "}" "#, r#" ~ "# => Token::DQuote, r#" ~ "# => Token::StringLiteral("}".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "{}" "#, r#" ~ "# => Token::DQuote, r#" ~~ "# => Token::StringLiteral("{}".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "}" "#, r#" ~ "# => Token::DQuote, r#" ~ "# => Token::StringLiteral("}".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "a\nb}}" "#, r#" ~ "# => Token::DQuote, r#" ~~~~~~ "# => Token::StringLiteral("a\nb}}".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "\"\"" "#, r#" ~ "# => Token::DQuote, r#" ~~~~ "# => Token::StringLiteral("\"\"".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "\\\"" "#, r#" ~ "# => Token::DQuote, r#" ~~~~ "# => Token::StringLiteral("\\\"".into()), r#" ~ "# => Token::DQuote, }; lex_ok! { r#" "\"\"""\"\"" "#, r#" ~ "# => Token::DQuote, r#" ~~~~ "# => Token::StringLiteral("\"\"".into()), r#" ~ "# => Token::DQuote, r#" ~ "# => Token::DQuote, r#" ~~~~ "# => Token::StringLiteral("\"\"".into()), r#" ~ "# => Token::DQuote, }; //lex_ko! { r#" "\\\" "#, " ~~~~~ " => ErrorKind::UnterminatedStringLiteral { start: Location::new(1,2,2), end: Location::new(1,7,7) } } Ok(()) } #[rustfmt::skip] #[test] fn heredoc() -> Result<()> { lex_ok! { r#"""" """"#, r#"~~~"# => Token::HereDocStart, r#"~~~~~~~~~~~~~~"# => Token::HereDocLiteral(" ".into()), r#" ~~~"# => Token::HereDocEnd, }; Ok(()) } #[test] fn test_preprocessor() -> Result<()> { lex_ok! { r#"use "foo.tremor" ;"#, r#"~~~ "# => Token::Use, r#" ~ "# => Token::DQuote, r#" ~~~~~~~~~~ "# => Token::StringLiteral("foo.tremor".into()), r#" ~ "# => Token::DQuote, r#" ~"# => Token::Semi, }; Ok(()) } #[test] fn test_test_literal_format_bug_regression() -> Result<()> { let snot = "match %{ test ~= base64|| } of default => \"badger\" end ".to_string(); let mut snot2 = snot.clone(); let mut include_stack = IncludeStack::default(); let badger2 = Preprocessor::preprocess( &ModulePath { mounts: vec![] }, "foo", &mut snot2, 0, &mut include_stack, )?; let mut res = String::new(); for b in Tokenizer::new(&snot) .filter_map(Result::ok) .collect::<Vec<TokenSpan>>() { res.push_str(&format!("{}", b.value)); } assert_eq!(snot, res); let mut res2 = String::new(); for b in badger2 .into_iter() .filter_map(Result::ok) .collect::<Vec<TokenSpan>>() { res2.push_str(&format!("{}", b.value)); } assert_eq!(snot, res2); Ok(()) } #[test] fn lexer_long_float() -> Result<()> { let f = 48_354_865_651_623_290_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000.0; let source = format!("{:.1}", f); // ensure we keep the .0 match Tokenizer::new(&source).next() { Some(Ok(token)) => match token.value { Token::FloatLiteral(f_token, _) => { assert_eq!(f, f_token); } t => assert!(false, "{:?} not a float", t), }, e => assert!(false, "{:?} unexpected", e), }; Ok(()) } use proptest::prelude::*; proptest! { // negative floats are constructed in the AST later #[test] fn float_literals_precision(f in 0_f64..f64::MAX) { if f.round() != f { let float = format!("{:.}", f); for token in Tokenizer::new(& float) { let _ = token?; } } } } proptest! { // negative floats are constructed in the AST later #[test] fn float_literals_scientific(f in 0_f64..f64::MAX) { let float = format!("{:e}", f); for token in Tokenizer::new(& float) { match token { Ok(spanned) => match spanned.value { Token::FloatLiteral(f_token, _f_str) => assert_eq!(f, f_token), _ => () } _ => () } } } } }
use aoc_runner_derive::{aoc, aoc_generator}; #[aoc_generator(day9)] fn parse_input(input: &str) -> Vec<u64> { input.lines().map(|v| v.parse::<u64>().unwrap()).collect() } fn has_sum(numbers: &[u64], target: u64) -> bool { for i in 0..numbers.len() { for j in 1..numbers.len() { if i == j { continue; } if numbers[i] + numbers[j] == target { return true; } } } false } fn find_rule_breaker(numbers: &[u64], preamble_size: usize) -> u64 { *numbers[preamble_size..] .iter() .enumerate() .find(|(i, n)| !has_sum(&numbers[*i..*i + preamble_size], **n)) .unwrap() .1 } fn find_weakness(numbers: &[u64], target: u64) -> u64 { // remove any numbers bigger than the target let subset: Vec<&u64> = numbers.iter().filter(|v| **v < target).collect(); for i in 0..subset.len() { for j in i..subset.len() { let set = &subset[i..j]; if set.iter().map(|v| **v).sum::<u64>() == target { return **(set.iter().max().unwrap()) + **(set.iter().min().unwrap()); } } } panic!("Solution not found"); } #[aoc(day9, part1)] fn solve_part1(numbers: &[u64]) -> u64 { find_rule_breaker(numbers, 25) } #[aoc(day9, part2)] fn solve_part2(numbers: &[u64]) -> u64 { find_weakness(&numbers, find_rule_breaker(&numbers, 25)) } #[cfg(test)] mod test { use super::*; #[test] fn test_rule_breaker() { let input = "35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576"; assert_eq!(find_rule_breaker(&parse_input(input), 5), 127); } #[test] fn test_weakness_finder() { let input = "35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576"; let numbers = parse_input(input); assert_eq!(find_weakness(&numbers, find_rule_breaker(&numbers, 5)), 62); } }
//============================================================================== // Notes //============================================================================== // mcu::input.rs // Watcher and handler for a GPIO pin defined as an input //============================================================================== // Crates and Mods //============================================================================== use core::cell::{Cell, RefCell}; use core::ops::DerefMut; use cortex_m::interrupt::{free, Mutex}; use nrf52832_pac::interrupt; use super::gpio; //============================================================================== // Enums, Structs, and Types //============================================================================== #[derive(Clone, Copy)] struct InputQueueEntry{ pin: Option<u8>, callback: &'static dyn Fn(), real_time_callback: bool } #[derive(Clone, Copy)] pub struct PinConfig { pub pin: u8, pub polarity: nrf52832_pac::gpiote::config::POLARITY_A, pub pull: nrf52832_pac::p0::pin_cnf::PULL_A, pub callback: &'static dyn Fn(), pub real_time_callback: bool } //============================================================================== // Variables //============================================================================== const EVENT_LEN: usize = 8; const INPUT_QUEUE_LEN: usize = 16; static mut EVENT_MAP: [InputQueueEntry; EVENT_LEN] = [ InputQueueEntry { pin: None, callback: &dummy_function, real_time_callback: false }; EVENT_LEN]; static HEAD: Mutex<Cell<usize>> = Mutex::new(Cell::new(0)); static TAIL: Mutex<Cell<usize>> = Mutex::new(Cell::new(0)); static QUEUE: Mutex<Cell<[u8; INPUT_QUEUE_LEN]>> = Mutex::new(Cell::new([0; INPUT_QUEUE_LEN])); static GPIOTE_HANDLE: Mutex<RefCell<Option<nrf52832_pac::GPIOTE>>> = Mutex::new(RefCell::new(None)); //============================================================================== // Public Functions //============================================================================== pub fn init(gpiote: nrf52832_pac::GPIOTE) { free(|cs| GPIOTE_HANDLE.borrow(cs).replace(Some(gpiote))); } pub fn init_pin(config: PinConfig) { // If pin is already configured, quit if get_event_exists(config.pin) { return; } // Get the next available interrupt index if let Some(event) = get_event_index(config.pin) { configure(config, event); // Assign this pin config to the event map unsafe { EVENT_MAP[event].pin = Some(config.pin); EVENT_MAP[event].callback = config.callback; EVENT_MAP[event].real_time_callback = config.real_time_callback; } } } //============================================================================== // Private Functions //============================================================================== fn configure(config: PinConfig, event: usize) { // Set pin config gpio::pin_setup(config.pin, nrf52832_pac::p0::pin_cnf::DIR_A::INPUT, gpio::PinState::PinLow, config.pull); // Pause interrupts during config nrf52832_pac::NVIC::mask(nrf52832_pac::Interrupt::GPIOTE); free(|cs| { if let Some(ref mut gpiote) = GPIOTE_HANDLE.borrow(cs).borrow_mut().deref_mut() { // Assign the pin config to the event gpiote.config[event].write(|w| unsafe { w .polarity().variant(config.polarity) .psel().bits(config.pin) .mode().event() }); // Enable the interrupt gpiote.intenset.modify(|_r, w| unsafe { w.bits(1 << event) }); // Just in case, clear any pending events that need handling gpiote.events_in[event].modify(|_r, w| unsafe { w.bits(0) }); } }); unsafe { nrf52832_pac::NVIC::unpend(nrf52832_pac::Interrupt::GPIOTE); nrf52832_pac::NVIC::unmask(nrf52832_pac::Interrupt::GPIOTE); } } fn dummy_function() {} fn get_event_exists(pin: u8) -> bool { // Returns true if the pin is already in the queue unsafe { for e in 0..EVENT_LEN { if let Some(tmp_pin) = EVENT_MAP[e].pin { if tmp_pin == pin { return true; } } } false } } fn get_event_index(pin: u8) -> Option<usize> { // Returns the index of the pin in the queue // If the pin does not have an index, one will be assigned and returned unsafe { for e in 0..EVENT_LEN { if let Some(tmp_pin) = EVENT_MAP[e].pin { if tmp_pin == pin { return Some(e); } } else { return Some(e); } } return None; } } //============================================================================== // Interrupt Handler //============================================================================== #[interrupt] fn GPIOTE() { let mut event: Option<usize> = None; free(|cs| { if let Some(ref mut gpiote) = GPIOTE_HANDLE.borrow(cs).borrow_mut().deref_mut() { // Find the event that caused the interrupt for e in 0..EVENT_LEN { if gpiote.events_in[e].read().bits() != 0 { // Clear the event flag gpiote.events_in[e].write(|w| unsafe { w.bits(0) }); event = Some(e); break; } } } }); // Safe this event in the queue if let Some(e) = event { // If real time callback enabled, run the handler immediately and return unsafe { if EVENT_MAP[e].real_time_callback { let f = EVENT_MAP[e].callback; f(); return; } } // grab the current tail position let tail: usize = free(|cs| TAIL.borrow(cs).get()); // Update the tail pointer to the next available position free(|cs| TAIL.borrow(cs).set( { let mut tail = TAIL.borrow(cs).get() + 1; if tail == EVENT_LEN { tail = 0; } tail })); // Push this event onto the queue free(|cs| { let mut queue = QUEUE.borrow(cs).get(); queue[tail] = e as u8; QUEUE.borrow(cs).set(queue); }) } } //============================================================================== // Task Handler //============================================================================== pub fn task_handler() { let mut head: usize = free(|cs| HEAD.borrow(cs).get()); let tail: usize = free(|cs| TAIL.borrow(cs).get()); while head != tail { let event = free(|cs| QUEUE.borrow(cs).get())[head] as usize; unsafe { let f = EVENT_MAP[event].callback; f(); } // Increment the head pointer head = head + 1; if head == EVENT_LEN { head = 0; } } // Reset the head pointer free(|cs| HEAD.borrow(cs).set(head)); }
use std::collections::HashMap; fn main() { let mut number_list = vec![1,4,77,2,2,5,12,32,13,235,12,2,245,432,532,1,23,45,324,23,5,234,23,5,32]; number_list.sort(); // sort this to work out the median later let mut total:f32 = 0 as f32; let mut number_counts= HashMap::new(); // get the total for i in &number_list { total += *i as f32; let count = number_counts.entry(i).or_insert(0); *count += 1; } // work out the mean let number_list_mean: f32 = total / number_list.len() as f32; // get the median let number_list_median: f32; // check to see if its an odd number, if it is then we need to get the median from the // mean of the two middle numbers if number_list.len() % 2 == 1 { number_list_median = { let first_index = (number_list.len() as f32 / 2 as f32).floor() as usize; let second_index = (number_list.len() as f32 / 2 as f32).ceil() as usize; (number_list[first_index] as f32 + number_list[second_index] as f32) / 2 as f32 } } else { number_list_median = number_list[number_list.len() / 2] as f32 } // taken from the latest answer on this SO question // https://stackoverflow.com/questions/34555837/sort-hashmap-data-by-value // need to understand what this does a bit more let number_list_mode = number_counts.iter().max_by(|a, b| a.1.cmp(&b.1)).unwrap(); println!("total {}", total); println!("mean {}", number_list_mean); println!("median {}", number_list_median); println!("mode {}", number_list_mode.0); }
use std::sync::Arc; use proptest::strategy::Just; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::erts::Node; use crate::runtime::distribution::nodes; use crate::erlang::list_to_pid_1::result; use crate::test::strategy; use crate::test::with_process; #[test] fn without_list_errors_badarg() { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_list(arc_process.clone()), ) }, |(arc_process, string)| { prop_assert_is_not_non_empty_list!(result(&arc_process, string), string); Ok(()) }, ); } #[test] fn with_list_encoding_local_pid() { with_process(|process| { let string = process.charlist_from_str("<"); assert_badarg!( result(&process, string), format!("string ({}) is missing 'node.number.serial>'", string) ); let string = process.charlist_from_str("<0"); assert_badarg!( result(&process, string), format!("string ({}) is missing '.number.serial>'", string) ); let string = process.charlist_from_str("<0."); assert_badarg!( result(&process, string), format!("string ({}) is missing 'number.serial>'", string) ); let string = process.charlist_from_str("<0.1"); assert_badarg!( result(&process, string), format!("string ({}) is missing '.serial>", string) ); let string = process.charlist_from_str("<0.1."); assert_badarg!( result(&process, string), format!("string ({}) is missing 'serial>", string) ); let string = process.charlist_from_str("<0.1.2"); assert_badarg!( result(&process, string), format!("string ({}) is missing '>'", string) ); assert_eq!( result(&process, process.charlist_from_str("<0.1.2>")), Ok(Pid::make_term(1, 2).unwrap()) ); assert_badarg!( result(&process, process.charlist_from_str("<0.1.2>?")), "extra characters (\"?\") beyond end of formatted pid" ); }) } #[test] fn with_list_encoding_external_pid_without_known_node_errors_badarg() { with_process(|process| { let string = process.charlist_from_str("<"); assert_badarg!( result(&process, string), format!("string ({}) is missing 'node.number.serial>'", string) ); let string = process.charlist_from_str("<2"); assert_badarg!( result(&process, string), format!("string ({}) is missing '.number.serial>'", string) ); let string = process.charlist_from_str("<2."); assert_badarg!( result(&process, string), format!("string ({}) is missing 'number.serial>'", string) ); let string = process.charlist_from_str("<2.3"); assert_badarg!( result(&process, string), format!("string ({}) is missing '.serial>", string) ); let string = process.charlist_from_str("<2.3."); assert_badarg!( result(&process, string), format!("string ({}) is missing 'serial>", string) ); let string = process.charlist_from_str("<2.3."); assert_badarg!( result(&process, string), format!("string ({}) is missing 'serial>", string) ); // MUST be a different `id` than other tests that insert the node. let arc_node = Arc::new(Node::new(2, Atom::try_from_str("2@external").unwrap(), 0)); assert_badarg!( result(&process, process.charlist_from_str("<2.3.4>")), "No node with id (2)" ); nodes::insert(arc_node.clone()); assert_eq!( result(&process, process.charlist_from_str("<2.3.4>")), Ok(process.external_pid(arc_node, 3, 4).unwrap()) ); assert_badarg!( result(&process, process.charlist_from_str("<2.3.4>?")), "extra characters (\"?\") beyond end of formatted pid" ); }); }
use core::fmt::{self, Debug, Display}; macro_rules! with_backtrace { ($($i:item)*) => ($(#[cfg(all(feature = "backtrace", feature = "std"))]$i)*) } macro_rules! without_backtrace { ($($i:item)*) => ($(#[cfg(not(all(feature = "backtrace", feature = "std")))]$i)*) } without_backtrace! { /// A `Backtrace`. /// /// This is an opaque wrapper around the backtrace provided by /// libbacktrace. A variety of optimizations have been performed to avoid /// unnecessary or ill-advised work: /// /// - If this crate is compiled in `no_std` compatible mode, `Backtrace` /// is an empty struct, and will be completely compiled away. /// - If this crate is run without the `RUST_BACKTRACE` environmental /// variable enabled, the backtrace will not be generated at runtime. /// - Even if a backtrace is generated, the most expensive part of /// generating a backtrace is symbol resolution. This backtrace does not /// perform symbol resolution until it is actually read (e.g. by /// printing it). If the Backtrace is never used for anything, symbols /// never get resolved. /// /// Even with these optimizations, including a backtrace in your failure /// may not be appropriate to your use case. You are not required to put a /// backtrace in a custom `Fail` type. /// /// > (We have detected that this crate was documented with no_std /// > compatibility turned on. The version of this crate that has been /// > documented here will never generate a backtrace.) pub struct Backtrace { _secret: (), } impl Backtrace { /// Constructs a new backtrace. This will only create a real backtrace /// if the crate is compiled in std mode and the `RUST_BACKTRACE` /// environmental variable is activated. /// /// > (We have detected that this crate was documented with no_std /// > compatibility turned on. The version of this crate that has been /// > documented here will never generate a backtrace.) pub fn new() -> Backtrace { Backtrace { _secret: () } } #[cfg(feature = "std")] pub(crate) fn none() -> Backtrace { Backtrace { _secret: () } } #[cfg(feature = "std")] pub(crate) fn is_none(&self) -> bool { true } } impl Default for Backtrace { fn default() -> Backtrace { Backtrace::new() } } impl Debug for Backtrace { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl Display for Backtrace { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } } with_backtrace! { extern crate backtrace; mod internal; use self::internal::InternalBacktrace; /// A `Backtrace`. /// /// This is an opaque wrapper around the backtrace provided by /// libbacktrace. A variety of optimizations have been performed to avoid /// unnecessary or ill-advised work: /// /// - If this crate is compiled in `no_std` compatible mode, `Backtrace` /// is an empty struct, and will be completely compiled away. /// - If this crate is run without the `RUST_BACKTRACE` environmental /// variable enabled, the backtrace will not be generated at runtime. /// - Even if a backtrace is generated, the most expensive part of /// generating a backtrace is symbol resolution. This backtrace does not /// perform symbol resolution until it is actually read (e.g. by /// printing it). If the Backtrace is never used for anything, symbols /// never get resolved. /// /// Even with these optimizations, including a backtrace in your failure /// may not be appropriate to your use case. You are not required to put a /// backtrace in a custom `Fail` type. pub struct Backtrace { internal: InternalBacktrace } impl Backtrace { /// Constructs a new backtrace. This will only create a real backtrace /// if the crate is compiled in std mode and the `RUST_BACKTRACE` /// environmental variable is activated. pub fn new() -> Backtrace { Backtrace { internal: InternalBacktrace::new() } } pub(crate) fn none() -> Backtrace { Backtrace { internal: InternalBacktrace::none() } } pub(crate) fn is_none(&self) -> bool { self.internal.is_none() } } impl Default for Backtrace { fn default() -> Backtrace { Backtrace::new() } } impl Debug for Backtrace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(bt) = self.internal.as_backtrace() { Debug::fmt(bt, f) } else { Ok(()) } } } impl Display for Backtrace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(bt) = self.internal.as_backtrace() { Debug::fmt(bt, f) } else { Ok(()) } } } }
use actix_web::HttpResponse; use actix_web::ResponseError; use bigneon_db::utils::errors::DatabaseError; use diesel::result::Error as DieselError; use errors::AuthError; use errors::*; use lettre::smtp::error::Error as SmtpError; use payments::PaymentProcessorError; use reqwest::Error as ReqwestError; use serde_json::Error as SerdeError; use std::error::Error; use std::fmt; use tari_client::TariError; #[derive(Debug)] pub struct BigNeonError(Box<ConvertToWebError + Send + Sync>); impl From<DatabaseError> for BigNeonError { fn from(e: DatabaseError) -> Self { BigNeonError(Box::new(e)) } } impl From<ReqwestError> for BigNeonError { fn from(e: ReqwestError) -> Self { BigNeonError(Box::new(e)) } } impl From<PaymentProcessorError> for BigNeonError { fn from(pe: PaymentProcessorError) -> Self { BigNeonError(Box::new(pe)) } } impl From<TariError> for BigNeonError { fn from(te: TariError) -> Self { BigNeonError(Box::new(te)) } } impl From<DieselError> for BigNeonError { fn from(e: DieselError) -> Self { BigNeonError(Box::new(e)) } } impl From<SerdeError> for BigNeonError { fn from(e: SerdeError) -> Self { BigNeonError(Box::new(e)) } } impl From<ApplicationError> for BigNeonError { fn from(e: ApplicationError) -> Self { BigNeonError(Box::new(e)) } } impl From<SmtpError> for BigNeonError { fn from(e: SmtpError) -> Self { BigNeonError(Box::new(e)) } } impl From<AuthError> for BigNeonError { fn from(e: AuthError) -> Self { BigNeonError(Box::new(e)) } } impl fmt::Display for BigNeonError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&*self.0.to_string()) } } impl Error for BigNeonError { fn description(&self) -> &str { self.0.description() } } impl ResponseError for BigNeonError { fn error_response(&self) -> HttpResponse { self.0.to_response() } }
pub use core::task::Waker as RawWaker; use atomic::{Atomic, Ordering}; use intrusive_collections::{LinkedList, LinkedListLink}; use object_id::ObjectId; use crate::prelude::*; /// A waiter. /// /// `Waiter`s are mostly used with `WaiterQueue`s. Yet, it is also possible to /// use `Waiter` with `Waker`. pub struct Waiter { inner: Arc<WaiterInner>, } /// The states of a waiter. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum WaiterState { Idle, Waiting, Woken, } impl Waiter { pub fn new() -> Self { let inner = Arc::new(WaiterInner::new()); Self { inner } } pub fn state(&self) -> WaiterState { self.inner.state() } pub fn reset(&self) { self.inner.state.store(WaiterState::Idle, Ordering::Relaxed); } pub fn wait(&self) -> WaitFuture<'_> { self.inner.wait() } pub fn waker(&self) -> Waker { Waker { inner: self.inner.clone(), } } pub(super) fn inner(&self) -> &Arc<WaiterInner> { &self.inner } } #[derive(Clone)] pub struct Waker { inner: Arc<WaiterInner>, } impl Waker { pub fn state(&self) -> WaiterState { self.inner.state() } pub fn wake(&self) -> Option<()> { self.inner.wake() } } // Accesible by WaiterQueue. pub(super) struct WaiterInner { state: Atomic<WaiterState>, raw_waker: Mutex<Option<RawWaker>>, queue_id: Atomic<ObjectId>, pub(super) link: LinkedListLink, } impl WaiterInner { pub fn new() -> Self { Self { state: Atomic::new(WaiterState::Idle), link: LinkedListLink::new(), raw_waker: Mutex::new(None), queue_id: Atomic::new(ObjectId::null()), } } pub fn state(&self) -> WaiterState { self.state.load(Ordering::Relaxed) } pub fn set_state(&self, new_state: WaiterState) { self.state.store(new_state, Ordering::Relaxed) } pub fn queue_id(&self) -> &Atomic<ObjectId> { &self.queue_id } pub fn wait(&self) -> WaitFuture<'_> { WaitFuture::new(self) } pub fn wake(&self) -> Option<()> { let mut raw_waker = self.raw_waker.lock(); match self.state() { WaiterState::Idle => { self.set_state(WaiterState::Woken); Some(()) } WaiterState::Waiting => { self.set_state(WaiterState::Woken); let raw_waker = raw_waker.take().unwrap(); raw_waker.wake(); Some(()) } WaiterState::Woken => None, } } } unsafe impl Sync for WaiterInner {} unsafe impl Send for WaiterInner {} pub struct WaitFuture<'a> { waiter: &'a WaiterInner, } impl<'a> WaitFuture<'a> { fn new(waiter: &'a WaiterInner) -> Self { Self { waiter } } } impl<'a> Future for WaitFuture<'a> { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut raw_waker = self.waiter.raw_waker.lock(); match self.waiter.state() { WaiterState::Idle => { self.waiter.set_state(WaiterState::Waiting); *raw_waker = Some(cx.waker().clone()); Poll::Pending } WaiterState::Waiting => { *raw_waker = Some(cx.waker().clone()); Poll::Pending } WaiterState::Woken => { debug_assert!(raw_waker.is_none()); Poll::Ready(()) } } } }
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use super::{DeclarationList, DeclarationListParser}; use crate::lexer::lexer::{Lexer, LocToken, Token}; use crate::lexer::preprocessor::context::PreprocContext; use crate::parser::declarations::{DeclHint, DeclarationParser, Specifier}; use crate::parser::statement::Statement; use crate::{check_semicolon, check_semicolon_or_not}; #[derive(Clone, Debug, PartialEq)] pub enum Linkage { Single(Statement), Multiple(DeclarationList), } #[derive(Clone, Debug, PartialEq)] pub struct Extern { pub(crate) language: String, pub(crate) linkage: Linkage, } pub(super) enum EPRes { Extern(Extern), Declaration(Statement), } pub struct ExternParser<'a, 'b, PC: PreprocContext> { lexer: &'b mut Lexer<'a, PC>, } impl<'a, 'b, PC: PreprocContext> ExternParser<'a, 'b, PC> { pub(super) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self { Self { lexer } } pub(super) fn parse(self, tok: Option<LocToken>) -> (Option<LocToken>, Option<EPRes>) { let tok = tok.unwrap_or_else(|| self.lexer.next_useful()); if tok.tok != Token::Extern { return (Some(tok), None); } let tok = self.lexer.next_useful(); if let Token::LiteralString(language) = tok.tok { let tok = self.lexer.next_useful(); match tok.tok { Token::LeftBrace => { let dlp = DeclarationListParser::new(self.lexer); let (tok, list) = dlp.parse(None); ( tok, Some(EPRes::Extern(Extern { language, linkage: Linkage::Multiple(list.unwrap()), })), ) } _ => { let dp = DeclarationParser::new(self.lexer); let (tok, decl) = dp.parse(Some(tok), None); let (_, decl): (Option<LocToken>, _) = check_semicolon_or_not!(self, tok, decl); ( None, Some(EPRes::Extern(Extern { language, linkage: Linkage::Single(decl.unwrap()), })), ) } } } else { let dp = DeclarationParser::new(self.lexer); let hint = DeclHint::Specifier(Specifier::EXTERN); let (tok, decl) = dp.parse(Some(tok), Some(hint)); let (tok, decl) = check_semicolon_or_not!(self, tok, decl); (tok, Some(EPRes::Declaration(decl.unwrap()))) } } }
use std::env; use std::fs::read_to_string; use std::io::BufReader; use openaip::parse; fn main() { let args: Vec<_> = env::args().collect(); let content = read_to_string(&args[1]).unwrap(); let file = parse(&content).unwrap(); for airspace in file.airspaces.unwrap() { println!("{:?}", airspace); } }
extern crate strip_ansi_escapes; use std::io; use strip_ansi_escapes::Writer; pub fn work() -> io::Result<()> { let stdin = io::stdin(); let mut in_lock = stdin.lock(); let stdout = io::stdout(); let out_lock = stdout.lock(); let mut writer = Writer::new(out_lock); io::copy(&mut in_lock, &mut writer)?; Ok(()) } pub fn main() { work().unwrap(); }
extern crate cc; use std::path::PathBuf; fn main() { let mut cxx = cc::Build::new(); cxx.cpp(true); cxx.include("vendor/Horde3D/Source/Horde3DEngine"); cxx.include("vendor/Horde3D/Source/Shared"); cxx.include("vendor/Extensions"); cxx.warnings(false); cxx.define("PLATFORM_MAC", "1"); let files_engine = &[ "egAnimatables.cpp", "egAnimation.cpp", "egCamera.cpp", "egCom.cpp", "egComputeNode.cpp", "egComputeBuffer.cpp", "egExtensions.cpp", "egGeometry.cpp", "egLight.cpp", "egMain.cpp", "egMaterial.cpp", "egModel.cpp", "egModules.cpp", "egParticle.cpp", "egPipeline.cpp", "egPrimitives.cpp", "egRendererBaseGL2.cpp", "egRendererBaseGL4.cpp", "egRenderer.cpp", "egResource.cpp", "egScene.cpp", "egSceneGraphRes.cpp", "egShader.cpp", "egTexture.cpp", "utImage.cpp", "utOpenGL.cpp", ]; let files_terrain = &["extension.cpp", "terrain.cpp"]; let files_external_texture = &["extension.cpp", "egTextureEx.cpp"]; for file in files_engine { cxx.file(PathBuf::from("vendor/Horde3D/Source/Horde3DEngine").join(file)); } for file in files_terrain { cxx.file(PathBuf::from("vendor/Extensions/Terrain/Source").join(file)); } for file in files_external_texture { cxx.file(PathBuf::from("vendor/Extensions/ExternalTexture/Source").join(file)); } cxx.compile("libhorde3d.a"); }
use actix; use database::db::PgConnection; pub struct AppState { pub db: actix::Addr<PgConnection>, }
use crate::prelude::*; #[repr(C)] #[derive(Debug, Clone)] pub struct VkSubresourceLayout { pub offset: VkDeviceSize, pub size: VkDeviceSize, pub rowPitch: VkDeviceSize, pub arrayPitch: VkDeviceSize, pub depthPitch: VkDeviceSize, }
/* Primitive Types: Integers: u8, i8, u16, i16, u32, i32, u64, i64, u128, i128 (these are different because they allocate the number of bits of memory they take in) ( u = unsigned: no negative values ) ( i = integers: can be pos and neg ) Floats: f32, f64 Boolean (bool) Characters (char) Tuples Arrays - fixed length */ // Rust is a statically typed language, which mens that it must know // the types of all variables at compile time, however, the compiler // can usually infer what type we want to use based on the value and // how we use it. pub fn run() { // An example of type inference // Defaults to i32 let x = 1; // Defaults to f64 let y = 2.5; // Examples of explicit types let z: i64 = 4545454545454545; // Find max size of i32 and i64 data types println!("Max of i32 type: {}", std::i32::MAX); println!("Max of i64 type: {}", std::i64::MAX); // Boolean let is_active = true; let is_explicitly_active: bool = true; let is_greater = 10 > 5; println!("{:?}", (x, y, z, is_active, is_explicitly_active)); println!("Is 10 > 5: {:?}", (is_greater)); // Char let a1 = 'a'; let b1: char = 'b'; // Since chars can be any unicode character, // we can bring in unicode emojis let face = '\u{1F600}'; println!("{:?}", (a1, b1, face)); }
//! Caching of [`NamespaceSchema`]. mod memory; pub use memory::*; mod sharded_cache; pub use sharded_cache::*; pub mod metrics; mod read_through_cache; pub use read_through_cache::*; use std::{collections::BTreeMap, error::Error, fmt::Debug, sync::Arc}; use async_trait::async_trait; use data_types::{ColumnsByName, NamespaceName, NamespaceSchema, TableSchema}; /// An abstract cache of [`NamespaceSchema`]. #[async_trait] pub trait NamespaceCache: Debug + Send + Sync { /// The type of error a [`NamespaceCache`] implementation produces /// when unable to read the [`NamespaceSchema`] requested from the /// cache. type ReadError: Error + Send; /// Return the [`NamespaceSchema`] for `namespace`. async fn get_schema( &self, namespace: &NamespaceName<'static>, ) -> Result<Arc<NamespaceSchema>, Self::ReadError>; /// Place `schema` in the cache, merging the set of tables and their columns /// with the existing entry for `namespace`, if any. /// /// All data except the set of tables/columns have "last writer wins" /// semantics. The resulting merged schema is returned, along with a set /// of change statistics. /// /// Concurrent calls to this method will race and may result in a schema /// change being lost. fn put_schema( &self, namespace: NamespaceName<'static>, schema: NamespaceSchema, ) -> (Arc<NamespaceSchema>, ChangeStats); } /// Change statistics describing how the cache entry was modified by the /// associated [`NamespaceCache::put_schema()`] call. #[derive(Debug, PartialEq, Eq)] pub struct ChangeStats { /// The new tables added to the cache, keyed by table name. pub(crate) new_tables: BTreeMap<String, TableSchema>, /// The new columns added to cache for all pre-existing tables, keyed by /// the table name. pub(crate) new_columns_per_table: BTreeMap<String, ColumnsByName>, /// The number of new columns added across new and existing tables. pub(crate) num_new_columns: usize, /// Indicates whether the change took place when an entry already /// existed. pub(crate) did_update: bool, } /// An optional [`NamespaceCache`] decorator layer. #[derive(Debug)] pub enum MaybeLayer<T, U> { /// With the optional layer. With(T), /// Without the operational layer. Without(U), } #[async_trait] impl<T, U, E> NamespaceCache for MaybeLayer<T, U> where T: NamespaceCache<ReadError = E>, U: NamespaceCache<ReadError = E>, E: Error + Send, { type ReadError = E; async fn get_schema( &self, namespace: &NamespaceName<'static>, ) -> Result<Arc<NamespaceSchema>, Self::ReadError> { match self { MaybeLayer::With(v) => v.get_schema(namespace).await, MaybeLayer::Without(v) => v.get_schema(namespace).await, } } fn put_schema( &self, namespace: NamespaceName<'static>, schema: NamespaceSchema, ) -> (Arc<NamespaceSchema>, ChangeStats) { match self { MaybeLayer::With(v) => v.put_schema(namespace, schema), MaybeLayer::Without(v) => v.put_schema(namespace, schema), } } }
use super::{utils::heap_object_impls, HeapObjectTrait}; use crate::heap::{ object_heap::HeapObject, DisplayWithSymbolTable, Heap, InlineObject, OrdWithSymbolTable, SymbolTable, }; use derive_more::Deref; use itertools::Itertools; use rustc_hash::FxHashMap; use std::{ cmp::Ordering, fmt::{self, Debug, Formatter}, hash::{Hash, Hasher}, num::NonZeroU64, ptr::{self, NonNull}, slice, }; #[derive(Clone, Copy, Deref)] pub struct HeapList(HeapObject); impl HeapList { const LEN_SHIFT: usize = 4; pub fn new_unchecked(object: HeapObject) -> Self { Self(object) } pub fn create(heap: &mut Heap, is_reference_counted: bool, value: &[InlineObject]) -> Self { let len = value.len(); let list = Self::create_uninitialized(heap, is_reference_counted, len); unsafe { ptr::copy_nonoverlapping(value.as_ptr(), list.items_pointer().as_ptr(), len) }; list } fn create_uninitialized(heap: &mut Heap, is_reference_counted: bool, len: usize) -> Self { assert_eq!( (len << Self::LEN_SHIFT) >> Self::LEN_SHIFT, len, "List is too long.", ); Self(heap.allocate( HeapObject::KIND_LIST, is_reference_counted, (len as u64) << Self::LEN_SHIFT, len * HeapObject::WORD_SIZE, )) } pub fn len(self) -> usize { (self.header_word() >> Self::LEN_SHIFT) as usize } pub fn get(self, index: usize) -> InlineObject { debug_assert!(index < self.len()); let word = self.unsafe_get_content_word(index); let word = unsafe { NonZeroU64::new_unchecked(word) }; InlineObject::new(word) } fn items_pointer(self) -> NonNull<InlineObject> { self.content_word_pointer(0).cast() } pub fn items<'a>(self) -> &'a [InlineObject] { unsafe { let pointer = self.items_pointer().as_ref(); slice::from_raw_parts(pointer, self.len()) } } #[must_use] pub fn insert(self, heap: &mut Heap, index: usize, value: InlineObject) -> Self { assert!(index <= self.len()); let len = self.len() + 1; let new_list = Self::create_uninitialized(heap, true, len); unsafe { ptr::copy_nonoverlapping( self.content_word_pointer(0).as_ptr(), new_list.content_word_pointer(0).as_ptr(), index, ); ptr::write(new_list.content_word_pointer(index).cast().as_ptr(), value); ptr::copy_nonoverlapping( self.content_word_pointer(index).as_ptr(), new_list.content_word_pointer(index + 1).as_ptr(), self.len() - index, ); } new_list } #[must_use] pub fn remove(self, heap: &mut Heap, index: usize) -> Self { assert!(index < self.len()); let len = self.len() - 1; let new_list = Self::create_uninitialized(heap, true, len); unsafe { ptr::copy_nonoverlapping( self.content_word_pointer(0).as_ptr(), new_list.content_word_pointer(0).as_ptr(), index, ); ptr::copy_nonoverlapping( self.content_word_pointer(index + 1).as_ptr(), new_list.content_word_pointer(index).as_ptr(), self.len() - index - 1, ); } new_list } #[must_use] pub fn replace(self, heap: &mut Heap, index: usize, value: InlineObject) -> Self { assert!(index < self.len()); let new_list = Self::create(heap, true, self.items()); unsafe { ptr::write(new_list.content_word_pointer(index).cast().as_ptr(), value) }; new_list } } impl Debug for HeapList { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let items = self.items(); write!( f, "({})", if items.is_empty() { ",".to_owned() } else { items.iter().map(|item| format!("{:?}", item)).join(", ") }, ) } } impl DisplayWithSymbolTable for HeapList { fn fmt(&self, f: &mut Formatter, symbol_table: &SymbolTable) -> fmt::Result { let items = self.items(); write!( f, "({})", if items.is_empty() { ",".to_owned() } else { items .iter() .map(|item| DisplayWithSymbolTable::to_string(item, symbol_table)) .join(", ") }, ) } } impl Eq for HeapList {} impl PartialEq for HeapList { fn eq(&self, other: &Self) -> bool { self.items() == other.items() } } impl Hash for HeapList { fn hash<H: Hasher>(&self, state: &mut H) { self.items().hash(state) } } impl OrdWithSymbolTable for HeapList { fn cmp(&self, symbol_table: &SymbolTable, other: &Self) -> Ordering { OrdWithSymbolTable::cmp(self.items(), symbol_table, other.items()) } } heap_object_impls!(HeapList); impl HeapObjectTrait for HeapList { fn content_size(self) -> usize { self.len() * HeapObject::WORD_SIZE } fn clone_content_to_heap_with_mapping( self, heap: &mut Heap, clone: HeapObject, address_map: &mut FxHashMap<HeapObject, HeapObject>, ) { let clone = Self(clone); for (index, &item) in self.items().iter().enumerate() { clone.unsafe_set_content_word( index, item.clone_to_heap_with_mapping(heap, address_map) .raw_word() .get(), ); } } fn drop_children(self, heap: &mut Heap) { for item in self.items() { item.drop(heap) } } fn deallocate_external_stuff(self) {} }
use lazy_static::lazy_static; pub use lighthouse_metrics::*; lazy_static! { pub static ref SLASHER_DATABASE_SIZE: Result<IntGauge> = try_create_int_gauge( "slasher_database_size", "Size of the LMDB database backing the slasher, in bytes" ); pub static ref SLASHER_RUN_TIME: Result<Histogram> = try_create_histogram( "slasher_process_batch_time", "Time taken to process a batch of blocks and attestations" ); pub static ref SLASHER_NUM_ATTESTATIONS_DROPPED: Result<IntGauge> = try_create_int_gauge( "slasher_num_attestations_dropped", "Number of attestations dropped per batch" ); pub static ref SLASHER_NUM_ATTESTATIONS_DEFERRED: Result<IntGauge> = try_create_int_gauge( "slasher_num_attestations_deferred", "Number of attestations deferred per batch" ); pub static ref SLASHER_NUM_ATTESTATIONS_VALID: Result<IntGauge> = try_create_int_gauge( "slasher_num_attestations_valid", "Number of valid attestations per batch" ); pub static ref SLASHER_NUM_BLOCKS_PROCESSED: Result<IntGauge> = try_create_int_gauge( "slasher_num_blocks_processed", "Number of blocks processed per batch", ); pub static ref SLASHER_NUM_CHUNKS_UPDATED: Result<IntCounterVec> = try_create_int_counter_vec( "slasher_num_chunks_updated", "Number of min or max target chunks updated on disk", &["array"], ); pub static ref SLASHER_COMPRESSION_RATIO: Result<Gauge> = try_create_float_gauge( "slasher_compression_ratio", "Compression ratio for min-max array chunks (higher is better)" ); }
use crate::grid::{Grid, Point}; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{BufReader, Lines}; use std::str::FromStr; pub fn part_1(input: &str) -> usize { let mut grid = parse_to_grid(input); println!("search for distance from 0,0 to {} {}", grid.xmax, grid.ymax); let start = Point::new(0, 0); let end = Point::new(grid.xmax, grid.ymax); run_dijkstra(&mut grid, start, end) } pub fn part_2(input: &str) -> usize { let mut grid = parse_to_grid_x5(input); println!("search for distance from 0,0 to {} {}", grid.xmax, grid.ymax); let start = Point::new(0, 0); let end = Point::new(grid.xmax, grid.ymax); run_dijkstra(&mut grid, start, end) } fn run_dijkstra(grid: &mut Grid, start: Point, end: Point) -> usize { // initialize everything at max distance let mut distances: HashMap<Point, u64> = HashMap::new(); // for point in grid.get_map().keys().copied() { // distances.insert(point, u64::MAX); // } //grid.print_grid(); // initialize for start let mut visited_points: HashSet<Point> = HashSet::new(); distances.insert(start, 0); // now loop until condition is satisfied let mut current_node = start; let mut current_node_distance = 0; loop { //println!("current node is: {}, current distance: {}", current_node, current_node_distance); grid .get_neighbour_key_value(&current_node) .iter() .for_each(|(neighbour, weight)| { let mut current_neighour_distance = distances.entry(*neighbour).or_insert(u64::MAX); if weight + current_node_distance < *current_neighour_distance { *current_neighour_distance = weight + current_node_distance; } }); visited_points.insert(current_node); distances.remove(&current_node); grid.remove_loc(&current_node); let mut scores: Vec<(Point, u64)> = distances.iter().map(|(key, value)| (*key, *value)).collect(); scores.sort_by(|(a, b), (c, d)| b.cmp(d)); let (node, distance, ) = scores[0]; current_node = node; current_node_distance = distance; if end == current_node { println!("Stopping because our next node is the end node, with distance {}", distances.get(&end).unwrap()); return *distances.get(&end).unwrap() as usize } } } fn parse_to_grid(input: &str) -> Grid { let mut grid = Grid::new(); for (y, line) in input.split("\n").enumerate() { //println!("{:?}", line.clone().trim().chars().collect::<Vec<char>>()); for (x, nr) in line .trim() .chars() .map(|s| u64::from_str(&*s.to_string()).unwrap()) .enumerate() { grid.add_to_grid(Point::new(x as isize, y as isize), nr); } } grid } fn parse_to_grid_x5(input: &str) -> Grid { let mut grid = Grid::new(); for (y, line) in input.split("\n").enumerate() { //println!("{:?}", line.clone().trim().chars().collect::<Vec<char>>()); for (x, nr) in line .trim() .chars() .map(|s| u64::from_str(&*s.to_string()).unwrap()) .enumerate() { grid.add_to_grid(Point::new(x as isize, y as isize), nr); let grid_size = line.len()-1; for n_x in 0..5 { for n_y in 0..5 { if n_x != 0 || n_y != 0 { let new_x = n_x*grid_size+x; let new_y = n_y*grid_size+y; let new_nr = 1+ ((nr-1+n_x as u64 +n_y as u64) % 9); grid.add_to_grid(Point::new(new_x as isize, new_y as isize ), new_nr); } } } } } grid } #[cfg(test)] mod tests { use crate::day15::{part_1, part_2}; #[test] fn test_part_1_example() { let input = include_str!(r"../resources/inputs/day15-example.txt"); assert_eq!(40, part_1(input)); } #[test] fn test_part_2_example() { let input = include_str!(r"../resources/inputs/day15-example.txt"); assert_eq!(315, part_2(input)); } #[test] fn test_part1_input() { let input2 = include_str!(r"../resources/inputs/day15-input.txt"); assert_eq!(398, part_1(input2)); } #[test] fn test_part2_input() { let input2 = include_str!(r"../resources/inputs/day15-input.txt"); assert_eq!(398, part_2(input2)); } }
use crate::quic_tunnel::connection; use crate::Shutdown; use anyhow::Result; use std::net::SocketAddr; use tokio::net::{TcpListener, TcpStream}; use tokio::sync::{broadcast, mpsc}; use tokio::time::{self, Duration}; use tracing::{error, trace}; /// TCP Server listener state. /// which performs the TCP listening and initialization of per-connection state. pub struct Listener { pub listener: TcpListener, pub quic_connection: quinn::Connection, pub tcp_dest_addr: SocketAddr, /// Broadcasts a shutdown signal to all active connections. pub notify_shutdown: broadcast::Sender<()>, /// Used as part of the graceful shutdown process to wait for client /// connections to complete processing. pub shutdown_complete_rx: mpsc::Receiver<()>, pub shutdown_complete_tx: mpsc::Sender<()>, } impl Listener { /// Run the server pub async fn run(&mut self) -> Result<()> { loop { let socket = self.accept().await?; trace!( "new connection accepted opening quic stream {:?}", socket.local_addr() ); let (quic_send, quic_recv) = self.quic_connection.open_bi().await?; // Create the necessary per-connection handler state. let mut conn = connection::Connection { shutdown: Shutdown::new(self.notify_shutdown.subscribe()), _shutdown_complete: self.shutdown_complete_tx.clone(), }; let addr = self.tcp_dest_addr; // Spawn a new task to process each stream. tokio::spawn(async move { if let Err(err) = conn .run_client_conn(addr, socket, quic_send, quic_recv) .await { error!(cause = ? err, "stream error"); } }); } } /// Accept an inbound connection. async fn accept(&mut self) -> Result<TcpStream> { let mut backoff = 1; // Try to accept a few times loop { match self.listener.accept().await { Ok((socket, _)) => return Ok(socket), Err(err) => { if backoff > 64 { // Accept has failed too many times. Return the error. return Err(err.into()); } } } // Pause execution until the back off period elapses. // sleep on tokio 0.3 time::delay_for(Duration::from_secs(backoff)).await; backoff *= 2; } } }
use screeps_foreman::planner::*; use screeps_foreman::visual::*; use screeps_foreman::location::*; use screeps_foreman::*; use log::*; use std::fs::File; use std::path::Path; use std::io::Read; use serde::*; use std::convert::*; use image::*; use std::time::*; use std::collections::HashMap; #[cfg(not(feature = "profile"))] use rayon::prelude::*; struct RoomDataPlannerDataSource { terrain: FastRoomTerrain, controllers: Vec<PlanLocation>, sources: Vec<PlanLocation>, minerals: Vec<PlanLocation>, } impl PlannerRoomDataSource for RoomDataPlannerDataSource { fn get_terrain(&mut self) -> &FastRoomTerrain { &self.terrain } fn get_controllers(&mut self) -> &[PlanLocation] { &self.controllers } fn get_sources(&mut self) -> &[PlanLocation] { &self.sources } fn get_minerals(&mut self) -> &[PlanLocation] { &self.minerals } } fn main() -> Result<(), String> { env_logger::init(); std::fs::create_dir_all("output").map_err(|err| format!("Failed to create output folder: {}", err))?; info!("Loading map data..."); let shard = "shard1"; let map_data = load_map_data(format!("resources/map-mmo-{}.json", shard))?; info!("Finished loading map data"); /* let rooms = map_data .get_rooms() .iter() .filter(|room_data| room_data.get_sources().len() == 2 && room_data.get_controllers().len() == 1) .take(1000) .collect::<Vec<_>>(); */ let rooms = vec![ //map_data.get_room("E33S31")?, //map_data.get_room("E34S31")?, //map_data.get_room("E35S31")?, //map_data.get_room("E33S31")?, //map_data.get_room("E11N11")?, //map_data.get_room("E11N1")?, //map_data.get_room("E29S11")?, map_data.get_room("W3S52")?, ]; let maximum_seconds = Some(60.0); //let maximum_seconds = Some(2.0); //let maximum_batch_seconds = None; let maximum_batch_seconds = Some(5.0); #[cfg(not(feature = "profile"))] let room_iter = rooms.par_iter(); #[cfg(feature = "profile")] let room_iter = rooms.iter(); let room_results: Vec<_> = room_iter .map(|room| { let res = run_room(shard, &room, maximum_seconds, maximum_batch_seconds); (room, res) }) .collect(); for (room, result) in room_results { match result { Ok(()) => { info!("Succesfully ran room planning: {}", room.name()); }, Err(err) => { error!("Failed running room planning: {} - Error: {}", room.name(), err); } } } Ok(()) } fn run_room(shard: &str, room: &RoomData, maximum_seconds: Option<f32>, maximum_batch_seconds: Option<f32>) -> Result<(), String> { let room_name = room.name(); info!("Planning: {}", room_name); let epoch = Instant::now(); #[cfg(feature = "profile")] { let epoch = epoch.clone(); screeps_timing::start_trace(Box::new(move || { let elapsed = epoch.elapsed(); elapsed.as_micros() as u64 })) } let plan_result = evaluate_plan(&room, maximum_seconds, maximum_batch_seconds); let duration = epoch.elapsed().as_secs_f32(); info!("Planning complete - Duration: {}", duration); #[cfg(feature = "profile")] { info!("Gathering trace..."); let trace = screeps_timing::stop_trace(); info!("Done gathering trace"); let trace_name = format!("output/{}_trace.json", room_name); let trace_file = &File::create(trace_name).map_err(|err| format!("Failed to crate trace file: {}", err))?; info!("Serializing trace to disk..."); serde_json::to_writer(trace_file, &trace).map_err(|err| format!("Failed to serialize json: {}", err))?; info!("Done serializing"); } let plan = plan_result?.ok_or("Failed to create plan for room")?; let mut img: RgbImage = ImageBuffer::new(500, 500); let terrain = room.get_terrain()?; render_terrain(&mut img, &terrain, 10); render_plan(&mut img, &plan, 10); let output_img_name = format!("output/{}.png", room_name); img.save(output_img_name).map_err(|err| format!("Failed to save image: {}", err))?; let serialized_plan = serialize_plan(shard, &room, &plan)?; let output_plan_name = format!("output/{}_plan.json", room_name); let output_plan_file = &File::create(output_plan_name).map_err(|err| format!("Failed to crate plan file: {}", err))?; serde_json::to_writer(output_plan_file, &serialized_plan).map_err(|err| format!("Failed to write plan json: {}", err))?; Ok(()) } #[derive(Serialize, Hash, Ord, PartialOrd, Eq, PartialEq)] #[serde(rename_all = "camelCase")] enum RoomPlannerStructure { Spawn = 0, Extension = 1, Road = 2, Wall = 3, Rampart = 4, KeeperLair = 5, Portal = 6, Controller = 7, Link = 8, Storage = 9, Tower = 10, Observer = 11, PowerBank = 12, PowerSpawn = 13, Extractor = 14, Lab = 15, Terminal = 16, Container = 17, Nuker = 18, Factory = 19, InvaderCore = 20, } impl From<StructureType> for RoomPlannerStructure { fn from(data: StructureType) -> Self { match data { StructureType::Spawn => RoomPlannerStructure::Spawn, StructureType::Extension => RoomPlannerStructure::Extension, StructureType::Road => RoomPlannerStructure::Road, StructureType::Wall => RoomPlannerStructure::Wall, StructureType::Rampart => RoomPlannerStructure::Rampart, StructureType::KeeperLair => RoomPlannerStructure::KeeperLair, StructureType::Portal => RoomPlannerStructure::Portal, StructureType::Controller => RoomPlannerStructure::Controller, StructureType::Link => RoomPlannerStructure::Link, StructureType::Storage => RoomPlannerStructure::Storage, StructureType::Tower => RoomPlannerStructure::Tower, StructureType::Observer => RoomPlannerStructure::Observer, StructureType::PowerBank => RoomPlannerStructure::PowerBank, StructureType::PowerSpawn => RoomPlannerStructure::PowerSpawn, StructureType::Extractor => RoomPlannerStructure::Extractor, StructureType::Lab => RoomPlannerStructure::Lab, StructureType::Terminal => RoomPlannerStructure::Terminal, StructureType::Container => RoomPlannerStructure::Container, StructureType::Nuker => RoomPlannerStructure::Nuker, StructureType::Factory => RoomPlannerStructure::Factory, StructureType::InvaderCore => RoomPlannerStructure::InvaderCore, } } } #[derive(Serialize)] struct RoomPlannerPosition { x: u8, y: u8 } impl From<Location> for RoomPlannerPosition { fn from(data: Location) -> Self { Self { x: data.x(), y: data.y() } } } #[derive(Serialize, Default)] struct RoomPlannerEntry { pos: Vec<RoomPlannerPosition> } #[derive(Serialize)] struct RoomPlannerData { name: String, shard: String, rcl: u32, buildings: HashMap<RoomPlannerStructure, RoomPlannerEntry> } impl RoomVisualizer for RoomPlannerData { fn render(&mut self, location: Location, structure_type: StructureType) { let entry = self.buildings .entry(structure_type.into()) .or_insert_with(RoomPlannerEntry::default); entry.pos.push(location.into()); } } fn serialize_plan(shard: &str, room_data: &RoomData, plan: &Plan) -> Result<RoomPlannerData, String> { let mut data = RoomPlannerData { name: room_data.name().to_owned(), shard: shard.to_owned(), rcl: 8, buildings: HashMap::new() }; plan.visualize(&mut data); Ok(data) } fn fill_region(img: &mut RgbImage, x: u32, y: u32, width: u32, height: u32, val: image::Rgb<u8>) { for x in x..x + width { for y in y..y + height { img.put_pixel(x, y, val); } } } fn render_terrain(img: &mut RgbImage, terrain: &FastRoomTerrain, pixel_size: u32) { for x in 0..50 { for y in 0..50 { let val = terrain.get_xy(x, y); let color = if val.contains(TerrainFlags::WALL) { Rgb([0, 0, 0]) } else if val.contains(TerrainFlags::SWAMP) { Rgb([255, 255, 255]) } else { Rgb([127, 127, 127]) }; fill_region(img, (x as u32) * pixel_size, (y as u32) * pixel_size, pixel_size, pixel_size, color); } } } struct ImgVisualizer<'a> { img: &'a mut RgbImage, pixel_size: u32 } impl<'a> RoomVisualizer for ImgVisualizer<'a> { fn render(&mut self, location: Location, structure: StructureType) { let color = match structure { StructureType::Road => Rgb([50, 0, 50]), StructureType::Rampart => Rgb([0, 255, 0]), StructureType::Spawn => Rgb([255, 255, 0]), StructureType::Storage => Rgb([0, 255, 255]), _ => Rgb([255, 0, 0]), }; fill_region(&mut self.img, location.x() as u32 * self.pixel_size, location.y() as u32 * self.pixel_size, self.pixel_size, self.pixel_size, color); } } fn render_plan(img: &mut RgbImage, plan: &Plan, pixel_size: u32) { let mut visualizer = ImgVisualizer { img, pixel_size }; plan.visualize(&mut visualizer) } fn terrain_string_to_vec<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error> where D: de::Deserializer<'de>, { struct JsonStringVisitor; impl<'de> de::Visitor<'de> for JsonStringVisitor { type Value = Vec<u8>; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a string containing terrain data") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { let mut buffer = Vec::with_capacity(v.len()); for mask in v.chars() { let val = mask.to_digit(16).ok_or_else(|| E::custom("Expected hex digit character".to_owned()))? as u8; buffer.push(val); } Ok(buffer) } } deserializer.deserialize_any(JsonStringVisitor) } #[derive(Deserialize)] struct RoomData { room: String, #[serde(deserialize_with = "terrain_string_to_vec")] terrain: Vec<u8>, objects: Vec<serde_json::Value> } impl RoomData { fn name(&self) -> &str { &self.room } fn get_terrain(&self) -> Result<FastRoomTerrain, String> { if self.terrain.len() != 50 * 50 { return Err("Terrain was not expected 50 x 50 layout".to_owned()); } let terrain = FastRoomTerrain::new(self.terrain.clone()); Ok(terrain) } fn get_object_type(&self, obj_type: &str) -> Vec<PlanLocation> { self.objects .iter() .filter_map(|o| o.as_object()) .filter(|o| o.get("type").map(|t| t == obj_type).unwrap_or(false)) .filter_map(|o| { let x = o.get("x")?.as_i64()?; let y = o.get("y")?.as_i64()?; Some(PlanLocation::new(x as i8, y as i8)) }) .collect() } fn get_sources(&self) -> Vec<PlanLocation> { self.get_object_type("source") } fn get_controllers(&self) -> Vec<PlanLocation> { self.get_object_type("controller") } fn get_minerals(&self) -> Vec<PlanLocation> { self.get_object_type("mineral") } } #[derive(Deserialize)] struct MapData { rooms: Vec<RoomData> } impl MapData { #[allow(dead_code)] fn get_room(&self, room_name: &str) -> Result<&RoomData, String> { self .rooms .iter() .find(|room| room.name() == room_name) .ok_or("Failed to find room".to_owned()) } #[allow(dead_code)] fn get_rooms(&self) -> &[RoomData] { &self.rooms } } fn load_map_data<P>(path: P) -> Result<MapData, String> where P: AsRef<Path> { let mut file = File::open(path).map_err(|err| format!("Failed to open map file: {}", err))?; let mut contents = String::new(); file.read_to_string(&mut contents).map_err(|err| format!("Failed to read string to buffer: {}", err))?; let data: MapData = serde_json::from_str(&contents).map_err(|err| format!("Failed to load json: {}", err))?; Ok(data) } fn evaluate_plan(room: &RoomData, max_seconds: Option<f32>, max_batch_seconds: Option<f32>) -> Result<Option<Plan>, String> { let mut data_source = RoomDataPlannerDataSource { terrain: room.get_terrain()?, controllers: room.get_controllers(), sources: room.get_sources(), minerals: room.get_minerals() }; let planner = Planner::new(screeps_foreman::scoring::score_state); let epoch = Instant::now(); let seed_result = planner.seed(screeps_foreman::layout::ALL_ROOT_NODES, &mut data_source)?; let mut running_state = match seed_result { PlanSeedResult::Complete(plan) => { info!("Seeding complete - plan complete"); return Ok(plan); } PlanSeedResult::Running(run_state) => { info!("Seeding complete - pending evaluation"); run_state } }; info!("Starting evaluating..."); let plan = loop { let batch_epoch = Instant::now(); let evaluate_result = planner.evaluate( screeps_foreman::layout::ALL_ROOT_NODES, &mut data_source, &mut running_state, || { let elapsed = epoch.elapsed().as_secs_f32(); if max_seconds.map(|max| elapsed >= max).unwrap_or(false) { return false; } let batch_elapsed = batch_epoch.elapsed().as_secs_f32(); if max_batch_seconds.map(|max| batch_elapsed >= max).unwrap_or(false) { return false; } true } )?; match evaluate_result { PlanEvaluationResult::Complete(plan) => { if plan.is_some() { info!("Evaluate complete - planned room layout."); } else { info!("Evaluate complete - failed to find room layout."); } break Ok(plan) }, PlanEvaluationResult::Running() => { if max_seconds.map(|max| epoch.elapsed().as_secs_f32() >= max).unwrap_or(false) { break Err("Exceeded maximum duration for planning".to_owned()); } } }; }?; Ok(plan) }
/// Error created when initializing the Executor. use failure::Fail; #[derive(Debug, Fail)] pub enum InitError { #[fail(display = "must be compiled with --feature=cuda to use cuda")] NeedsCudaFeature, }
//! Optimizations are a necessity for Candy code to run reasonably fast. For //! example, without optimizations, if two modules import a third module using //! `use "..foo"`, then the `foo` module is instantiated twice completely //! separately. Because this module can in turn depend on other modules, this //! approach would lead to exponential code blowup. //! //! When optimizing code in general, there are two main objectives: //! //! - Making the code fast. //! - Making the code small. //! //! Some optimizations benefit both of these objectives. For example, removing //! ignored computations from the program makes it smaller, but also means //! there's less code to be executed. Other optimizations further one objective, //! but harm the other. For example, inlining functions (basically copying their //! code to where they're used), can make the code bigger, but also potentially //! faster because there are less function calls to be performed. //! //! Depending on the use case, the tradeoff between both objectives changes. To //! put you in the right mindset, here are just two use cases: //! //! - Programming for a microcontroller with 1 MB of ROM available for the //! program. In this case, you want your code to be as fast as possible while //! still fitting in 1 MB. Interestingly, the importance of code size is a //! step function: There's no benefit in only using 0.5 MB, but 1.1 MB makes //! the program completely unusable. //! //! - Programming for a WASM module to be downloaded. In this case, you might //! have some concrete measurements on how performance and download size //! affect user retention. //! //! It should be noted that we can't judge performance statically. Although some //! optimizations such as inlining typically improve performance, there are rare //! cases where they don't. For example, inlining a function that's used in //! multiple places means the CPU's branch predictor can't benefit from the //! knowledge gained by previous function executions. Inlining might also make //! your program bigger, causing more cache misses. Thankfully, Candy is not yet //! optimized enough for us to care about such details. //! //! This module contains several optimizations. All of them operate on the MIR. //! Some are called "obvious". Those are optimizations that typically improve //! both performance and code size. Whenever they can be applied, they should be //! applied. use self::{ current_expression::{Context, CurrentExpression}, pure::PurenessInsights, }; use super::{hir, hir_to_mir::HirToMir, mir::Mir, tracing::TracingConfig}; use crate::{ error::CompilerError, mir::{Body, Expression, MirError, VisibleExpressions}, module::Module, string_to_rcst::ModuleError, utils::DoHash, }; use rustc_hash::FxHashSet; use std::{mem, sync::Arc}; use tracing::debug; mod cleanup; mod common_subtree_elimination; mod complexity; mod constant_folding; mod constant_lifting; mod current_expression; mod inlining; mod module_folding; mod pure; mod reference_following; mod tree_shaking; mod utils; mod validate; #[salsa::query_group(OptimizeMirStorage)] pub trait OptimizeMir: HirToMir { #[salsa::cycle(recover_from_cycle)] fn optimized_mir(&self, module: Module, tracing: TracingConfig) -> OptimizedMirResult; } pub type OptimizedMirResult = Result< ( Arc<Mir>, Arc<PurenessInsights>, Arc<FxHashSet<CompilerError>>, ), ModuleError, >; fn optimized_mir( db: &dyn OptimizeMir, module: Module, tracing: TracingConfig, ) -> OptimizedMirResult { debug!("{module}: Compiling."); let (mir, errors) = db.mir(module.clone(), tracing.clone())?; let mut mir = (*mir).clone(); let mut pureness = PurenessInsights::default(); let mut errors = (*errors).clone(); let complexity_before = mir.complexity(); mir.optimize(db, &tracing, &mut pureness, &mut errors); let complexity_after = mir.complexity(); debug!("{module}: Done. Optimized from {complexity_before} to {complexity_after}"); Ok((Arc::new(mir), Arc::new(pureness), Arc::new(errors))) } impl Mir { pub fn optimize( &mut self, db: &dyn OptimizeMir, tracing: &TracingConfig, pureness: &mut PurenessInsights, errors: &mut FxHashSet<CompilerError>, ) { let mut context = Context { db, tracing, errors, visible: &mut VisibleExpressions::none_visible(), id_generator: &mut self.id_generator, pureness, }; context.optimize_body(&mut self.body); if cfg!(debug_assertions) { self.validate(); } self.cleanup(pureness); } } impl Context<'_> { fn optimize_body(&mut self, body: &mut Body) { // Even though `self.visible` is mutable, this function guarantees that // the value is the same after returning. let mut index = 0; while index < body.expressions.len() { // Thoroughly optimize the expression. let mut expression = CurrentExpression::new(body, index); self.optimize_expression(&mut expression); if cfg!(debug_assertions) { expression.validate(self.visible); } let id = expression.id(); self.pureness.visit_optimized(id, &expression); module_folding::apply(self, &mut expression); index = expression.index() + 1; let expression = mem::replace(&mut *expression, Expression::Parameter); self.visible.insert(id, expression); } for (id, expression) in &mut body.expressions { *expression = self.visible.remove(*id); } common_subtree_elimination::eliminate_common_subtrees(body, self.pureness); tree_shaking::tree_shake(body, self.pureness); reference_following::remove_redundant_return_references(body); } fn optimize_expression(&mut self, expression: &mut CurrentExpression) { 'outer: loop { if let Expression::Function { parameters, responsible_parameter, body, .. } = &mut **expression { for parameter in &*parameters { self.visible.insert(*parameter, Expression::Parameter); } self.visible .insert(*responsible_parameter, Expression::Parameter); self.pureness .enter_function(parameters, *responsible_parameter); self.optimize_body(body); for parameter in &*parameters { self.visible.remove(*parameter); } self.visible.remove(*responsible_parameter); } loop { let hashcode_before = expression.do_hash(); reference_following::follow_references(self, expression); constant_folding::fold_constants(self, expression); let is_call = matches!(**expression, Expression::Call { .. }); inlining::inline_tiny_functions(self, expression); inlining::inline_functions_containing_use(self, expression); if is_call && matches!(**expression, Expression::Function { .. }) { // We inlined a function call and the resulting code starts with // a function definition. We need to visit that first before // continuing the optimizations. continue 'outer; } constant_lifting::lift_constants(self, expression); if expression.do_hash() == hashcode_before { break 'outer; } } } // TODO: If this is a call to the `needs` function with `True` as the // first argument, optimize it away. This is not correct – calling // `needs True 3 4` should panic instead. But we figured this is // temporarily fine until we have data flow. if let Expression::Call { function, arguments, .. } = &**expression && let Expression::Function { original_hirs, .. } = self.visible.get(*function) && original_hirs.contains(&hir::Id::needs()) && arguments.len() == 3 && let Expression::Tag { symbol, value: None } = self.visible.get(arguments[0]) && symbol == "True" { **expression = Expression::nothing(); } } } fn recover_from_cycle( _db: &dyn OptimizeMir, cycle: &[String], module: &Module, _tracing: &TracingConfig, ) -> OptimizedMirResult { let error = CompilerError::for_whole_module( module.clone(), MirError::ModuleHasCycle { cycle: cycle.to_vec(), }, ); let mir = Mir::build(|body| { let reason = body.push_text(error.payload.to_string()); let responsible = body.push_hir_id(hir::Id::new(module.clone(), vec![])); body.push_panic(reason, responsible); }); Ok(( Arc::new(mir), Arc::default(), Arc::new(FxHashSet::from_iter([error])), )) }
use std::collections::HashMap; const INPUT: &str = include_str!("./input"); fn part_1(input: &str) -> usize { let sorted_arr = sort_input(input); let (ones, threes) = sorted_arr .windows(2) .fold((0, 0), |(ones, threes), w| match w[1] - w[0] { 1 => (ones + 1, threes), 3 => (ones, threes + 1), _ => unreachable!(), }); ones * threes } fn sort_input(input: &str) -> Vec<u32> { let mut sorted_arr = vec![0]; let numbers = input .trim_end() .lines() .map(|l| l.parse().unwrap()) .collect::<Vec<u32>>(); sorted_arr.extend(numbers); sorted_arr.sort(); sorted_arr.push(sorted_arr.last().unwrap() + 3); sorted_arr } fn total_arrange(sorted_arr: &[u32], index: usize, dp: &mut HashMap<usize, usize>) -> usize { if index == sorted_arr.len() - 1 { return 1; } let start = sorted_arr[index]; let total = sorted_arr .iter() .enumerate() .skip(index + 1) .take_while(|(_, x)| (1..=3).contains(&(*x - start))) .map(|(i, _)| { dp.get(&i) .copied() .unwrap_or_else(|| total_arrange(&sorted_arr, i, dp)) }) .sum::<usize>(); dp.insert(index, total); total } fn part_2(input: &str) -> usize { total_arrange(&sort_input(input), 0, &mut HashMap::new()) } const TEST_INPUT_1: &str = r#"16 10 15 5 1 11 7 19 6 12 4"#; const TEST_INPUT_2: &str = r#"28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3"#; #[test] fn test_part_1() { assert_eq!(part_1(TEST_INPUT_1), 35); assert_eq!(part_1(TEST_INPUT_2), 220); assert_eq!(part_1(INPUT), 1914); } #[test] fn test_part_2() { assert_eq!(part_2(TEST_INPUT_1), 8); assert_eq!(part_2(TEST_INPUT_2), 19208); assert_eq!(part_2(INPUT), 9256148959232); }
use crate::stream::{Buf, BufMut, CodedInputStream, CodedOutputStream}; use crate::Result; use std::cell::UnsafeCell; use std::fmt::{self, Debug}; pub trait Message { fn merge_from(&mut self, input: &mut CodedInputStream<impl Buf>) -> Result<()>; fn write_to(&self, output: &mut CodedOutputStream<impl BufMut>) -> Result<()>; fn len(&self) -> usize; fn merge_from_bytes(&mut self, s: &[u8]) -> Result<()> { let mut input = CodedInputStream::new(s); self.merge_from(&mut input) } fn write_to_vec(&self, s: &mut Vec<u8>) -> Result<()> { let mut output = CodedOutputStream::new(s); self.write_to(&mut output)?; output.flush() } fn write_as_bytes(&self) -> Result<Vec<u8>> { let mut v = Vec::with_capacity(self.len()); self.write_to_vec(&mut v)?; Ok(v) } } impl<T: Message> Message for Box<T> { fn merge_from(&mut self, input: &mut CodedInputStream<impl Buf>) -> Result<()> { self.as_mut().merge_from(input) } fn write_to(&self, output: &mut CodedOutputStream<impl BufMut>) -> Result<()> { self.as_ref().write_to(output) } fn len(&self) -> usize { self.as_ref().len() } fn merge_from_bytes(&mut self, s: &[u8]) -> Result<()> { self.as_mut().merge_from_bytes(s) } fn write_to_vec(&self, s: &mut Vec<u8>) -> Result<()> { self.as_ref().write_to_vec(s) } fn write_as_bytes(&self) -> Result<Vec<u8>> { self.as_ref().write_as_bytes() } } pub trait MergeFrom { fn merge_from(&mut self, other: Self); } pub struct CacheSize { size: UnsafeCell<u32>, } impl Default for CacheSize { fn default() -> Self { CacheSize::new(0) } } impl PartialEq for CacheSize { fn eq(&self, _: &CacheSize) -> bool { true } } impl CacheSize { pub const fn new(size: u32) -> CacheSize { CacheSize { size: UnsafeCell::new(size), } } pub unsafe fn set_size(&self, size: u32) { *self.size.get() = size; } } impl Debug for CacheSize { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", unsafe { *self.size.get() }) } } impl Clone for CacheSize { fn clone(&self) -> Self { CacheSize { size: UnsafeCell::new(unsafe { *self.size.get() }), } } }
mod common; #[test] fn basic() { let name = "my-app"; let cmd = common::basic_command(name); common::assert_matches_path( "tests/snapshots/basic.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn feature_sample() { let name = "my-app"; let cmd = common::feature_sample_command(name); common::assert_matches_path( "tests/snapshots/feature_sample.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn special_commands() { let name = "my-app"; let cmd = common::special_commands_command(name); common::assert_matches_path( "tests/snapshots/special_commands.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn quoting() { let name = "my-app"; let cmd = common::quoting_command(name); common::assert_matches_path( "tests/snapshots/quoting.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn aliases() { let name = "my-app"; let cmd = common::aliases_command(name); common::assert_matches_path( "tests/snapshots/aliases.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn sub_subcommands() { let name = "my-app"; let cmd = common::sub_subcommands_command(name); common::assert_matches_path( "tests/snapshots/sub_subcommands.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn value_hint() { let name = "my-app"; let cmd = common::value_hint_command(name); common::assert_matches_path( "tests/snapshots/value_hint.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn value_terminator() { let name = "my-app"; let cmd = common::value_terminator_command(name); common::assert_matches_path( "tests/snapshots/value_terminator.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn two_multi_valued_arguments() { let name = "my-app"; let cmd = common::two_multi_valued_arguments_command(name); common::assert_matches_path( "tests/snapshots/two_multi_valued_arguments.zsh", clap_complete::shells::Zsh, cmd, name, ); } #[test] fn subcommand_last() { let name = "my-app"; let cmd = common::subcommand_last(name); common::assert_matches_path( "tests/snapshots/subcommand_last.zsh", clap_complete::shells::Zsh, cmd, name, ); }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "Storage_AccessCache")] pub mod AccessCache; #[cfg(feature = "Storage_BulkAccess")] pub mod BulkAccess; #[cfg(feature = "Storage_Compression")] pub mod Compression; #[cfg(feature = "Storage_FileProperties")] pub mod FileProperties; #[cfg(feature = "Storage_Pickers")] pub mod Pickers; #[cfg(feature = "Storage_Provider")] pub mod Provider; #[cfg(feature = "Storage_Search")] pub mod Search; #[cfg(feature = "Storage_Streams")] pub mod Streams; #[link(name = "windows")] extern "system" {} pub type AppDataPaths = *mut ::core::ffi::c_void; pub type ApplicationData = *mut ::core::ffi::c_void; pub type ApplicationDataCompositeValue = *mut ::core::ffi::c_void; pub type ApplicationDataContainer = *mut ::core::ffi::c_void; pub type ApplicationDataContainerSettings = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ApplicationDataCreateDisposition(pub i32); impl ApplicationDataCreateDisposition { pub const Always: Self = Self(0i32); pub const Existing: Self = Self(1i32); } impl ::core::marker::Copy for ApplicationDataCreateDisposition {} impl ::core::clone::Clone for ApplicationDataCreateDisposition { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ApplicationDataLocality(pub i32); impl ApplicationDataLocality { pub const Local: Self = Self(0i32); pub const Roaming: Self = Self(1i32); pub const Temporary: Self = Self(2i32); pub const LocalCache: Self = Self(3i32); pub const SharedLocal: Self = Self(4i32); } impl ::core::marker::Copy for ApplicationDataLocality {} impl ::core::clone::Clone for ApplicationDataLocality { fn clone(&self) -> Self { *self } } pub type ApplicationDataSetVersionHandler = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct CreationCollisionOption(pub i32); impl CreationCollisionOption { pub const GenerateUniqueName: Self = Self(0i32); pub const ReplaceExisting: Self = Self(1i32); pub const FailIfExists: Self = Self(2i32); pub const OpenIfExists: Self = Self(3i32); } impl ::core::marker::Copy for CreationCollisionOption {} impl ::core::clone::Clone for CreationCollisionOption { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct FileAccessMode(pub i32); impl FileAccessMode { pub const Read: Self = Self(0i32); pub const ReadWrite: Self = Self(1i32); } impl ::core::marker::Copy for FileAccessMode {} impl ::core::clone::Clone for FileAccessMode { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct FileAttributes(pub u32); impl FileAttributes { pub const Normal: Self = Self(0u32); pub const ReadOnly: Self = Self(1u32); pub const Directory: Self = Self(16u32); pub const Archive: Self = Self(32u32); pub const Temporary: Self = Self(256u32); pub const LocallyIncomplete: Self = Self(512u32); } impl ::core::marker::Copy for FileAttributes {} impl ::core::clone::Clone for FileAttributes { fn clone(&self) -> Self { *self } } pub type IStorageFile = *mut ::core::ffi::c_void; pub type IStorageFile2 = *mut ::core::ffi::c_void; pub type IStorageFilePropertiesWithAvailability = *mut ::core::ffi::c_void; pub type IStorageFolder = *mut ::core::ffi::c_void; pub type IStorageFolder2 = *mut ::core::ffi::c_void; pub type IStorageItem = *mut ::core::ffi::c_void; pub type IStorageItem2 = *mut ::core::ffi::c_void; pub type IStorageItemProperties = *mut ::core::ffi::c_void; pub type IStorageItemProperties2 = *mut ::core::ffi::c_void; pub type IStorageItemPropertiesWithProvider = *mut ::core::ffi::c_void; pub type IStreamedFileDataRequest = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct KnownFolderId(pub i32); impl KnownFolderId { pub const AppCaptures: Self = Self(0i32); pub const CameraRoll: Self = Self(1i32); pub const DocumentsLibrary: Self = Self(2i32); pub const HomeGroup: Self = Self(3i32); pub const MediaServerDevices: Self = Self(4i32); pub const MusicLibrary: Self = Self(5i32); pub const Objects3D: Self = Self(6i32); pub const PicturesLibrary: Self = Self(7i32); pub const Playlists: Self = Self(8i32); pub const RecordedCalls: Self = Self(9i32); pub const RemovableDevices: Self = Self(10i32); pub const SavedPictures: Self = Self(11i32); pub const Screenshots: Self = Self(12i32); pub const VideosLibrary: Self = Self(13i32); pub const AllAppMods: Self = Self(14i32); pub const CurrentAppMods: Self = Self(15i32); pub const DownloadsFolder: Self = Self(16i32); } impl ::core::marker::Copy for KnownFolderId {} impl ::core::clone::Clone for KnownFolderId { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct KnownFoldersAccessStatus(pub i32); impl KnownFoldersAccessStatus { pub const DeniedBySystem: Self = Self(0i32); pub const NotDeclaredByApp: Self = Self(1i32); pub const DeniedByUser: Self = Self(2i32); pub const UserPromptRequired: Self = Self(3i32); pub const Allowed: Self = Self(4i32); pub const AllowedPerAppFolder: Self = Self(5i32); } impl ::core::marker::Copy for KnownFoldersAccessStatus {} impl ::core::clone::Clone for KnownFoldersAccessStatus { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct KnownLibraryId(pub i32); impl KnownLibraryId { pub const Music: Self = Self(0i32); pub const Pictures: Self = Self(1i32); pub const Videos: Self = Self(2i32); pub const Documents: Self = Self(3i32); } impl ::core::marker::Copy for KnownLibraryId {} impl ::core::clone::Clone for KnownLibraryId { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct NameCollisionOption(pub i32); impl NameCollisionOption { pub const GenerateUniqueName: Self = Self(0i32); pub const ReplaceExisting: Self = Self(1i32); pub const FailIfExists: Self = Self(2i32); } impl ::core::marker::Copy for NameCollisionOption {} impl ::core::clone::Clone for NameCollisionOption { fn clone(&self) -> Self { *self } } pub type SetVersionDeferral = *mut ::core::ffi::c_void; pub type SetVersionRequest = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct StorageDeleteOption(pub i32); impl StorageDeleteOption { pub const Default: Self = Self(0i32); pub const PermanentDelete: Self = Self(1i32); } impl ::core::marker::Copy for StorageDeleteOption {} impl ::core::clone::Clone for StorageDeleteOption { fn clone(&self) -> Self { *self } } pub type StorageFile = *mut ::core::ffi::c_void; pub type StorageFolder = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct StorageItemTypes(pub u32); impl StorageItemTypes { pub const None: Self = Self(0u32); pub const File: Self = Self(1u32); pub const Folder: Self = Self(2u32); } impl ::core::marker::Copy for StorageItemTypes {} impl ::core::clone::Clone for StorageItemTypes { fn clone(&self) -> Self { *self } } pub type StorageLibrary = *mut ::core::ffi::c_void; pub type StorageLibraryChange = *mut ::core::ffi::c_void; pub type StorageLibraryChangeReader = *mut ::core::ffi::c_void; pub type StorageLibraryChangeTracker = *mut ::core::ffi::c_void; pub type StorageLibraryChangeTrackerOptions = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct StorageLibraryChangeType(pub i32); impl StorageLibraryChangeType { pub const Created: Self = Self(0i32); pub const Deleted: Self = Self(1i32); pub const MovedOrRenamed: Self = Self(2i32); pub const ContentsChanged: Self = Self(3i32); pub const MovedOutOfLibrary: Self = Self(4i32); pub const MovedIntoLibrary: Self = Self(5i32); pub const ContentsReplaced: Self = Self(6i32); pub const IndexingStatusChanged: Self = Self(7i32); pub const EncryptionChanged: Self = Self(8i32); pub const ChangeTrackingLost: Self = Self(9i32); } impl ::core::marker::Copy for StorageLibraryChangeType {} impl ::core::clone::Clone for StorageLibraryChangeType { fn clone(&self) -> Self { *self } } pub type StorageLibraryLastChangeId = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct StorageOpenOptions(pub u32); impl StorageOpenOptions { pub const None: Self = Self(0u32); pub const AllowOnlyReaders: Self = Self(1u32); pub const AllowReadersAndWriters: Self = Self(2u32); } impl ::core::marker::Copy for StorageOpenOptions {} impl ::core::clone::Clone for StorageOpenOptions { fn clone(&self) -> Self { *self } } pub type StorageProvider = *mut ::core::ffi::c_void; pub type StorageStreamTransaction = *mut ::core::ffi::c_void; pub type StreamedFileDataRequest = *mut ::core::ffi::c_void; pub type StreamedFileDataRequestedHandler = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct StreamedFileFailureMode(pub i32); impl StreamedFileFailureMode { pub const Failed: Self = Self(0i32); pub const CurrentlyUnavailable: Self = Self(1i32); pub const Incomplete: Self = Self(2i32); } impl ::core::marker::Copy for StreamedFileFailureMode {} impl ::core::clone::Clone for StreamedFileFailureMode { fn clone(&self) -> Self { *self } } pub type SystemAudioProperties = *mut ::core::ffi::c_void; pub type SystemDataPaths = *mut ::core::ffi::c_void; pub type SystemGPSProperties = *mut ::core::ffi::c_void; pub type SystemImageProperties = *mut ::core::ffi::c_void; pub type SystemMediaProperties = *mut ::core::ffi::c_void; pub type SystemMusicProperties = *mut ::core::ffi::c_void; pub type SystemPhotoProperties = *mut ::core::ffi::c_void; pub type SystemVideoProperties = *mut ::core::ffi::c_void; pub type UserDataPaths = *mut ::core::ffi::c_void;
use regex::Regex; use std::collections::HashMap; use std::env; use std::fs::File; use std::io::BufRead; use std::io::BufReader; pub fn count(input: impl BufRead) -> HashMap<String, usize> { let re = Regex::new(r"\w+").unwrap(); let mut freqs = HashMap::new(); for line in input.lines() { let line = line.unwrap(); for m in re.find_iter(&line) { let word = m.as_str().to_string(); *freqs.entry(word).or_insert(0) += 1; } } freqs } fn main() { let filename = env::args().nth(1).expect("1 argument FILENAME required"); let file = File::open(filename).unwrap(); let reader = BufReader::new(&file); let freqs = count(reader); println!("{:?}", freqs); }
mod empty; mod field; pub trait Lens<T, U> { fn with<V, F: FnOnce(&U) -> V>(&self, data: &T, f: F) -> V; fn with_mut<V, F: FnOnce(&mut U) -> V>(&self, data: &mut T, f: F) -> V; } pub use empty::NoLens; pub use field::Field;
pub struct Solution; use self::Token::*; use std::iter::Peekable; use std::str::Bytes; enum Token { Plus, Minus, Times, Divide, Number(i32), } struct Tokens<'a> { bytes: Peekable<Bytes<'a>>, } impl<'a> Tokens<'a> { fn new(s: &'a str) -> Self { Self { bytes: s.bytes().peekable(), } } } impl<'a> Iterator for Tokens<'a> { type Item = Token; fn next(&mut self) -> Option<Self::Item> { while self.bytes.peek() == Some(&b' ') { self.bytes.next(); } match self.bytes.next() { None => None, Some(b'+') => Some(Plus), Some(b'-') => Some(Minus), Some(b'*') => Some(Times), Some(b'/') => Some(Divide), Some(b) if b.is_ascii_digit() => { let mut n = (b - b'0') as i32; while self.bytes.peek().map_or(false, |b| b.is_ascii_digit()) { n = n * 10 + (self.bytes.next().unwrap() - b'0') as i32; } Some(Number(n)) } _ => unreachable!(), } } } fn take_number<'a>(tokens: &mut Peekable<Tokens<'a>>) -> i32 { match tokens.next() { Some(Number(n)) => n, _ => unreachable!(), } } fn take_term<'a>(tokens: &mut Peekable<Tokens<'a>>) -> i32 { let mut res = take_number(tokens); loop { match tokens.peek() { Some(Times) => { tokens.next(); res *= take_number(tokens); } Some(Divide) => { tokens.next(); res /= take_number(tokens); } _ => { return res; } } } } impl Solution { pub fn calculate(s: String) -> i32 { let tokens = &mut Tokens::new(&s).peekable(); let mut res = take_term(tokens); loop { match tokens.next() { None => { return res; } Some(Plus) => { res += take_term(tokens); } Some(Minus) => { res -= take_term(tokens); } _ => unreachable!(), } } } } #[test] fn test0227() { fn case(s: &str, want: i32) { let got = Solution::calculate(s.to_string()); assert_eq!(got, want); } case("3+2*2", 7); case(" 3/2 ", 1); case(" 3+5 / 2 ", 5); }
use crate::utils::{read_u16_vec, write_u16_vec}; use mila::{BinArchiveReader, BinArchiveWriter}; type Result<T> = std::result::Result<T, mila::ArchiveError>; pub struct FE14CharacterView { pub address: usize, pub bitflags: Vec<u8>, pub pid: String, pub fid: Option<String>, pub aid: Option<String>, pub name: Option<String>, pub description: Option<String>, pub pointers: Vec<u8>, pub id: u16, pub support_route: u8, pub army: u8, pub replacing: u16, pub parent: u16, pub classes: Vec<u16>, pub support_id: i16, pub level: i8, pub internal_level: i8, pub enemy_flag: u8, pub unknown: Vec<u8>, pub bases: Vec<u8>, pub growths: Vec<u8>, pub modifiers: Vec<u8>, pub penalties: Vec<u8>, pub bonuses: Vec<u8>, pub weapon_ranks: Vec<u8>, pub skills: Vec<u16>, pub skill_flags: Vec<u8>, pub personal_skills: Vec<u16>, pub birthday: Vec<u8>, pub reclass_1: Vec<u16>, pub parent_id: u16, pub child_id: u16, pub support_index: i16, pub level_cap: u8, pub body_type: u8, pub combat_music: Option<String>, pub voice: Option<String>, pub recruit_equip_weapon: u16, pub special_shop_item: u16, pub padding: Vec<u8>, } impl FE14CharacterView { pub fn read(reader: &mut BinArchiveReader) -> Result<Self> { Ok(FE14CharacterView { address: reader.tell(), bitflags: reader.read_bytes(8)?, pid: reader .read_string()? .ok_or_else(|| mila::ArchiveError::OtherError("Null PID.".to_string()))?, fid: reader.read_string()?, aid: reader.read_string()?, name: reader.read_string()?, description: reader.read_string()?, pointers: reader.read_bytes(8)?, id: reader.read_u16()?, support_route: reader.read_u8()?, army: reader.read_u8()?, replacing: reader.read_u16()?, parent: reader.read_u16()?, classes: read_u16_vec(reader, 2)?, support_id: reader.read_i16()?, level: reader.read_i8()?, internal_level: reader.read_i8()?, enemy_flag: reader.read_u8()?, unknown: reader.read_bytes(3)?, bases: reader.read_bytes(8)?, growths: reader.read_bytes(8)?, modifiers: reader.read_bytes(8)?, penalties: reader.read_bytes(8)?, bonuses: reader.read_bytes(8)?, weapon_ranks: reader.read_bytes(8)?, skills: read_u16_vec(reader, 5)?, skill_flags: reader.read_bytes(2)?, personal_skills: read_u16_vec(reader, 3)?, birthday: reader.read_bytes(2)?, reclass_1: read_u16_vec(reader, 2)?, parent_id: reader.read_u16()?, child_id: reader.read_u16()?, support_index: reader.read_i16()?, level_cap: reader.read_u8()?, body_type: reader.read_u8()?, combat_music: reader.read_string()?, voice: reader.read_string()?, recruit_equip_weapon: reader.read_u16()?, special_shop_item: reader.read_u16()?, padding: reader.read_bytes(4)?, }) } pub fn write(&self, writer: &mut BinArchiveWriter) -> Result<()> { writer.seek(self.address); writer.write_bytes(&self.bitflags)?; writer.write_string(Some(&self.pid))?; writer.write_string(self.fid.as_deref())?; writer.write_string(self.aid.as_deref())?; writer.write_string(self.name.as_deref())?; writer.write_string(self.description.as_deref())?; writer.write_bytes(&self.pointers)?; writer.write_u16(self.id)?; writer.write_u8(self.support_route)?; writer.write_u8(self.army)?; writer.write_u16(self.replacing)?; writer.write_u16(self.parent)?; write_u16_vec(writer, &self.classes)?; writer.write_i16(self.support_id)?; writer.write_i8(self.level)?; writer.write_i8(self.internal_level)?; writer.write_u8(self.enemy_flag)?; writer.write_bytes(&self.unknown)?; writer.write_bytes(&self.bases)?; writer.write_bytes(&self.growths)?; writer.write_bytes(&self.modifiers)?; writer.write_bytes(&self.penalties)?; writer.write_bytes(&self.bonuses)?; writer.write_bytes(&self.weapon_ranks)?; write_u16_vec(writer, &self.skills)?; writer.write_bytes(&self.skill_flags)?; write_u16_vec(writer, &self.personal_skills)?; writer.write_bytes(&self.birthday)?; write_u16_vec(writer, &self.reclass_1)?; writer.write_u16(self.parent_id)?; writer.write_u16(self.child_id)?; writer.write_i16(self.support_index)?; writer.write_u8(self.level_cap)?; writer.write_u8(self.body_type)?; writer.write_string(self.combat_music.as_deref())?; writer.write_string(self.voice.as_deref())?; writer.write_u16(self.recruit_equip_weapon)?; writer.write_u16(self.special_shop_item)?; writer.write_bytes(&self.padding)?; Ok(()) } }
use std::io::Write; use std::path::Path; use std::process::{Child, Command, Stdio}; use std::{env, io}; fn main() { loop { print!("\u{279c} "); io::stdout().flush().unwrap(); // Read line input let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); // must be peekable so we know when we are on the last command let mut commands = input.trim().split(" | ").peekable(); let mut previous_command = None; // Deterim wether command is empty while let Some(command) = commands.next() { let mut parts = command.trim().split_whitespace(); let command = parts.next().unwrap(); let args = parts; match command { "cd" => { let new_dir = args.peekable().peek().map_or("/", |x| *x); let root = Path::new(new_dir); if let Err(e) = env::set_current_dir(&root) { eprintln!("{}", e); } previous_command = None; } "exit" => return, command => { // Test for pip let stdin = previous_command.map_or(Stdio::inherit(), |output: Child| { Stdio::from(output.stdout.unwrap()) }); let stdout = if commands.peek().is_some() { // there is another command piped behind this one // prepare to send output to the next command Stdio::piped() } else { // there are no more commands piped behind this one // send output to shell stdout Stdio::inherit() }; let output = Command::new(command) .args(args) .stdin(stdin) .stdout(stdout) .spawn(); match output { Ok(output) => { previous_command = Some(output); } Err(e) => { previous_command = None; eprintln!("{}", e); } }; } } } // Reach the final if let Some(mut final_command) = previous_command { // block until the final command has finished if let Err(error) = final_command.wait() { println!("{}", error) } } } }
// Computes a^n by the right-to-left binary exponentiation algorithm // Input: A number a and a list b(n) of binary digits b_I, ..., b_0 // in the binary expansion of a nonnegative integer n // Output: The value of a^n fn rl_binary_exponentiation(a: u8, b: &[u8]) -> u64 { let mut term: u64 = a as u64; // initializes a^(2^i) let i = b.len(); let mut product: u64; if b[i - 1] == 1 { product = a as u64; } else { product = 1; } for j in 1..i { term = term * term; if b[i - 1 - j] == 1 { product = product * term; } } product } fn main() { let b = [1, 1, 0, 1]; println!("Value of 5^13 (RL): {}", rl_binary_exponentiation(5, &b)); }
use scanner_proc_macro::insert_scanner; #[insert_scanner] fn main() { let s = scan!(String); let mut s: Vec<char> = s.chars().collect(); s.sort(); for ch in s { print!("{}", ch); } println!(); }
use super::{ not::Not, passthrough::Passthrough, ActiveFilter, DynamicFilter, FilterResult, GroupMatcher, LayoutFilter, }; use crate::internals::{query::view::Fetch, storage::component::ComponentTypeId, world::WorldId}; /// A filter which always matches `true`. #[derive(Debug, Clone, Default)] pub struct Any; impl GroupMatcher for Any { fn can_match_group() -> bool { false } fn group_components() -> Vec<ComponentTypeId> { vec![] } } impl LayoutFilter for Any { fn matches_layout(&self, _: &[ComponentTypeId]) -> FilterResult { FilterResult::Match(true) } } impl DynamicFilter for Any { fn prepare(&mut self, _: WorldId) {} fn matches_archetype<F: Fetch>(&mut self, _: &F) -> FilterResult { FilterResult::Match(true) } } impl std::ops::Not for Any { type Output = Not<Self>; #[inline] fn not(self) -> Self::Output { Not { filter: self } } } impl<Rhs: ActiveFilter> std::ops::BitAnd<Rhs> for Any { type Output = Rhs; #[inline] fn bitand(self, rhs: Rhs) -> Self::Output { rhs } } impl std::ops::BitAnd<Passthrough> for Any { type Output = Self; #[inline] fn bitand(self, _: Passthrough) -> Self::Output { self } } impl<Rhs: ActiveFilter> std::ops::BitOr<Rhs> for Any { type Output = Self; #[inline] fn bitor(self, _: Rhs) -> Self::Output { self } } impl std::ops::BitOr<Passthrough> for Any { type Output = Self; #[inline] fn bitor(self, _: Passthrough) -> Self::Output { self } }
//! A `Constant` holds a single value. use crate::Error; use num_bigint::{BigInt, BigUint, ToBigInt}; use num_traits::{FromPrimitive, One, ToPrimitive, Zero}; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; use std::fmt; use std::ops::*; /// A constant value for Falcon IL /// /// IL Constants in Falcon are backed by both rust's `u64` primitive, and /// `BigUint` from the `num-bigint` crate. This allows modelling and simulation /// of instructions which must operate on values >64 bits in size. When a /// Constant has 64 or less bits, the `u64` will be used, incurring minimal /// performance overhead. /// /// The Falcon IL Expression operations are provided as methods over `Constant`. #[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] pub struct Constant { value: BigUint, bits: usize, } impl Constant { /// Create a new `Constant` with the given value and bitness. pub fn new(value: u64, bits: usize) -> Constant { Constant { value: Constant::trim_value(BigUint::from_u64(value).unwrap(), bits), bits, } } /// Create a new `Constant` from the given `BigUint`. pub fn new_big(value: BigUint, bits: usize) -> Constant { Constant { value: Constant::trim_value(value, bits), bits, } } /// Crates a constant from a decimal string of the value pub fn from_decimal_string(s: &str, bits: usize) -> Result<Constant, Error> { let constant = Constant::new_big(s.parse()?, bits); Ok(match constant.bits().cmp(&bits) { Ordering::Less => constant.zext(bits)?, Ordering::Greater => constant.trun(bits)?, Ordering::Equal => constant, }) } /// Create a new `Constant` with the given bits and a value of zero pub fn new_zero(bits: usize) -> Constant { Constant { value: BigUint::from_u64(0).unwrap(), bits, } } fn trim_value(value: BigUint, bits: usize) -> BigUint { let mask = BigUint::from_u64(1).unwrap() << bits; let mask = mask - BigUint::from_u64(1).unwrap(); value & mask } /// Ugly trickery to convert BigUint to BigInt fn to_bigint(&self) -> BigInt { let sign_bit = self.value.clone() >> (self.bits - 1); if sign_bit == BigUint::from_u64(1).unwrap() { let mask = BigUint::from_i64(1).unwrap() << self.bits; let mask = mask - BigUint::from_i64(1).unwrap(); let v = self.value.clone() ^ mask; let v = v + BigUint::from_u64(1).unwrap(); BigInt::from_i64(-1).unwrap() * v.to_bigint().unwrap() } else { self.value.to_bigint().unwrap() } } /// Get the value of this `Constant` if it is a `u64`. pub fn value_u64(&self) -> Option<u64> { self.value.to_u64() } /// Sign-extend the constant out to 64-bits, and return it as an `i64` pub fn value_i64(&self) -> Option<i64> { match self.bits().cmp(&64) { Ordering::Greater => None, Ordering::Equal => self.value.to_u64().map(|v| v as i64), Ordering::Less => self.sext(64).ok()?.value.to_u64().map(|v| v as i64), } } /// Get the value of this `Constant` if it is a `u128`. pub fn value_u128(&self) -> Option<u128> { self.value.to_u128() } /// Get the value of this `Constant` if it is a `BigUint`. pub fn value(&self) -> &BigUint { &self.value } /// Get the number of bits for this `Constant`. pub fn bits(&self) -> usize { self.bits } /// Returns true if the value in this Constant is 0, false otherwise. pub fn is_zero(&self) -> bool { self.value.is_zero() } /// Returns true if the value in this constant is 1, false otherwise. pub fn is_one(&self) -> bool { self.value.is_one() } pub fn add(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits != rhs.bits() { Err(Error::Sort) } else { Ok(Constant::new_big( self.value.clone() + rhs.value.clone(), self.bits, )) } } pub fn sub(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else if self.value < rhs.value { let lhs = self.value.clone(); let lhs = lhs | (BigUint::from_u64(1).unwrap() << self.bits); Ok(Constant::new_big(lhs - rhs.value.clone(), self.bits)) } else { Ok(Constant::new_big( self.value.clone().sub(rhs.value.clone()), self.bits, )) } } pub fn mul(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else { Ok(Constant::new_big( self.value.clone() * rhs.value.clone(), self.bits, )) } } pub fn divu(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else if rhs.is_zero() { Err(Error::DivideByZero) } else { Ok(Constant::new_big( self.value.clone() / rhs.value.clone(), self.bits, )) } } pub fn modu(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else if rhs.is_zero() { Err(Error::DivideByZero) } else { Ok(Constant::new_big( self.value.clone() % rhs.value.clone(), self.bits, )) } } pub fn divs(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else if rhs.is_zero() { Err(Error::DivideByZero) } else { let lhs = self.to_bigint(); let rhs = rhs.to_bigint(); let r = lhs / rhs; if r >= BigInt::from_i64(0).unwrap() { Ok(Constant::new_big(r.to_biguint().unwrap(), self.bits)) } else { let mask = BigInt::from_i64(1).unwrap() << self.bits; let mask = mask - BigInt::from_i64(1).unwrap(); let r = (r - BigInt::from_u64(1).unwrap()) ^ mask; let r = r * BigInt::from_i64(-1).unwrap(); Ok(Constant::new_big(r.to_biguint().unwrap(), self.bits)) } } } pub fn mods(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else if rhs.is_zero() { Err(Error::DivideByZero) } else { let lhs = self.to_bigint(); let rhs = rhs.to_bigint(); let r = lhs % rhs; if r >= BigInt::from_i64(0).unwrap() { Ok(Constant::new_big(r.to_biguint().unwrap(), self.bits)) } else { let mask = BigInt::from_i64(1).unwrap() << self.bits; let mask = mask - BigInt::from_i64(1).unwrap(); let r = (r - BigInt::from_u64(1).unwrap()) ^ mask; let r = r * BigInt::from_i64(-1).unwrap(); Ok(Constant::new_big(r.to_biguint().unwrap(), self.bits)) } } } pub fn and(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else { Ok(Constant::new_big( self.value.clone() & rhs.value.clone(), self.bits, )) } } pub fn or(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else { Ok(Constant::new_big( self.value.clone() | rhs.value.clone(), self.bits, )) } } pub fn xor(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else { Ok(Constant::new_big( self.value.clone() ^ rhs.value.clone(), self.bits, )) } } pub fn shl(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else { // If, for some reason, an analysis generates a very large shift // value (for example << 0xFFFFFFFF_FFFFFFFF:64), this will cause // the bigint library to attempt gigantic memory allocations, and // crash. We have a basic sanity check here to just set the value // to 0 if we are shifting left by a value greater than the variable // width, which is the correct behavior. let r = rhs .value .to_usize() .map(|bits| { if bits >= self.bits() { BigUint::from_u64(0).unwrap() } else { self.value.clone() << bits } }) .unwrap_or_else(|| BigUint::from_u64(0).unwrap()); Ok(Constant::new_big(r, self.bits)) } } pub fn shr(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else { let r = rhs .value .to_usize() .map(|bits| self.value.clone() >> bits) .unwrap_or_else(|| BigUint::from_u64(0).unwrap()); Ok(Constant::new_big(r, self.bits)) } } pub fn ashr(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else { let r = rhs .value .to_usize() .map(|bits| { let value = self.value() >> bits; let msb = self.value() >> (self.bits - 1); if msb.is_zero() { value } else { let all_one = BigUint::from_u64(u64::MAX).unwrap(); let fill = all_one << (self.bits - bits); fill | value } }) .unwrap_or_else(|| BigUint::from_u64(0).unwrap()); Ok(Constant::new_big(r, self.bits)) } } pub fn cmpeq(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else if self.value == rhs.value { Ok(Constant::new(1, 1)) } else { Ok(Constant::new(0, 1)) } } pub fn cmpneq(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else if self.value == rhs.value { Ok(Constant::new(0, 1)) } else { Ok(Constant::new(1, 1)) } } pub fn cmpltu(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { Err(Error::Sort) } else if self.value < rhs.value { Ok(Constant::new(1, 1)) } else { Ok(Constant::new(0, 1)) } } pub fn cmplts(&self, rhs: &Constant) -> Result<Constant, Error> { if self.bits() != rhs.bits() { return Err(Error::Sort); } let lhs = self.to_bigint(); let rhs = rhs.to_bigint(); if lhs < rhs { Ok(Constant::new(1, 1)) } else { Ok(Constant::new(0, 1)) } } pub fn trun(&self, bits: usize) -> Result<Constant, Error> { if bits >= self.bits() { Err(Error::Sort) } else { Ok(Constant::new_big(self.value.clone(), bits)) } } pub fn zext(&self, bits: usize) -> Result<Constant, Error> { if bits <= self.bits() { Err(Error::Sort) } else { Ok(Constant::new_big(self.value.clone(), bits)) } } pub fn sext(&self, bits: usize) -> Result<Constant, Error> { if bits <= self.bits() || bits % 8 > 0 { Err(Error::Sort) } else { let sign_bit = self.value.clone() >> (self.bits - 1); let value = if sign_bit == BigUint::from_u64(1).unwrap() { let mask = BigUint::from_u64(1).unwrap() << bits; let mask = mask - BigUint::from_u64(1).unwrap(); let mask = mask << self.bits; self.value.clone() | mask } else { self.value.clone() }; Ok(Constant::new_big(value, bits)) } } } impl fmt::Display for Constant { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "0x{:X}:{}", self.value, self.bits) } } #[test] fn constant_add() { assert_eq!( Constant::new(1, 64).add(&Constant::new(1, 64)).unwrap(), Constant::new(2, 64) ); assert_eq!( Constant::new(0xff, 8).add(&Constant::new(1, 8)).unwrap(), Constant::new(0, 8) ); } #[test] fn constant_sub() { assert_eq!( Constant::new(1, 64).sub(&Constant::new(1, 64)).unwrap(), Constant::new(0, 64) ); assert_eq!( Constant::new(0, 64).sub(&Constant::new(1, 64)).unwrap(), Constant::new(0xffffffffffffffff, 64) ); } #[test] fn constant_mul() { assert_eq!( Constant::new(6, 64).mul(&Constant::new(4, 64)).unwrap(), Constant::new(24, 64) ); } #[test] fn constant_divu() { assert_eq!( Constant::new(6, 64).divu(&Constant::new(4, 64)).unwrap(), Constant::new(1, 64) ); } #[test] fn constant_modu() { assert_eq!( Constant::new(6, 64).modu(&Constant::new(4, 64)).unwrap(), Constant::new(2, 64) ); } #[test] fn constant_divs() { assert_eq!( Constant::new(6, 64).divs(&Constant::new(4, 64)).unwrap(), Constant::new(1, 64) ); } #[test] fn constant_mods() { assert_eq!( Constant::new(6, 64).mods(&Constant::new(4, 64)).unwrap(), Constant::new(2, 64) ); } #[test] fn constant_and() { assert_eq!( Constant::new(0xff00ff, 64) .and(&Constant::new(0xf0f0f0, 64)) .unwrap(), Constant::new(0xf000f0, 64) ); } #[test] fn constant_or() { assert_eq!( Constant::new(0xff00ff, 64) .or(&Constant::new(0xf0f0f0, 64)) .unwrap(), Constant::new(0xfff0ff, 64) ); } #[test] fn constant_xor() { assert_eq!( Constant::new(0xff00ff, 64) .xor(&Constant::new(0xf0f0f0, 64)) .unwrap(), Constant::new(0x0ff00f, 64) ); } #[test] fn constant_shl() { assert_eq!( Constant::new(1, 64).shl(&Constant::new(8, 64)).unwrap(), Constant::new(0x100, 64) ); } #[test] fn constant_shr() { assert_eq!( Constant::new(0x100, 64).shr(&Constant::new(8, 64)).unwrap(), Constant::new(1, 64) ); } #[test] fn constant_ashr() { assert_eq!( Constant::new(0x40000000, 32) .ashr(&Constant::new(0x10, 32)) .unwrap(), Constant::new(0x00004000, 32) ); assert_eq!( Constant::new(0x80000000, 32) .ashr(&Constant::new(0x10, 32)) .unwrap(), Constant::new(0xffff8000, 32) ); } #[test] fn constant_cmpeq() { assert_eq!( Constant::new(1, 64).cmpeq(&Constant::new(1, 64)).unwrap(), Constant::new(1, 1) ); assert_eq!( Constant::new(1, 64).cmpeq(&Constant::new(2, 64)).unwrap(), Constant::new(0, 1) ); } #[test] fn constant_cmpneq() { assert_eq!( Constant::new(1, 64).cmpneq(&Constant::new(1, 64)).unwrap(), Constant::new(0, 1) ); assert_eq!( Constant::new(1, 64).cmpneq(&Constant::new(2, 64)).unwrap(), Constant::new(1, 1) ); } #[test] fn constant_cmpltu() { assert_eq!( Constant::new(1, 64).cmpltu(&Constant::new(1, 64)).unwrap(), Constant::new(0, 1) ); assert_eq!( Constant::new(1, 64).cmpltu(&Constant::new(2, 64)).unwrap(), Constant::new(1, 1) ); } #[test] fn constant_cmplts() { assert_eq!( Constant::new(1, 64).cmplts(&Constant::new(1, 64)).unwrap(), Constant::new(0, 1) ); assert_eq!( Constant::new(1, 64).cmplts(&Constant::new(2, 64)).unwrap(), Constant::new(1, 1) ); assert_eq!( Constant::new(0xffffffffffffffff, 64) .cmplts(&Constant::new(1, 64)) .unwrap(), Constant::new(1, 1) ); }
enum State { /// Interpret characters as normal Normal, /// A backslash escape was detected Escape, /// \x was detected Hex1, /// First digit was parsed Hex2, } fn decode(source: &[u8]) -> Vec<u8> { use State::*; let mut state = Normal; let mut buf = Vec::new(); let mut d1: u8 = 0; let mut d2: u8; for &ch in source.iter() { match state { Normal => { match ch { b'\\' => state = Escape, b'"' => {} // Just ignore quotes. What could possibly go wrong? _ => buf.push(ch), } } Escape => match ch { c @ b'\\' | c @ b'"' => { buf.push(c); state = Normal; } b'x' => { state = Hex1; } _ => panic!("Invalid escape: {ch}"), }, Hex1 => { d1 = ch; state = Hex2; } Hex2 => { d2 = ch; state = Normal; // Lol inefficient buf.push(u8::from_str_radix(&format!("{}{}", d1 as char, d2 as char), 16).unwrap()); } } } buf } fn encode(source: &[u8]) -> Vec<u8> { let mut buf = vec![b'"']; for &b in source.iter() { if b == b'"' || b == b'\\' { buf.push(b'\\'); } buf.push(b); } // Finally lol buf.push(b'"'); buf } fn part1(input: &str) -> usize { let mut src_len = 0; let mut repr_len = 0; for line in input.lines() { src_len += line.len(); let decoded = decode(line.as_bytes()); repr_len += decoded.len(); } src_len - repr_len } fn part2(input: &str) -> usize { let mut src_len = 0; let mut encoded_len = 0; for line in input.lines() { src_len += line.len(); let encoded = encode(line.as_bytes()); encoded_len += encoded.len(); } encoded_len - src_len } aoc::tests! { fn decode: b"\"\"" => b""; b"\"abc\"" => b"abc"; b"\"aaa\\\"aaa\"" => b"aaa\"aaa"; b"\\x27" => b"'"; fn part1: r#" "" "abc" "aaa\"aaa" "\x27" "# => 12; in => 1350; fn encode: br#""""# => br#""\"\"""#; br#""abc""# => br#""\"abc\"""#; br#""aaa\"aaa""# => br#""\"aaa\\\"aaa\"""#; br#""\x27""# => br#""\"\\x27\"""#; fn part2: in => 2085; } aoc::main!(part1, part2);
use std::future::Future; use std::pin::Pin; #[cfg(feature = "sgx")] use std::prelude::v1::*; use std::sync::atomic::{AtomicU64, Ordering}; #[cfg(not(feature = "sgx"))] use std::sync::Mutex; #[cfg(feature = "sgx")] use std::sync::SgxMutex as Mutex; use std::task::{Context, Poll, Waker}; /// A counter for wait and wakeup. /// /// The APIs of EventCounter are similar to that of Liunx's eventfd. pub struct EventCounter { counter: AtomicU64, wakers: Mutex<Vec<Waker>>, } impl EventCounter { pub fn new(init_counter: u64) -> EventCounter { Self { counter: AtomicU64::new(init_counter), wakers: Mutex::new(Vec::new()), } } /// Write to the counter. /// /// Write does two things: 1) increase the counter by one; 2) unblock any blocking read. pub fn write(&self) { let mut wakers = self.wakers.lock().unwrap(); let old_counter = self.counter.fetch_add(1, Ordering::Relaxed); if old_counter > 0 { return; } for waker in wakers.drain(..) { waker.wake(); } } /// Read from the counter. /// /// Read always returns an non-zero value of the counter and resets the counter to zero. /// If the current value of the counter is zero, it blocks until somebody else writes /// to the counter. pub fn read(&self) -> impl Future<Output = u64> + '_ { Read::new(self) } } impl Default for EventCounter { fn default() -> Self { Self::new(0) } } struct Read<'a> { inner: &'a EventCounter, } impl<'a> Read<'a> { fn new(inner: &'a EventCounter) -> Self { Self { inner } } } impl<'a> Future for Read<'a> { type Output = u64; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut wakers = self.inner.wakers.lock().unwrap(); let old_counter = self.inner.counter.swap(0, Ordering::Relaxed); if old_counter > 0 { return Poll::Ready(old_counter); } let waker = cx.waker().clone(); wakers.push(waker); Poll::Pending } }
use std::os::unix::io::AsRawFd; /// Is this stream an TTY? #[cfg(not(target_os = "redox"))] pub fn is_tty<T: AsRawFd>(stream: T) -> bool { use libc; unsafe { libc::isatty(stream.as_raw_fd()) == 1} } /// This will panic. #[cfg(target_os = "redox")] pub fn is_tty<T: AsRawFd>(_stream: T) -> bool { unimplemented!(); }
#![recursion_limit = "1024"] use std::env::var_os; use std::sync::Arc; use futures::try_join; mod engine; use engine::engine_builder::*; use engine::resources::resource_manager::ResourceManager; const WEB_SERVICE_ADDR: &str = "0.0.0.0"; const TICKS_PER_SECOND: u8 = 30; const DEFAULT_PORT: &str = "8000"; #[tokio::main] async fn main() { let port = match var_os("PORT") { Some(val) => val.into_string().unwrap(), None => String::from(DEFAULT_PORT), }; println!("Use port: {}", &port); let ip = match my_internet_ip::get() { Ok(ip) => ip.to_string() + ":" + &port, Err(_e) => { println!("Couldn't get public IP. Local only."); WEB_SERVICE_ADDR.to_string() + ":" + &port } }; let service_address = String::from(WEB_SERVICE_ADDR) + ":" + &port; println!("Server will operate at: {}", &ip); let game_config = GameConfig { ticks_per_second: TICKS_PER_SECOND, service_address, public_address: ip, }; let resource_manager = Arc::new(ResourceManager::new()); let (game, network, sdp) = build_engine(game_config, &resource_manager).await; println!("engine running..."); try_join!(game, network, sdp,).unwrap(); }
extern crate declarative_dataflow; extern crate differential_dataflow; extern crate timely; use std::time::Instant; use timely::Configuration; use differential_dataflow::operators::Count; use declarative_dataflow::plan::Join; use declarative_dataflow::server::{Register, RegisterSource, Server}; use declarative_dataflow::sources::{JsonFile, Source}; use declarative_dataflow::{Plan, Rule, Value}; fn main() { let filename = std::env::args().nth(1).unwrap(); timely::execute(Configuration::Process(1), move |worker| { let mut server = Server::<u64, u64>::new(Default::default()); let e = 1; let rules = vec![Rule { name: "q1".to_string(), plan: Plan::Join(Join { variables: vec![e], left_plan: Box::new(Plan::MatchAV( e, "target".to_string(), Value::String("Russian".to_string()), )), right_plan: Box::new(Plan::MatchAV( e, "guess".to_string(), Value::String("Russian".to_string()), )), }), }]; let obj_source = Source::JsonFile(JsonFile { path: filename.clone(), }); worker.dataflow::<u64, _, _>(|scope| { server.register_source( RegisterSource { names: vec!["target".to_string(), "guess".to_string()], source: obj_source, }, scope, ); server.register( Register { rules, publish: vec!["q1".to_string()], }, scope, ); server .interest("q1", scope) .map(|_x| ()) .count() .inspect(|x| println!("RESULT {:?}", x)); }); let timer = Instant::now(); while !server.probe.done() { worker.step(); } println!("finished at {:?}", timer.elapsed()); }) .unwrap(); }
use memory::*; pub struct Bus<'a> { pub memory: &'a mut Memory, } impl Bus<'_> { pub fn new(memory: &mut Memory) -> Bus { Bus { memory: memory } } pub fn read_u8(&self, addr: u32) -> u8 { self.memory.read_u8(addr.wrapping_sub(0x8000_0000) as u64) } pub fn read_u16(&self, addr: u32) -> u16 { self.memory.read_u16(addr.wrapping_sub(0x8000_0000) as u64) } pub fn read_u32(&self, addr: u32) -> u32 { self.memory.read_u32(addr.wrapping_sub(0x8000_0000) as u64) } pub fn write_u8(&mut self, addr: u32, value: u8) { self.memory.write_u8(addr.wrapping_sub(0x8000_0000) as u64, value) } pub fn write_u16(&mut self, addr: u32, value: u16) { self.memory.write_u16(addr.wrapping_sub(0x8000_0000) as u64, value) } pub fn write_u32(&mut self, addr: u32, value: u32) { self.memory.write_u32(addr.wrapping_sub(0x8000_0000) as u64, value) } }
// error handling use std::io; use std::result; use std::error; use std::fmt; pub type Result<T> = result::Result<T, CustomError>; #[derive(Debug)] pub enum CustomError { Io(io::Error), } impl fmt::Display for CustomError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { CustomError::Io(ref err) => { match err.kind() { io::ErrorKind::NotFound => { write!(f, "未找到文件,路径不正确") } _ => panic!("unresolved error encountered") } }, } } } impl error::Error for CustomError { fn description(&self) -> &str { match *self { CustomError::Io(ref err) => err.description(), } } fn cause(&self) -> Option<&error::Error> { match *self { CustomError::Io(ref err) => Some(err), } } } impl From<io::Error> for CustomError { fn from(err: io::Error) -> CustomError { CustomError::Io(err) } }
use crate::*; const URL: &str = "https://api.zoom.us/v2/metrics/meetings?type=past&page_size=300"; #[derive(Debug, Serialize, Deserialize)] pub struct Claims { iss: String, exp: usize, } pub fn get_ms_time() -> usize { let start = SystemTime::now(); let since_the_epoch = start .duration_since(UNIX_EPOCH) .expect("Time went backwards"); since_the_epoch.as_millis() as usize } pub fn generate_jwt(key: &String, secret: &String) -> String { let my_claims = Claims { iss: key.to_string(), exp: get_ms_time(), }; encode( &Header::default(), &my_claims, &EncodingKey::from_secret(secret.as_ref()), ) .unwrap() } pub fn fetch_zoom_data( key: &String, secret: &String, next_page_token: Option<&String>, ) -> std::result::Result<ZoomResponse, ZoomError> { let token = generate_jwt(key, secret); let mut final_url = URL.to_string(); if next_page_token.is_some() { final_url = format!("{}&next_page_token={}", final_url, next_page_token.unwrap()) } if false { final_url = format!("{}&from={}&to={}", final_url, "2020-04-03", "2020-04-03") } // println!("-- DOWNLOADING --"); println!("URL \t\t | {}", final_url); let response = minreq::get(final_url) .with_header("authorization", format!("Bearer {}", token)) .send() .unwrap(); let data: Value = response.json().unwrap(); let is_error = data.as_object().unwrap().contains_key("code"); if is_error { return Err(response.json().unwrap()); }; Ok(response.json().unwrap()) } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ZoomError { pub code: i64, pub message: String, } impl fmt::Display for ZoomError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "invalid first item to double") } } impl error::Error for ZoomError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { // Generic error, underlying cause isn't tracked. None } } impl Default for ZoomResponse { fn default() -> Self { ZoomResponse { from: String::from(""), to: String::from(""), page_count: 0, page_size: 0, total_records: 0, next_page_token: String::from(""), meetings: vec![], } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ZoomResponse { pub from: String, pub to: String, pub page_count: usize, pub page_size: usize, pub total_records: usize, pub next_page_token: String, pub meetings: MeetingMetrics, } pub type MeetingMetrics = Vec<Meeting>; #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Meeting { pub uuid: String, pub duration: String, pub email: String, pub end_time: String, pub has_3rd_party_audio: bool, pub has_pstn: bool, pub has_recording: bool, pub has_screen_share: bool, pub has_sip: bool, pub has_video: bool, pub has_voip: bool, pub host: String, pub id: i64, pub participants: i64, pub start_time: String, pub topic: String, pub user_type: String, }
use json_utils::json::JsMap; use json_utils::json::JsValue; pub fn js_value_eq(left: &JsValue, right: &JsValue) -> bool { match (left, right) { (JsValue::Null, JsValue::Null) => true, (JsValue::Bool(left), JsValue::Bool(right)) => left == right, (JsValue::String(left), JsValue::String(right)) => left == right, (JsValue::Number(left), JsValue::Number(right)) => left == right, (JsValue::Array(left), JsValue::Array(right)) => js_array_eq(left, right), (JsValue::Object(left), JsValue::Object(right)) => js_object_eq(left, right), (_, _) => false, } } fn js_array_eq(left: &Vec<JsValue>, right: &Vec<JsValue>) -> bool { if left.len() == right.len() { left.iter() .zip(right.iter()) .all(|(left, right)| js_value_eq(left, right)) } else { false } } fn js_object_eq(left: &JsMap<String, JsValue>, right: &JsMap<String, JsValue>) -> bool { if left.len() == right.len() { left.keys().all(|key| { if let (Some(left), Some(right)) = (left.get(key), right.get(key)) { js_value_eq(left, right) } else { false } }) } else { false } } #[test] fn test_01_eq_neq() { assert!(js_value_eq(&json!(null), &json!(null))); assert!(!js_value_eq(&json!(null), &json!(false))); assert!(!js_value_eq(&json!(null), &json!(true))); assert!(js_value_eq(&json!(true), &json!(true))); assert!(js_value_eq(&json!(false), &json!(false))); assert!(!js_value_eq(&json!(true), &json!(false))); assert!(js_value_eq(&json!("a string"), &json!("a string"))); assert!(!js_value_eq(&json!("a string"), &json!("another one"))); assert!(js_value_eq(&json!(1), &json!(1))); assert!(!js_value_eq(&json!(1), &json!(2))); assert!(js_value_eq(&json!(-1), &json!(-1))); assert!(!js_value_eq(&json!(-1), &json!(1))); assert!(!js_value_eq(&json!(-1), &json!(-2))); assert!(js_value_eq(&json!(1.0), &json!(1.0))); assert!(js_value_eq(&json!(1.1), &json!(1.1))); assert!(!js_value_eq(&json!(1), &json!(1.1))); assert!(!js_value_eq(&json!(1.2), &json!(1.1))); assert!(js_value_eq(&json!([]), &json!([]))); assert!(js_value_eq(&json!([1]), &json!([1]))); assert!(js_value_eq(&json!([1, 2]), &json!([1, 2]))); assert!(js_value_eq(&json!([1, 2, 3]), &json!([1, 2, 3]))); assert!(!js_value_eq(&json!([]), &json!([0]))); assert!(!js_value_eq(&json!([1]), &json!([1, 0]))); assert!(!js_value_eq(&json!([1, 2]), &json!([1, 2, 0]))); assert!(!js_value_eq(&json!([1, 2, 3]), &json!([1, 2, 3, 0]))); assert!(!js_value_eq(&json!([1, 2]), &json!([2, 1]))); assert!(!js_value_eq(&json!([1, 2, 3]), &json!([1, 3, 2]))); assert!(js_value_eq(&json!({}), &json!({}))); assert!(js_value_eq(&json!({"a": 1}), &json!({"a": 1}))); assert!(js_value_eq( &json!({"a": 1, "b": 2}), &json!({"a": 1, "b": 2}) )); assert!(js_value_eq( &json!({"a": 1, "b": 2}), &json!({"b": 2, "a": 1}) )); assert!(!js_value_eq(&json!({"a": "1"}), &json!({"a": 1}))); assert!(!js_value_eq( &json!({"a": 1, "b": "2"}), &json!({"a": 1, "b": 2}) )); assert!(!js_value_eq( &json!({"a": 1, "b": "2"}), &json!({"b": 2, "a": 1}) )); assert!(!js_value_eq(&json!({}), &json!({"_": 0}))); assert!(!js_value_eq(&json!({"a": 1}), &json!({"a": 1, "_": 0}))); assert!(!js_value_eq( &json!({"a": 1, "b": 2}), &json!({"a": 1, "b": 2, "_": 0}) )); assert!(!js_value_eq( &json!({"a": 1, "b": 2}), &json!({"b": 2, "a": 1, "_": 0}) )); assert!(!js_value_eq( &json!({"b": 2, "c": 1}), &json!({"a": 1, "b": 2}) )); }
use gtk::*; pub fn create_image() -> Image { let image = Image::new(); image.set_halign(gtk::Align::Start); image.set_valign(gtk::Align::Start); image } pub fn create_window(application: &Application) -> ApplicationWindow { let window = ApplicationWindow::new(application); window.set_title("Mosaic creator 1.0.0"); window.set_border_width(10); window.set_position(WindowPosition::Center); window.set_default_size(1600, 900); window.connect_delete_event(move |win, _| { win.destroy(); Inhibit(false) }); window } pub fn create_dummy_scroller() -> ScrolledWindow { let scroller = gtk::ScrolledWindow::new( gtk::NONE_ADJUSTMENT, gtk::NONE_ADJUSTMENT ); scroller.set_policy(PolicyType::External, PolicyType::External); scroller }
pub mod channel; pub mod mutex; pub mod rwlock; pub mod atomic_counters;
pub mod clippycheck;
//! //! Create attribute objects using the `Attribute` enum. //! //! //! Example //! ------- //! ``` //! use proffer::*; //! //! let a = Attribute::from("#![be_cool]"); //! //! let src_code = a.generate(); //! let expected = "#![be_cool]"; //! assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code)) //! ``` use crate::SrcCode; use serde::{Deserialize, Serialize}; /// Represents a single Rust attribute to a module, function, etc. #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Attribute { /// Attribute representing an attribute for an item. ie. `#[foo(bar)]` ItemAttr(String), /// Attribute representing a scoped level attribute. ie. `#![warn(...)]` ScopeAttr(String), } // TODO: Use TryFrom when https://github.com/rust-lang/rust/issues/50133 is resolved. impl<S: ToString> From<S> for Attribute { fn from(attribute: S) -> Self { let attribute = attribute.to_string(); if attribute.starts_with("#!") { Attribute::ScopeAttr(attribute) } else if attribute.starts_with('#') { Attribute::ItemAttr(attribute) } else { panic!("No Attribute match for '{}'", attribute) } } } impl SrcCode for Attribute { fn generate(&self) -> String { match self { Attribute::ScopeAttr(s) | Attribute::ItemAttr(s) => s.to_owned(), } } }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GString; use glib_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMHTMLFormElement; use DOMNode; use DOMObject; glib_wrapper! { pub struct DOMHTMLLabelElement(Object<webkit2_webextension_sys::WebKitDOMHTMLLabelElement, webkit2_webextension_sys::WebKitDOMHTMLLabelElementClass, DOMHTMLLabelElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget; match fn { get_type => || webkit2_webextension_sys::webkit_dom_html_label_element_get_type(), } } pub const NONE_DOMHTML_LABEL_ELEMENT: Option<&DOMHTMLLabelElement> = None; pub trait DOMHTMLLabelElementExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_form(&self) -> Option<DOMHTMLFormElement>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_html_for(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn set_html_for(&self, value: &str); fn connect_property_form_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_html_for_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMHTMLLabelElement>> DOMHTMLLabelElementExt for O { fn get_form(&self) -> Option<DOMHTMLFormElement> { unsafe { from_glib_none( webkit2_webextension_sys::webkit_dom_html_label_element_get_form( self.as_ref().to_glib_none().0, ), ) } } fn get_html_for(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_label_element_get_html_for( self.as_ref().to_glib_none().0, ), ) } } fn set_html_for(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_label_element_set_html_for( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn connect_property_form_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_form_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLLabelElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLLabelElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLLabelElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::form\0".as_ptr() as *const _, Some(transmute(notify_form_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_html_for_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_html_for_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLLabelElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLLabelElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLLabelElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::html-for\0".as_ptr() as *const _, Some(transmute(notify_html_for_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } } impl fmt::Display for DOMHTMLLabelElement { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMHTMLLabelElement") } }
use crate::prelude::*; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Position { pub x: f32, pub y: f32, pub rotation: euclid::Angle::<f32>, } #[derive(Clone, Copy, Debug, PartialEq)] pub struct Renderable { pub index: usize, pub template: Template, } #[derive(Clone, Copy, Debug, PartialEq)] pub struct GDSpatial;
use std::cmp::{min, max}; impl Solution { pub fn max_profit(prices: Vec<i32>) -> i32 { if prices.len() <= 1 { return 0; } let mut minum = prices[0]; let mut maxium = 0; for v in prices { maxium = maxium.max(v - minum); minum = minum.min(v); } maxium } }
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time; use md5; use sha1::Sha1; use crate::http::Context; pub use self::ip_util::*; mod ip_util; /// Generate user's pwd. It's use SHA1 algorithm pub fn pwd<P: Into<String>>(p: P) -> String { let mut s = Sha1::new(); s.update(p.into().as_bytes()); s.digest().to_string() } /// Gets unixstamp of system time pub fn unix_sec() -> u64 { time::SystemTime::now() .duration_since(time::UNIX_EPOCH) .unwrap() .as_secs() } pub fn hash<T: Hash>(t: T) -> u64 { let mut hasher = DefaultHasher::new(); t.hash(&mut hasher); hasher.finish() } /// Return short hash letters pub fn short_hash<T: Hash>(t: T) -> String { let digest = md5::compute(hash(t).to_string()); (&format!("{:x}", digest)[16..24]).to_owned() } #[test] fn test_hash() { let h1 = short_hash("to2.net"); let h2 = short_hash("s.to2.net"); assert_eq!(h1, h2); } /// Get prefix link of current request url. pub fn self_pre_link(ctx: &Context) -> String { let host = ctx.header("Host"); let origin = ctx.header("Origin"); if origin.ends_with(&host) { return origin; } let mut s = origin[0..origin.find("//").unwrap_or(0)].to_owned(); if s.len() == 0 { s.push_str("http:"); } s.push_str("//"); s.push_str(&host); s }
use fs_extra::dir::create; use fs_extra::file::write_all; use super::fixtures::{get_app_content, get_package_json, get_rollup, get_main, get_index_html, get_global_css, get_component_content, get_component_test, get_babel, get_jest}; use super::utils::{update_values_in_files}; pub fn generate_new_application(name: &str) { create(format!("{}/", name), false); create(format!("{}/src", name), false); create(format!("{}/src/ui", name), false); create(format!("{}/src/ui/components", name), false); create(format!("{}/public", name), false); write_all(format!("{}/src/App.svelte", name), get_app_content()); write_all(format!("{}/src/main.js", name), get_main()); write_all(format!("{}/public/index.html", name), get_index_html()); write_all(format!("{}/public/global.css", name), get_global_css()); let package_path = format!("{}/package.json", name).to_string(); write_all(&package_path, get_package_json()); update_values_in_files("{AppName}", name, &package_path); write_all(format!("{}/rollup.config.js", name), get_rollup()); write_all(format!("{}/babel.config.js", name), get_babel()); write_all(format!("{}/jest.config.js", name), get_jest()); println!("✨ Generated project in /{}", name); println!("To get started, run `cd /{}` and run `yarn` to install dependencies and the `yarn run dev` to start the server.", name); } pub fn generate_files(blueprint: &str, name: &str, capitalized_name: String) { let test_path = format!("src/ui/components/{}/Component.spec.js", name).to_string(); create(format!("src/ui/components/{}", name), false); write_all(format!("src/ui/components/{}/Component.svelte", name), get_component_content()); write_all(&test_path, get_component_test()); update_values_in_files("{ComponentName}", &capitalized_name, &test_path); println!("✨ Generated {} in src/ui/components/{}", blueprint, name); println!("🔬 Generated test in src/ui/components/{}", name); }
use proconio::{input, marker::Bytes}; fn main() { input! { s: Bytes, }; for b in s { print!("{}", 1 - (b - b'0')); } println!(); }
use sdl2::pixels::Color as SdlColor; use std::ops::{Add, AddAssign, Mul}; #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub struct Color { r: u8, g: u8, b: u8, } impl Color { #[allow(non_snake_case)] pub const fn RGB(r: u8, g: u8, b: u8) -> Color { Color { r, g, b } } pub const fn zero() -> Color { Color::RGB(0, 0, 0) } } impl Mul<f32> for Color { type Output = Self; fn mul(self, rhs: f32) -> Self { let times = |x| ((x as f32) * rhs).min(255.) as u8; Color::RGB(times(self.r), times(self.g), times(self.b)) } } impl Add for Color { type Output = Self; fn add(self, rhs: Self) -> Self { let plus = |a: u8, b: u8| ((a as u16) + (b as u16)).min(255).max(0) as u8; Color::RGB( plus(self.r, rhs.r), plus(self.g, rhs.g), plus(self.b, rhs.b), ) } } impl AddAssign for Color { fn add_assign(&mut self, other: Self) { *self = *self + other } } impl Into<SdlColor> for Color { fn into(self) -> SdlColor { SdlColor::RGB(self.r, self.g, self.b) } } impl From<SdlColor> for Color { fn from(raw: SdlColor) -> Color { Color::RGB(raw.r, raw.g, raw.b) } }
extern crate clap; extern crate term_size; #[macro_use] extern crate quick_error; extern crate users; extern crate size; extern crate time; use clap::{App, Arg}; mod core; mod meta; use crate::core::Core; #[derive(Debug)] pub struct Options { display_all: bool, display_long: bool, } fn main() { let app = App::new("l") .version("1.0.0") .author("lome") .about("this is a l") .arg(Arg::with_name("all") .short("a") .help("Show all file and dir")) .arg(Arg::with_name("long") .short("l") .help("show file all info")) .arg(Arg::with_name("FILE") .multiple(true).default_value(".")) .get_matches(); let option = Options { display_all: app.is_present("all"), display_long: app.is_present("long") }; let files: Vec<&str> = app .values_of("FILE") .expect("not get any file") .collect(); let core = Core::new(&option); core.run(files); }
#[test] fn scan_test() { let iter = (0..10).scan(0, |sum, item| { *sum += item; if *sum > 10 { None } else { Some(item * item) } }); assert_eq!(iter.collect::<Vec<i32>>(), vec![0, 1, 4, 9, 16]); }
use std::cmp::{Ordering, PartialEq, PartialOrd}; use std::ops::{Add, Neg}; ///Struct representing a Complex number #[derive(Debug)] pub struct Complex<T> { pub re: T, pub im: T, } impl<T> PartialEq for Complex<T> where T: PartialEq, { fn eq(&self, other: &Complex<T>) -> bool { self.re == other.re && self.im == other.im } } impl<T> Add for Complex<T> where T: Add<Output = T>, { type Output = Self; fn add(self, rhs: Self) -> Self { Complex { re: self.re + rhs.re, im: self.im + rhs.im, } } } impl<T, O> Neg for Complex<T> where T: Neg<Output = O>, { type Output = Complex<O>; fn neg(self) -> Complex<O> { Complex { re: -self.re, im: -self.im, } } } #[derive(Debug, PartialEq)] struct Interval<T> { lower: T, upper: T, } impl<T> PartialOrd<Interval<T>> for Interval<T> where T: PartialOrd, { fn partial_cmp(&self, other: &Interval<T>) -> Option<Ordering> { match self { s if s == other => Some(Ordering::Equal), s if s.lower >= other.upper => Some(Ordering::Greater), s if s.upper <= other.lower => Some(Ordering::Less), _ => None, } } } // fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>; #[test] fn complex_add_test() { let complex1 = Complex { re: 2, im: 5 }; let complex2 = Complex { re: 5, im: 3 }; assert_eq!(complex1 + complex2, Complex { re: 7, im: 8 }); } #[test] fn complex_negate_test() { let complex1 = Complex { re: 5, im: 10 }; let complex2 = &(-complex1); assert_eq!(complex2.re, -5); assert_eq!(complex2.im, -10); } #[test] fn interval_ordering_test() { assert!( Interval { lower: 10, upper: 20 } < Interval { lower: 20, upper: 40 } ); assert!(Interval { lower: 7, upper: 8 } >= Interval { lower: 0, upper: 1 }); assert!(Interval { lower: 7, upper: 8 } <= Interval { lower: 7, upper: 8 }); }
pub struct Solution; impl Solution { pub fn min_window(s: String, t: String) -> String { let s = s.as_bytes(); let t = t.as_bytes(); let mut balance = vec![0_isize; 128]; let mut count = 0; for i in 0..t.len() { let n = &mut balance[t[i] as usize]; if *n == 0 { count += 1; } *n += 1; } let mut i_min = 0; let mut j_min = std::usize::MAX; let mut i = 0; let mut j = 0; while j < s.len() { let n = &mut balance[s[j] as usize]; *n -= 1; if *n == 0 { count -= 1; } j += 1; while count == 0 { if j - i < j_min - i_min { i_min = i; j_min = j; } let n = &mut balance[s[i] as usize]; if *n == 0 { count += 1; } *n += 1; i += 1; } } if j_min == std::usize::MAX { String::new() } else { String::from_utf8(s[i_min..j_min].to_vec()).unwrap() } } } #[test] fn test0076() { assert_eq!( Solution::min_window("ADOBECODEBANC".to_string(), "ABC".to_string()), "BANC".to_string() ); assert_eq!( Solution::min_window("a".to_string(), "aa".to_string()), "".to_string() ); }
#[derive(juniper::ScalarValue)] struct ScalarValue; fn main() {}
use serde::{Serialize, Deserialize}; use std::collections::HashMap; #[derive(Debug, Serialize, Deserialize)] pub struct Message { pub content: HashMap<String, String>, } impl Message { pub fn new() -> Self { Message { content: HashMap::new(), } } pub fn put(&mut self, k: String, v: String) { self.content.insert(k, v); } pub fn get(&mut self, k: String) -> Option<&String> { self.content.get(&k) } } #[derive(Serialize, Deserialize, Debug)] pub struct Point { pub x: i32, pub y: i32, } #[cfg(test)] mod test { use super::*; #[test] fn test_point() { let point = Point { x: 1, y: 2 }; // Convert the Point to a JSON string. let serialized = serde_json::to_string(&point).unwrap(); // Prints serialized = {"x":1,"y":2} println!("serialized = {}", serialized); // Convert the JSON string back to a Point. let deserialized: Point = serde_json::from_str(&serialized).unwrap(); // Prints deserialized = Point { x: 1, y: 2 } println!("deserialized = {:?}", deserialized); let mut message = HashMap::new(); message.insert("reply_to", "127.0.0.1:6000"); message.insert("action", "heartbeat"); let m_str = serde_json::to_string(&message).unwrap(); println!("{}", m_str); let mut msg: HashMap<String, String> = serde_json::from_str(&m_str).unwrap(); println!("{:?}", msg); } #[test] fn test_timeout() { } }
extern crate proconio; use proconio::input; use proconio::marker::Chars; fn main() { input! { (R, C): (usize, usize), (sy, sx): (usize, usize), (gy, gx): (usize, usize), a: [Chars; R], } let (sy, sx) = (sy - 1, sx - 1); let (gy, gx) = (gy - 1, gx - 1); let mut d = vec![vec![-1; C]; R]; let dydx = [(-1, 0), (0, -1), (1, 0), (0, 1)]; let mut q = std::collections::VecDeque::new(); d[sy][sx] = 0; q.push_back((sy, sx)); while let Some((y, x)) = q.pop_front() { for (dy, dx) in &dydx { let ny = y as isize + dy; let nx = x as isize + dx; if 0 <= ny && ny < R as isize && 0 <= nx && nx < C as isize { let ny = ny as usize; let nx = nx as usize; if a[ny][nx] == '.' && d[ny][nx] == -1 { d[ny][nx] = d[y][x] + 1; q.push_back((ny, nx)); } } } } println!("{}", d[gy][gx]); }
//! Re-exports from the `gen` submodules. pub mod associated_types; pub mod attribute; pub mod r#enum; pub mod field; pub mod function; pub mod generics; pub mod r#impl; pub mod module; pub mod r#struct; pub mod r#trait; pub use associated_types::*; pub use attribute::*; pub use field::*; pub use function::*; pub use generics::*; pub use module::*; pub use r#enum::*; pub use r#impl::*; pub use r#struct::*; pub use r#trait::*;
//! Terminal I/O. use std::mem::MaybeUninit; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::thread; use anyhow::{Context, Error}; use libc::STDOUT_FILENO; use log::*; use nix::ioctl_read_bad; use terminfo::{capability as cap, expand}; use tokio::fs::File; use tokio::io::{self, AsyncWriteExt, BufWriter}; use crate::ui::{Coordinates, Screen, Size}; mod input; pub use input::{Key, Stdin}; pub struct Terminal { terminfo: terminfo::Database, stdout: BufWriter<File>, /// The screen that should be drawn on the next refresh. back: Screen, pub cursor: Coordinates, } impl Terminal { pub async fn new() -> Result<Self, Error> { let mut stdout = File::from_std(unsafe { std::fs::File::from_raw_fd(STDOUT_FILENO) }); let terminfo = terminfo::Database::from_env().context("failed to initialize terminfo")?; if let Some(smcup) = terminfo.get::<cap::EnterCaMode>() { stdout.write_all(smcup.as_ref()).await?; } let size = get_size(stdout.as_raw_fd())?; Ok(Terminal { terminfo, stdout: BufWriter::new(stdout), back: Screen::new(size), cursor: Coordinates::zero(), }) } /// Returns a sequence of bytes that can be used to restore the terminal to its original state. /// This does *not* include the TTY settings, `input::Stdin` is responsible for that. pub fn restore_sequence(&self) -> Vec<u8> { let mut seq = vec![]; if let Some(rmcup) = self.terminfo.get::<cap::ExitCaMode>() { seq.extend_from_slice(rmcup.as_ref()); } else { warn!("no rmcup capability in terminfo"); } if let Some(cnorm) = self.terminfo.get::<cap::CursorNormal>() { seq.extend_from_slice(cnorm.as_ref()); } else { warn!("no cnorm capability in terminfo"); } seq } pub fn screen(&mut self) -> &mut Screen { &mut self.back } pub fn size(&self) -> Size { self.back.size } pub fn refresh_size(&mut self) -> Result<Size, Error> { self.back.size = get_size(self.stdout.get_ref().as_raw_fd())?; Ok(self.size()) } pub async fn refresh(&mut self) -> io::Result<()> { self.hide_cursor().await?; if let Some(cl) = self.terminfo.get::<cap::ClearScreen>() { self.stdout.write_all(cl.as_ref()).await?; } let mut last_color = None; { let mut rows = self.back.iter_rows().peekable(); while let Some(row) = rows.next() { for col in row { if col.color != last_color { match col.color { Some(color) => { self.stdout .write_all( format!("\x1b[38;2;{};{};{}m", color.r, color.g, color.b) .as_bytes(), ) .await?; } None => { let sgr0 = self.terminfo.get::<cap::ExitAttributeMode>().unwrap(); self.stdout.write_all(sgr0.as_ref()).await?; } } last_color = col.color; } if let Some(c) = col.c { let mut buf = [0; 4]; self.stdout .write_all(c.encode_utf8(&mut buf).as_bytes()) .await?; } } if rows.peek().is_some() { self.stdout.write_all(b"\r\n").await?; } } } let cup = expand!(self .terminfo .get::<cap::CursorAddress>().unwrap().as_ref(); self.cursor.y, self.cursor.x) .unwrap(); self.stdout.write_all(&cup).await?; self.show_cursor().await?; self.stdout.flush().await } async fn hide_cursor(&mut self) -> io::Result<()> { let civis = expand!(self .terminfo .get::<cap::CursorInvisible>() .unwrap() .as_ref()) .unwrap(); self.stdout.write_all(&civis).await } async fn show_cursor(&mut self) -> io::Result<()> { let cnorm = expand!(self.terminfo.get::<cap::CursorNormal>().unwrap().as_ref()).unwrap(); self.stdout.write_all(&cnorm).await } } impl Drop for Terminal { fn drop(&mut self) { if !thread::panicking() { let _ = futures::executor::block_on(async move { let seq = self.restore_sequence(); self.stdout.write_all(&seq).await?; self.stdout.flush().await?; Ok::<(), io::Error>(()) }); } } } /// Queries the terminal size on a file descriptor. fn get_size(fd: RawFd) -> nix::Result<Size> { ioctl_read_bad!(tiocgwinsz, libc::TIOCGWINSZ, libc::winsize); let size = unsafe { let mut winsize = MaybeUninit::zeroed(); tiocgwinsz(fd, winsize.as_mut_ptr())?; winsize.assume_init() }; Ok(Size::new(size.ws_col, size.ws_row)) }
use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; fn main() { let n: usize = parse_line().unwrap(); let pp: Vec<u64> = parse_line().unwrap(); let qq: Vec<u64> = parse_line().unwrap(); let mut a = 0; let mut b = 0; for (i, num) in (1..=n as u64).into_iter().permutations(n).enumerate() { if pp == num { a = i as i64 + 1; } if qq == num { b = i as i64 + 1; } } println!("{}", (a - b).abs()); }
use std::io::Stdout; use grapl_observe::{ metric_reporter::{ tag, MetricReporter, }, timers::{ time_fut_ms, TimedFutureExt, }, }; use rusoto_core::RusotoError; use rusoto_s3::PutObjectError as InnerPutObjectError; use rusoto_sqs::{ DeleteMessageError as InnerDeleteMessageError, DeleteMessageRequest, Message as SqsMessage, ReceiveMessageError as InnerReceiveMessageError, ReceiveMessageRequest, SendMessageRequest, Sqs, }; use tokio::{ task::{ JoinError, JoinHandle, }, time::error::Elapsed, }; use tracing::{ debug, error, Instrument, }; use crate::errors::{ CheckedError, Recoverable, }; impl CheckedError for InnerDeleteMessageError { fn error_type(&self) -> Recoverable { match self { Self::InvalidIdFormat(_) => Recoverable::Persistent, Self::ReceiptHandleIsInvalid(_) => Recoverable::Persistent, } } } // PutObjectError has no variants, and conveys no information // about what went wrong, so we must assume a transient error impl CheckedError for InnerPutObjectError { fn error_type(&self) -> Recoverable { Recoverable::Transient } } impl<E> CheckedError for RusotoError<E> where E: CheckedError + 'static, { /// In all cases, other than Service there's no way to inspect the error /// since it's just a String, so we default to assuming it's transient, even though /// that may not always be the case. fn error_type(&self) -> Recoverable { match self { RusotoError::Service(e) => e.error_type(), RusotoError::HttpDispatch(_) | RusotoError::Credentials(_) | RusotoError::Validation(_) | RusotoError::ParseError(_) | RusotoError::Unknown(_) | RusotoError::Blocking => Recoverable::Transient, } } } pub async fn get_message<SqsT>( queue_url: String, sqs_client: SqsT, metric_reporter: &mut MetricReporter<Stdout>, ) -> Result<Vec<SqsMessage>, RusotoError<InnerReceiveMessageError>> where SqsT: Sqs + Clone + Send + Sync + 'static, { const WAIT_TIME_SECONDS: i64 = 20; let messages = sqs_client.receive_message(ReceiveMessageRequest { max_number_of_messages: Some(10), queue_url, visibility_timeout: Some(30), wait_time_seconds: Some(WAIT_TIME_SECONDS), ..Default::default() }); let messages = tokio::time::timeout( std::time::Duration::from_secs((WAIT_TIME_SECONDS as u64) + 1), messages, ); let (messages, ms) = time_fut_ms(messages).await; let messages = messages .expect("timeout") .map(|m| m.messages.unwrap_or_else(|| vec![])); if let Ok(ref msgs) = messages { metric_reporter .histogram( "sqs_executor.receive_message", ms as f64, &[tag("success", true), tag("empty_receive", msgs.is_empty())][..], ) .unwrap_or_else(|e| { error!( error = e.to_string().as_str(), metric_name = "sqs_executor.receive_message", "Failed to report histogram metric", ) }); } else { metric_reporter .histogram( "sqs_executor.receive_message", ms as f64, &[tag("success", false)], ) .unwrap_or_else(|e| { error!( error = e.to_string().as_str(), metric_name = "sqs_executor.receive_message", "Failed to report histogram metric", ) }); }; Ok(messages?) } #[derive(thiserror::Error, Debug)] pub enum SendMessageError { #[error("SendMessageError {0}")] InnerSendMessageError(#[from] RusotoError<rusoto_sqs::SendMessageError>), #[error("SendMessage Timeout")] Timeout(#[from] Elapsed), } impl CheckedError for rusoto_sqs::SendMessageError { fn error_type(&self) -> Recoverable { Recoverable::Persistent } } impl CheckedError for SendMessageError { fn error_type(&self) -> Recoverable { match self { Self::InnerSendMessageError(e) => e.error_type(), _ => Recoverable::Transient, } } } pub fn send_message<SqsT>( queue_url: String, message_body: String, sqs_client: SqsT, mut metric_reporter: MetricReporter<Stdout>, ) -> JoinHandle<Result<(), SendMessageError>> where SqsT: Sqs + Clone + Send + Sync + 'static, { tokio::task::spawn(async move { let metric_reporter = &mut metric_reporter; let mut last_err = None; for i in 0..5u64 { let sqs_client = sqs_client.clone(); let res = sqs_client.send_message(SendMessageRequest { queue_url: queue_url.clone(), message_body: message_body.clone(), ..Default::default() }); let res = tokio::time::timeout(std::time::Duration::from_secs(21), res) .timed() .await; match res { (Ok(Ok(_)), ms) => { metric_reporter .histogram( "sqs_executor.send_message.ms", ms as f64, &[tag("success", true)], ) .unwrap_or_else(|e| { error!( error = e.to_string().as_str(), metric_name = "sqs_executor.send_message", "Failed to report histogram metric", ) }); debug!("Send message: {}", queue_url.clone()); return Ok(()); } (Ok(Err(e)), ms) => { metric_reporter .histogram( "sqs_executor.send_message.ms", ms as f64, &[tag("success", false)], ) .unwrap_or_else(|e| { error!( error = e.to_string().as_str(), metric_name = "sqs_executor.send_message", "Failed to report histogram metric", ) }); if let Recoverable::Persistent = e.error_type() { return Err(SendMessageError::from(e)); } else { last_err = Some(SendMessageError::from(e)); tokio::time::sleep(std::time::Duration::from_millis(10 * i)).await; } } (Err(e), ms) => { metric_reporter .histogram( "sqs_executor.send_message.ms", ms as f64, &[tag("success", false)], ) .unwrap_or_else(|e| { error!( error = e.to_string().as_str(), metric_name = "sqs_executor.send_message", "Failed to report histogram metric with timeout", ) }); last_err = Some(SendMessageError::from(e)); tokio::time::sleep(std::time::Duration::from_millis(10 * i)).await; } } } Err(last_err.unwrap()) }) } #[tracing::instrument(skip(sqs_client, queue_url, receipt_handle, metric_reporter))] pub fn delete_message<SqsT>( sqs_client: SqsT, queue_url: String, receipt_handle: String, mut metric_reporter: MetricReporter<Stdout>, ) -> tokio::task::JoinHandle<()> where SqsT: Sqs + Clone + Send + Sync + 'static, { let delete_f = async move { let metric_reporter = &mut metric_reporter; for _ in 0..5u8 { match sqs_client .clone() .delete_message(DeleteMessageRequest { queue_url: queue_url.clone(), receipt_handle: receipt_handle.clone(), }) .timed() .await { (Ok(_), ms) => { metric_reporter .histogram( "sqs_executor.delete_message.ms", ms as f64, &[tag("success", true)], ) .unwrap_or_else(|e| error!("sqs_executor.delete_message.ms: {:?}", e)); debug!("Deleted message: {}", receipt_handle.clone()); return; } (Err(e), ms) => { metric_reporter .histogram( "sqs_executor.delete_message.ms", ms as f64, &[tag("success", false)], ) .unwrap_or_else(|e| error!("sqs_executor.delete_message.ms: {:?}", e)); error!( "Failed to delete_message with: {:?} {:?}", e, e.error_type() ); if let Recoverable::Persistent = e.error_type() { return; } } } } }; tokio::task::spawn(delete_f.in_current_span()) } #[derive(thiserror::Error, Debug)] pub enum MoveToDeadLetterError { #[error("SerializeError {0}")] SerializeError(#[from] serde_json::Error), #[error("SendMessageError {0}")] SendMessageError(#[from] SendMessageError), #[error("DeleteMessageError {0}")] DeleteMessageError(#[from] InnerDeleteMessageError), #[error("JoinError {0}")] JoinError(#[from] JoinError), } pub async fn move_to_dead_letter<SqsT>( sqs_client: SqsT, message: &impl serde::Serialize, publish_to_queue: String, delete_from_queue: String, receipt_handle: String, metric_reporter: MetricReporter<Stdout>, ) -> Result<(), MoveToDeadLetterError> where SqsT: Sqs + Clone + Send + Sync + 'static, { debug!( publish_to_queue = publish_to_queue.as_str(), delete_from_queue = delete_from_queue.as_str(), "Moving message to deadletter queue" ); let message = serde_json::to_string(&message); let message = message?; send_message( publish_to_queue, message, sqs_client.clone(), metric_reporter.clone(), ) .await??; delete_message( sqs_client, delete_from_queue, receipt_handle, metric_reporter, ) .await?; Ok(()) }
//! Myers' diff algorithm. //! //! * time: `O((N+M)D)` //! * space `O(N+M)` //! //! See [the original article by Eugene W. Myers](http://www.xmailserver.org/diff2.pdf) //! describing it. //! //! The implementation of this algorithm is based on the implementation by //! Brandon Williams. //! //! # Heuristics //! //! At present this implementation of Myers' does not implement any more advanced //! heuristics that would solve some pathological cases. For instance passing two //! large and completely distinct sequences to the algorithm will make it spin //! without making reasonable progress. Currently the only protection in the //! library against this is to pass a deadline to the diffing algorithm. //! //! For potential improvements here see [similar#15](https://github.com/mitsuhiko/similar/issues/15). use std::ops::{Index, IndexMut, Range}; use std::time::Instant; use crate::algorithms::utils::{common_prefix_len, common_suffix_len, is_empty_range}; use crate::algorithms::DiffHook; /// Myers' diff algorithm. /// /// Diff `old`, between indices `old_range` and `new` between indices `new_range`. pub fn diff<Old, New, D>( d: &mut D, old: &Old, old_range: Range<usize>, new: &New, new_range: Range<usize>, ) -> Result<(), D::Error> where Old: Index<usize> + ?Sized, New: Index<usize> + ?Sized, D: DiffHook, New::Output: PartialEq<Old::Output>, { diff_deadline(d, old, old_range, new, new_range, None) } /// Myers' diff algorithm with deadline. /// /// Diff `old`, between indices `old_range` and `new` between indices `new_range`. /// /// This diff is done with an optional deadline that defines the maximal /// execution time permitted before it bails and falls back to an approximation. pub fn diff_deadline<Old, New, D>( d: &mut D, old: &Old, old_range: Range<usize>, new: &New, new_range: Range<usize>, deadline: Option<Instant>, ) -> Result<(), D::Error> where Old: Index<usize> + ?Sized, New: Index<usize> + ?Sized, D: DiffHook, New::Output: PartialEq<Old::Output>, { let max_d = max_d(old_range.len(), new_range.len()); let mut vb = V::new(max_d); let mut vf = V::new(max_d); conquer( d, old, old_range, new, new_range, &mut vf, &mut vb, deadline, )?; d.finish() } // A D-path is a path which starts at (0,0) that has exactly D non-diagonal // edges. All D-paths consist of a (D - 1)-path followed by a non-diagonal edge // and then a possibly empty sequence of diagonal edges called a snake. /// `V` contains the endpoints of the furthest reaching `D-paths`. For each /// recorded endpoint `(x,y)` in diagonal `k`, we only need to retain `x` because /// `y` can be computed from `x - k`. In other words, `V` is an array of integers /// where `V[k]` contains the row index of the endpoint of the furthest reaching /// path in diagonal `k`. /// /// We can't use a traditional Vec to represent `V` since we use `k` as an index /// and it can take on negative values. So instead `V` is represented as a /// light-weight wrapper around a Vec plus an `offset` which is the maximum value /// `k` can take on in order to map negative `k`'s back to a value >= 0. #[derive(Debug)] struct V { offset: isize, v: Vec<usize>, // Look into initializing this to -1 and storing isize } impl V { fn new(max_d: usize) -> Self { Self { offset: max_d as isize, v: vec![0; 2 * max_d], } } fn len(&self) -> usize { self.v.len() } } impl Index<isize> for V { type Output = usize; fn index(&self, index: isize) -> &Self::Output { &self.v[(index + self.offset) as usize] } } impl IndexMut<isize> for V { fn index_mut(&mut self, index: isize) -> &mut Self::Output { &mut self.v[(index + self.offset) as usize] } } fn max_d(len1: usize, len2: usize) -> usize { // XXX look into reducing the need to have the additional '+ 1' (len1 + len2 + 1) / 2 + 1 } #[inline(always)] fn split_at(range: Range<usize>, at: usize) -> (Range<usize>, Range<usize>) { (range.start..at, at..range.end) } /// A `Snake` is a sequence of diagonal edges in the edit graph. Normally /// a snake has a start end end point (and it is possible for a snake to have /// a length of zero, meaning the start and end points are the same) however /// we do not need the end point which is why it's not implemented here. /// /// The divide part of a divide-and-conquer strategy. A D-path has D+1 snakes /// some of which may be empty. The divide step requires finding the ceil(D/2) + /// 1 or middle snake of an optimal D-path. The idea for doing so is to /// simultaneously run the basic algorithm in both the forward and reverse /// directions until furthest reaching forward and reverse paths starting at /// opposing corners 'overlap'. fn find_middle_snake<Old, New>( old: &Old, old_range: Range<usize>, new: &New, new_range: Range<usize>, vf: &mut V, vb: &mut V, deadline: Option<Instant>, ) -> Option<(usize, usize)> where Old: Index<usize> + ?Sized, New: Index<usize> + ?Sized, New::Output: PartialEq<Old::Output>, { let n = old_range.len(); let m = new_range.len(); // By Lemma 1 in the paper, the optimal edit script length is odd or even as // `delta` is odd or even. let delta = n as isize - m as isize; let odd = delta & 1 == 1; // The initial point at (0, -1) vf[1] = 0; // The initial point at (N, M+1) vb[1] = 0; // We only need to explore ceil(D/2) + 1 let d_max = max_d(n, m); assert!(vf.len() >= d_max); assert!(vb.len() >= d_max); for d in 0..d_max as isize { // are we running for too long? if let Some(deadline) = deadline { if Instant::now() > deadline { break; } } // Forward path for k in (-d..=d).rev().step_by(2) { let mut x = if k == -d || (k != d && vf[k - 1] < vf[k + 1]) { vf[k + 1] } else { vf[k - 1] + 1 }; let y = (x as isize - k) as usize; // The coordinate of the start of a snake let (x0, y0) = (x, y); // While these sequences are identical, keep moving through the // graph with no cost if x < old_range.len() && y < new_range.len() { let advance = common_prefix_len( old, old_range.start + x..old_range.end, new, new_range.start + y..new_range.end, ); x += advance; } // This is the new best x value vf[k] = x; // Only check for connections from the forward search when N - M is // odd and when there is a reciprocal k line coming from the other // direction. if odd && (k - delta).abs() <= (d - 1) { // TODO optimize this so we don't have to compare against n if vf[k] + vb[-(k - delta)] >= n { // Return the snake return Some((x0 + old_range.start, y0 + new_range.start)); } } } // Backward path for k in (-d..=d).rev().step_by(2) { let mut x = if k == -d || (k != d && vb[k - 1] < vb[k + 1]) { vb[k + 1] } else { vb[k - 1] + 1 }; let mut y = (x as isize - k) as usize; // The coordinate of the start of a snake if x < n && y < m { let advance = common_suffix_len( old, old_range.start..old_range.start + n - x, new, new_range.start..new_range.start + m - y, ); x += advance; y += advance; } // This is the new best x value vb[k] = x; if !odd && (k - delta).abs() <= d { // TODO optimize this so we don't have to compare against n if vb[k] + vf[-(k - delta)] >= n { // Return the snake return Some((n - x + old_range.start, m - y + new_range.start)); } } } // TODO: Maybe there's an opportunity to optimize and bail early? } // deadline reached None } #[allow(clippy::too_many_arguments)] fn conquer<Old, New, D>( d: &mut D, old: &Old, mut old_range: Range<usize>, new: &New, mut new_range: Range<usize>, vf: &mut V, vb: &mut V, deadline: Option<Instant>, ) -> Result<(), D::Error> where Old: Index<usize> + ?Sized, New: Index<usize> + ?Sized, D: DiffHook, New::Output: PartialEq<Old::Output>, { // Check for common prefix let common_prefix_len = common_prefix_len(old, old_range.clone(), new, new_range.clone()); if common_prefix_len > 0 { d.equal(old_range.start, new_range.start, common_prefix_len)?; } old_range.start += common_prefix_len; new_range.start += common_prefix_len; // Check for common suffix let common_suffix_len = common_suffix_len(old, old_range.clone(), new, new_range.clone()); let common_suffix = ( old_range.end - common_suffix_len, new_range.end - common_suffix_len, ); old_range.end -= common_suffix_len; new_range.end -= common_suffix_len; if is_empty_range(&old_range) && is_empty_range(&new_range) { // Do nothing } else if is_empty_range(&new_range) { d.delete(old_range.start, old_range.len(), new_range.start)?; } else if is_empty_range(&old_range) { d.insert(old_range.start, new_range.start, new_range.len())?; } else if let Some((x_start, y_start)) = find_middle_snake( old, old_range.clone(), new, new_range.clone(), vf, vb, deadline, ) { let (old_a, old_b) = split_at(old_range, x_start); let (new_a, new_b) = split_at(new_range, y_start); conquer(d, old, old_a, new, new_a, vf, vb, deadline)?; conquer(d, old, old_b, new, new_b, vf, vb, deadline)?; } else { d.delete( old_range.start, old_range.end - old_range.start, new_range.start, )?; d.insert( old_range.start, new_range.start, new_range.end - new_range.start, )?; } if common_suffix_len > 0 { d.equal(common_suffix.0, common_suffix.1, common_suffix_len)?; } Ok(()) } #[test] fn test_find_middle_snake() { let a = &b"ABCABBA"[..]; let b = &b"CBABAC"[..]; let max_d = max_d(a.len(), b.len()); let mut vf = V::new(max_d); let mut vb = V::new(max_d); let (x_start, y_start) = find_middle_snake(a, 0..a.len(), b, 0..b.len(), &mut vf, &mut vb, None).unwrap(); assert_eq!(x_start, 4); assert_eq!(y_start, 1); } #[test] fn test_diff() { let a: &[usize] = &[0, 1, 2, 3, 4]; let b: &[usize] = &[0, 1, 2, 9, 4]; let mut d = crate::algorithms::Replace::new(crate::algorithms::Capture::new()); diff(&mut d, a, 0..a.len(), b, 0..b.len()).unwrap(); insta::assert_debug_snapshot!(d.into_inner().ops()); } #[test] fn test_contiguous() { let a: &[usize] = &[0, 1, 2, 3, 4, 4, 4, 5]; let b: &[usize] = &[0, 1, 2, 8, 9, 4, 4, 7]; let mut d = crate::algorithms::Replace::new(crate::algorithms::Capture::new()); diff(&mut d, a, 0..a.len(), b, 0..b.len()).unwrap(); insta::assert_debug_snapshot!(d.into_inner().ops()); } #[test] fn test_pat() { let a: &[usize] = &[0, 1, 3, 4, 5]; let b: &[usize] = &[0, 1, 4, 5, 8, 9]; let mut d = crate::algorithms::Capture::new(); diff(&mut d, a, 0..a.len(), b, 0..b.len()).unwrap(); insta::assert_debug_snapshot!(d.ops()); } #[test] fn test_deadline_reached() { use std::ops::Index; use std::time::Duration; let a = (0..100).collect::<Vec<_>>(); let mut b = (0..100).collect::<Vec<_>>(); b[10] = 99; b[50] = 99; b[25] = 99; struct SlowIndex<'a>(&'a [usize]); impl<'a> Index<usize> for SlowIndex<'a> { type Output = usize; fn index(&self, index: usize) -> &Self::Output { std::thread::sleep(Duration::from_millis(1)); &self.0[index] } } let slow_a = SlowIndex(&a); let slow_b = SlowIndex(&b); // don't give it enough time to do anything interesting let mut d = crate::algorithms::Replace::new(crate::algorithms::Capture::new()); diff_deadline( &mut d, &slow_a, 0..a.len(), &slow_b, 0..b.len(), Some(Instant::now() + Duration::from_millis(50)), ) .unwrap(); insta::assert_debug_snapshot!(d.into_inner().ops()); }
use ::json_to_final_ast; use ::spec_type_to_final_ast; use ::backend::javascript::size_of::generate_size_of; use super::super::builder::ToJavascript; fn test_size_of(spec: &str, data: &str, result: &str) { let ir = spec_type_to_final_ast(spec).unwrap(); let size_of = generate_size_of(ir).unwrap(); let mut out = String::new(); size_of.to_javascript(&mut out, 0); println!("{}", out); super::test_with_data_eq(&out, data, result); } #[test] fn simple_scalar() { test_size_of( r#" def_type("test") => u8; "#, "0", "1" ); } #[test] fn container() { test_size_of( r#" def_type("test") => container { field("foo") => u8; field("bar") => u8; }; "#, "{foo: 0, bar: 0}", "2" ); } #[test] fn array() { test_size_of( r#" def_type("test") => container(virtual: "true") { virtual_field("len", ref: "arr", prop: "length") => u8; field("arr") => array(ref: "../len") => u8; }; "#, "[1, 2, 3]", "4" ); } #[test] fn union() { let spec = r#" def_type("test") => container(virtual: "true") { virtual_field("tag", ref: "data", prop: "tag") => u8; field("data") => union("test_union", ref: "../tag") { variant("zero", match: "0") => u8; variant("one", match: "1") => container { field("woo") => u8; field("hoo") => u8; }; }; }; "#; test_size_of( spec, "{tag: \"zero\", data: 0}", "2", ); test_size_of( spec, "{tag: \"one\", data: {woo: 0, hoo: 1}}", "3" ); } //#[test] fn protodef_spec_tests() { for case in ::test_harness::json_spec_cases() { println!("Testing {}", case.name); let ast = ::json_to_final_ast(&::json::stringify(case.json_type)).unwrap(); let size_of = generate_size_of(ast).unwrap(); let mut out = String::new(); size_of.to_javascript(&mut out, 0); for value in case.values { super::test_with_data_eq( &out, &value.json_value, &format!("{}", value.serialized.len())); } } }
use actix_web::{get, post, web, App, HttpResponse, HttpServer}; use serde::{Serialize, Deserialize}; use hello_world::customer_service::CustomerService; use std::sync::Arc; use hello_world::event_publishing::DomainEventPublisher; use hello_world::mysql_util::new_connection_pool; #[derive(Serialize, Deserialize)] struct CreateCustomerRequest { name : String, credit_limit: i64 } #[derive(Serialize, Deserialize)] struct CreateCustomerResponse { id : i64 } #[derive(Serialize, Deserialize)] struct GetCustomerResponse { id : i64, name : String, credit_limit: i64 } #[post("/customers")] async fn create_customer(customer_service : web::Data<CustomerService>, request : web::Json<CreateCustomerRequest>) -> actix_web::Result<HttpResponse> { let id = customer_service.save_customer(&request.name, request.credit_limit).await.unwrap(); Ok(HttpResponse::Ok().json(CreateCustomerResponse { id: id })) } #[get("/customers/{id}")] async fn get_customer(customer_service : web::Data<CustomerService>, path : web::Path<(i64,)>) -> actix_web::Result<HttpResponse> { let x = customer_service.find_customer(path.into_inner().0).await.unwrap(); match x { Some(customer) => Ok(HttpResponse::Ok().json(GetCustomerResponse { id: customer.id, name: customer.name, credit_limit: customer.credit_limit})), None => Ok(HttpResponse::NotFound().body("found found")), } } #[actix_web::main] async fn main() -> std::io::Result<()> { let pool = new_connection_pool().await.unwrap(); let domain_event_publisher = Arc::new(DomainEventPublisher{}); let customer_service : CustomerService = CustomerService::new(&domain_event_publisher, &pool); let customer_service_data= web::Data::new(customer_service); HttpServer::new(move || { App::new() .app_data(customer_service_data.clone()) // .data_factory(|| { // let result : Result<CustomerService, ()> = Ok(CustomerService::new(domain_event_publisher.clone(), &pool)); // future::ready(result) }) .service(create_customer) .service(get_customer) }) .bind("127.0.0.1:8080")? .run() .await }
#[doc = "Reader of register AHB4ENR"] pub type R = crate::R<u32, super::AHB4ENR>; #[doc = "Writer for register AHB4ENR"] pub type W = crate::W<u32, super::AHB4ENR>; #[doc = "Register AHB4ENR `reset()`'s with value 0"] impl crate::ResetValue for super::AHB4ENR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "0GPIO peripheral clock enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GPIOAEN_A { #[doc = "0: The selected clock is disabled"] DISABLED = 0, #[doc = "1: The selected clock is enabled"] ENABLED = 1, } impl From<GPIOAEN_A> for bool { #[inline(always)] fn from(variant: GPIOAEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `GPIOAEN`"] pub type GPIOAEN_R = crate::R<bool, GPIOAEN_A>; impl GPIOAEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> GPIOAEN_A { match self.bits { false => GPIOAEN_A::DISABLED, true => GPIOAEN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == GPIOAEN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == GPIOAEN_A::ENABLED } } #[doc = "Write proxy for field `GPIOAEN`"] pub struct GPIOAEN_W<'a> { w: &'a mut W, } impl<'a> GPIOAEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOAEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOBEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOBEN`"] pub type GPIOBEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOBEN`"] pub struct GPIOBEN_W<'a> { w: &'a mut W, } impl<'a> GPIOBEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOBEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOCEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOCEN`"] pub type GPIOCEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOCEN`"] pub struct GPIOCEN_W<'a> { w: &'a mut W, } impl<'a> GPIOCEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOCEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIODEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIODEN`"] pub type GPIODEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIODEN`"] pub struct GPIODEN_W<'a> { w: &'a mut W, } impl<'a> GPIODEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIODEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOEEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOEEN`"] pub type GPIOEEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOEEN`"] pub struct GPIOEEN_W<'a> { w: &'a mut W, } impl<'a> GPIOEEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOEEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOFEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOFEN`"] pub type GPIOFEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOFEN`"] pub struct GPIOFEN_W<'a> { w: &'a mut W, } impl<'a> GPIOFEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOFEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOGEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOGEN`"] pub type GPIOGEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOGEN`"] pub struct GPIOGEN_W<'a> { w: &'a mut W, } impl<'a> GPIOGEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOGEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOHEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOHEN`"] pub type GPIOHEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOHEN`"] pub struct GPIOHEN_W<'a> { w: &'a mut W, } impl<'a> GPIOHEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOHEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOIEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOIEN`"] pub type GPIOIEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOIEN`"] pub struct GPIOIEN_W<'a> { w: &'a mut W, } impl<'a> GPIOIEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOIEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOJEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOJEN`"] pub type GPIOJEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOJEN`"] pub struct GPIOJEN_W<'a> { w: &'a mut W, } impl<'a> GPIOJEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOJEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "0GPIO peripheral clock enable"] pub type GPIOKEN_A = GPIOAEN_A; #[doc = "Reader of field `GPIOKEN`"] pub type GPIOKEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `GPIOKEN`"] pub struct GPIOKEN_W<'a> { w: &'a mut W, } impl<'a> GPIOKEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOKEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "CRC peripheral clock enable"] pub type CRCEN_A = GPIOAEN_A; #[doc = "Reader of field `CRCEN`"] pub type CRCEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `CRCEN`"] pub struct CRCEN_W<'a> { w: &'a mut W, } impl<'a> CRCEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CRCEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "BDMA and DMAMUX2 Clock Enable"] pub type BDMAEN_A = GPIOAEN_A; #[doc = "Reader of field `BDMAEN`"] pub type BDMAEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `BDMAEN`"] pub struct BDMAEN_W<'a> { w: &'a mut W, } impl<'a> BDMAEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BDMAEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "ADC3 Peripheral Clocks Enable"] pub type ADC3EN_A = GPIOAEN_A; #[doc = "Reader of field `ADC3EN`"] pub type ADC3EN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `ADC3EN`"] pub struct ADC3EN_W<'a> { w: &'a mut W, } impl<'a> ADC3EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADC3EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "HSEM peripheral clock enable"] pub type HSEMEN_A = GPIOAEN_A; #[doc = "Reader of field `HSEMEN`"] pub type HSEMEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `HSEMEN`"] pub struct HSEMEN_W<'a> { w: &'a mut W, } impl<'a> HSEMEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSEMEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Backup RAM Clock Enable"] pub type BKPRAMEN_A = GPIOAEN_A; #[doc = "Reader of field `BKPRAMEN`"] pub type BKPRAMEN_R = crate::R<bool, GPIOAEN_A>; #[doc = "Write proxy for field `BKPRAMEN`"] pub struct BKPRAMEN_W<'a> { w: &'a mut W, } impl<'a> BKPRAMEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BKPRAMEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOAEN_A::DISABLED) } #[doc = "The selected clock is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } impl R { #[doc = "Bit 0 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioaen(&self) -> GPIOAEN_R { GPIOAEN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioben(&self) -> GPIOBEN_R { GPIOBEN_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiocen(&self) -> GPIOCEN_R { GPIOCEN_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioden(&self) -> GPIODEN_R { GPIODEN_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioeen(&self) -> GPIOEEN_R { GPIOEEN_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiofen(&self) -> GPIOFEN_R { GPIOFEN_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiogen(&self) -> GPIOGEN_R { GPIOGEN_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiohen(&self) -> GPIOHEN_R { GPIOHEN_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioien(&self) -> GPIOIEN_R { GPIOIEN_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiojen(&self) -> GPIOJEN_R { GPIOJEN_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioken(&self) -> GPIOKEN_R { GPIOKEN_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 19 - CRC peripheral clock enable"] #[inline(always)] pub fn crcen(&self) -> CRCEN_R { CRCEN_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 21 - BDMA and DMAMUX2 Clock Enable"] #[inline(always)] pub fn bdmaen(&self) -> BDMAEN_R { BDMAEN_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 24 - ADC3 Peripheral Clocks Enable"] #[inline(always)] pub fn adc3en(&self) -> ADC3EN_R { ADC3EN_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - HSEM peripheral clock enable"] #[inline(always)] pub fn hsemen(&self) -> HSEMEN_R { HSEMEN_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 28 - Backup RAM Clock Enable"] #[inline(always)] pub fn bkpramen(&self) -> BKPRAMEN_R { BKPRAMEN_R::new(((self.bits >> 28) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioaen(&mut self) -> GPIOAEN_W { GPIOAEN_W { w: self } } #[doc = "Bit 1 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioben(&mut self) -> GPIOBEN_W { GPIOBEN_W { w: self } } #[doc = "Bit 2 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiocen(&mut self) -> GPIOCEN_W { GPIOCEN_W { w: self } } #[doc = "Bit 3 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioden(&mut self) -> GPIODEN_W { GPIODEN_W { w: self } } #[doc = "Bit 4 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioeen(&mut self) -> GPIOEEN_W { GPIOEEN_W { w: self } } #[doc = "Bit 5 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiofen(&mut self) -> GPIOFEN_W { GPIOFEN_W { w: self } } #[doc = "Bit 6 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiogen(&mut self) -> GPIOGEN_W { GPIOGEN_W { w: self } } #[doc = "Bit 7 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiohen(&mut self) -> GPIOHEN_W { GPIOHEN_W { w: self } } #[doc = "Bit 8 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioien(&mut self) -> GPIOIEN_W { GPIOIEN_W { w: self } } #[doc = "Bit 9 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpiojen(&mut self) -> GPIOJEN_W { GPIOJEN_W { w: self } } #[doc = "Bit 10 - 0GPIO peripheral clock enable"] #[inline(always)] pub fn gpioken(&mut self) -> GPIOKEN_W { GPIOKEN_W { w: self } } #[doc = "Bit 19 - CRC peripheral clock enable"] #[inline(always)] pub fn crcen(&mut self) -> CRCEN_W { CRCEN_W { w: self } } #[doc = "Bit 21 - BDMA and DMAMUX2 Clock Enable"] #[inline(always)] pub fn bdmaen(&mut self) -> BDMAEN_W { BDMAEN_W { w: self } } #[doc = "Bit 24 - ADC3 Peripheral Clocks Enable"] #[inline(always)] pub fn adc3en(&mut self) -> ADC3EN_W { ADC3EN_W { w: self } } #[doc = "Bit 25 - HSEM peripheral clock enable"] #[inline(always)] pub fn hsemen(&mut self) -> HSEMEN_W { HSEMEN_W { w: self } } #[doc = "Bit 28 - Backup RAM Clock Enable"] #[inline(always)] pub fn bkpramen(&mut self) -> BKPRAMEN_W { BKPRAMEN_W { w: self } } }
use super::atom; use crate::error::Error; use std::io::{Cursor, Read}; use tokio::io::AsyncReadExt; #[derive(Debug, Eq, PartialEq)] pub enum Packet { Handshake(Handshake), HandshakeRequest(HandshakeRequest), Ping(Ping), } pub async fn read<S: AsyncReadExt + Unpin>(source: &mut S) -> Result<Packet, Error> { let length = atom::read_varint_async(source).await? as usize; let mut buf = vec![0; length]; if length > 0 { source.read_exact(&mut buf).await?; } let mut cursor = Cursor::new(buf); let packet_id = atom::read_varint(&mut cursor)?; trace!("reading packet type {:#}", packet_id); match packet_id { Handshake::ID => match length { // Empty packet with 1-byte packet id has length 1 (for the packet id) 1 => Ok(Packet::HandshakeRequest(HandshakeRequest {})), _ => Ok(Packet::Handshake(Handshake::decode(&mut cursor)?)), }, Ping::ID => Ok(Packet::Ping(Ping::decode(&mut cursor)?)), id => Err(format!("Unknown packet id {}", id).into()), } } #[cfg(test)] type AsyncTestResult = Result<(), Error>; #[tokio::test] async fn test_read_handshake() -> AsyncTestResult { let mut buf: Vec<u8> = vec![ 0x10, 0x00, 0xe0, 0x05, 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x1f, 0x90, 0x01, ]; let mut cursor = Cursor::new(&mut buf); let expected = Handshake { protocol_version: 736, server_address: "localhost".to_owned(), server_port: 8080, next_state: 1, }; assert_eq!(Packet::Handshake(expected), read(&mut cursor).await?); Ok(()) } #[tokio::test] async fn test_read_handshake_request() -> AsyncTestResult { let mut buf: Vec<u8> = vec![0x01, 0x00]; let mut cursor = Cursor::new(&mut buf); assert_eq!( Packet::HandshakeRequest(HandshakeRequest {}), read(&mut cursor).await? ); Ok(()) } #[tokio::test] async fn test_read_ping() -> AsyncTestResult { let mut buf: Vec<u8> = vec![0x09, 0x01]; buf.extend_from_slice(&((123 as i64).to_be_bytes())); let mut cursor = Cursor::new(&mut buf); assert_eq!( Packet::Ping(Ping { payload: 123 }), read(&mut cursor).await? ); Ok(()) } #[derive(Debug, Eq, PartialEq)] pub struct Handshake { pub protocol_version: i32, pub server_address: String, pub server_port: u16, pub next_state: i32, } impl Handshake { const ID: i32 = 0x00; fn decode(source: &mut impl Read) -> Result<Self, Error> { Ok(Handshake { protocol_version: atom::read_varint(source)?, server_address: atom::read_string(source)?, server_port: atom::read_u16(source)?, next_state: atom::read_varint(source)?, }) } } // Minecraft sends a 0x00 empty request after the hanshake packet #[derive(Debug, Eq, PartialEq)] pub struct HandshakeRequest {} #[derive(Debug, Eq, PartialEq)] pub struct Ping { pub payload: i64, } impl Ping { const ID: i32 = 0x01; fn decode(source: &mut impl Read) -> Result<Self, Error> { Ok(Ping { payload: atom::read_i64(source)?, }) } }
use crate::ecmult::ECMultContext; use crate::field::Field; use crate::group::{Affine, Jacobian}; use crate::{util, Error, Message, PublicKey, Scalar, ECMULT_CONTEXT}; use digest::{Digest, Input}; use sha2::Sha256; /// A Schnorr signature. pub struct SchnorrSignature { pub r: Scalar, pub s: Scalar, } impl SchnorrSignature { pub fn parse(p: &[u8; util::SIGNATURE_SIZE]) -> SchnorrSignature { let mut r = Scalar::default(); let mut s = Scalar::default(); // TODO: Okay for signature to overflow? let _ = r.set_b32(array_ref!(p, 0, 32)); let _ = s.set_b32(array_ref!(p, 32, 32)); SchnorrSignature { r, s } } pub fn parse_slice(p: &[u8]) -> Result<SchnorrSignature, Error> { if p.len() != util::SIGNATURE_SIZE { return Err(Error::InvalidInputLength); } let mut a = [0; util::SIGNATURE_SIZE]; a.copy_from_slice(p); Ok(Self::parse(&a)) } } impl ECMultContext { pub fn verify_raw_schnorr(&self, sigr: &Scalar, sigs: &Scalar, pubkey: &Affine, e: &Scalar) -> bool { let mut rx = Field::default(); // TODO: check sigr < p, sigs < n? let _ = rx.set_b32(&sigr.b32()); let nege = e.neg(); let mut pubkeyj: Jacobian = Jacobian::default(); pubkeyj.set_ge(pubkey); let mut rj: Jacobian = Jacobian::default(); self.ecmult(&mut rj, &pubkeyj, &nege, &sigs); // TODO: does it check jacobi(y(R)) == 1 where jacobi is the Jacobi symbol of x / p? if rj.has_quad_y_var() // checks rj.is_infinity() && rj.eq_x_var(&rx) { return true; } return false; } } /// Check signature is a valid message signed by public key. pub fn schnorr_verify(message: &Message, signature: &SchnorrSignature, pubkey: &PublicKey) -> bool { let pk = pubkey.serialize_compressed(); let mut sha = Sha256::default(); sha.process(&signature.r.b32()); sha.process(&pk); sha.process(&message.0.b32()); let mut buf = [0u8; 32]; buf.copy_from_slice(&sha.result()[..]); let mut e = Scalar::default(); let _ = e.set_b32(&buf); ECMULT_CONTEXT.verify_raw_schnorr(&signature.r, &signature.s, &pubkey.0, &e) }
use rand::{random, Rng}; use std::sync::Arc; pub type SimTime = u64; pub const TICKS_PER_SECOND: SimTime = 1; pub const MS_PER_TICK: SimTime = 1000 / TICKS_PER_SECOND; pub trait SimRng { fn random(&self) -> f64; fn random_from_range(&self, low_inclusive: i64, high_exclusive: i64) -> i64; } struct RealRng {} impl SimRng for RealRng { fn random(&self) -> f64 { random::<f64>() } fn random_from_range(&self, low_inclusive: i64, high_exclusive: i64) -> i64 { rand::thread_rng().gen_range(low_inclusive..high_exclusive) } } pub struct SimState { milliseconds: SimTime, pub rng: Arc<dyn SimRng + Sync + Send>, } impl SimState { pub fn new<T: SimRng + Sync + Send + 'static>(rng: T) -> Self { SimState { milliseconds: 0, rng: Arc::<T>::new(rng), } } } impl Default for SimState { fn default() -> Self { SimState { milliseconds: 0, rng: Arc::<RealRng>::new(RealRng {}), } } } impl SimState { pub fn tick(&mut self) -> SimTime { self.milliseconds += MS_PER_TICK; self.milliseconds } pub fn now(&self) -> SimTime { self.milliseconds } }
#[allow(unused_imports)] use crate::naive::solve_naive; #[allow(unused_imports)] use crate::util::{read_data, bench}; #[allow(unused_imports)] use crate::xsort::xsort_par; #[allow(unused_imports)] use crate::boxing::boxing_ser; mod util; mod naive; mod xsort; mod boxing; fn main() { println!("Welcome to Rust gym 1"); // let calculate_reference = false; // let expected_dist2 = if calculate_reference { // println!("solving brute-force to find reference distance"); // let points = read_data(); // let (refp1, refp2) = solve_naive(&points); // refp1.dist2(&refp2) // // expected minimum distance 430.809 found in 40833 ms //// println!("expected minimum distance {0:.3} found in {1:} ms", //// expected_dist1.sqrt(), now.elapsed().as_nanos() as f64 / 1_000_000.0); // } else { // 430.80863789034777 // }; // bench("xsort_par", xsort_par, 20); bench("boxing_ser", boxing_ser, 20); }
use crate::extractors::amp_spectrum; pub fn compute(signal: &Vec<f64>) -> Vec<f64> { let amp_spec: Vec<f64> = amp_spectrum::compute(signal); let pow_spec: Vec<f64> = amp_spec.iter().map(|bin| bin.powi(2)).into_iter().collect(); return pow_spec; } #[cfg(test)] mod tests { use super::compute; use crate::utils::test; use std::f64; const FLOAT_PRECISION: f64 = 0.333_333; fn test_against(dataset: &test::data::TestDataSet) -> () { let power_spec = compute(&dataset.signal); test::data::approx_compare_vec( &power_spec, &dataset.features.powerSpectrum, FLOAT_PRECISION, ); } #[test] fn test_power_spectrum() { let datasets = test::data::get_all(); for dataset in datasets.iter() { test_against(dataset); } } }
use color_eyre::{ eyre::{eyre, Report, Result, WrapErr}, Section, }; use reqwest::header::{HeaderMap, HeaderValue, ACCEPT}; use serde::{Deserialize, Serialize}; use tokio::{runtime::Handle, task}; use crate::nix::{NixLicense, NixPackage, NixPackageMeta}; #[non_exhaustive] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubRepo { pub id: u64, pub node_id: String, pub name: String, pub full_name: String, pub private: bool, pub owner: GitHubOwner, pub html_url: String, #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, pub fork: bool, pub url: String, pub forks_url: String, pub keys_url: String, pub collaborators_url: String, pub teams_url: String, pub hooks_url: String, pub issue_events_url: String, pub events_url: String, pub assignees_url: String, pub branches_url: String, pub tags_url: String, pub blobs_url: String, pub git_tags_url: String, pub git_refs_url: String, pub trees_url: String, pub statuses_url: String, pub languages_url: String, pub stargazers_url: String, pub contributors_url: String, pub subscribers_url: String, pub subscription_url: String, pub commits_url: String, pub git_commits_url: String, pub comments_url: String, pub issue_comment_url: String, pub contents_url: String, pub compare_url: String, pub merges_url: String, pub archive_url: String, pub downloads_url: String, pub issues_url: String, pub pulls_url: String, pub milestones_url: String, pub notifications_url: String, pub labels_url: String, pub releases_url: String, pub deployments_url: String, pub created_at: String, pub updated_at: String, pub pushed_at: String, pub git_url: String, pub ssh_url: String, pub clone_url: String, pub svn_url: String, #[serde(skip_serializing_if = "Option::is_none")] pub homepage: Option<String>, pub size: u64, pub stargazers_count: u64, pub watchers_count: u64, #[serde(skip_serializing_if = "Option::is_none")] pub language: Option<String>, pub has_issues: bool, pub has_projects: bool, pub has_downloads: bool, pub has_wiki: bool, pub has_pages: bool, pub forks_count: u64, #[serde(skip_serializing_if = "Option::is_none")] pub mirror_url: Option<bool>, pub archived: bool, pub disabled: bool, pub open_issues_count: u64, pub license: GitHubLicense, pub forks: u64, pub open_issues: u64, pub watchers: u64, pub default_branch: String, #[serde(skip_serializing_if = "Option::is_none")] pub temp_clone_token: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub organization: Option<GitHubOrganization>, pub network_count: u64, pub subscribers_count: u64, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubOwner { pub login: String, pub id: u64, pub node_id: String, pub avatar_url: String, pub gravatar_id: String, pub url: String, pub html_url: String, pub followers_url: String, pub following_url: String, pub gists_url: String, pub starred_url: String, pub subscriptions_url: String, pub organizations_url: String, pub repos_url: String, pub events_url: String, pub received_events_url: String, #[serde(rename = "type")] pub type_field: String, pub site_admin: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubLicense { pub key: String, pub name: String, pub spdx_id: String, pub url: String, pub node_id: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubOrganization { pub login: String, pub id: u64, pub node_id: String, pub avatar_url: String, pub gravatar_id: String, pub url: String, pub html_url: String, pub followers_url: String, pub following_url: String, pub gists_url: String, pub starred_url: String, pub subscriptions_url: String, pub organizations_url: String, pub repos_url: String, pub events_url: String, pub received_events_url: String, #[serde(rename = "type")] pub type_field: String, pub site_admin: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubTags { #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<Vec<GitHubTag>>, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubTag { pub name: String, pub commit: GitHubCommit, pub zipball_url: String, pub tarball_url: String, pub node_id: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct GitHubCommit { pub sha: String, pub url: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubBranches { #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<Vec<GitHubTag>>, } /// For all branches /// /repos/{owner}/{repo}/branches /// For specific branch /// /repos/{owner}/{repo}/branches/{branch} #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubBranch { pub name: String, pub commit: GitHubCommit, pub protected: bool, pub protection: GitHubProtection, protection_url: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubProtection { pub required_status_checks: GitHubRequiredStatusChecks, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubRequiredStatusChecks { pub enforcement_level: String, pub contexts: Vec<String>, } /// Path is optional /// get /repos/{owner}/{repo}/contents/{path} #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubContents { pub contents: Vec<GitHubContent>, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubContent { #[serde(rename = "type")] pub type_type: String, pub encoding: String, pub size: u64, pub name: String, pub path: String, pub content: String, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: String, #[serde(rename = "_links")] pub links: GitHubContentLinks, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubContentLinks { pub git: String, #[serde(rename = "self")] pub self_type: String, pub html: String, } /// /repos/{owner}/{repo}/releases #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubReleases { pub releases: Vec<GitHubRelease>, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubRelease { pub url: String, pub html_url: String, pub assets_url: String, pub upload_url: String, pub tarball_url: String, pub zipball_url: String, pub id: u64, pub node_id: String, pub tag_name: String, pub target_commitish: String, pub name: String, pub body: String, pub draft: bool, pub prerelease: bool, pub created_at: String, pub published_at: String, pub author: GitHubReleaseAuthor, pub assets: Vec<GitHubReleaseAssets>, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubReleaseAuthor { pub login: String, pub id: u64, pub node_id: String, pub avatar_url: String, pub gravatar_id: String, pub url: String, pub html_url: String, pub followers_url: String, pub following_url: String, pub gists_url: String, pub starred_url: String, pub subscriptions_url: String, pub organizations_url: String, pub repos_url: String, pub events_url: String, pub received_events_url: String, #[serde(rename = "type")] pub type_type: String, pub site_admin: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubReleaseAssets { pub url: String, pub browser_download_url: String, pub id: u64, pub node_id: String, pub name: String, pub label: String, pub state: String, pub content_type: String, pub size: u64, pub download_count: u64, pub created_at: String, pub updated_at: String, pub uploader: GitHubReleaseAssetsUploader, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GitHubReleaseAssetsUploader { pub login: String, pub id: u64, pub node_id: String, pub avatar_url: String, pub gravatar_id: String, pub url: String, pub html_url: String, pub followers_url: String, pub following_url: String, pub gists_url: String, pub starred_url: String, pub subscriptions_url: String, pub organizations_url: String, pub repos_url: String, pub events_url: String, pub received_events_url: String, #[serde(rename = "type")] pub type_type: String, pub site_admin: bool, } impl GitHubRepo { pub async fn get(github_owner_repo: &str) -> Result<GitHubRepo> { let owner_repo: Vec<&str> = github_owner_repo.split('/').collect(); let owner = owner_repo[0]; let repo = owner_repo[1]; let url = format!("https://api.github.com/repos/{}/{}", owner, repo); let response: GitHubRepo = reqwest::Client::new() .get(url) .header("Accept", "application/vnd.github.v3+json") .header("User-Agent", "nxpkgr") .send() .await? .json() .await?; Ok(response) } }
extern crate uarc_emu as ue; fn main() { }
use super::minimax::*; use super::alphabeta::*; use super::types::*; use crate::game::*; pub fn next_turn(game: &Game, ai_config: &AIConfig) -> AITurnRes { let start_time = instant::Instant::now(); let res = if ai_config.algorithm == Algorithm::AlphaBeta { alphabeta( &game, 0, -f32::INFINITY, f32::INFINITY, game.current_player(), ai_config ) } else { minimax( &game, 0, game.current_player(), ai_config ) }; AITurnRes { hole: res.best_move.unwrap(), thinking_time: start_time.elapsed().as_millis() as usize, nodes_visited: res.nodes_visited } }
use test_win32_class_factory::*; use windows::core::*; use Windows::Foundation::*; use Windows::Win32::Foundation::BOOL; use Windows::Win32::System::Com::IClassFactory; #[implement(Windows::Foundation::{IClosable, IStringable})] struct Object(); #[allow(non_snake_case)] impl Object { pub fn ToString(&self) -> Result<HSTRING> { Ok("Object".into()) } pub fn Close(&self) -> Result<()> { Ok(()) } } #[implement(Windows::Win32::System::Com::IClassFactory)] struct Factory(); #[allow(non_snake_case)] impl Factory { pub fn CreateInstance(&self, outer: &Option<IUnknown>, iid: *const GUID, object: *mut RawPtr) -> HRESULT { assert!(outer.is_none()); let unknown: IUnknown = Object().into(); unsafe { unknown.query(iid, object) } } pub fn LockServer(&self, lock: BOOL) -> Result<()> { assert!(lock.as_bool()); Ok(()) } } #[test] fn test() -> Result<()> { unsafe { let factory: IClassFactory = Factory().into(); factory.LockServer(true)?; let stringable: IStringable = factory.CreateInstance(None)?; assert!(stringable.ToString()? == "Object"); let closable: IClosable = factory.CreateInstance(None)?; closable.Close()?; Ok(()) } }
use serde::{Deserialize, Serialize}; use std; use std::fmt; use std::sync::Arc; use utils::*; use crate::ir; /// A fully specified size. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Size { factor: u32, params: Vec<Arc<ir::Parameter>>, max_val: u32, } impl Size { /// Create a new fully specified size. pub fn new(factor: u32, params: Vec<Arc<ir::Parameter>>, max_val: u32) -> Self { Size { factor, params, max_val, } } /// Creates a new constant size. pub fn new_const(factor: u32) -> Self { Size { factor, max_val: factor, ..Size::default() } } /// Creates a new size equal to a parameter. pub fn new_param(param: Arc<ir::Parameter>, max_val: u32) -> Size { Size { params: vec![param], max_val, ..Size::default() } } /// Returns the size if it is a constant. pub fn as_constant(&self) -> Option<u32> { if self.params.is_empty() { Some(self.factor) } else { None } } /// Returns the maximum value the size can take. pub fn max(&self) -> u32 { self.max_val } } impl Default for Size { fn default() -> Self { Size { factor: 1, params: Vec::new(), max_val: 1, } } } impl fmt::Display for Size { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut params = self.params.iter(); if self.factor != 1 { write!(fmt, "{}", self.factor)?; } else if let Some(param) = params.next() { write!(fmt, "{}", param)?; } for param in params { write!(fmt, "*{}", param.name)?; } if !self.params.is_empty() { write!(fmt, " [<= {}]", self.max_val)?; } Ok(()) } } impl<T> std::ops::MulAssign<T> for Size where T: std::borrow::Borrow<Size>, { fn mul_assign(&mut self, rhs: T) { let rhs = rhs.borrow(); self.factor *= rhs.factor; self.params.extend(rhs.params.iter().cloned()); self.max_val = self.max_val.saturating_mul(rhs.max_val); } } /// A size whose exact value is not yet decided. The value of `size` is /// `product(size.factors())/product(size.divisors())`. #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)] pub struct PartialSize { static_factor: u32, param_factors: Vec<Arc<ir::Parameter>>, dim_factors: VecSet<ir::DimId>, divisors: VecSet<ir::DimId>, } impl PartialSize { /// Creates a new 'PartialSize'. pub fn new(factor: u32, params: Vec<Arc<ir::Parameter>>) -> Self { assert!(factor != 0); PartialSize { static_factor: factor, param_factors: params, ..Self::default() } } /// Creates a new `PartialSize` equals to the size of a dimension. pub fn new_dim_size(dim: ir::DimId) -> Self { PartialSize { dim_factors: VecSet::new(vec![dim]), ..Self::default() } } /// Add divisors to the size. pub fn add_divisors(&mut self, divisors: &VecSet<ir::DimId>) { self.divisors = self.divisors.union(divisors); self.simplify(); } /// Returns the size of a dimension if it is staticaly known. pub fn as_int(&self) -> Option<u32> { let no_params = self.param_factors.is_empty(); if no_params && self.dim_factors.is_empty() && self.divisors.is_empty() { Some(self.static_factor) } else { None } } /// Simplifies the fraction factor/divisor. fn simplify(&mut self) { let dim_factors = std::mem::replace(&mut self.dim_factors, VecSet::default()); let divisors = std::mem::replace(&mut self.divisors, VecSet::default()); let (new_dim_factors, new_divisors) = dim_factors.relative_difference(divisors); self.dim_factors = new_dim_factors; self.divisors = new_divisors; } /// Returns the factors composing the size. pub fn factors(&self) -> (u32, &[Arc<ir::Parameter>], &[ir::DimId]) { (self.static_factor, &self.param_factors, &self.dim_factors) } /// Returns the divisors composing the size. pub fn divisors(&self) -> &[ir::DimId] { &self.divisors } } impl Default for PartialSize { fn default() -> Self { PartialSize { static_factor: 1, param_factors: Vec::new(), dim_factors: VecSet::default(), divisors: VecSet::default(), } } } impl fmt::Display for PartialSize { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use itertools::Itertools; if self.static_factor != 1 { write!(fmt, "{}", self.static_factor)?; if !self.param_factors.is_empty() || !self.dim_factors.is_empty() { write!(fmt, "*")?; } } write!( fmt, "{}", self.param_factors .iter() .map(|p| p.name.clone()) .chain(self.dim_factors.iter().map(|d| format!("{:?}", d))) .format("*") )?; if !self.divisors.is_empty() { write!( fmt, "/{}", self.divisors .iter() .map(|d| format!("{:?}", *d)) .format("/") )?; } Ok(()) } } impl<'a> std::ops::MulAssign<&'a PartialSize> for PartialSize { fn mul_assign(&mut self, rhs: &'a PartialSize) { self.static_factor *= rhs.static_factor; self.param_factors.extend(rhs.param_factors.iter().cloned()); self.dim_factors = self.dim_factors.union(&rhs.dim_factors); self.divisors = self.divisors.union(&rhs.divisors); self.simplify(); } } impl<'a> std::ops::Mul<&'a PartialSize> for PartialSize { type Output = Self; fn mul(mut self, rhs: &PartialSize) -> Self { self *= rhs; self } } impl<'a> std::iter::Product<&'a PartialSize> for PartialSize { fn product<I>(iter: I) -> Self where I: Iterator<Item = &'a PartialSize>, { let mut static_factor = 1; let mut param_factors = vec![]; let mut dim_factors = vec![]; let mut divisors = vec![]; for s in iter { static_factor *= s.static_factor; param_factors.extend(s.param_factors.iter().cloned()); dim_factors.extend(s.dim_factors.iter().cloned()); divisors.extend(s.divisors.iter().cloned()); } let dim_factors = VecSet::new(dim_factors); let divisors = VecSet::new(divisors); let mut total = PartialSize { static_factor, param_factors, dim_factors, divisors, }; total.simplify(); total } } impl From<Size> for PartialSize { fn from(size: Size) -> PartialSize { PartialSize::new(size.factor, size.params) } }
use alloc::{string::String, sync::Arc, vec::Vec}; use core::sync::atomic::AtomicBool; use serde::Deserialize; use crate::{ commands::{Command, RunnableContext}, context::CommandRegistry, error::ShellError, evaluate::{CallInfo, Value}, parser::syntax_shape::SyntaxShape, shell::Shell, signature::Signature, }; #[derive(Deserialize)] pub struct CdArgs { pub dst: Option<String>, } pub struct Cd; impl Command for Cd { fn name(&self) -> &str { "cd" } fn signature(&self) -> Signature { Signature::build(self.name()) .optional( "destination", SyntaxShape::Path, "the directory to change to", ) .desc(self.usage()) } fn usage(&self) -> &str { "Change to a new path." } fn run( &self, call_info: CallInfo, input: Option<Vec<Value>>, ctrl_c: Arc<AtomicBool>, shell: Arc<dyn Shell>, _registry: &CommandRegistry, ) -> Result<Option<Vec<Value>>, ShellError> { call_info.process(&shell, ctrl_c, cd, input)?.run() } } fn cd(args: CdArgs, ctx: &RunnableContext) -> Result<Option<Vec<Value>>, ShellError> { ctx.shell.cd(args) }
use cast::i8; use encoding::{all::WINDOWS_1252, DecoderTrap, Encoding as _}; use enum_ordinalize::Ordinalize; use raw_seeders::{Literal, LittleEndian, SerdeLike}; use serde::{de, ser}; use serde_seeded::{seed, seeded}; use std::{borrow::Cow, fmt::Display, marker::PhantomData}; #[derive(Debug, seed, seeded)] pub struct Header { #[seeded(Literal(b"ARC\0"))] magic: (), #[seeded(LittleEndian)] version: u32, #[seeded(LittleEndian)] pub asset_count: u32, #[seeded(LittleEndian)] pub part_count: u32, #[seeded(SerdeLike)] unknown: [u8; 8], #[seeded(LittleEndian)] pub part_info_offset: u32, } impl Header { pub fn string_offset(&self) -> u32 { self.part_info_offset + self.part_count * PartInfo::SIZE as u32 } pub fn asset_info_offset_from_end(&self) -> u32 { self.asset_count * AssetInfo::SIZE as u32 } } #[derive(seed, seeded)] pub struct PartInfo { #[seeded(LittleEndian)] pub offset: u32, #[seeded(LittleEndian)] pub compressed_length: u32, #[seeded(LittleEndian)] pub data_length: u32, } impl PartInfo { pub const SIZE: usize = 12; } #[derive(seed, seeded)] pub struct AssetInfo { #[seeded] pub storage: Storage, //u32 #[seeded(LittleEndian)] pub offset: u32, #[seeded(LittleEndian)] pub compressed_length: u32, #[seeded(LittleEndian)] pub asset_length: u32, #[seeded(SerdeLike)] unknown: [u8; 12], #[seeded(LittleEndian)] pub part_count: u32, #[seeded(LittleEndian)] pub first_part: u32, #[seeded(LittleEndian)] pub name_length: u32, #[seeded(LittleEndian)] pub name_offset: u32, } impl AssetInfo { pub const SIZE: usize = 44; } #[derive(Clone, Copy, Ordinalize)] pub enum Storage { TODODeleted = 0, Uncompressed = 1, Compressed = 3, } impl Storage { fn seed<'de>() -> impl de::DeserializeSeed<'de, Value = Self> { struct Seed; impl<'de> de::DeserializeSeed<'de> for Seed { type Value = Storage; fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { let value = u32::from_le_bytes(PhantomData.deserialize(deserializer)?); let value = i8(value).map_err(de::Error::custom)?; let value = Storage::from_ordinal(value).ok_or_else(|| { de::Error::invalid_value( de::Unexpected::Signed(value as i64), &"a Storage value", ) })?; Ok(value) } } Seed } fn seeded(&self) -> impl ser::Serialize { (self.ordinal() as u32).to_le_bytes() } } pub fn cp1252<'a>(data: Cow<'a, [u8]>) -> Result<Cow<'a, str>, Box<dyn Display>> { Ok(WINDOWS_1252 .decode(data.as_ref(), DecoderTrap::Strict) .map_err(|e| Box::new(e) as _)? .into()) }
//! https://docs.microsoft.com/en-us/windows/desktop/power/battery-information-str #![allow(non_snake_case, clippy::unreadable_literal)] use std::default::Default; use std::mem; use std::ops; use std::str::{self, FromStr}; use crate::Technology; use winapi::shared::ntdef; pub const BATTERY_CAPACITY_RELATIVE: ntdef::ULONG = 0x40000000; pub const BATTERY_SYSTEM_BATTERY: ntdef::ULONG = 0x80000000; STRUCT! {#[cfg_attr(target_arch = "x86", repr(packed))] #[derive(Debug)] struct BATTERY_INFORMATION { Capabilities: ntdef::ULONG, Technology: ntdef::UCHAR, Reserved: [ntdef::UCHAR; 3], Chemistry: [ntdef::UCHAR; 4], DesignedCapacity: ntdef::ULONG, // mWh FullChargedCapacity: ntdef::ULONG, // mWh DefaultAlert1: ntdef::ULONG, DefaultAlert2: ntdef::ULONG, CriticalBias: ntdef::ULONG, CycleCount: ntdef::ULONG, }} impl Default for BATTERY_INFORMATION { #[inline] fn default() -> Self { unsafe { mem::zeroed() } } } #[derive(Debug)] pub struct BatteryInformation(BATTERY_INFORMATION); impl Default for BatteryInformation { fn default() -> Self { BatteryInformation(BATTERY_INFORMATION::default()) } } impl ops::Deref for BatteryInformation { type Target = BATTERY_INFORMATION; fn deref(&self) -> &Self::Target { &self.0 } } impl ops::DerefMut for BatteryInformation { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl BatteryInformation { #[inline] pub fn is_system_battery(&self) -> bool { (self.0.Capabilities & BATTERY_SYSTEM_BATTERY) != 0 } #[inline] pub fn is_relative(&self) -> bool { (self.0.Capabilities & BATTERY_CAPACITY_RELATIVE) != 0 } pub fn technology(&self) -> Technology { let raw = unsafe { str::from_utf8_unchecked(&self.0.Chemistry) }; match Technology::from_str(raw) { Ok(tech) => tech, Err(_) => Technology::Unknown, } } // Originally `mWh`, matches `Battery::energy_full_design` result #[inline] pub fn designed_capacity(&self) -> u32 { self.0.DesignedCapacity } // Originally `mWh`, matches `Battery::energy_full` result #[inline] pub fn full_charged_capacity(&self) -> u32 { self.0.FullChargedCapacity } pub fn cycle_count(&self) -> Option<u32> { if self.0.CycleCount == 0 { None } else { Some(self.0.CycleCount) } } }
use std::fmt; use super::TimeFormatter; use num_bigint::BigInt; #[derive(Debug)] pub struct SolverResult { pub result: BigInt, pub time_taken: u64, } impl fmt::Display for SolverResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {}", self.result, self.time_taken.format_as_time()) } } impl From<String> for SolverResult { fn from(s: String) -> Self { let parts = s .split_ascii_whitespace() .map(std::string::ToString::to_string) .collect::<Vec<String>>(); assert_eq!(parts.len(), 2); let result = parts[0] .parse::<BigInt>() .expect("could not parse BigUint"); let time_taken = parts[1].parse::<u64>().expect("could not parse u64"); Self { result, time_taken, } } } impl From<&str> for SolverResult { fn from(s: &str) -> Self { SolverResult::from(String::from(s)) } } impl From<Vec<u8>> for SolverResult { fn from(s: Vec<u8>) -> Self { SolverResult::from(String::from_utf8_lossy(s.as_slice()).to_string()) } }
use std::thread; use std::time::Duration; use std::sync::mpsc; fn main() { // thread1(); // thread2(); // thread3(); // thread4(); // thread5(); // thread6(); // thread7(); // thread8(); dead_lock(); } fn thread1() { // This thread gets killed when the main thread exits thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } } fn thread2() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } // This forces the parent thread to wait for the child thread to finish handle.join().unwrap(); } fn thread3() { let v = vec![1, 2, 3]; // To share data between threads, we use `move` to give ownership of the variable to the thread. let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); // But v is not accessible anymore here. handle.join().unwrap(); } fn thread4() { // Alternatively threads can communicate via messages. let (tx, rx) = mpsc::channel(); // The thread gets ownership of the transmitter thread::spawn(move || { let val = String::from("hi"); // send returns a Result tx.send(val).unwrap(); // We can not access val after sending it }); // Here we receive messages let received = rx.recv().unwrap(); println!("Got: {}", received); /* recv blocks and waits for a message, it returns a Result as well. An error in thrown if the channel closes without getting a message. try_recv does not block, it returns a Result instantly telling us if there has been a message or an error if there is no error. */ } fn thread5() { let (tx, rx) = mpsc::channel(); // We can send multiple messages thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("thread"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } // MPSC means Multiple Producers Single Consumer, meaning we can have multiple senders but just one receiver. fn thread6() { let (tx, rx) = mpsc::channel(); // We can clone the transmitter to send data from multiple places let tx1 = mpsc::Sender::clone(&tx); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("thread"), ]; for val in vals { tx1.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); thread::spawn(move || { let vals = vec![ String::from("more"), String::from("messages"), String::from("for"), String::from("you"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } // Alternatively we can also share a state between threads and use Mutexes. use std::sync::Mutex; fn thread7() { let m = Mutex::new(5); { // lock blocks the thread until it can acquire the mutex let mut num = m.lock().unwrap(); // Then the value can be modified *num = 6; } println!("m = {:?}", m); // When the mutex goes out of scope, the data it contains gets freed } // When we have multiple threads we can give ownership of an object too all of them. We need to use Arc that is atomic and thread-safe but slower than Rc. use std::sync::Arc; fn thread8() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } /* Any object implementing the trait Send can gets its ownership transfered to a thread. Any object implementing the trait Sync can be accessed in threads. If an object has only properties that implement those 2 traits, the object itself implements automatically those 2 traits. */
/// /// Holds GUI widgets /// use std::collections::HashMap; use gtk; use gui; pub struct ComponentStore<'a> { components: HashMap<String, Box<gtk::WidgetTrait + 'a>>, } impl <'a>ComponentStore<'a> { pub fn new() -> ComponentStore<'a> { ComponentStore { components: HashMap::new() } } } impl gui::ComponentStoreTrait for ComponentStore { fn add_component(&mut self, name: String, component: Box<gtk::WidgetTrait>) -> () { self.components.insert(name, component); } fn remove_component(&mut self, name: &String) -> () { self.components.remove(name); } fn get_component(&self, name: &String) -> Option<&Box<gtk::WidgetTrait>> { self.components.get(name) } }
#[macro_use] pub mod tree; pub use self::canonize::Canonizer; pub use self::trace::Tracer; pub use self::translate::Translator; mod canonize; mod trace; mod translate; #[cfg(test)] mod tests;
#[macro_use] extern crate scan_fmt; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let filename = "src/input.txt"; let file = File::open(filename).unwrap(); let reader = BufReader::new(file); let mut fabric = HashMap::new(); let mut all_claim_ids = vec![]; for line in reader.lines() { match line { Ok(str) => { let (claim_id, left_offset, top_offset, width, height) = convert_line_to_variables(str); let plots = dimensions_to_plots(left_offset, top_offset, width, height); all_claim_ids.push(claim_id); for plot in plots.iter() { if !fabric.contains_key(&plot.to_string()) { fabric.insert(plot.to_string(), vec![claim_id]); } else { let claims = fabric.get(plot); match claims { Some(c) => { let mut claim = c.clone(); claim.push(claim_id); fabric.insert(plot.to_string(), claim); } None => println!("Ooops"), } } } } Err(e) => println!("Could not convert line: {}", e), } } let mut count = 0; for val in fabric.values() { if val.len() > 1 { count += 1; for claim in val.iter() { all_claim_ids.iter() .position(|&n| n == *claim) .map(|e| all_claim_ids.remove(e)) .is_some(); } } } println!("How many square inches of fabric are within two or more claims: {}", count); println!("What is the ID of the only claim that doesn't overlap: {:?}", all_claim_ids); } fn convert_line_to_variables(str: String) -> (u16, u16, u16, u16, u16) { // #1 @ 483,830: 24x18 let (claim_id, left_offset, top_offset, width, height) = scan_fmt!(&str, "#{} @ {},{}: {}x{}", u16, u16, u16, u16, u16); return ( claim_id.unwrap(), left_offset.unwrap(), top_offset.unwrap(), width.unwrap(), height.unwrap(), ); } fn dimensions_to_plots(left_offset: u16, top_offset: u16, width: u16, height: u16) -> Vec<String> { let mut plots = vec![]; for x in left_offset..(left_offset + width) { for y in top_offset..(top_offset + height) { plots.push(format!("{}x{}", x, y)); } } return plots; } #[cfg(test)] mod tests { use super::*; #[test] fn test_convert_line_to_variables() { assert_eq!(convert_line_to_variables(String::from("#1 @ 483,830: 24x18")), (1, 483, 830, 24, 18)); } #[test] fn test_dimensions_to_plots() { assert_eq!(dimensions_to_plots(0, 0, 1, 2), vec!(String::from("0x0"), String::from("0x1"))); } }
use std::rc::Rc; use std::sync::Arc; use futures::{Future, IntoFuture, Poll}; pub use void::Void; mod and_then; mod and_then_apply; mod and_then_apply_fn; mod apply; mod apply_cfg; pub mod blank; pub mod boxed; mod cell; mod fn_service; mod fn_transform; mod from_err; mod map; mod map_err; mod map_init_err; mod then; mod transform; mod transform_map_init_err; pub use self::and_then::{AndThen, AndThenNewService}; use self::and_then_apply::AndThenTransform; use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService}; pub use self::apply::{Apply, ApplyNewService}; pub use self::apply_cfg::ApplyConfig; pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService}; pub use self::fn_transform::FnTransform; pub use self::from_err::{FromErr, FromErrNewService}; pub use self::map::{Map, MapNewService}; pub use self::map_err::{MapErr, MapErrNewService}; pub use self::map_init_err::MapInitErr; pub use self::then::{Then, ThenNewService}; pub use self::transform::{ApplyTransform, IntoTransform, Transform}; /// An asynchronous function from `Request` to a `Response`. pub trait Service { /// Requests handled by the service. type Request; /// Responses given by the service. type Response; /// Errors produced by the service. type Error; /// The future response value. type Future: Future<Item = Self::Response, Error = Self::Error>; /// Returns `Ready` when the service is able to process requests. /// /// If the service is at capacity, then `NotReady` is returned and the task /// is notified when the service becomes ready again. This function is /// expected to be called while on a task. /// /// This is a **best effort** implementation. False positives are permitted. /// It is permitted for the service to return `Ready` from a `poll_ready` /// call and the next invocation of `call` results in an error. fn poll_ready(&mut self) -> Poll<(), Self::Error>; /// Process the request and return the response asynchronously. /// /// This function is expected to be callable off task. As such, /// implementations should take care to not call `poll_ready`. If the /// service is at capacity and the request is unable to be handled, the /// returned `Future` should resolve to an error. /// /// Calling `call` without calling `poll_ready` is permitted. The /// implementation must be resilient to this fact. fn call(&mut self, req: Self::Request) -> Self::Future; } /// An extension trait for `Service`s that provides a variety of convenient /// adapters pub trait ServiceExt: Service { /// Apply function to specified service and use it as a next service in /// chain. fn apply_fn<F, B, B1, Out>(self, service: B1, f: F) -> AndThenApply<Self, B, F, Out> where Self: Sized, F: FnMut(Self::Response, &mut B) -> Out, Out: IntoFuture, Out::Error: Into<Self::Error>, B: Service<Error = Self::Error>, B1: IntoService<B>, { AndThenApply::new(self, service, f) } /// Call another service after call to this one has resolved successfully. /// /// This function can be used to chain two services together and ensure that /// the second service isn't called until call to the fist service have /// finished. Result of the call to the first service is used as an /// input parameter for the second service's call. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it. fn and_then<F, B>(self, service: F) -> AndThen<Self, B> where Self: Sized, F: IntoService<B>, B: Service<Request = Self::Response, Error = Self::Error>, { AndThen::new(self, service.into_service()) } /// Map this service's error to any error implementing `From` for /// this service`s `Error`. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it. fn from_err<E>(self) -> FromErr<Self, E> where Self: Sized, E: From<Self::Error>, { FromErr::new(self) } /// Chain on a computation for when a call to the service finished, /// passing the result of the call to the next service `B`. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it. fn then<B>(self, service: B) -> Then<Self, B> where Self: Sized, B: Service<Request = Result<Self::Response, Self::Error>, Error = Self::Error>, { Then::new(self, service) } /// Map this service's output to a different type, returning a new service /// of the resulting type. /// /// This function is similar to the `Option::map` or `Iterator::map` where /// it will change the type of the underlying service. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it, similar to the existing `map` methods in the /// standard library. fn map<F, R>(self, f: F) -> Map<Self, F, R> where Self: Sized, F: FnMut(Self::Response) -> R, { Map::new(self, f) } /// Map this service's error to a different error, returning a new service. /// /// This function is similar to the `Result::map_err` where it will change /// the error type of the underlying service. This is useful for example to /// ensure that services have the same error type. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it. fn map_err<F, E>(self, f: F) -> MapErr<Self, F, E> where Self: Sized, F: Fn(Self::Error) -> E, { MapErr::new(self, f) } } impl<T: ?Sized> ServiceExt for T where T: Service {} /// Creates new `Service` values. /// /// Acts as a service factory. This is useful for cases where new `Service` /// values must be produced. One case is a TCP servier listener. The listner /// accepts new TCP streams, obtains a new `Service` value using the /// `NewService` trait, and uses that new `Service` value to process inbound /// requests on that new TCP stream. /// /// `Config` is a service factory configuration type. pub trait NewService<Config = ()> { /// Requests handled by the service. type Request; /// Responses given by the service type Response; /// Errors produced by the service type Error; /// The `Service` value created by this factory type Service: Service< Request = Self::Request, Response = Self::Response, Error = Self::Error, >; /// Errors produced while building a service. type InitError; /// The future of the `Service` instance. type Future: Future<Item = Self::Service, Error = Self::InitError>; /// Create and return a new service value asynchronously. fn new_service(&self, cfg: &Config) -> Self::Future; /// Apply transform service to specified service and use it as a next service in /// chain. fn apply<T, T1, B, B1>( self, transform: T1, service: B1, ) -> AndThenTransform<T, Self, B, Config> where Self: Sized, T: Transform<B::Service, Request = Self::Response, InitError = Self::InitError>, T::Error: From<Self::Error>, T1: IntoTransform<T, B::Service>, B: NewService<Config, InitError = Self::InitError>, B1: IntoNewService<B, Config>, { AndThenTransform::new(transform.into_transform(), self, service.into_new_service()) } /// Apply function to specified service and use it as a next service in /// chain. fn apply_fn<B, I, F, Out>( self, service: I, f: F, ) -> AndThenApplyNewService<Self, B, F, Out, Config> where Self: Sized, B: NewService<Config, Error = Self::Error, InitError = Self::InitError>, I: IntoNewService<B, Config>, F: FnMut(Self::Response, &mut B::Service) -> Out, Out: IntoFuture, Out::Error: Into<Self::Error>, { AndThenApplyNewService::new(self, service, f) } /// Map this service's config type to a different config, /// and use for nested service fn apply_cfg<F, C, B, B1>(self, service: B1, f: F) -> ApplyConfig<F, Self, B, Config, C> where Self: Sized, F: Fn(&Config) -> C, B1: IntoNewService<B, C>, B: NewService< C, Request = Self::Response, Error = Self::Error, InitError = Self::InitError, >, { ApplyConfig::new(self, service, f) } /// Call another service after call to this one has resolved successfully. fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B, Config> where Self: Sized, F: IntoNewService<B, Config>, B: NewService< Config, Request = Self::Response, Error = Self::Error, InitError = Self::InitError, >, { AndThenNewService::new(self, new_service) } /// `NewService` that create service to map this service's error /// and new service's init error to any error /// implementing `From` for this service`s `Error`. /// /// Note that this function consumes the receiving new service and returns a /// wrapped version of it. fn from_err<E>(self) -> FromErrNewService<Self, E, Config> where Self: Sized, E: From<Self::Error>, { FromErrNewService::new(self) } /// Create `NewService` to chain on a computation for when a call to the /// service finished, passing the result of the call to the next /// service `B`. /// /// Note that this function consumes the receiving future and returns a /// wrapped version of it. fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B, Config> where Self: Sized, F: IntoNewService<B, Config>, B: NewService< Config, Request = Result<Self::Response, Self::Error>, Error = Self::Error, InitError = Self::InitError, >, { ThenNewService::new(self, new_service) } /// Map this service's output to a different type, returning a new service /// of the resulting type. fn map<F, R>(self, f: F) -> MapNewService<Self, F, R, Config> where Self: Sized, F: FnMut(Self::Response) -> R, { MapNewService::new(self, f) } /// Map this service's error to a different error, returning a new service. fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E, Config> where Self: Sized, F: Fn(Self::Error) -> E, { MapErrNewService::new(self, f) } /// Map this service's init error to a different error, returning a new service. fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E, Config> where Self: Sized, F: Fn(Self::InitError) -> E, { MapInitErr::new(self, f) } } impl<'a, S> Service for &'a mut S where S: Service + 'a, { type Request = S::Request; type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&mut self) -> Poll<(), S::Error> { (**self).poll_ready() } fn call(&mut self, request: Self::Request) -> S::Future { (**self).call(request) } } impl<S> Service for Box<S> where S: Service + ?Sized, { type Request = S::Request; type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&mut self) -> Poll<(), S::Error> { (**self).poll_ready() } fn call(&mut self, request: Self::Request) -> S::Future { (**self).call(request) } } impl<S, C> NewService<C> for Rc<S> where S: NewService<C>, { type Request = S::Request; type Response = S::Response; type Error = S::Error; type Service = S::Service; type InitError = S::InitError; type Future = S::Future; fn new_service(&self, cfg: &C) -> S::Future { self.as_ref().new_service(cfg) } } impl<S, C> NewService<C> for Arc<S> where S: NewService<C>, { type Request = S::Request; type Response = S::Response; type Error = S::Error; type Service = S::Service; type InitError = S::InitError; type Future = S::Future; fn new_service(&self, cfg: &C) -> S::Future { self.as_ref().new_service(cfg) } } /// Trait for types that can be converted to a `Service` pub trait IntoService<T> where T: Service, { /// Convert to a `Service` fn into_service(self) -> T; } /// Trait for types that can be converted to a `NewService` pub trait IntoNewService<T, C = ()> where T: NewService<C>, { /// Convert to an `NewService` fn into_new_service(self) -> T; } impl<T> IntoService<T> for T where T: Service, { fn into_service(self) -> T { self } } impl<T, C> IntoNewService<T, C> for T where T: NewService<C>, { fn into_new_service(self) -> T { self } } /// Trait for types that can be converted to a configurable `NewService` pub trait IntoConfigurableNewService<T, C> where T: NewService<C>, { /// Convert to an `NewService` fn into_new_service(self) -> T; } impl<T, C> IntoConfigurableNewService<T, C> for T where T: NewService<C>, { fn into_new_service(self) -> T { self } }