text
stringlengths
8
4.13M
use crate::{ backend::Backend, examples::data::ExampleData, utils::{shell_quote, shell_single_quote}, }; use drogue_cloud_service_api::endpoints::Endpoints; use patternfly_yew::*; use serde_json::json; use yew::prelude::*; #[derive(Clone, Debug, Properties, PartialEq, Eq)] pub struct Props { pub endpoints: Endpoints, pub data: ExampleData, } pub struct RegisterDevices { props: Props, } impl Component for RegisterDevices { type Message = (); type Properties = Props; fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _msg: Self::Message) -> ShouldRender { false } fn change(&mut self, props: Self::Properties) -> ShouldRender { if self.props != props { self.props = props; true } else { false } } fn view(&self) -> Html { let mut cards: Vec<_> = vec![html! { <Alert title="Requirements" r#type=Type::Info inline=true > <Content> <p> {"The following examples assume that you have the "} <a href="https://github.com/drogue-iot/drg" target="_blank">{"Drogue Command Line Client"}</a>{", "} <a href="https://httpie.io" target="_blank">{"HTTPie"}</a> {", and the "} <a href="https://hivemq.github.io/hivemq-mqtt-client/" target="_blank">{"MQTT client"}</a> {" installed. The commands are also expected to be executed in a Bash like shell."} </p> <p>{r#"Of course, it is possible to use another shell or HTTP/MQTT client with Drogue IoT. We simply wanted to keep the examples simple."#}</p> </Content> </Alert> }]; if let Some(api) = Backend::url("") { let login_cmd = format!(r#"drg login {url}"#, url = shell_quote(api)); cards.push(html!{ <Card title=html!{"Log in"}> <div> {"Log in to the backend. This will ask you to open the login URL in the browser, in order to follow the OpenID Connect login flow."} </div> <Clipboard code=true readonly=true variant=ClipboardVariant::Expandable value=login_cmd/> </Card> }); } let create_app_cmd = format!(r#"drg create app {name}"#, name = self.props.data.app_id); let create_device_cmd = format!( r#"drg create device --app {app} {device} --data {spec}"#, app = self.props.data.app_id, device = shell_quote(&self.props.data.device_id), spec = shell_single_quote(json!({"credentials": {"credentials":[ {"pass": self.props.data.password}, ]}})), ); cards.push(html!{ <Card title={html!{"Create a new application"}}> <div> {"As a first step, you will need to create a new application."} </div> <Clipboard code=true readonly=true variant=ClipboardVariant::Expandable value=create_app_cmd/> </Card> }); cards.push(html!{ <Card title={html!{"Create a new device"}}> <div> {"As part of your application, you can then create a new device."} </div> <Clipboard code=true readonly=true variant=ClipboardVariant::Expandable value=create_device_cmd/> </Card> }); cards .iter() .map(|card| { html! {<StackItem> { card.clone() } </StackItem>} }) .collect() } }
// data.rs provides structs and enums to represent data recived from clients as we store it before // usage. use crate::server::network::packet; #[derive(Clone, Eq, PartialEq, Debug)] /// The WebSocket server's state and storage pub struct ServerData { /// represents the highest unique ID handed out by the server. usid: usize, /// represents all the received data and packets to the server. pub packets: PacketList, /// represents all the client connections connected_ips: Vec<ws::Sender>, /// reperesents the current login password for the admin portal pub admin_pass: usize, /// represents a long token to confirm admin identitiy pub token: String, } impl ServerData { /// Creates a new ServerData pub fn new() -> ServerData { let mut a = ServerData { usid: 0, packets: PacketList::new(), connected_ips: vec![], admin_pass: 2239, token: String::from("NOTOKEN"), }; a.gen_token(); return a; } pub fn gen_token(&mut self) -> String { let mut rng = rand::thread_rng(); use rand::Rng; let a: u128 = rng.gen(); let b: u128 = rng.gen(); let c: u128 = rng.gen(); self.token = format!("{:X}{:X}{:X}", a, b, c); return self.token.clone(); } /// Gets a unique USID (User Session IDentification) and increments the interal USID counter pub fn get_next_usid(&mut self) -> usize { self.usid += 1; return self.usid; } /// Adds a new connection to the list of active connections pub fn new_connection(&mut self, connection: ws::Sender) { self.connected_ips.push(connection); } /// Gives amount of connections in the list of active connections pub fn amount_connected(self) -> usize { return self.connected_ips.len(); } /// Removes a connection from the list of active connections by index pub fn remove_connection(&mut self, index: usize) { self.connected_ips.remove(index); } /// Gets a clone of all connections pub fn get_connections(self) -> Vec<ws::Sender> { return self.connected_ips.clone(); } } #[derive(Clone, Eq, PartialEq, Debug)] pub struct PacketList { pub pings: Vec<WrappedPacket>, pub general: Vec<WrappedPacket>, pub game: Vec<WrappedPacket>, } impl PacketList { pub fn new() -> PacketList { PacketList { pings: vec![], general: vec![], game: vec![] } } pub fn get_pings_after(self, after: std::time::SystemTime) -> Vec<WrappedPacket> { let mut qualifying_packets = vec![]; for i in self.pings { if i.time > after { qualifying_packets.push(i.clone()); } } return qualifying_packets; } } #[derive(Clone, Eq, PartialEq, Debug)] pub struct WrappedPacket { pub packet: packet::Packet, pub time: std::time::SystemTime, pub usid: Option<usize>, pub game: Option<usize>, pub team: Option<usize>, } impl WrappedPacket { pub fn new_from_packet(packet: packet::Packet) -> WrappedPacket { WrappedPacket { packet: packet.clone(), time: std::time::SystemTime::now(), usid: packet.get_usid(), game: None, team: None } } pub fn new_with_team(packet: packet::Packet, game: usize, team: usize) -> WrappedPacket { WrappedPacket { packet: packet.clone(), time: std::time::SystemTime::now(), usid: packet.get_usid(), game: Some(game), team: Some(team) } } }
#[derive(Debug)] pub enum OpCode { OpReturn } pub struct Chunk { pub code: Vec<OpCode> } impl Chunk { pub fn new() -> Self { Chunk { code: Vec::new() } } }
fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=libarm_cortexM4lf_math.a"); // Link against prebuilt cmsis math println!( "cargo:rustc-link-search={}", std::env::var("CARGO_MANIFEST_DIR").unwrap() ); println!("cargo:rustc-link-lib=static=arm_cortexM4lf_math"); }
fn main() { let compiler_knows_this_is_initialized; let mut x = 1u8; loop { if x > std::rand::random() { compiler_knows_this_is_initialized = x; break; } x += 1; } println!("{:?}", compiler_knows_this_is_initialized); goto(); } // Normally Rust won't let you access a variable that it isn't sure was initialized. For example: // fn main() { // let mut foo: uint; // if 1 > std::rand::random() { // foo = 1; // } // println!("{}", foo); // } // won't compile, because the compiler can't be sure that the foo variable is always initialized before use. // In the example, however, the compiler is smart enough to deduce that the variable is always initialized, because it is set just before the only break statement on the loop. This shows incredible amount of polish, I wouldn't have bet on it compiling. fn goto() { // 'lifetime : for i in 1..10 { 'lifetime2 : for j in 1..10 { let s = format!("({}, {}) ", i, j); print!("{}", s); if i % 2 == 0 { break 'lifetime; } } } }
use oxygengine::prelude::*; #[allow(dead_code)] #[derive(Debug, Copy, Clone)] pub enum FollowMode { Instant, Delayed(Scalar), } #[derive(Debug, Copy, Clone)] pub struct Follow(pub Option<Entity>, pub FollowMode); impl Component for Follow { type Storage = VecStorage<Self>; }
use amethyst::{ //assets::{ AssetStorage, Loader, Handle }, //core::transform::Transform, ecs::{ Component, DenseVecStorage }, //prelude::*, //renderer::{ Camera, ImageFormat, SpriteRender, SpriteSheet, SpriteSheetFormat, Texture } }; pub const VELOCITY_X : f32 = 75.0; pub const VELOCITY_Y : f32 = 50.0; pub const RADIUS : f32 = 2.0; pub struct Ball { pub velocity: [ f32; 2 ], pub radius: f32, } impl Component for Ball { type Storage = DenseVecStorage< Self >; }
use http::{is_valid_url, resolve_url, retrieve_asset}; use std::default::Default; use std::io; use html5ever::parse_document; use html5ever::rcdom::{Handle, NodeData, RcDom}; use html5ever::serialize::{serialize, SerializeOpts}; use html5ever::tendril::TendrilSink; enum NodeMatch { Icon, Image, StyleSheet, Anchor, Script, Form, Other, } const PNG_PIXEL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; const JS_DOM_EVENT_ATTRS: [&str; 21] = [ // Input "onfocus", "onblur", "onselect", "onchange", "onsubmit", "onreset", "onkeydown", "onkeypress", "onkeyup", // Mouse "onmouseover", "onmouseout", "onmousedown", "onmouseup", "onmousemove", // Click "onclick", "ondblclick", // Load "onload", "onunload", "onabort", "onerror", "onresize", ]; #[allow(clippy::cognitive_complexity)] pub fn walk_and_embed_assets(url: &str, node: &Handle, opt_no_js: bool, opt_no_images: bool) { match node.data { NodeData::Document => { // Dig deeper for child in node.children.borrow().iter() { walk_and_embed_assets(&url, child, opt_no_js, opt_no_images); } } NodeData::Doctype { .. } => {} NodeData::Text { .. } => {} NodeData::Comment { .. } => { // Note: in case of opt_no_js being set to true, there's no need to worry about // getting rid of comments that may contain scripts, e.g. <!--[if IE]><script>... // since that's not part of W3C standard and gets ignored by browsers other than IE [5, 9] } NodeData::Element { ref name, ref attrs, .. } => { let attrs_mut = &mut attrs.borrow_mut(); let mut found = NodeMatch::Other; if &name.local == "link" { for attr in attrs_mut.iter_mut() { if &attr.name.local == "rel" { if is_icon(&attr.value.to_string()) { found = NodeMatch::Icon; break; } else if attr.value.to_string() == "stylesheet" { found = NodeMatch::StyleSheet; break; } } } } else if &name.local == "img" { found = NodeMatch::Image; } else if &name.local == "a" { found = NodeMatch::Anchor; } else if &name.local == "script" { found = NodeMatch::Script; } else if &name.local == "form" { found = NodeMatch::Form; } match found { NodeMatch::Icon => { for attr in attrs_mut.iter_mut() { if &attr.name.local == "href" { let href_full_url = resolve_url(&url, &attr.value.to_string()); let favicon_datauri = retrieve_asset(&href_full_url.unwrap(), true, ""); attr.value.clear(); attr.value.push_slice(favicon_datauri.unwrap().as_str()); } } } NodeMatch::Image => { for attr in attrs_mut.iter_mut() { if &attr.name.local == "src" { if opt_no_images { attr.value.clear(); attr.value.push_slice(PNG_PIXEL); } else { let src_full_url = resolve_url(&url, &attr.value.to_string()); let img_datauri = retrieve_asset(&src_full_url.unwrap(), true, ""); attr.value.clear(); attr.value.push_slice(img_datauri.unwrap().as_str()); } } } } NodeMatch::Anchor => { for attr in attrs_mut.iter_mut() { if &attr.name.local == "href" { // Do not touch hrefs which begin with a hash sign if attr.value.to_string().chars().nth(0) == Some('#') { continue; } let href_full_url = resolve_url(&url, &attr.value.to_string()); attr.value.clear(); attr.value.push_slice(href_full_url.unwrap().as_str()); } } } NodeMatch::StyleSheet => { for attr in attrs_mut.iter_mut() { if &attr.name.local == "href" { let href_full_url = resolve_url(&url, &attr.value.to_string()); let css_datauri = retrieve_asset(&href_full_url.unwrap(), true, "text/css"); attr.value.clear(); attr.value.push_slice(css_datauri.unwrap().as_str()); } } } NodeMatch::Script => { if opt_no_js { // Get rid of src and inner content of SCRIPT tags for attr in attrs_mut.iter_mut() { if &attr.name.local == "src" { attr.value.clear(); } } node.children.borrow_mut().clear(); } else { for attr in attrs_mut.iter_mut() { if &attr.name.local == "src" { let src_full_url = resolve_url(&url, &attr.value.to_string()); let js_datauri = retrieve_asset( &src_full_url.unwrap(), true, "application/javascript", ); attr.value.clear(); attr.value.push_slice(js_datauri.unwrap().as_str()); } } } } NodeMatch::Form => { for attr in attrs_mut.iter_mut() { if &attr.name.local == "action" { // Do not touch action props which are set to a URL if is_valid_url(&attr.value) { continue; } let href_full_url = resolve_url(&url, &attr.value.to_string()); attr.value.clear(); attr.value.push_slice(href_full_url.unwrap().as_str()); } } } NodeMatch::Other => {} } if opt_no_js { // Get rid of JS event attributes for attr in attrs_mut.iter_mut() { if JS_DOM_EVENT_ATTRS.contains(&attr.name.local.to_lowercase().as_str()) { attr.value.clear(); } } } // Dig deeper for child in node.children.borrow().iter() { walk_and_embed_assets(&url, child, opt_no_js, opt_no_images); } } NodeData::ProcessingInstruction { .. } => unreachable!(), } } pub fn html_to_dom(data: &str) -> html5ever::rcdom::RcDom { parse_document(RcDom::default(), Default::default()) .from_utf8() .read_from(&mut data.as_bytes()) .unwrap() } pub fn print_dom(handle: &Handle) { // TODO: append <meta http-equiv="Access-Control-Allow-Origin" content="'self'"/> to the <head> if opt_isolate serialize(&mut io::stdout(), handle, SerializeOpts::default()).unwrap(); } fn is_icon(attr_value: &str) -> bool { attr_value == "icon" || attr_value == "shortcut icon" || attr_value == "mask-icon" || attr_value == "apple-touch-icon" } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_icon() { assert_eq!(is_icon("icon"), true); assert_eq!(is_icon("stylesheet"), false); } }
use glob::glob; use scraper::{Html, Selector}; use version_compare::Version; use std::{cmp::Ordering, fs}; use std::collections::HashMap; fn compare_versions (a: &String, b: &String) -> Ordering { let parts_a = a.split("/").collect::<Vec<_>>(); let parts_b = b.split("/").collect::<Vec<_>>(); Version::from(parts_a[1]).unwrap().partial_cmp(&Version::from(parts_b[1]).unwrap()).unwrap() } fn main () -> Result<(), Box<dyn std::error::Error>> { let mut files: HashMap<String, String> = HashMap::new(); for entry in glob("./docs/**/*.html").expect("Failed") { let full_path = match entry { Ok(path) => path.display().to_string(), _ => panic!("Could not get path") }; let parts: Vec<&str> = full_path.split("/").collect(); let file_path = format!("{}/{}", parts[1], parts[2]); if parts[3] == "Entities.html" || parts[3] == "Addons.html" { if !files.contains_key(&file_path) { files.insert(file_path.to_string(), parts[3].to_string()); } // update to entities.html if it exists if files.get(&file_path).unwrap() == "Addons.html" && parts[3] == "Entities.html" { files.insert(file_path.to_string(), "Entities.html".to_string()); } } } let mut versions_list = files.keys().collect::<Vec<_>>(); versions_list.sort_by(|a, b| compare_versions(a, b)); let latest_version = versions_list[versions_list.len() - 1].split("/").collect::<Vec<_>>()[1]; let mut versions_map: HashMap<String, String> = HashMap::new(); let sel = Selector::parse("p[id^=\"minecraft:\"]").unwrap(); for version_path in &versions_list { let filename = files.get(&version_path.to_string()).unwrap(); let version = version_path.split("/").collect::<Vec<_>>()[1]; let file_content = fs::read_to_string(format!("./docs/{}/{}", version_path, filename)).unwrap_or_default(); let document = Html::parse_document(&file_content); // println!("{} {}", filename, version); for element in document.select(&sel) { let id = element.text().collect::<Vec<_>>().join(""); // println!("id: {}", id); versions_map.insert(id.to_string(), version.to_string()); } } let mut components_ordered: Vec<_> = versions_map.keys().collect::<Vec<_>>(); components_ordered.sort(); println!("{} | {}", "Component", "Version"); println!("--- | ---"); for component in components_ordered { let last = versions_map.get(component).unwrap(); let parts = last.split(".").map(|s| s.parse::<i32>().unwrap()).collect::<Vec<_>>(); let link = format!("https://bedrock.dev/docs/{}.{}.0.0/{}/Entities#{}", parts[0], parts[1], last, component); // ignore 1.8 if parts[0] == 1 && parts[1] == 8 { continue; } if last != latest_version { println!("{} | [{}]({})", component, last, link); } }; Ok(()) }
use std::sync::MutexGuard; use nia_interpreter_core::EventLoopHandle; use nia_interpreter_core::NiaGetDefinedActionsCommandResult; use nia_interpreter_core::NiaInterpreterCommand; use nia_interpreter_core::NiaInterpreterCommandResult; use nia_protocol_rust::GetDefinedActionsResponse; use crate::error::NiaServerError; use crate::error::NiaServerResult; use crate::protocol::{ NiaAction, NiaActionEnum, NiaGetDefinedActionsRequest, NiaNamedAction, }; use crate::protocol::{NiaConvertable, Serializable}; #[derive(Debug, Clone)] pub struct NiaGetDefinedActionsResponse { command_result: NiaGetDefinedActionsCommandResult, } impl NiaGetDefinedActionsResponse { fn try_from( _nia_define_action_request: NiaGetDefinedActionsRequest, event_loop_handle: MutexGuard<EventLoopHandle>, ) -> Result<NiaGetDefinedActionsResponse, NiaServerError> { let interpreter_command = NiaInterpreterCommand::make_get_defined_actions_command(); event_loop_handle .send_command(interpreter_command) .map_err(|_| { NiaServerError::interpreter_error( "Error sending command to the interpreter.", ) })?; let execution_result = event_loop_handle.receive_result().map_err(|_| { NiaServerError::interpreter_error( "Error reading command from the interpreter.", ) })?; let response = match execution_result { NiaInterpreterCommandResult::GetDefinedActions(command_result) => { NiaGetDefinedActionsResponse { command_result } } _ => { return NiaServerError::interpreter_error( "Unexpected command result.", ) .into(); } }; Ok(response) } pub fn from( nia_define_action_request: NiaGetDefinedActionsRequest, event_loop_handle: MutexGuard<EventLoopHandle>, ) -> NiaGetDefinedActionsResponse { let try_result = NiaGetDefinedActionsResponse::try_from( nia_define_action_request, event_loop_handle, ); match try_result { Ok(result) => result, Err(error) => { let message = format!("Execution failure: {}", error.get_message()); let command_result = NiaGetDefinedActionsCommandResult::Failure(message); NiaGetDefinedActionsResponse { command_result } } } } } impl Serializable< NiaGetDefinedActionsResponse, nia_protocol_rust::GetDefinedActionsResponse, > for NiaGetDefinedActionsResponse { fn to_pb(&self) -> GetDefinedActionsResponse { let command_result = &self.command_result; let mut get_defined_actions_response = nia_protocol_rust::GetDefinedActionsResponse::new(); match command_result { NiaGetDefinedActionsCommandResult::Success(defined_actions) => { let mut actions = defined_actions .iter() .map(|interpreter_action| { NiaNamedAction::from_interpreter_repr( interpreter_action, ) }) .map(|action_result| { action_result.map(|action| action.to_pb()) }) .collect::<NiaServerResult<Vec<nia_protocol_rust::NamedAction>>>(); match actions { Ok(actions) => { let repeated = protobuf::RepeatedField::from_vec(actions); let mut success_result = nia_protocol_rust::GetDefinedActionsResponse_SuccessResult::new(); success_result.set_named_actions(repeated); get_defined_actions_response .set_success_result(success_result); } Err(error) => { let message = error.get_message(); let mut error_result = nia_protocol_rust::GetDefinedActionsResponse_ErrorResult::new(); error_result.set_message(protobuf::Chars::from( message.clone(), )); get_defined_actions_response .set_error_result(error_result); } } } NiaGetDefinedActionsCommandResult::Error(error_message) => { let mut error_result = nia_protocol_rust::GetDefinedActionsResponse_ErrorResult::new(); error_result .set_message(protobuf::Chars::from(error_message.clone())); get_defined_actions_response.set_error_result(error_result); } NiaGetDefinedActionsCommandResult::Failure(failure_message) => { let mut failure_result = nia_protocol_rust::GetDefinedActionsResponse_FailureResult::new(); failure_result.set_message(protobuf::Chars::from( failure_message.clone(), )); get_defined_actions_response.set_failure_result(failure_result); } } get_defined_actions_response } fn from_pb( object_pb: GetDefinedActionsResponse, ) -> NiaServerResult<NiaGetDefinedActionsResponse> { unreachable!() } }
use num::traits::{Num, NumCast}; use super::mm::{MM, ToMM}; use super::m::{M, ToM}; use super::km::{KM, ToKM}; /// ToCM is the canonical trait to use for input in centimeters. /// /// For example the millimeters type (MM) implements the ToCM trait and thus /// millimeters can be given as a parameter to any input that seeks centimeters. pub trait ToCM{ type Output; /// to_cm returns these units in centimeters, performing conversion if needed. fn to_cm(self) -> CM<Self::Output>; } /// CM represents centimeters (1/100th a meter). /// /// # Examples /// /// ``` /// use fiz_math::unit::CM; /// /// let x = CM(1.0); /// println!("{:?}", x); /// ``` unit!(CM); impl<T: Num + NumCast> ToMM for CM<T> { type Output = T; /// to_mm returns these centimeters converted to millimeters. /// /// # Examples /// /// ``` /// use fiz_math::unit::{CM, MM, ToMM}; /// /// assert_eq!(CM(1.0).to_mm(), MM(10.0)); /// ``` fn to_mm(self) -> MM<T> { MM(self.0 * T::from(10).unwrap()) } } impl<T: Num + NumCast> ToCM for CM<T> { type Output = T; /// to_cm simply returns self. /// /// # Examples /// /// ``` /// use fiz_math::unit::{CM, ToCM}; /// /// assert_eq!(CM(1.0).to_cm(), CM(1.0)); /// ``` fn to_cm(self) -> CM<T> { self } } impl<T: Num + NumCast> ToM for CM<T> { type Output = T; /// to_m returns these centimeters converted to meters. /// /// # Examples /// /// ``` /// use fiz_math::unit::{CM, M, ToM}; /// /// assert_eq!(CM(100.0).to_m(), M(1.0)); /// ``` fn to_m(self) -> M<T> { M(self.0 / T::from(100).unwrap()) } } impl<T: Num + NumCast> ToKM for CM<T> { type Output = T; /// to_km returns these centimeters converted to kilometers. /// /// # Examples /// /// ``` /// use fiz_math::unit::{CM, KM, ToKM}; /// /// assert_eq!(CM(100000.0).to_km(), KM(1.0)); /// ``` fn to_km(self) -> KM<T> { KM(self.0 / T::from(100000).unwrap()) } }
#[doc = "Register `C2ICR` reader"] pub type R = crate::R<C2ICR_SPEC>; #[doc = "Register `C2ICR` writer"] pub type W = crate::W<C2ICR_SPEC>; #[doc = "Field `ISC0` reader - Interrupt(N) semaphore n clear bit"] pub type ISC0_R = crate::BitReader<ISC0R_A>; #[doc = "Interrupt(N) semaphore n clear bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ISC0R_A { #[doc = "0: Always reads 0"] NoEffect = 0, } impl From<ISC0R_A> for bool { #[inline(always)] fn from(variant: ISC0R_A) -> Self { variant as u8 != 0 } } impl ISC0_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<ISC0R_A> { match self.bits { false => Some(ISC0R_A::NoEffect), _ => None, } } #[doc = "Always reads 0"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == ISC0R_A::NoEffect } } #[doc = "Interrupt(N) semaphore n clear bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ISC0W_AW { #[doc = "0: Interrupt semaphore x status ISFx and masked status MISFx not affected"] NoEffect = 0, #[doc = "1: Interrupt semaphore x status ISFx and masked status MISFx cleared"] Clear = 1, } impl From<ISC0W_AW> for bool { #[inline(always)] fn from(variant: ISC0W_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `ISC0` writer - Interrupt(N) semaphore n clear bit"] pub type ISC0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ISC0W_AW>; impl<'a, REG, const O: u8> ISC0_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Interrupt semaphore x status ISFx and masked status MISFx not affected"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(ISC0W_AW::NoEffect) } #[doc = "Interrupt semaphore x status ISFx and masked status MISFx cleared"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(ISC0W_AW::Clear) } } #[doc = "Field `ISC1` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC1_R; #[doc = "Field `ISC2` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC2_R; #[doc = "Field `ISC3` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC3_R; #[doc = "Field `ISC4` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC4_R; #[doc = "Field `ISC5` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC5_R; #[doc = "Field `ISC6` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC6_R; #[doc = "Field `ISC7` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC7_R; #[doc = "Field `ISC8` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC8_R; #[doc = "Field `ISC9` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC9_R; #[doc = "Field `ISC10` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC10_R; #[doc = "Field `ISC11` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC11_R; #[doc = "Field `ISC12` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC12_R; #[doc = "Field `ISC13` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC13_R; #[doc = "Field `ISC14` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC14_R; #[doc = "Field `ISC15` reader - Interrupt(N) semaphore n clear bit"] pub use ISC0_R as ISC15_R; #[doc = "Field `ISC1` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC1_W; #[doc = "Field `ISC2` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC2_W; #[doc = "Field `ISC3` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC3_W; #[doc = "Field `ISC4` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC4_W; #[doc = "Field `ISC5` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC5_W; #[doc = "Field `ISC6` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC6_W; #[doc = "Field `ISC7` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC7_W; #[doc = "Field `ISC8` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC8_W; #[doc = "Field `ISC9` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC9_W; #[doc = "Field `ISC10` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC10_W; #[doc = "Field `ISC11` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC11_W; #[doc = "Field `ISC12` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC12_W; #[doc = "Field `ISC13` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC13_W; #[doc = "Field `ISC14` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC14_W; #[doc = "Field `ISC15` writer - Interrupt(N) semaphore n clear bit"] pub use ISC0_W as ISC15_W; impl R { #[doc = "Bit 0 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc0(&self) -> ISC0_R { ISC0_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc1(&self) -> ISC1_R { ISC1_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc2(&self) -> ISC2_R { ISC2_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc3(&self) -> ISC3_R { ISC3_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc4(&self) -> ISC4_R { ISC4_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc5(&self) -> ISC5_R { ISC5_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc6(&self) -> ISC6_R { ISC6_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc7(&self) -> ISC7_R { ISC7_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc8(&self) -> ISC8_R { ISC8_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc9(&self) -> ISC9_R { ISC9_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc10(&self) -> ISC10_R { ISC10_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc11(&self) -> ISC11_R { ISC11_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc12(&self) -> ISC12_R { ISC12_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc13(&self) -> ISC13_R { ISC13_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc14(&self) -> ISC14_R { ISC14_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - Interrupt(N) semaphore n clear bit"] #[inline(always)] pub fn isc15(&self) -> ISC15_R { ISC15_R::new(((self.bits >> 15) & 1) != 0) } } impl W { #[doc = "Bit 0 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc0(&mut self) -> ISC0_W<C2ICR_SPEC, 0> { ISC0_W::new(self) } #[doc = "Bit 1 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc1(&mut self) -> ISC1_W<C2ICR_SPEC, 1> { ISC1_W::new(self) } #[doc = "Bit 2 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc2(&mut self) -> ISC2_W<C2ICR_SPEC, 2> { ISC2_W::new(self) } #[doc = "Bit 3 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc3(&mut self) -> ISC3_W<C2ICR_SPEC, 3> { ISC3_W::new(self) } #[doc = "Bit 4 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc4(&mut self) -> ISC4_W<C2ICR_SPEC, 4> { ISC4_W::new(self) } #[doc = "Bit 5 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc5(&mut self) -> ISC5_W<C2ICR_SPEC, 5> { ISC5_W::new(self) } #[doc = "Bit 6 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc6(&mut self) -> ISC6_W<C2ICR_SPEC, 6> { ISC6_W::new(self) } #[doc = "Bit 7 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc7(&mut self) -> ISC7_W<C2ICR_SPEC, 7> { ISC7_W::new(self) } #[doc = "Bit 8 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc8(&mut self) -> ISC8_W<C2ICR_SPEC, 8> { ISC8_W::new(self) } #[doc = "Bit 9 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc9(&mut self) -> ISC9_W<C2ICR_SPEC, 9> { ISC9_W::new(self) } #[doc = "Bit 10 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc10(&mut self) -> ISC10_W<C2ICR_SPEC, 10> { ISC10_W::new(self) } #[doc = "Bit 11 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc11(&mut self) -> ISC11_W<C2ICR_SPEC, 11> { ISC11_W::new(self) } #[doc = "Bit 12 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc12(&mut self) -> ISC12_W<C2ICR_SPEC, 12> { ISC12_W::new(self) } #[doc = "Bit 13 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc13(&mut self) -> ISC13_W<C2ICR_SPEC, 13> { ISC13_W::new(self) } #[doc = "Bit 14 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc14(&mut self) -> ISC14_W<C2ICR_SPEC, 14> { ISC14_W::new(self) } #[doc = "Bit 15 - Interrupt(N) semaphore n clear bit"] #[inline(always)] #[must_use] pub fn isc15(&mut self) -> ISC15_W<C2ICR_SPEC, 15> { ISC15_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "HSEM Interrupt clear register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`c2icr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`c2icr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct C2ICR_SPEC; impl crate::RegisterSpec for C2ICR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`c2icr::R`](R) reader structure"] impl crate::Readable for C2ICR_SPEC {} #[doc = "`write(|w| ..)` method takes [`c2icr::W`](W) writer structure"] impl crate::Writable for C2ICR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets C2ICR to value 0"] impl crate::Resettable for C2ICR_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub mod types; pub mod config; pub mod net; pub mod errors; pub mod momo; pub mod parser; pub mod threads;
/* * TODO: show the gtk scrollbars instead of the Servo scrollbars? * TODO: send CloseBrowser event (on tab close?). */ extern crate epoxy; extern crate gdk; extern crate gdk_sys; extern crate glib_itc; extern crate gtk; extern crate servo; extern crate shared_library; mod convert; mod eventloop; pub mod view; mod window; pub use view::WebView;
pub mod interrupt; pub mod timer; pub mod ioregister; use std::fmt; use super::mem; use super::util; use super::debugger; pub enum EventRequest { BootstrapDisable, DMATransfer(u8), //left nibble of address to be used. HDMATransfer, JoypadUpdate, SpeedModeSwitch, } #[derive(Copy, Clone, PartialEq, Debug)] enum Flag { Z, N, H, C, } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Reg { A, F, B, C, D, E, H, L, AF, BC, DE, HL, SP, PC, } impl Reg { #[inline] pub fn pair_from_ddd(byte: u8) -> Reg { match byte & 0b111 { 0b000 => Reg::B, 0b001 => Reg::C, 0b010 => Reg::D, 0b011 => Reg::E, 0b100 => Reg::H, 0b101 => Reg::L, 0b110 => Reg::HL, 0b111 => Reg::A, _ => unreachable!(), } } #[inline] pub fn pair_from_dd(byte: u8) -> Reg { match byte & 0b11 { 0b00 => Reg::BC, 0b01 => Reg::DE, 0b10 => Reg::HL, 0b11 => Reg::SP, _ => unreachable!(), } } } #[derive(Copy, Clone, Debug)] pub struct Instruction { pub prefix: Option<u8>, pub opcode: u8, pub imm8: Option<u8>, pub imm16: Option<u16>, pub address: u16, pub cycles: u32, } impl Default for Instruction { fn default() -> Instruction { Instruction { prefix: None, opcode: 0x0, imm8: None, imm16: None, address: 0x0, cycles: 0, } } } impl fmt::Display for Instruction { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let prefix = match self.prefix { Some(val) => format!("{:#x}", val), None => "".to_owned(), }; let imm8 = match self.imm8 { Some(val) => format!("{:#x}", val), None => "".to_owned(), }; let imm16 = match self.imm16 { Some(val) => format!("{:#01$x}", val, 6), None => "".to_owned(), }; let mut opcode = format!("{:#x}", self.opcode); if prefix != "" { opcode = format!("{}{:x}", prefix, self.opcode); } let addr = format!("{:#01$x}", self.address, 6); if imm8 == "" && imm16 == "" { write!( f, "{}: {} - ({})", addr, debugger::instr_to_human(self), opcode ) } else { write!( f, "{}: {} - ({} {}{})", addr, debugger::instr_to_human(self), opcode, imm8, imm16 ) } } } #[derive(Debug)] pub struct Cpu { // [A,F,B,C,D,E,H,L,SP,PC] regs: [u8; 12], ime_flag: bool, // interrupt master enable flag halt_flag: bool, // cpu doesn't run until an interrupt occurs. last_instruction: Option<Instruction>, } impl fmt::Display for Cpu { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let regs_names = ["AF", "BC", "DE", "HL", "SP", "PC"]; let flags = format!("[{:#01$b} ZNHC]", self.flags() >> 4, 6); let mut regs = "".to_owned(); let mut i = 0; while i < 12 { let value = (self.regs[i] as u16) << 8 | self.regs[i + 1] as u16; let value_fmt = format!("{:#01$x}", value, 6); regs = regs + &format!("{}({}) ", value_fmt, regs_names[i / 2]); i += 2; } write!(f, "{} {}", flags, regs) } } impl Default for Cpu { fn default() -> Cpu { Cpu { regs: [0; 12], ime_flag: true, halt_flag: false, last_instruction: None, } } } impl Cpu { #[inline] fn reg_index(reg: Reg) -> usize { match reg { Reg::A | Reg::AF => 0, Reg::F => 1, Reg::B | Reg::BC => 2, Reg::C => 3, Reg::D | Reg::DE => 4, Reg::E => 5, Reg::H | Reg::HL => 6, Reg::L => 7, Reg::SP => 8, Reg::PC => 10, } } #[inline] fn reg_is8(reg: Reg) -> bool { match reg { Reg::A | Reg::F | Reg::B | Reg::C | Reg::D | Reg::E | Reg::H | Reg::L => true, _ => false, } } pub fn restart(&mut self) { self.regs = [0; 12]; self.ime_flag = true; self.halt_flag = false; self.last_instruction = None; } #[inline] fn reg_set16(&mut self, reg: Reg, value: u16) { let index = Cpu::reg_index(reg); if Cpu::reg_is8(reg) { self.regs[index] = value as u8; } else { self.regs[index] = (value >> 8) as u8; self.regs[index + 1] = value as u8; } } #[inline] fn reg_set8(&mut self, reg: Reg, value: u8) { self.reg_set16(reg, value as u16); } #[inline] pub fn reg16(&self, reg: Reg) -> u16 { let index = Cpu::reg_index(reg); if Cpu::reg_is8(reg) { self.regs[index] as u16 } else { ((self.regs[index] as u16) << 8) | self.regs[index + 1] as u16 } } #[inline] fn reg8(&self, reg: Reg) -> u8 { if !Cpu::reg_is8(reg) { panic!("Trying to get 8 bits from 16-bit register: {:?}", reg) } let index = Cpu::reg_index(reg); self.regs[index] } #[inline] fn flag_mask(flag: Flag) -> u8 { match flag { Flag::Z => 0b1000_0000, Flag::N => 0b0100_0000, Flag::H => 0b0010_0000, Flag::C => 0b0001_0000, } } #[inline] fn flag_set(&mut self, set: bool, flag: Flag) { let mut flags = self.reg8(Reg::F); let mask = Cpu::flag_mask(flag); if set { flags |= mask; } else { flags &= !mask; } self.reg_set8(Reg::F, flags); } #[inline] fn flag_is_set(&self, flag: Flag) -> bool { self.flag_bit(flag) == 0b1 } #[inline] fn flag_bit(&self, flag: Flag) -> u8 { let m = match flag { Flag::Z => 7, Flag::N => 6, Flag::H => 5, Flag::C => 4, }; (self.flags() >> m) & 0b1 } #[inline] fn flags(&self) -> u8 { self.reg8(Reg::F) } #[inline] fn push_sp8(&mut self, value: u8, memory: &mut mem::Memory) { let sp = self.reg16(Reg::SP) - 1; self.mem_write(sp, value, memory); self.reg_set16(Reg::SP, sp); } #[inline] fn push_sp16(&mut self, value: u16, memory: &mut mem::Memory) { self.push_sp8((value >> 8) as u8, memory); self.push_sp8(value as u8, memory); } #[inline] fn pop_sp8(&mut self, memory: &mem::Memory) -> u8 { let sp = self.reg16(Reg::SP); self.reg_set16(Reg::SP, sp + 1); memory.read_byte(sp) } #[inline] fn pop_sp16(&mut self, memory: &mem::Memory) -> u16 { let lo = self.pop_sp8(memory); let hi = self.pop_sp8(memory); ((hi as u16) << 8) | lo as u16 } fn increment_reg(&mut self, reg: Reg) { if Cpu::reg_is8(reg) { let val = self.reg8(reg).wrapping_add(1); self.reg_set8(reg, val); } else { let val = self.reg16(reg).wrapping_add(1); self.reg_set16(reg, val); } } fn decrement_reg(&mut self, reg: Reg) { if Cpu::reg_is8(reg) { let val = self.reg8(reg).wrapping_sub(1); self.reg_set8(reg, val); } else { let val = self.reg16(reg).wrapping_sub(1); self.reg_set16(reg, val); } } #[inline] fn mem_at_reg(&self, reg: Reg, memory: &mem::Memory) -> u8 { let addr = self.reg16(reg); memory.read_byte(addr) } #[inline] fn mem_next8(&mut self, memory: &mem::Memory) -> u8 { let value = self.mem_at_reg(Reg::PC, memory); self.increment_reg(Reg::PC); value } // next 2 bytes. #[inline] fn mem_next16(&mut self, memory: &mem::Memory) -> u16 { let n1 = self.mem_next8(memory) as u16; let n2 = self.mem_next8(memory) as u16; (n2 << 8) | n1 } // function for having control of memory writes #[inline] fn mem_write(&self, address: u16, value: u8, memory: &mut mem::Memory) -> Option<EventRequest> { let (value, event) = match address { ioregister::DIV_REGISTER_ADDR => { //zero out the internal counter too memory.write_byte(ioregister::TIMER_INTERNAL_COUNTER_ADDR, 0); (0, None) } ioregister::SVBK_REGISTER_ADDR => if value == 0 { (1, None) } else { (value, None) }, ioregister::LY_REGISTER_ADDR => (0, None), ioregister::BGPD_REGISTER_ADDR => { // TODO: cgb only (do nothing otherwise?) // TODO: bg palette data can't be written/read when STAT register is in mode 3. let bgpi = memory.read_byte(ioregister::BGPI_REGISTER_ADDR); let addr = bgpi & 0b0011_1111; if bgpi >> 7 == 0b1 { // auto-increment index memory.write_byte(ioregister::BGPI_REGISTER_ADDR, 0b1000_0000 | (addr + 1)); } memory.write_bg_palette(addr, value); (value, None) } ioregister::OBPD_REGISTER_ADDR => { // TODO: same as TODOs above? let obpi = memory.read_byte(ioregister::OBPI_REGISTER_ADDR); let addr = obpi & 0b0011_1111; if obpi >> 7 == 0b1 { // auto-increment index memory.write_byte(ioregister::OBPI_REGISTER_ADDR, 0b1000_0000 | (addr + 1)); } memory.write_sprite_palette(addr, value); (value, None) } ioregister::DMA_REGISTER_ADDR => { (value, Some(EventRequest::DMATransfer(self.reg8(Reg::A)))) } ioregister::HDMA5_REGISTER_ADDR => (value, Some(EventRequest::HDMATransfer)), ioregister::JOYPAD_REGISTER_ADDR => (value, Some(EventRequest::JoypadUpdate)), _ => (value, None), }; memory.write_byte(address, value); event } pub fn bypass_nintendo_logo(&mut self, memory: &mut mem::Memory) { if memory.is_bootstrap_enabled() { memory.disable_bootstrap(); self.reg_set16(Reg::PC, 0x100); } } pub fn handle_interrupts(&mut self, memory: &mut mem::Memory) { if let Some(interrupt) = interrupt::next_request(memory) { self.halt_flag = false; if self.ime_flag { self.ime_flag = false; let pc = self.reg16(Reg::PC); self.push_sp16(pc, memory); self.reg_set16(Reg::PC, interrupt::address(interrupt)); interrupt::remove_request(interrupt, memory); // since the interrupt request is removed and interrupts are disabled, // simply returning to the main loop seems correct. } } } pub fn run_instruction( &mut self, memory: &mut mem::Memory, ) -> (Instruction, Option<EventRequest>) { if self.halt_flag { return (self.last_instruction.unwrap(), None); } if let Some(ref last_instr) = self.last_instruction { if last_instr.opcode == 0xFB { // EI self.ime_flag = true; } } // ********************************************* let mut event = None; let addr = self.reg16(Reg::PC); let byte = self.mem_next8(memory); let mut instruction = Instruction::default(); instruction.opcode = byte; match byte { /***************************************/ /* Misc/Control instructions */ /***************************************/ 0x0 => { //NOP instruction.cycles = 4; if addr == 0x100 { event = Some(EventRequest::BootstrapDisable); } } 0x10 => { //STOP let key1 = memory.read_byte(ioregister::KEY1_REGISTER_ADDR); if (key1 & 0b1) == 1 { memory.write_byte(ioregister::KEY1_REGISTER_ADDR, (!key1) & 0b1000_0000); event = Some(EventRequest::SpeedModeSwitch); } else { ioregister::LCDCRegister::disable_lcd(memory); self.halt_flag = true; } instruction.cycles = 4; } 0x76 => { //HALT instruction.cycles = 4; self.halt_flag = true; } 0xF3 => { //DI instruction.cycles = 4; self.ime_flag = false } 0xFB => { //EI instruction.cycles = 4; } 0xCB => { //CB-prefixed let (i, e) = self.exec_cb_prefixed(memory); instruction = i; event = e; } /**************************************/ /* 8 bit rotations/shifts */ /**************************************/ 0x07 | 0x17 | 0x0F | 0x1F => { //RLCA; RLA; RRCA; RRA instruction = self.exec_rotates_shifts(byte); } /**************************************/ /* 8 bit load/store/move instructions */ /**************************************/ 0x02 | 0x12 => { //LD (rr),A; let (i, e) = self.exec_ld_rr_a(byte, memory); instruction = i; event = e; } 0x22 => { //LD (HL+),A let (i, e) = self.exec_ld_rr_a(byte, memory); instruction = i; event = e; self.increment_reg(Reg::HL); } 0x32 => { //LD (HL-),A let (i, e) = self.exec_ld_rr_a(byte, memory); instruction = i; event = e; self.decrement_reg(Reg::HL); } 0x0A | 0x1A => { //LD A,(rr); instruction = self.exec_ld_a_rr(byte, memory); } 0x2A => { //LD A,(HL+); instruction = self.exec_ld_a_rr(byte, memory); self.increment_reg(Reg::HL); } 0x3A => { //LD A,(HL-) instruction = self.exec_ld_a_rr(byte, memory); self.decrement_reg(Reg::HL); } 0x06 | 0x16 | 0x26 | 0x0E | 0x1E | 0x2E | 0x3E | 0x36 => { //LD r,n; LD (HL),n let reg = Reg::pair_from_ddd(byte >> 3); let immediate = self.mem_next8(memory); let cycles: u32; if reg == Reg::HL { // LD (HL),n let addr = self.reg16(Reg::HL); event = self.mem_write(addr, immediate, memory); cycles = 12; } else { // LD r,n self.reg_set8(reg, immediate); cycles = 8 } instruction.cycles = cycles; instruction.imm8 = Some(immediate); } 0x40..=0x75 | 0x77..=0x7F => { //LD r,r; LD r,(HL); LD (HL),r let reg_rhs = Reg::pair_from_ddd(byte); let reg_lhs = Reg::pair_from_ddd(byte >> 3); let cycles: u32; if reg_rhs == Reg::HL { let value = self.mem_at_reg(Reg::HL, memory); self.reg_set8(reg_lhs, value); cycles = 8; } else if reg_lhs == Reg::HL { let addr = self.reg16(Reg::HL); let rhs_val = self.reg8(reg_rhs); event = self.mem_write(addr, rhs_val, memory); cycles = 8; } else { let rhs_val = self.reg8(reg_rhs); self.reg_set8(reg_lhs, rhs_val); cycles = 4; } instruction.cycles = cycles; } 0xE0 => { //LDH (n),A let immediate = 0xFF00 + (self.mem_next8(memory) as u16); event = self.mem_write(immediate, self.reg8(Reg::A), memory); instruction.cycles = 12; instruction.imm8 = Some(immediate as u8); } 0xF0 => { //LDH A,(n) let immediate = self.mem_next8(memory); let value = memory.read_byte(0xFF00 + (immediate as u16)); self.reg_set8(Reg::A, value); instruction.cycles = 12; instruction.imm8 = Some(immediate); } 0xE2 => { //LD (C),A let addr = 0xFF00 + (self.reg8(Reg::C) as u16); event = self.mem_write(addr, self.reg8(Reg::A), memory); instruction.cycles = 8 } 0xF2 => { //LD A,(C) let value = memory.read_byte(0xFF00 + (self.reg8(Reg::C) as u16)); self.reg_set8(Reg::A, value); instruction.cycles = 8 } 0xEA => { //LD (nn),A let val = self.mem_next16(memory); event = self.mem_write(val, self.reg8(Reg::A), memory); instruction.cycles = 16; instruction.imm16 = Some(val); } 0xFA => { //LD A,(nn) let addr = self.mem_next16(memory); let val = memory.read_byte(addr); self.reg_set8(Reg::A, val); instruction.cycles = 16; instruction.imm16 = Some(addr); } /***************************************/ /* 16 bit load/store/move instructions */ /***************************************/ 0x01 | 0x11 | 0x21 | 0x31 => { //LD rr,nn let reg = Reg::pair_from_dd(byte >> 4); let val = self.mem_next16(memory); self.reg_set16(reg, val); instruction.cycles = 12; instruction.imm16 = Some(val); } 0x08 => { //LD (nn), SP let addr = self.mem_next16(memory); let val = self.reg16(Reg::SP); event = self.mem_write(addr, val as u8, memory); self.mem_write(addr + 1, (val >> 8) as u8, memory); instruction.cycles = 20; instruction.imm16 = Some(addr); } 0xC1 | 0xD1 | 0xE1 | 0xF1 => { //POP rr let mut reg = Reg::pair_from_dd(byte >> 4); if reg == Reg::SP { reg = Reg::AF; } let mut sp_val = self.pop_sp16(memory); if reg == Reg::AF { // The lower 4 bits of flags are zero even when set // otherwise. sp_val &= !0xF; } self.reg_set16(reg, sp_val); instruction.cycles = 12; } 0xC5 | 0xD5 | 0xE5 | 0xF5 => { //PUSH rr let mut reg = Reg::pair_from_dd(byte >> 4); if reg == Reg::SP { reg = Reg::AF; } let val = self.reg16(reg); self.push_sp16(val, memory); instruction.cycles = 16; } 0xF8 => { //LD HL,SP+n let imm = util::sign_extend(self.mem_next8(memory)); let sp = self.reg16(Reg::SP); if util::is_neg16(imm) { let imm_ts = util::twos_complement(imm); let res = sp.wrapping_sub(imm_ts); self.reg_set16(Reg::HL, res); self.flag_set((res & 0xff) <= (sp & 0xff), Flag::C); self.flag_set((res & 0xf) <= (sp & 0xf), Flag::H); } else { let res = sp.wrapping_add(imm); self.reg_set16(Reg::HL, res); self.flag_set((sp & 0xff) as u32 + imm as u32 > 0xff, Flag::C); self.flag_set((sp & 0xf) + (imm & 0xf) > 0xf, Flag::H); } self.flag_set(false, Flag::Z); self.flag_set(false, Flag::N); instruction.cycles = 12; instruction.imm8 = Some(imm as u8); } 0xF9 => { //LD SP,HL let hl = self.reg16(Reg::HL); self.reg_set16(Reg::SP, hl); instruction.cycles = 8; } /*****************************************/ /* 8 bit arithmetic/logical instructions */ /*****************************************/ 0x80..=0xBF | 0xC6 | 0xD6 | 0xE6 | 0xF6 | 0xCE | 0xDE | 0xEE | 0xFE => { //ADD A,r; ADD A,(HL) //ADC A,r; ADC A,(HL) //SUB r; SUB (HL); SBC A,r; SBC A,(HL) //AND r; AND (HL) //XOR r; XOR (HL) //ADD A,n; ADC A,n; SUB n; SBC A,n; AND n; XOR n; OR n; CP n; instruction = self.exec_bit_alu8(byte, memory); } 0x04 | 0x14 | 0x24 | 0x34 | 0x0C | 0x1C | 0x2C | 0x3C | 0x05 | 0x15 | 0x25 | 0x35 | 0x0D | 0x1D | 0x2D | 0x3D => { //INC r; INC (HL) //DEC r; DEC (HL) let (i, e) = self.exec_inc_dec(byte, memory); instruction = i; event = e; } 0x27 => { //DAA let c_flag = self.flag_is_set(Flag::C); let h_flag = self.flag_is_set(Flag::H); let n_flag = self.flag_is_set(Flag::N); let mut reg_a = self.reg8(Reg::A) as u16; if n_flag { if h_flag { reg_a = reg_a.wrapping_sub(0x06) & 0xFF; } if c_flag { reg_a = reg_a.wrapping_sub(0x60); } } else { if h_flag || (reg_a & 0xF) >= 0xA { reg_a += 0x06; } if c_flag || reg_a >= 0xA0 { reg_a += 0x60; } } self.flag_set(false, Flag::H); if reg_a & 0x100 == 0x100 { self.flag_set(true, Flag::C); } reg_a &= 0xFF; self.flag_set(reg_a == 0, Flag::Z); self.reg_set8(Reg::A, reg_a as u8); instruction.cycles = 4; } 0x37 => { //SCF self.flag_set(false, Flag::N); self.flag_set(false, Flag::H); self.flag_set(true, Flag::C); instruction.cycles = 4; } 0x2F => { //CPL let val = self.reg8(Reg::A); self.reg_set8(Reg::A, !val); self.flag_set(true, Flag::N); self.flag_set(true, Flag::H); instruction.cycles = 4; } 0x3F => { //CCF let c = self.flag_is_set(Flag::C); self.flag_set(false, Flag::N); self.flag_set(false, Flag::H); self.flag_set(!c, Flag::C); instruction.cycles = 4; } /******************************************/ /* 16 bit arithmetic/logical instructions */ /******************************************/ 0x03 | 0x13 | 0x23 | 0x33 => { //INC rr let reg = Reg::pair_from_dd(byte >> 4); self.increment_reg(reg); instruction.cycles = 8; } 0x0B | 0x1B | 0x2B | 0x3B => { //DEC rr let reg = Reg::pair_from_dd(byte >> 4); self.decrement_reg(reg); instruction.cycles = 8; } 0x09 | 0x19 | 0x29 | 0x39 => { //ADD HL,rr let reg = Reg::pair_from_dd(byte >> 4); let value = self.reg16(reg); let hl = self.reg16(Reg::HL); self.reg_set16(Reg::HL, hl.wrapping_add(value)); self.flag_set(false, Flag::N); self.flag_set(util::has_half_carry16(hl, value), Flag::H); self.flag_set(util::has_carry16(hl, value), Flag::C); instruction.cycles = 8; } 0xE8 => { //ADD SP,n let imm = util::sign_extend(self.mem_next8(memory)); let sp = self.reg16(Reg::SP); if util::is_neg16(imm) { let imm_ts = util::twos_complement(imm); let res = sp.wrapping_sub(imm_ts); self.reg_set16(Reg::SP, res); self.flag_set((res & 0xff) <= (sp & 0xff), Flag::C); self.flag_set((res & 0xf) <= (sp & 0xf), Flag::H); } else { let res = sp.wrapping_add(imm); self.reg_set16(Reg::SP, res); self.flag_set((sp & 0xff) as u32 + imm as u32 > 0xff, Flag::C); self.flag_set((sp & 0xf) + (imm & 0xf) > 0xf, Flag::H); } self.flag_set(false, Flag::Z); self.flag_set(false, Flag::N); instruction.cycles = 16; instruction.imm8 = Some(imm as u8); } /******************************************/ /* Jumps/Calls */ /******************************************/ 0x18 | 0x20 | 0x28 | 0x30 | 0x38 => { //JR n; JR c,n instruction = self.exec_jr(byte, memory); } 0xC2 | 0xC3 | 0xCA | 0xD2 | 0xDA | 0xE9 => { //JP nn; JP c,nn; JP (HL) instruction = self.exec_jp(byte, memory); } 0xC0 | 0xC8 | 0xC9 | 0xD0 | 0xD8 | 0xD9 => { //RET; RET c; RETI instruction = self.exec_ret(byte, memory); } 0xC4 | 0xCC | 0xCD | 0xD4 | 0xDC => { //CALL nn; CALL c,nn instruction = self.exec_call(byte, memory); } 0xC7 | 0xCF | 0xD7 | 0xDF | 0xE7 | 0xEF | 0xF7 | 0xFF => { //RST let pc = self.reg16(Reg::PC); self.push_sp16(pc, memory); let addr = byte as u16 & 0b0011_1000; self.reg_set16(Reg::PC, addr); instruction.cycles = 16; } _ => panic!("Unknown instruction: {:#x} at address {:#x}", byte, addr), } if instruction.prefix.is_none() { instruction.opcode = byte; } instruction.address = addr; self.last_instruction = Some(instruction); (instruction, event) } // Instructions execution codes fn exec_ret(&mut self, opcode: u8, memory: &mem::Memory) -> Instruction { let should_return: bool; let mut cycles = 20; match opcode { 0xC0 => { // RET NZ should_return = !self.flag_is_set(Flag::Z); } 0xC8 => { // RET Z should_return = self.flag_is_set(Flag::Z); } 0xC9 => { // RET should_return = true; cycles = 16; } 0xD0 => { // RET NC should_return = !self.flag_is_set(Flag::C); } 0xD8 => { // RET C should_return = self.flag_is_set(Flag::C); } 0xD9 => { // RETI should_return = true; cycles = 16; self.ime_flag = true; } _ => unreachable!(), } if should_return { let addr = self.pop_sp16(memory); self.reg_set16(Reg::PC, addr); } else { cycles = 8; } let mut instr = Instruction::default(); instr.cycles = cycles; instr } fn exec_rotates_shifts(&mut self, opcode: u8) -> Instruction { let mut value = self.reg8(Reg::A); let bit_7 = (value >> 7) & 0b1; let bit_0 = value & 0b1; let bit: u8; match opcode { 0x07 => { // RLCA value = (value << 1) | bit_7; bit = bit_7; } 0x0F => { // RRCA value = (value >> 1) | (bit_0 << 7); bit = bit_0; } 0x17 => { // RLA value = (value << 1) | self.flag_bit(Flag::C); bit = bit_7; } 0x1F => { // RRA value = (value >> 1) | (self.flag_bit(Flag::C) << 7); bit = bit_0 } _ => unreachable!(), } self.reg_set8(Reg::A, value); self.flag_set(bit == 1, Flag::C); // TODO: what to believe? // Z80 manual says Z flag is not affected; // Gameboy manual says it is. // self.flag_set(value == 0, Flag::Z); self.flag_set(false, Flag::Z); self.flag_set(false, Flag::N); self.flag_set(false, Flag::H); let mut instr = Instruction::default(); instr.cycles = 4; instr } fn exec_call(&mut self, opcode: u8, memory: &mut mem::Memory) -> Instruction { // push next instruction onto stack let immediate = self.mem_next16(memory); let should_jump: bool; match opcode { 0xC4 => { // CALL NZ,a16 should_jump = !self.flag_is_set(Flag::Z); } 0xCC => { // CALL Z,a16 should_jump = self.flag_is_set(Flag::Z); } 0xCD => { // CALL a16 should_jump = true; } 0xD4 => { // CALL NC,a16 should_jump = !self.flag_is_set(Flag::C); } 0xDC => { // CALL C,a16 should_jump = self.flag_is_set(Flag::C); } _ => unreachable!(), } let mut cycles = 12u32; if should_jump { let pc = self.reg16(Reg::PC); self.push_sp16(pc, memory); self.reg_set16(Reg::PC, immediate); cycles = 24; } let mut instr = Instruction::default(); instr.cycles = cycles; instr.imm16 = Some(immediate); instr } fn exec_cb_prefixed( &mut self, memory: &mut mem::Memory, ) -> (Instruction, Option<EventRequest>) { let opcode = self.mem_next8(memory); let reg = Reg::pair_from_ddd(opcode); let mut value: u8; if reg == Reg::HL { value = memory.read_byte(self.reg16(Reg::HL)); } else { value = self.reg8(reg); } let bit = (opcode >> 3) & 0b111; let mut cycles = if reg == Reg::HL { 16 } else { 8 }; let mut is_bit_op = false; match opcode { 0x00..=0x07 => { // RLC b let bit_7 = (value >> 7) & 0b1; value = (value << 1) | bit_7; self.flag_set(bit_7 == 1, Flag::C); } 0x08..=0x0F => { // RRC m let bit_0 = value & 0b1; value = (value >> 1) | (bit_0 << 7); self.flag_set(bit_0 == 1, Flag::C); } 0x10..=0x17 => { // RL m let bit_7 = (value >> 7) & 0b1; value = (value << 1) | self.flag_bit(Flag::C); self.flag_set(bit_7 == 1, Flag::C); } 0x18..=0x1F => { // RR m let bit_c = self.flag_bit(Flag::C); let bit_0 = value & 0b1; value = (value >> 1) | (bit_c << 7); self.flag_set(bit_0 == 1, Flag::C); } 0x20..=0x27 => { // SLA n let bit_7 = (value >> 7) & 0b1; value = value << 1; self.flag_set(bit_7 == 1, Flag::C); } 0x28..=0x2F => { // SRA n let bit_7 = value & 0b1000_0000; let bit_0 = value & 0b1; value = (value >> 1) | bit_7; self.flag_set(bit_0 == 1, Flag::C); } 0x30..=0x37 => { // SWAP n value = (value << 4) | (value >> 4); self.flag_set(false, Flag::C); } 0x38..=0x3F => { // SRL n let bit_0 = value & 0b1; value = value >> 1; self.flag_set(bit_0 == 1, Flag::C); } 0x40..=0x7F => { // BIT b,r; BIT b,(HL) cycles = if reg == Reg::HL { 12 } else { 8 }; self.flag_set(((value >> bit) & 0b1) == 0b0, Flag::Z); self.flag_set(false, Flag::N); self.flag_set(true, Flag::H); is_bit_op = true; } 0x80..=0xBF => { // RES b,r; RES b,(HL) value = value & !(1 << bit); } 0xC0..=0xFF => { // SET b,r; SET b,(HL) value = value | (1 << bit); } _ => unreachable!(), } let mut event = None; if !is_bit_op { if reg == Reg::HL { event = self.mem_write(self.reg16(Reg::HL), value, memory) } else { self.reg_set8(reg, value); } } if opcode <= 0x3F { self.flag_set(value == 0, Flag::Z); self.flag_set(false, Flag::N); self.flag_set(false, Flag::H); } let mut instr = Instruction::default(); instr.prefix = Some(0xCB); instr.opcode = opcode; instr.cycles = cycles; (instr, event) } fn exec_jp(&mut self, opcode: u8, memory: &mut mem::Memory) -> Instruction { let should_jump: bool; let mut jump_to_hl = false; match opcode { 0xC3 => { // JP nn should_jump = true; } 0xC2 => { // JP NZ,nn should_jump = !self.flag_is_set(Flag::Z); } 0xCA => { // JP Z,nn should_jump = self.flag_is_set(Flag::Z); } 0xD2 => { // JP NC,nn should_jump = !self.flag_is_set(Flag::C); } 0xDA => { // JP C,nn should_jump = self.flag_is_set(Flag::C); } 0xE9 => { // JP (HL) should_jump = true; jump_to_hl = true; } _ => unreachable!(), } let cycles: u32; let mut imm16 = None; if should_jump { let val = if jump_to_hl { cycles = 4; self.reg16(Reg::HL) } else { cycles = 16; let imm = self.mem_next16(memory); imm16 = Some(imm); imm }; self.reg_set16(Reg::PC, val); } else if jump_to_hl { cycles = 4; } else { imm16 = Some(self.mem_next16(memory)); //mem_next increments PC twice. cycles = 12; } let mut instr = Instruction::default(); instr.cycles = cycles; instr.imm16 = imm16; instr } fn exec_jr(&mut self, opcode: u8, memory: &mut mem::Memory) -> Instruction { let should_jump: bool; let mut cycles = 8; match opcode { 0x18 => { // JR n should_jump = true; cycles = 12; } 0x20 => { // JR NZ,r8 should_jump = !self.flag_is_set(Flag::Z); } 0x28 => { // JR Z,r8 should_jump = self.flag_is_set(Flag::Z); } 0x30 => { // JR NC,r8 should_jump = !self.flag_is_set(Flag::C); } 0x38 => { // JR C,r8 should_jump = self.flag_is_set(Flag::C); } _ => unreachable!(), } let imm8 = self.mem_next8(memory); if should_jump { let imm = util::sign_extend(imm8); cycles = 12; let mut addr = self.reg16(Reg::PC); if util::is_neg16(imm) { addr = addr - util::twos_complement(imm); } else { addr = addr + imm; } self.reg_set16(Reg::PC, addr); } let mut instr = Instruction::default(); instr.cycles = cycles; instr.imm8 = Some(imm8); instr } fn exec_inc_dec( &mut self, opcode: u8, memory: &mut mem::Memory, ) -> (Instruction, Option<EventRequest>) { let reg = Reg::pair_from_ddd(opcode >> 3); let result: u8; let cycles: u32; let reg_val: u8; if reg == Reg::HL { cycles = 12; reg_val = self.mem_at_reg(Reg::HL, memory); } else { cycles = 4; reg_val = self.reg8(reg); } match opcode { 0x04 | 0x14 | 0x24 | 0x34 | 0x0C | 0x1C | 0x2C | 0x3C => { // INC result = reg_val.wrapping_add(1); self.flag_set(false, Flag::N); self.flag_set(util::has_half_carry(reg_val, 1), Flag::H); } 0x05 | 0x15 | 0x25 | 0x35 | 0x0D | 0x1D | 0x2D | 0x3D => { // DEC result = reg_val.wrapping_sub(1); self.flag_set(true, Flag::N); self.flag_set(util::has_borrow(reg_val, result), Flag::H); } _ => unreachable!(), } self.flag_set(result == 0, Flag::Z); let mut event = None; if reg == Reg::HL { event = self.mem_write(self.reg16(Reg::HL), result, memory); } else { self.reg_set8(reg, result); } let mut instr = Instruction::default(); instr.cycles = cycles; (instr, event) } fn exec_bit_alu8(&mut self, opcode: u8, memory: &mem::Memory) -> Instruction { let reg_a_val = self.reg8(Reg::A); let reg = Reg::pair_from_ddd(opcode); let value: u8; let mut cycles = 8; let mut imm8 = None; if opcode > 0xBF { value = self.mem_next8(memory); imm8 = Some(value); } else if reg == Reg::HL { value = self.mem_at_reg(reg, memory); } else { value = self.reg8(reg); cycles = 4; } let result: u8; let mut unchange_a = false; match opcode { 0x80..=0x87 | 0xC6 => { // ADD result = reg_a_val.wrapping_add(value); self.flag_set(false, Flag::N); self.flag_set(util::has_half_carry(reg_a_val, value), Flag::H); self.flag_set(util::has_carry(reg_a_val, value), Flag::C); } 0x88..=0x8F | 0xCE => { // ADC let c = self.flag_bit(Flag::C); let val2 = value.wrapping_add(c); result = reg_a_val.wrapping_add(val2); self.flag_set(false, Flag::N); self.flag_set( util::has_half_carry(reg_a_val, val2) || util::has_half_carry(value, c), Flag::H, ); self.flag_set( util::has_carry(reg_a_val, val2) || util::has_carry(value, c), Flag::C, ); } 0x90..=0x97 | 0xD6 => { // SUB result = reg_a_val.wrapping_sub(value); self.flag_set(true, Flag::N); self.flag_set(util::has_borrow(reg_a_val, value), Flag::H); self.flag_set(value > reg_a_val, Flag::C); } 0x98..=0x9F | 0xDE => { // SBC let c = self.flag_bit(Flag::C); let val2 = value.wrapping_add(c); result = reg_a_val.wrapping_sub(val2); self.flag_set(true, Flag::N); self.flag_set( util::has_borrow(reg_a_val, val2) || util::has_half_carry(value, c), Flag::H, ); self.flag_set(val2 > reg_a_val || util::has_carry(value, c), Flag::C); } 0xA0..=0xA7 | 0xE6 => { // AND result = reg_a_val & value; self.flag_set(false, Flag::N); self.flag_set(true, Flag::H); self.flag_set(false, Flag::C); } 0xA8..=0xAF | 0xEE => { // XOR result = reg_a_val ^ value; self.flag_set(false, Flag::N); self.flag_set(false, Flag::H); self.flag_set(false, Flag::C); } 0xB0..=0xB7 | 0xF6 => { // OR result = reg_a_val | value; self.flag_set(false, Flag::N); self.flag_set(false, Flag::H); self.flag_set(false, Flag::C); } 0xB8..=0xBF | 0xFE => { // CP result = if reg_a_val == value { 0x0 } else { 0x1 }; self.flag_set(true, Flag::N); self.flag_set(util::has_borrow(reg_a_val, value), Flag::H); self.flag_set(reg_a_val < value, Flag::C); unchange_a = true; } _ => unreachable!(), } self.flag_set(result == 0, Flag::Z); if !unchange_a { self.reg_set8(Reg::A, result); } let mut instr = Instruction::default(); instr.cycles = cycles; instr.imm8 = imm8; instr } fn exec_ld_a_rr(&mut self, opcode: u8, memory: &mut mem::Memory) -> Instruction { let mut reg = Reg::pair_from_dd(opcode >> 4); if reg == Reg::SP { reg = Reg::HL; } let val = self.mem_at_reg(reg, memory); self.reg_set8(Reg::A, val); let mut instr = Instruction::default(); instr.cycles = 8; instr } fn exec_ld_rr_a( &mut self, opcode: u8, memory: &mut mem::Memory, ) -> (Instruction, Option<EventRequest>) { let mut reg = Reg::pair_from_dd(opcode >> 4); if reg == Reg::SP { reg = Reg::HL; } let addr = self.reg16(reg); let val = self.reg8(Reg::A); let event = self.mem_write(addr, val, memory); let mut instr = Instruction::default(); instr.cycles = 8; (instr, event) } }
#![deny(warnings)] extern crate env_logger; #[macro_use] extern crate log as irrelevant_log; extern crate juniper; extern crate juniper_warp; extern crate warp; use juniper::*; use warp::{http::Response, log, Filter}; #[derive(GraphQLEnum)] enum Episode { NewHope, Empire, Jedi, } #[derive(GraphQLObject)] #[graphql(description = "A humanoid creature in the Star Wars universe")] struct Human { id: String, name: String, appears_in: Vec<Episode>, home_planet: String, } #[derive(GraphQLInputObject)] #[graphql(description = "A humanoid creature in the Star Wars universe")] struct NewHuman { name: String, appears_in: Vec<Episode>, home_planet: String, } pub struct QueryRoot; graphql_object!(QueryRoot: () |&self| { field human(&executor, id: String) -> FieldResult<Human> { Ok(Human{ id: "1234".to_owned(), name: "Luke".to_owned(), appears_in: vec![Episode::NewHope], home_planet: "Mars".to_owned(), }) } }); pub struct MutationRoot; graphql_object!(MutationRoot: () |&self| { field createHuman(&executor, new_human: NewHuman) -> FieldResult<Human> { Ok(Human{ id: "1234".to_owned(), name: new_human.name, appears_in: new_human.appears_in, home_planet: new_human.home_planet, }) } }); pub type Schema = RootNode<'static, QueryRoot, MutationRoot>; fn main() { pub fn schema() -> Schema { Schema::new(QueryRoot {}, MutationRoot {}) } ::std::env::set_var("RUST_LOG", "warp_server"); env_logger::init(); let log = log("warp_server"); let homepage = warp::path::end().map(|| { Response::builder() .header("content-type", "text/html") .body(format!( "<html><h1>juniper_warp</h1><div>visit <a href=\"/graphiql\">/graphiql</a></html>" )) }); info!("Listening on 127.0.0.1:3030"); let state = warp::any().map(move || ()); let graphql_filter = juniper_warp::make_graphql_filter(schema(), state.boxed()); warp::serve( warp::get2() .and(warp::path("graphiql")) .and(juniper_warp::graphiql_filter("/graphql")) .or(homepage) .or(warp::path("graphql").and(graphql_filter)) .with(log), ) .run(([127, 0, 0, 1], 3030)); }
use std::collections::HashMap; use std::time::Duration; use chrono::{DateTime, Utc}; use reqwest::{Client, Method, Url}; use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT}; use crate::authentication::Authentication; use crate::ClientError; use crate::utils::{build_url, merge_headers}; pub struct CallContext { pub start: DateTime<Utc>, pub url: Url, pub method: Method, } pub trait ClientBuilder { fn new(url_root: &str) -> Result<Self, ClientError> where Self: std::marker::Sized; fn set_timeout(self, timeout: u64) -> Self; fn set_headers(self, headers: HeaderMap) -> Self; fn set_auth<A: Authentication + 'static>(self, auth: A) -> Self; } pub trait BaseClient { // To implement fn url_root(&self) -> &Url; fn timeout(&self) -> &u64; fn headers(&self) -> &HeaderMap; fn auth(&self) -> Option<&Box<dyn Authentication>>; fn do_request(&self, method: Method, path: String, params: Option<HashMap<String, String>>, data: Option<String>, headers: Option<HeaderMap>, timeout: Option<u64>) -> Result<String, ClientError> { let start = chrono::Utc::now(); let url = build_url(self.url_root(), path, params)?; let cli = Client::builder() .timeout(Duration::from_secs(timeout.unwrap_or(self.timeout().clone()))) .default_headers(merge_headers(self.headers(), headers)) .build()?; debug!("{} {}", &method, &url.as_str()); let mut req = cli.request(method.clone(), url.clone()); if let Some(auth) = self.auth() { if let Some((name, value)) = auth.as_header() { req = req.header(name, value); } } if let Some(txt) = data { req = req.body::<String>(txt); } let mut resp = req.send()?; let end = { chrono::Utc::now() - start }.to_std().unwrap(); let human = humantime::format_duration(end).to_string(); let lenght = resp.content_length().unwrap_or(0); match resp.status().is_success() { true => { info!("{} {} - {} - {} [{}]", &method, &url.as_str(), resp.status(), lenght, &human); Ok(resp.text()?) } false => { error!("{} {} - {} - {} [{}]", &method, &url.as_str(), resp.status(), lenght, &human); Err(ClientError::from(&mut resp)) } } } fn head(&self, path: String, params: Option<HashMap<String, String>>, headers: Option<HeaderMap>, timeout: Option<u64>) -> Result<(), ClientError> { self.do_request(Method::HEAD, path, params, None, headers, timeout)?; Ok(()) } } #[derive(Debug)] pub struct HttpClient { url_root: Url, timeout: u64, headers: HeaderMap, auth: Option<Box<dyn Authentication>>, } impl ClientBuilder for HttpClient { fn new(url_root: &str) -> Result<HttpClient, ClientError> { Ok(HttpClient { url_root: Url::parse(url_root.trim_end_matches("/"))?, timeout: 10, headers: { let mut headers = HeaderMap::new(); headers.append( USER_AGENT, HeaderValue::from_str(&format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")))?, ); headers }, auth: None, }) } fn set_timeout(mut self, timeout: u64) -> HttpClient { self.timeout = timeout; self } fn set_headers(mut self, headers: HeaderMap) -> HttpClient { self.headers.extend(headers); self } fn set_auth<A: Authentication + 'static>(mut self, auth: A) -> HttpClient { self.auth = Some(Box::new(auth)); self } } impl BaseClient for HttpClient { fn url_root(&self) -> &Url { &self.url_root } fn timeout(&self) -> &u64 { &self.timeout } fn headers(&self) -> &HeaderMap { &self.headers } fn auth(&self) -> Option<&Box<dyn Authentication>> { self.auth.as_ref() } } impl HttpClient { pub fn get(&self, path: String, params: Option<HashMap<String, String>>, headers: Option<HeaderMap>, timeout: Option<u64>) -> Result<String, ClientError> { self.do_request(Method::GET, path, params, None, headers, timeout) } pub fn post(&self, path: String, params: Option<HashMap<String, String>>, data: Option<String>, headers: Option<HeaderMap>, timeout: Option<u64>) -> Result<String, ClientError> { self.do_request(Method::POST, path, params, data, headers, timeout) } pub fn put(&self, path: String, params: Option<HashMap<String, String>>, data: Option<String>, headers: Option<HeaderMap>, timeout: Option<u64>) -> Result<String, ClientError> { self.do_request(Method::PUT, path, params, data, headers, timeout) } pub fn delete(&self, path: String, params: Option<HashMap<String, String>>, headers: Option<HeaderMap>, timeout: Option<u64>) -> Result<String, ClientError> { self.do_request(Method::DELETE, path, params, None, headers, timeout) } }
use crate::ast; use crate::{Parse, ParseError, ParseErrorKind, Parser, Spanned, ToTokens}; /// A single argument in a closure. /// /// # Examples /// /// ```rust /// use rune::{parse_all, ast}; /// /// parse_all::<ast::FnArg>("self").unwrap(); /// parse_all::<ast::FnArg>("_").unwrap(); /// parse_all::<ast::FnArg>("abc").unwrap(); /// ``` #[derive(Debug, Clone, ToTokens, Spanned)] pub enum FnArg { /// The `self` parameter. Self_(ast::Self_), /// Ignoring the argument with `_`. Ignore(ast::Underscore), /// Binding the argument to an ident. Ident(ast::Ident), } impl Parse for FnArg { fn parse(parser: &mut Parser<'_>) -> Result<Self, ParseError> { let token = parser.token_peek_eof()?; Ok(match token.kind { ast::Kind::Self_ => Self::Self_(parser.parse()?), ast::Kind::Underscore => Self::Ignore(parser.parse()?), ast::Kind::Ident(..) => Self::Ident(parser.parse()?), _ => { return Err(ParseError::new( token, ParseErrorKind::ExpectedFunctionArgument, )) } }) } }
use error_chain::error_chain; error_chain! { errors { ConnectionError {} ChannelError {} } }
pub(crate) mod persistent_parameters; #[cfg(test)] mod tests; use crate::connected_peers::{ Behaviour as ConnectedPeersBehaviour, Config as ConnectedPeersConfig, Event as ConnectedPeersEvent, }; use crate::peer_info::{ Behaviour as PeerInfoBehaviour, Config as PeerInfoConfig, Event as PeerInfoEvent, }; use crate::request_responses::{ Event as RequestResponseEvent, RequestHandler, RequestResponsesBehaviour, }; use crate::reserved_peers::{ Behaviour as ReservedPeersBehaviour, Config as ReservedPeersConfig, Event as ReservedPeersEvent, }; use crate::PeerInfoProvider; use derive_more::From; use libp2p::allow_block_list::{Behaviour as AllowBlockListBehaviour, BlockedPeers}; use libp2p::connection_limits::{Behaviour as ConnectionLimitsBehaviour, ConnectionLimits}; use libp2p::gossipsub::{ Behaviour as Gossipsub, Config as GossipsubConfig, Event as GossipsubEvent, MessageAuthenticity, }; use libp2p::identify::{Behaviour as Identify, Config as IdentifyConfig, Event as IdentifyEvent}; use libp2p::kad::{Kademlia, KademliaConfig, KademliaEvent}; use libp2p::ping::{Behaviour as Ping, Event as PingEvent}; use libp2p::swarm::behaviour::toggle::Toggle; use libp2p::swarm::NetworkBehaviour; use libp2p::PeerId; use void::Void as VoidEvent; type BlockListBehaviour = AllowBlockListBehaviour<BlockedPeers>; pub(crate) struct BehaviorConfig<RecordStore> { /// Identity keypair of a node used for authenticated connections. pub(crate) peer_id: PeerId, /// The configuration for the [`Identify`] behaviour. pub(crate) identify: IdentifyConfig, /// The configuration for the [`Kademlia`] behaviour. pub(crate) kademlia: KademliaConfig, /// The configuration for the [`Gossipsub`] behaviour. pub(crate) gossipsub: Option<GossipsubConfig>, /// Externally provided implementation of the custom record store for Kademlia DHT, pub(crate) record_store: RecordStore, /// The configuration for the [`RequestResponsesBehaviour`] protocol. pub(crate) request_response_protocols: Vec<Box<dyn RequestHandler>>, /// Connection limits for the swarm. pub(crate) connection_limits: ConnectionLimits, /// The configuration for the [`ReservedPeersBehaviour`]. pub(crate) reserved_peers: ReservedPeersConfig, /// The configuration for the [`PeerInfo`] protocol. pub(crate) peer_info_config: PeerInfoConfig, /// Provides peer-info for local peer. pub(crate) peer_info_provider: Option<PeerInfoProvider>, /// The configuration for the [`ConnectedPeers`] protocol (general instance). pub(crate) general_connected_peers_config: Option<ConnectedPeersConfig>, /// The configuration for the [`ConnectedPeers`] protocol (special instance). pub(crate) special_connected_peers_config: Option<ConnectedPeersConfig>, } #[derive(Debug, Clone, Copy)] pub(crate) struct GeneralConnectedPeersInstance; #[derive(Debug, Clone, Copy)] pub(crate) struct SpecialConnectedPeersInstance; #[derive(NetworkBehaviour)] #[behaviour(to_swarm = "Event")] #[behaviour(event_process = false)] pub(crate) struct Behavior<RecordStore> { pub(crate) identify: Identify, pub(crate) kademlia: Kademlia<RecordStore>, pub(crate) gossipsub: Toggle<Gossipsub>, pub(crate) ping: Ping, pub(crate) request_response: RequestResponsesBehaviour, pub(crate) connection_limits: ConnectionLimitsBehaviour, pub(crate) block_list: BlockListBehaviour, pub(crate) reserved_peers: ReservedPeersBehaviour, pub(crate) peer_info: Toggle<PeerInfoBehaviour>, pub(crate) general_connected_peers: Toggle<ConnectedPeersBehaviour<GeneralConnectedPeersInstance>>, pub(crate) special_connected_peers: Toggle<ConnectedPeersBehaviour<SpecialConnectedPeersInstance>>, } impl<RecordStore> Behavior<RecordStore> where RecordStore: Send + Sync + libp2p::kad::store::RecordStore + 'static, { pub(crate) fn new(config: BehaviorConfig<RecordStore>) -> Self { let kademlia = Kademlia::<RecordStore>::with_config( config.peer_id, config.record_store, config.kademlia, ); let gossipsub = config .gossipsub .map(|gossip_config| { Gossipsub::new( // TODO: Do we want message signing? MessageAuthenticity::Anonymous, gossip_config, ) .expect("Correct configuration") }) .into(); let peer_info = config .peer_info_provider .map(|provider| PeerInfoBehaviour::new(config.peer_info_config, provider)); Self { identify: Identify::new(config.identify), kademlia, gossipsub, ping: Ping::default(), request_response: RequestResponsesBehaviour::new(config.request_response_protocols) //TODO: Convert to an error. .expect("RequestResponse protocols registration failed."), connection_limits: ConnectionLimitsBehaviour::new(config.connection_limits), block_list: BlockListBehaviour::default(), reserved_peers: ReservedPeersBehaviour::new(config.reserved_peers), peer_info: peer_info.into(), general_connected_peers: config .general_connected_peers_config .map(ConnectedPeersBehaviour::new) .into(), special_connected_peers: config .special_connected_peers_config .map(ConnectedPeersBehaviour::new) .into(), } } } #[derive(Debug, From)] pub(crate) enum Event { Identify(IdentifyEvent), Kademlia(KademliaEvent), Gossipsub(GossipsubEvent), Ping(PingEvent), RequestResponse(RequestResponseEvent), /// Event stub for connection limits and block list behaviours. We won't receive such events. VoidEventStub(VoidEvent), ReservedPeers(ReservedPeersEvent), PeerInfo(PeerInfoEvent), GeneralConnectedPeers(ConnectedPeersEvent<GeneralConnectedPeersInstance>), SpecialConnectedPeers(ConnectedPeersEvent<SpecialConnectedPeersInstance>), }
//! Code related to mutation of generic [`crate::Kind`]s. use crate::lens::Lens; use dyn_clone::{clone_trait_object, DynClone}; use std::{fmt::Debug, marker::PhantomData}; /// Describes a mutation that should be applied to an object pub trait Mutator<T>: Debug + Send + DynClone { /// Apply the mutation to the given target. fn apply(self: Box<Self>, target: &mut T); } clone_trait_object!(<T> Mutator<T>); /// A mutator that does nothing. #[derive(Debug, Clone)] pub struct NopMutator; impl<T> Mutator<T> for NopMutator { fn apply(self: Box<Self>, _target: &mut T) { () } } /// A mutator which uses a lens to set the new value #[derive(Debug, Clone)] pub struct LensSet<L: Lens>(L::Target); impl<L: Lens> LensSet<L> { pub fn new(new: L::Target) -> Self { Self(new) } } impl<S, T: Debug + Clone + Send, L: Lens<Source = S, Target = T>> Mutator<S> for LensSet<L> { fn apply(self: Box<Self>, target: &mut S) { *L::get_mut(target) = self.0.clone() } } /// Mutates an object by first applying a lens, then another mutator. #[derive(Debug, Clone)] pub struct InnerMutation<L: Lens>(Box<dyn Mutator<L::Target>>, PhantomData<L>); impl<L: Lens> InnerMutation<L> { pub fn new(m: Box<dyn Mutator<L::Target>>) -> Self { Self(m, PhantomData) } } impl<L: Lens> Mutator<L::Source> for InnerMutation<L> where L::Target: Debug + Clone + Send, { fn apply(self: Box<Self>, target: &mut L::Source) { self.0.apply(L::get_mut(target)) } }
#[doc = "Register `MTLRxQDR` reader"] pub type R = crate::R<MTLRX_QDR_SPEC>; #[doc = "Register `MTLRxQDR` writer"] pub type W = crate::W<MTLRX_QDR_SPEC>; #[doc = "Field `RWCSTS` reader - MTL Rx Queue Write Controller Active Status"] pub type RWCSTS_R = crate::BitReader; #[doc = "Field `RWCSTS` writer - MTL Rx Queue Write Controller Active Status"] pub type RWCSTS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RRCSTS` reader - MTL Rx Queue Read Controller State"] pub type RRCSTS_R = crate::FieldReader; #[doc = "Field `RRCSTS` writer - MTL Rx Queue Read Controller State"] pub type RRCSTS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `RXQSTS` reader - MTL Rx Queue Fill-Level Status"] pub type RXQSTS_R = crate::FieldReader; #[doc = "Field `RXQSTS` writer - MTL Rx Queue Fill-Level Status"] pub type RXQSTS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PRXQ` reader - Number of Packets in Receive Queue"] pub type PRXQ_R = crate::FieldReader<u16>; #[doc = "Field `PRXQ` writer - Number of Packets in Receive Queue"] pub type PRXQ_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 14, O, u16>; impl R { #[doc = "Bit 0 - MTL Rx Queue Write Controller Active Status"] #[inline(always)] pub fn rwcsts(&self) -> RWCSTS_R { RWCSTS_R::new((self.bits & 1) != 0) } #[doc = "Bits 1:2 - MTL Rx Queue Read Controller State"] #[inline(always)] pub fn rrcsts(&self) -> RRCSTS_R { RRCSTS_R::new(((self.bits >> 1) & 3) as u8) } #[doc = "Bits 4:5 - MTL Rx Queue Fill-Level Status"] #[inline(always)] pub fn rxqsts(&self) -> RXQSTS_R { RXQSTS_R::new(((self.bits >> 4) & 3) as u8) } #[doc = "Bits 16:29 - Number of Packets in Receive Queue"] #[inline(always)] pub fn prxq(&self) -> PRXQ_R { PRXQ_R::new(((self.bits >> 16) & 0x3fff) as u16) } } impl W { #[doc = "Bit 0 - MTL Rx Queue Write Controller Active Status"] #[inline(always)] #[must_use] pub fn rwcsts(&mut self) -> RWCSTS_W<MTLRX_QDR_SPEC, 0> { RWCSTS_W::new(self) } #[doc = "Bits 1:2 - MTL Rx Queue Read Controller State"] #[inline(always)] #[must_use] pub fn rrcsts(&mut self) -> RRCSTS_W<MTLRX_QDR_SPEC, 1> { RRCSTS_W::new(self) } #[doc = "Bits 4:5 - MTL Rx Queue Fill-Level Status"] #[inline(always)] #[must_use] pub fn rxqsts(&mut self) -> RXQSTS_W<MTLRX_QDR_SPEC, 4> { RXQSTS_W::new(self) } #[doc = "Bits 16:29 - Number of Packets in Receive Queue"] #[inline(always)] #[must_use] pub fn prxq(&mut self) -> PRXQ_W<MTLRX_QDR_SPEC, 16> { PRXQ_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Rx queue debug register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mtlrx_qdr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mtlrx_qdr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MTLRX_QDR_SPEC; impl crate::RegisterSpec for MTLRX_QDR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`mtlrx_qdr::R`](R) reader structure"] impl crate::Readable for MTLRX_QDR_SPEC {} #[doc = "`write(|w| ..)` method takes [`mtlrx_qdr::W`](W) writer structure"] impl crate::Writable for MTLRX_QDR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets MTLRxQDR to value 0"] impl crate::Resettable for MTLRX_QDR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::{ collections::{HashMap, HashSet, VecDeque}, fmt, }; use uuid::Uuid; pub struct CircularDependancyError; impl fmt::Debug for CircularDependancyError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Error in toposort - circular dependency") } } pub fn toposort( input: &HashMap<Uuid, HashSet<Uuid>>, ) -> Result<Vec<Uuid>, CircularDependancyError> { if input.is_empty() { Ok(Vec::new()) } else { let mut in_degree: HashMap<Uuid, i32> = HashMap::new(); for (key, val) in input.iter() { let _ = *in_degree.entry(*key).or_insert(0); for adj in val { *in_degree.entry(*adj).or_insert(0) += 1; } } let mut deque: VecDeque<Uuid> = VecDeque::new(); for (key, val) in in_degree.iter() { if *val == 0 { deque.push_back(*key); } } let mut ret: Vec<Uuid> = Vec::new(); while let Some(node) = deque.pop_front() { ret.push(node); for adj_node in input[&node].iter() { *in_degree.entry(*adj_node).or_insert(0) -= 1; if in_degree[adj_node] == 0 { deque.push_back(*adj_node); } } } if ret.len() > input.len() { return Err(CircularDependancyError); } Ok(ret) } }
extern crate advent; use advent::day5::*; use std::thread; const INPUT: &'static str = "ojvtpuvg"; pub fn main() { let basic = thread::spawn(|| get_password(INPUT)); let indexed = thread::spawn(|| get_indexed_password(INPUT)); println!("{} (basic): {}", INPUT, basic.join().unwrap()); println!("{} (indexed): {}", INPUT, indexed.join().unwrap()); }
extern crate num; pub mod err { pub const USER_EXIT: &'static str = "Exit from user"; pub const TEXTURE_NOT_FOUND: &'static str = "Unable to find texture"; } #[derive(Clone)] pub struct Vec2D { pub x: f32, pub y: f32, } impl Vec2D { pub fn new<T: num::cast::AsPrimitive<f32>>(x: T, y: T) -> Vec2D { Vec2D { x: x.as_(), y: y.as_(), } } } #[derive(Clone, Debug)] pub struct Rect { pub x: f32, pub y: f32, pub width: u32, pub height: u32, } impl Rect { pub fn new<T: num::cast::AsPrimitive<f32>, U: num::cast::AsPrimitive<u32>>( x: T, y: T, width: U, height: U, ) -> Rect { Rect { x: x.as_(), y: y.as_(), width: width.as_(), height: height.as_(), } } } #[derive(Clone, PartialEq)] pub enum Event { Up, Down, Right, Left, Action, }
// Can build and run with: // 1. cargo build // 2. cargo run fn main() { let x = 7; // Rust has type inference // x = 10; // And vars are immutable by default let (y, z) = (1, 2); // And has pattern matching. Tuple deconstructing. let mut a = 1; // This is mutable a = 2; let mut b: i32; // This is mutable and has a type of "signed 32-bit int" // It's also not assigned, so this will warn at compile-time. // println!("{}", b); // If we try to use b without assignment, we error on compile. if x == 5 { println!("x is 5!"); } else if x == 6 { println!("x is 6!"); } else { println!("x is not 5 or 6"); } // We can also do this. Which is super awesome. // if is an expression. let c = if x == 5 { 10 } else if x == 6 { 15 } else { 20 }; // c: i32 (also, note the semicolon). println!("{}", c); // let is a statement let d = x; // d is of type (), the unit type // ; turn expressions into statements by throwing away the value and returing () print_num(a); // functions print_sum(a, x); print_num(magic(a)); print_num(prod(x)); // a = die(); // diverging functions (return-type !) can be used as any type let t: (i32, &str) = (1, "Hello, world."); // Tuples. They don't have to be typed. // We can assign same-size, same-type tuples into each other, if mut. let mut u = t; if t == u { println!("match"); } else { println!("does not match."); } let origin: Point = Point{ x: 0, y: 0 }; // immutable println!("Origin: ({}, {})", origin.x, origin.y); let mut origin2: Point = Point{ x: 0, y: 0 }; // mutable. Individual fields cannot be mutable? origin2.x = 1; println!("Origin: ({}, {})", origin2.x, origin2.y); struct Inches(i32); // newtype (size-1 tuple-struct) let length = Inches(10); let Inches(in_len) = length; // Unpacks the tuple into in_len } // void function. takes in a param of type i32 named x. fn print_num(x: i32) { println!("Num is {}", x); } fn print_sum(x: i32, y: i32) { // Must always declare param types println!("Num is {}", sum(x, y)); } fn sum(x: i32, y: i32) -> i32 { // returns type i32. I really like this syntax. x + y } fn magic(x: i32) -> i32 { if x < 5 { return x; } // early returns are allowed x + 1 // although it is the norm to leave off return of what you are returning generally } // The more Rust-ful way of writing magic fn prod(x: i32) -> i32 { if x < 5 { x } else { x + 1 } } /// `die` is a diverging function. We know this from !. /// /// # Markdown /// /// Rust doc comments support it. fn die() -> ! { // ! denotes does not return panic!("Whelp, we're dead."); } // We can return multiple values! fn two(x: i32) -> (i32, i32) { (x, x + 1) } struct Point { x: i32, y: i32, } struct Point2 { //mut x: i32, // Individual fields cannot be mutable :( y: i32, }
//! Save and restore manager state. use crate::errors::Result; use crate::Manager; pub trait State { /// Write current state to a file. /// It will be used to restore the state after soft reload. /// /// # Errors /// /// Will return error if unable to create `state_file` or /// if unable to serialize the text. /// May be caused by inadequate permissions, not enough /// space on drive, or other typical filesystem issues. fn save(&self, manager: &Manager) -> Result<()>; /// Load saved state if it exists. fn load(&self, manager: &mut Manager); }
use crate::config::{MailConfig, SSL}; use rocket::State; use rocket::response::content::Xml; use serde::Serialize; use uuid::Uuid; #[derive(Serialize)] #[serde(rename_all = "PascalCase")] struct PayloadContent { email_account_type: String, email_address: String, incoming_mail_server_authentication: String, incoming_mail_server_host_name: String, incoming_mail_server_port_number: u16, incoming_mail_server_use_ssl: bool, outgoing_mail_server_authentication: String, outgoing_mail_server_host_name: String, outgoing_mail_server_port_number: u16, outgoing_mail_server_use_ssl: bool, payload_description: String, payload_display_name: String, payload_identifier: String, payload_organization: String, payload_type: String, #[serde(rename = "PayloadUUID")] payload_uuid: Uuid, payload_version: u32, prevent_app_sheet: bool, prevent_move: bool, #[serde(rename = "SMIMEEnabled")] smime_enabled: bool, #[serde(rename = "allowMailDrop")] allow_mail_drop: bool, } #[derive(Serialize)] #[serde(rename_all = "PascalCase")] struct MobileConfig { payload_content: Vec<PayloadContent>, payload_description: String, payload_display_name: String, payload_identifier: String, payload_organization: String, payload_removal_disallowed: bool, payload_type: String, #[serde(rename = "PayloadUUID")] payload_uuid: Uuid, payload_version: u32, } struct Server { auth: String, hostname: String, port: u16, use_ssl: bool, } use openssl::pkcs7::{Pkcs7, Pkcs7Flags}; use openssl::pkey::PKey; use openssl::stack::Stack; use openssl::x509::X509; fn sign(ssl: &SSL, input: &[u8]) -> Result<Vec<u8>, failure::Error> { let data = std::fs::read(&ssl.key)?; let pkey = PKey::private_key_from_pem(&data)?; let data = std::fs::read(&ssl.chain)?; let cert = X509::from_pem(&data)?; let mut certs = Stack::new()?; certs.push(cert)?; let data = std::fs::read(&ssl.cert)?; let cert = X509::from_pem(&data)?; let flags = Pkcs7Flags::STREAM; let pkcs7 = Pkcs7::sign(&cert, &pkey, &certs.as_ref(), input, flags)?; let data = pkcs7.to_der()?; Ok(data) } #[get("/email.mobileconfig?<email>")] pub fn mobileconfig(config: &State<MailConfig>, email: String) -> Xml<Vec<u8>> { let domain = email.split("@").last().unwrap().to_string(); let identifier = domain.split('.').into_iter().rev().collect::<Vec<&str>>().join("."); let domain_config = config.domains.get(&domain).unwrap(); let mut incoming_server = None; let mut outgoing_server = None; for server in &domain_config.servers { let use_ssl = match server.encrypt.as_str() { "ssl" => true, "starttls" => true, _ => false, }; let auth = match server.auth.as_str() { "plain" => "EmailAuthPassword", "cram-md5" => "EmailAuthCRAMMD5", _ => "EmailAuthNone", }; let item = Server { auth: auth.to_string(), hostname: server.hostname.clone(), port: server.port, use_ssl, }; if server.protocol == "smtp" { outgoing_server.get_or_insert(item); } else { incoming_server.get_or_insert(item); } } let incoming_server = incoming_server.unwrap(); let outgoing_server = outgoing_server.unwrap(); let response = MobileConfig { payload_content: vec![PayloadContent { email_account_type: "EmailTypeIMAP".to_string(), email_address: email.clone(), incoming_mail_server_authentication: incoming_server.auth, incoming_mail_server_host_name: incoming_server.hostname, incoming_mail_server_port_number: incoming_server.port, incoming_mail_server_use_ssl: incoming_server.use_ssl, outgoing_mail_server_authentication: outgoing_server.auth, outgoing_mail_server_host_name: outgoing_server.hostname, outgoing_mail_server_port_number: outgoing_server.port, outgoing_mail_server_use_ssl: outgoing_server.use_ssl, payload_description: "Configures your e-mail account.".to_string(), payload_display_name: "IMAP Account".to_string(), payload_identifier: format!("{}.mobileconfig", identifier), payload_organization: domain.clone(), payload_type: "com.apple.mail.managed".to_string(), payload_uuid: Uuid::new_v4(), payload_version: 1, prevent_app_sheet: false, prevent_move: false, smime_enabled: false, allow_mail_drop: true, }], payload_description: format!("Install this profile to automatically configure the e-mail account for {}", email), payload_display_name: "Mail Account".to_string(), payload_identifier: format!("{}.mobileconfig", identifier), payload_organization: domain.clone(), payload_removal_disallowed: false, payload_type: "Configuration".to_string(), payload_uuid: Uuid::new_v4(), payload_version: 1, }; let mut data = vec![]; let _ = plist::to_writer_xml(&mut data, &response); let response = String::from_utf8(data).unwrap(); let response = format!("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>{}", response); let mut response = response.into_bytes(); if let Some(ssl) = &config.ssl { response = sign(ssl, &response).unwrap(); } Xml(response) }
#[macro_export] macro_rules! tests_for_parser { ($parser: ident, $name: ident, $input: expr, $expected: expr) => { paste::item! { /// test roundtrip from source with unix line endings #[test] fn [<$name __ $parser __ unix>]() { let input = $input.replace("\r\n", "\n"); let expected = $expected.replace("\r\n", "\n"); let result = $parser(&input); assert_snapshot!( stringify!([<$name __ $parser __ unix>]), format!("{}\n---\n{:#?}", &input, &result)); if let Ok(ast) = result { assert_eq!(ast.to_string(), expected); assert_snapshot!( stringify!([<$name __ visit _ $parser __ win>]), format!("{}\n---\n{:#?}", &input, [<visit _ $parser>](&ast))); } } /// test roundtrip from source with windows line endings #[test] fn [<$name __ $parser __ win>]() { // this is weird, but ensures all line endings are windows line endings let input = $input.replace("\r\n", "\n").replace("\n", "\r\n"); // always expect unix line endings as output let expected = $expected.replace("\r\n", "\n"); let result = $parser(&input); assert_snapshot!( stringify!([<$name __ $parser __ win>]), format!("{}\n---\n{:#?}", &$input.replace("\r\n", "\n"), &result)); if let Ok(ast) = result { assert_eq!(ast.to_string(), expected); assert_snapshot!( stringify!([<$name __ visit _ $parser __ win>]), format!("{}\n---\n{:#?}", &$input.replace("\r\n", "\n"), &[<visit _ $parser>](&ast))); } } } }; } #[macro_export] macro_rules! test { ($name: ident, $input: expr, $expected: expr) => { tests_for_parser!(parse_query, $name, $input, $expected); tests_for_parser!(parse_schema, $name, $input, $expected); }; } use graphql_parser::{query, query::Node as QueryNode, schema, schema::Node as SchemaNode, Name}; pub fn visit_parse_query<'a>(doc: &query::Document<'a>) -> Print { let mut p = Print::default(); doc.accept(&mut p); p } pub fn visit_parse_schema<'a>(doc: &schema::Document<'a>) -> Print { let mut p = Print::default(); doc.accept(&mut p); p } #[derive(Debug, Default)] pub struct Print { output: Vec<Visit>, } #[derive(Debug)] pub struct Visit { event: String, name: Option<String>, } macro_rules! print { ($action:ident $mod:ident :: $Type:ident) => { fn $action<'a>(&mut self, node: &$mod::$Type<'a>) { self.output.push(Visit { event: String::from(stringify!($action)), name: node.name().map(String::from), }) } }; } impl query::Visitor for Print { print!(enter_query query::Document); print!(leave_query query::Document); print!(enter_query_def query::Definition); print!(leave_query_def query::Definition); print!(enter_sel_set query::SelectionSet); print!(leave_sel_set query::SelectionSet); print!(enter_sel query::Selection); print!(leave_sel query::Selection); } impl schema::Visitor for Print { print!(enter_schema schema::Document); print!(enter_schema_def schema::Definition); print!(enter_field schema::Field); print!(leave_field schema::Field); print!(leave_schema_def schema::Definition); print!(leave_schema schema::Document); }
use std::io::ErrorKind; use std::path::PathBuf; use std::fs; use errors::Result; /// Directory for putting output files in. Will be created lazily when the first /// file is created. pub struct OutDir { path: PathBuf, created: bool, } impl OutDir { pub fn new(path: PathBuf) -> Result<OutDir> { Ok(OutDir { path, created: false }) } pub fn create_file(&mut self, filename: &str) -> Result<fs::File> { if !self.created { match fs::create_dir(&self.path) { Ok(()) => (), Err(e) if e.kind() == ErrorKind::AlreadyExists => (), Err(e) => Err(e)?, } self.created = true; } Ok(fs::File::create(self.path.join(filename))?) } }
use atty::Stream; use clap::Clap; use std::error::Error; use std::path::PathBuf; use viuer::{print, print_from_file}; #[derive(Clap, Debug)] #[clap(about = "View random anime fanart in your terminal")] struct Cli { /// Resize the image to a provided height #[clap(short, long)] height: Option<u32>, /// Resize the image to a provided width #[clap(short, long)] width: Option<u32>, #[clap(subcommand)] subcommand: Option<Subcommand>, } #[derive(Clap, Debug)] enum Subcommand { #[clap(name = "safe")] Safebooru(Safebooru), #[clap(name = "dan")] Danbooru(Danbooru), #[clap(name = "url")] Url(Url), #[clap(name = "file")] File(File), } /// Look at random images from Safebooru #[derive(Clap, Debug)] pub struct Safebooru { /// Show data related to image (url, rating, dimensions, tags) #[clap(short, long)] pub details: bool, /// Only display images with suggestive content #[clap(short, long)] pub questionable: bool, /// Search for an image based on Safebooru tags. /// Pass as a string separated by spaces or commas. /// Look at Safebooru's cheatsheet for a full list of search options #[clap(short, long)] pub tags: Option<String>, } /// Look at random images from Danbooru #[derive(Clap, Debug)] pub struct Danbooru { /// Show data related to image (artist, source, character, url, rating, dimensions, tags) #[clap(short, long)] pub details: bool, /// Only display images lacking sexual content. Includes lingerie, /// swimsuits, innocent romance, etc. NOTE: this doesn't mean "safe /// for work." #[clap(short, long)] pub safe: bool, /// Only display images with some nox-explicit nudity or sexual content #[clap(short, long)] pub questionable: bool, /// Only display images with explicit sexual content #[clap(short, long)] pub explicit: bool, /// Search for an image based on Danbooru tags. /// Pass as a string separated by spaces or commas. /// Look at Danbooru's cheatsheet for a full list of search options #[clap(short, long)] pub tags: Option<String>, /// Pass your Danbooru username for authentication. /// NOTE: This doesn't set a persistent environmental variable and /// instead only works for one session #[clap(short, long, requires("key"))] pub username: Option<String>, /// Pass your Danbooru API key for authentication. /// NOTE: This doesn't set a persistent environmental variable and /// instead only works for one session #[clap(short, long, requires("username"))] pub key: Option<String>, } /// View an image from a url #[derive(Clap, Debug)] struct Url { /// The URL of an image (e.g. https://i.redd.it/7tycieudz3c61.png) image_url: String, } /// View an image from your file system #[derive(Clap, Debug)] struct File { /// The path to an image file (e.g. ~/Pictures/your-image.jpg) #[clap(parse(from_os_str), value_hint = clap::ValueHint::FilePath)] file_path: PathBuf, } pub fn run() -> Result<(), Box<dyn Error>> { let args = Cli::parse(); let result: Result<(), Box<dyn Error>>; let Cli { width, height, .. } = args; let config = viuer::Config { width, height, absolute_offset: false, ..Default::default() }; // Read from stdin if atty::isnt(Stream::Stdin) { result = show_image_from_stdin(config); return result; } if let Some(subcommand) = args.subcommand { match subcommand { Subcommand::Danbooru(args) => { let dan_args = Danbooru { ..args }; let dan_args = Subcommand::Danbooru(dan_args); result = show_random_image(dan_args, config); } Subcommand::Safebooru(args) => { let safe_args = Safebooru { ..args }; let safe_args = Subcommand::Safebooru(safe_args); result = show_random_image(safe_args, config); } Subcommand::File(file) => { result = show_image_with_path(file.file_path, config); } Subcommand::Url(url) => { result = show_image_with_url(url.image_url, config); } }; } else { let default_options = Safebooru { details: false, questionable: false, tags: None, }; let default = Subcommand::Safebooru(default_options); result = show_random_image(default, config); } result } fn show_random_image(args: Subcommand, config: viuer::Config) -> Result<(), Box<dyn Error>> { use crate::api::{danbooru, safebooru}; let image_url = match args { Subcommand::Danbooru(args) => danbooru::grab_random_image(args), Subcommand::Safebooru(args) => safebooru::grab_random_image(args), _ => panic!( "Invalid subcommand passed to show_random_image. \ Only valid ones are 'Danbooru' and 'Safebooru'." ), }; show_image_with_url(image_url, config) } fn show_image_with_url(image_url: String, config: viuer::Config) -> Result<(), Box<dyn Error>> { let image_bytes = reqwest::blocking::get(&image_url)?.bytes()?; let image = image::load_from_memory(&image_bytes)?; print(&image, &config)?; Ok(()) } fn show_image_with_path(image_path: PathBuf, config: viuer::Config) -> Result<(), Box<dyn Error>> { print_from_file(image_path, &config)?; Ok(()) } fn show_image_from_stdin(config: viuer::Config) -> Result<(), Box<dyn Error>> { use std::io::{stdin, Read}; let stdin = stdin(); let mut handle = stdin.lock(); let mut buffer: Vec<u8> = Vec::new(); let _ = handle.read_to_end(&mut buffer)?; let image = image::load_from_memory(&buffer)?; print(&image, &config)?; Ok(()) }
fn main() { for x in 1..101 { match x % 15 { 0 => println!("fizzbuzz"), i if i % 3 == 0 => println!("fizz"), i if i % 5 == 0 => println!("buzz"), _ => println!("{}", x), } } }
use conformal_visualizer::create_gridlines; use nannou::prelude::*; use nannou::ui::prelude::*; use num::Complex; fn main() { nannou::app(model).update(update).view(view).run(); } struct Model { ui: Ui, ids: Ids, scale: f32, position: Point2, apply_function: bool, resolution: f32, x_min: f32, x_max: f32, y_min: f32, y_max: f32, parameter_1: Complex<f32>, parameter_homotopy: f32, } widget_ids! { struct Ids { scale, apply_function, resolution, x_min, x_max, y_min, y_max, parameter_1, parameter_homotopy, } } fn model(app: &App) -> Model { // Set the loop mode to wait for events, an energy-efficient option for pure-GUI apps. app.new_window() .key_released(key_released) .mouse_wheel(mouse_wheel) .build() .unwrap(); app.set_loop_mode(LoopMode::Wait); // Create the UI. let mut ui = app.new_ui().build().unwrap(); // Generate some ids for our widgets. let ids = Ids::new(ui.widget_id_generator()); // Init our variables let scale = 5.0; let position = pt2(0.0, 0.0); let apply_function = true; let resolution = 2.0; let x_min = -0.0; let x_max = 1.0; let y_min = 0.0; let y_max = 1.0; let parameter_1 = Complex::<f32>::new(1.0, 0.0); let parameter_homotopy = 0.0; Model { ui, ids, scale, position, apply_function, resolution, x_min, x_max, y_min, y_max, parameter_1, parameter_homotopy, } } fn key_released(_app: &App, model: &mut Model, key: Key) { match key { Key::Space => model.apply_function = !model.apply_function, Key::R => model.parameter_1 = Complex::new(1.0, 0.0), _ => {} } } fn mouse_wheel(app: &App, model: &mut Model, dt: MouseScrollDelta, _phase: TouchPhase) { match dt { MouseScrollDelta::PixelDelta(pos) => { if app.keys.down.contains(&Key::A) { model.x_min -= pos.x as f32 / pow(2.0, model.resolution as usize) as f32 / 2.0 } if app.keys.down.contains(&Key::D) { model.x_max -= pos.x as f32 / pow(2.0, model.resolution as usize) as f32 / 2.0 } if app.keys.down.contains(&Key::W) { model.y_max -= pos.y as f32 / pow(2.0, model.resolution as usize) as f32 / 2.0 } if app.keys.down.contains(&Key::S) { model.y_min -= pos.y as f32 / pow(2.0, model.resolution as usize) as f32 / 2.0 } if app.keys.down.contains(&Key::LShift) { model.scale -= pos.y as f32 / 10.0 } if app.keys.down.contains(&Key::LControl) { model.resolution -= pos.y as f32 / 20.0 } if app.keys.down.is_empty() { model.position -= pt2(pos.x as f32, pos.y as f32) / model.scale.exp() * 10.0 } } _ => {} } } fn update(_app: &App, model: &mut Model, _update: Update) { // Calling `set_widgets` allows us to instantiate some widgets. let ui = &mut model.ui.set_widgets(); fn slider(val: f32, min: f32, max: f32) -> widget::Slider<'static, f32> { widget::Slider::new(val, min, max) .w_h(200.0, 30.0) .label_font_size(15) .rgb(0.3, 0.3, 0.3) .label_rgb(1.0, 1.0, 1.0) .border(0.0) } for value in slider(model.scale, 10.0, 500.0) .top_left_with_margin(10.0) .label("Scale") .set(model.ids.scale, ui) { model.scale = value; } for value in widget::Toggle::new(model.apply_function) .w_h(200.0, 30.0) .label_font_size(15) .rgb(0.3, 0.3, 0.3) .label_rgb(1.0, 1.0, 1.0) .border(0.0) .down(10.0) .label("Apply function") .set(model.ids.apply_function, ui) { model.apply_function = value; } for value in slider(model.resolution, 0.0, 5.0) .down(10.0) .label("Resolution") .set(model.ids.resolution, ui) { model.resolution = value; } for value in slider(model.x_min, -15.0, 15.0) .down(10.0) .label("x_min") .set(model.ids.x_min, ui) { model.x_min = value; } for value in slider(model.x_max, -15.0, 15.0) .down(10.0) .label("x_max") .set(model.ids.x_max, ui) { model.x_max = value; } for value in slider(model.y_min, -15.0, 15.0) .down(10.0) .label("y_min") .set(model.ids.y_min, ui) { model.y_min = value; } for value in slider(model.y_max, -15.0, 15.0) .down(10.0) .label("y_max") .set(model.ids.y_max, ui) { model.y_max = value; } for (x, y) in widget::XYPad::new( model.parameter_1.re, -3.0, 3.0, model.parameter_1.im, -3.0, 3.0, ) .down(10.0) .w_h(200.0, 200.0) .label("Parameter 1") .label_font_size(15) .rgb(0.3, 0.3, 0.3) .label_rgb(1.0, 1.0, 1.0) .border(0.0) .set(model.ids.parameter_1, ui) { model.parameter_1 = Complex::<f32>::new(x, y); } for value in slider(model.parameter_homotopy, 0.0, 1.0) .down(10.0) .label("homotopy parameter") .set(model.ids.parameter_homotopy, ui) { model.parameter_homotopy = value; } } fn coordinate_lines(model: &Model) -> Vec<Vec<Point2>> { vec![ vec![ to_screen_coords(-1.0, 0.0, model), to_screen_coords(1.0, 0.0, model), ], vec![ to_screen_coords(0.0, -1.0, model), to_screen_coords(0.0, 1.0, model), ], ] } fn to_screen_coords(x: f32, y: f32, model: &Model) -> Point2 { (pt2(x, y) + model.position) * model.scale.exp() } // Draw the state of your `Model` into the given `Frame` here. fn view(app: &App, model: &Model, frame: Frame) { let (points, line_structure) = create_gridlines( 4.0, model.resolution, model.x_min, model.x_max, model.y_min, model.y_max, ); let points = points.map(|z| { if model.apply_function { // change this to visualize a different function (1.0 - z) / (1.0 + z) * model.parameter_1 } else { z } }); let mut points = points.map(|z| to_screen_coords(z.re, z.im, model)); // Begin drawing let draw = app.draw(); draw.background().rgb(0.02, 0.02, 0.02); for coord_line in coordinate_lines(&model) { draw.arrow() .weight(1.0) .head_length(0.1 * model.scale.exp()) .head_width(0.05 * model.scale.exp()) .color(srgba(1.0, 1.0, 1.0, 1.0)) .start(coord_line[0]) .end(coord_line[1]); } for line_len in line_structure { let line: Vec<_> = points.by_ref().take(line_len).collect(); draw.polyline() .weight(2.0) .color(srgba(1.0, 1.0, 1.0, 1.0)) .points(line); } // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); // Draw the state of the `Ui` to the frame. model.ui.draw_to_frame(app, &frame).unwrap(); }
use core::ops::Index; use necsim_core_bond::{NonNegativeF64, PositiveF64}; use super::{Habitat, LineageReference, OriginSampler}; use crate::{ landscape::{IndexedLocation, Location}, lineage::{GlobalLineageReference, Lineage}, }; #[allow(clippy::inline_always, clippy::inline_fn_without_body)] #[contract_trait] pub trait LineageStore<H: Habitat, R: LineageReference<H>>: crate::cogs::Backup + Sized + core::fmt::Debug { type LineageReferenceIterator<'a>: Iterator<Item = R>; #[must_use] fn from_origin_sampler<'h, O: OriginSampler<'h, Habitat = H>>(origin_sampler: O) -> Self where H: 'h; #[must_use] fn get_number_total_lineages(&self) -> usize; #[must_use] fn iter_local_lineage_references(&self) -> Self::LineageReferenceIterator<'_>; #[must_use] fn get(&self, reference: R) -> Option<&Lineage>; } #[allow(clippy::inline_always, clippy::inline_fn_without_body)] #[allow(clippy::module_name_repetitions)] #[contract_trait] pub trait LocallyCoherentLineageStore<H: Habitat, R: LineageReference<H>>: LineageStore<H, R> + Index<R, Output = Lineage> { #[must_use] #[debug_requires( habitat.contains(indexed_location.location()), "indexed location is inside habitat" )] fn get_active_global_lineage_reference_at_indexed_location( &self, indexed_location: &IndexedLocation, habitat: &H, ) -> Option<&GlobalLineageReference>; #[debug_requires( habitat.contains(indexed_location.location()), "indexed location is inside habitat" )] #[debug_requires(self.get(reference.clone()).is_some(), "lineage reference is valid")] #[debug_requires(!self[reference.clone()].is_active(), "lineage is inactive")] #[debug_ensures(self[old(reference.clone())].is_active(), "lineage was activated")] #[debug_ensures( self[old(reference.clone())].indexed_location() == Some(&old(indexed_location.clone())), "lineage was added to indexed_location" )] #[debug_ensures( self.get_active_global_lineage_reference_at_indexed_location( &old(indexed_location.clone()), old(habitat) ) == Some(self[old(reference.clone())].global_reference()), "lineage is now indexed at indexed_location" )] fn insert_lineage_to_indexed_location_locally_coherent( &mut self, reference: R, indexed_location: IndexedLocation, habitat: &H, ); #[must_use] #[debug_requires(self.get(reference.clone()).is_some(), "lineage reference is valid")] #[debug_requires(self[reference.clone()].is_active(), "lineage is active")] #[debug_ensures(old(habitat).contains(ret.0.location()), "prior location is inside habitat")] #[debug_ensures(!self[old(reference.clone())].is_active(), "lineage was deactivated")] #[debug_ensures( ret.0 == old(self[reference.clone()].indexed_location().unwrap().clone()), "returns the individual's prior IndexedLocation" )] #[debug_ensures( ret.1 == old(self[reference.clone()].last_event_time()), "returns the individual's prior last event time" )] #[debug_ensures(self.get_active_global_lineage_reference_at_indexed_location( &ret.0, old(habitat) ).is_none(), "lineage is no longer indexed at its prior IndexedLocation")] #[debug_ensures( self[old(reference.clone())].last_event_time() == old(event_time), "updates the time of the last event of the lineage reference" )] fn extract_lineage_from_its_location_locally_coherent( &mut self, reference: R, event_time: PositiveF64, habitat: &H, ) -> (IndexedLocation, NonNegativeF64); #[debug_requires( self.get(local_lineage_reference.clone()).is_some(), "lineage reference is valid" )] #[debug_requires( !self[local_lineage_reference.clone()].is_active(), "lineage is inactive" )] #[debug_ensures( self.get(old(local_lineage_reference.clone())).is_none(), "lineage was removed" )] #[debug_ensures( ret == old(self[local_lineage_reference.clone()].global_reference().clone()), "returns the individual's GlobalLineageReference" )] fn emigrate(&mut self, local_lineage_reference: R) -> GlobalLineageReference; #[must_use] #[debug_requires( habitat.contains(indexed_location.location()), "indexed location is inside habitat" )] #[debug_ensures(self[ret.clone()].is_active(), "lineage was activated")] #[debug_ensures( self[ret.clone()].indexed_location() == Some(&old(indexed_location.clone())), "lineage was added to indexed_location" )] #[debug_ensures( self.get_active_global_lineage_reference_at_indexed_location( &old(indexed_location.clone()), old(habitat) ) == Some(self[ret.clone()].global_reference()), "lineage is now indexed at indexed_location" )] fn immigrate_locally_coherent( &mut self, habitat: &H, global_reference: GlobalLineageReference, indexed_location: IndexedLocation, time_of_emigration: PositiveF64, ) -> R; } #[allow(clippy::inline_always, clippy::inline_fn_without_body)] #[allow(clippy::module_name_repetitions)] #[contract_trait] pub trait GloballyCoherentLineageStore<H: Habitat, R: LineageReference<H>>: LocallyCoherentLineageStore<H, R> { type LocationIterator<'a>: Iterator<Item = Location>; #[must_use] fn iter_active_locations(&self, habitat: &H) -> Self::LocationIterator<'_>; #[must_use] #[debug_requires(habitat.contains(location), "location is inside habitat")] fn get_active_local_lineage_references_at_location_unordered( &self, location: &Location, habitat: &H, ) -> &[R]; #[debug_ensures( self.get_active_local_lineage_references_at_location_unordered( &old(indexed_location.location().clone()), old(habitat) ).last() == Some(&old(reference.clone())), "lineage is now indexed unordered at indexed_location.location()" )] #[debug_ensures( old(self.get_active_local_lineage_references_at_location_unordered( indexed_location.location(), old(habitat) ).len() + 1) == self.get_active_local_lineage_references_at_location_unordered( &old(indexed_location.location().clone()), old(habitat) ).len(), "unordered active lineage index at given location has grown by 1" )] fn insert_lineage_to_indexed_location_globally_coherent( &mut self, reference: R, indexed_location: IndexedLocation, habitat: &H, ) { self.insert_lineage_to_indexed_location_locally_coherent( reference, indexed_location, habitat, ); } #[must_use] #[debug_ensures( self.get_active_local_lineage_references_at_location_unordered( ret.0.location(), old(habitat), ).len() + 1 == old(self.get_active_local_lineage_references_at_location_unordered( self[reference.clone()].indexed_location().unwrap().location(), old(habitat), ).len()), "unordered active lineage index at returned location has shrunk by 1")] fn extract_lineage_from_its_location_globally_coherent( &mut self, reference: R, event_time: PositiveF64, habitat: &H, ) -> (IndexedLocation, NonNegativeF64) { self.extract_lineage_from_its_location_locally_coherent(reference, event_time, habitat) } #[must_use] #[debug_ensures( self.get_active_local_lineage_references_at_location_unordered( &old(indexed_location.location().clone()), old(habitat) ).last() == Some(&ret), "lineage is now indexed unordered at indexed_location.location()" )] #[debug_ensures( old(self.get_active_local_lineage_references_at_location_unordered( indexed_location.location(), old(habitat) ).len() + 1) == self.get_active_local_lineage_references_at_location_unordered( &old(indexed_location.location().clone()), old(habitat) ).len(), "unordered active lineage index at given location has grown by 1" )] fn immigrate_globally_coherent( &mut self, habitat: &H, global_reference: GlobalLineageReference, indexed_location: IndexedLocation, time_of_emigration: PositiveF64, ) -> R { self.immigrate_locally_coherent( habitat, global_reference, indexed_location, time_of_emigration, ) } }
extern crate serde_yaml; mod tag; use serde_yaml::Value; use std::env; use std::fs::File; use std::io::prelude::*; use std::process; fn main() { let args: Vec<String> = env::args().collect(); let filename = match args.get(1) { Some(path) => path, None => { eprintln!("no file specified"); process::exit(1); } }; println!("reading from: {}", filename); let file = match File::open(filename) { Ok(f) => f, Err(reason) => { eprintln!("could not open {} due to: {}", filename, reason); process::exit(2); } }; let systems: Value = match serde_yaml::from_reader(&file) { Ok(value) => value, Err(reason) => { eprintln!("could not parse {} due to: {}", filename, reason); process::exit(1); } }; println!("{:?}", systems); }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - control register"] pub ctr: CTR, } #[doc = "CTR (rw) register accessor: control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ctr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ctr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ctr`] module"] pub type CTR = crate::Reg<ctr::CTR_SPEC>; #[doc = "control register"] pub mod ctr;
use dirs::config_dir; use serde::{Deserialize, Serialize}; use std::env; use std::collections::HashMap; use std::fs; use std::path::{Path, PathBuf}; use tempdir::TempDir; #[derive(Debug, Deserialize, Serialize)] pub struct RegistryConfig { token: String, } impl PartialEq for RegistryConfig { fn eq(&self, other: &Self) -> bool { self.token == other.token } } #[derive(Debug, Deserialize, Serialize)] pub struct BuffCliConfig { pub preferred_registry: String, registries: HashMap<String, RegistryConfig>, } pub fn get_default_registry_url() -> String { match std::env::var("BUFF_REGISTRY_URL") { Ok(s) => s, _ => "localhost:50051".to_string(), } } impl BuffCliConfig { pub fn new() -> Self { let path = get_config_path(); let mut config = BuffCliConfig { preferred_registry: get_default_registry_url(), registries: HashMap::new(), }; if path.exists() { let toml_content = fs::read_to_string(path).unwrap(); config = toml::from_str(&toml_content).expect("Failed to parse toml"); } config } pub fn add_registry(&mut self, url: &str, token: &str) { self.registries.insert( url.to_string(), RegistryConfig { token: token.to_string(), }, ); } pub fn save(&self) { let config_path = get_config_path(); //note(itay): Annoyingly, this is how we extract the dir from a path //that might end with a filename. let config_dir = config_path.with_file_name(""); if !config_dir.exists() { std::fs::create_dir(config_dir).expect("Failed to create config dir"); } let toml_content = toml::to_string(self).unwrap(); fs::write(config_path, toml_content).expect("Failed to save config"); } } fn get_config_path() -> PathBuf { match env::var("BUFF_HOME") { Ok(s) => std::env::current_dir() .unwrap() .join(&s) .join("config.toml"), _ => config_dir().unwrap().join("buff/config.toml"), } } #[test] fn should_new() { env::set_var("BUFF_HOME", "../tests/fixtures/buff_home"); let config = BuffCliConfig::new(); assert_eq!(config.preferred_registry, "localhost:50051"); assert_eq!(config.registries.len(), 2); assert_eq!( config.registries["localhost:50051"], RegistryConfig { token: "token1".to_string() } ); assert_eq!( config.registries["localhost:50052"], RegistryConfig { token: "token2".to_string() } ); } #[test] fn should_save() { let tmp_dir = TempDir::new("buff_test").unwrap(); let url = "localhost:50051"; let token = "newtoken"; env::set_var("BUFF_HOME", tmp_dir.path().join("buff")); let mut config = BuffCliConfig::new(); config.add_registry(url, token); config.save(); config = BuffCliConfig::new(); assert_eq!(config.registries.len(), 1); assert_eq!( config.registries[url], RegistryConfig { token: token.to_string() } ); }
#[doc = "Reader of register TEMP_ITR1"] pub type R = crate::R<u32, super::TEMP_ITR1>; #[doc = "Writer for register TEMP_ITR1"] pub type W = crate::W<u32, super::TEMP_ITR1>; #[doc = "Register TEMP_ITR1 `reset()`'s with value 0"] impl crate::ResetValue for super::TEMP_ITR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TS1_LITTHD`"] pub type TS1_LITTHD_R = crate::R<u16, u16>; #[doc = "Write proxy for field `TS1_LITTHD`"] pub struct TS1_LITTHD_W<'a> { w: &'a mut W, } impl<'a> TS1_LITTHD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } #[doc = "Reader of field `TS1_HITTHD`"] pub type TS1_HITTHD_R = crate::R<u16, u16>; #[doc = "Write proxy for field `TS1_HITTHD`"] pub struct TS1_HITTHD_W<'a> { w: &'a mut W, } impl<'a> TS1_HITTHD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0xffff << 16)) | (((value as u32) & 0xffff) << 16); self.w } } impl R { #[doc = "Bits 0:15 - TS1_LITTHD"] #[inline(always)] pub fn ts1_litthd(&self) -> TS1_LITTHD_R { TS1_LITTHD_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - TS1_HITTHD"] #[inline(always)] pub fn ts1_hitthd(&self) -> TS1_HITTHD_R { TS1_HITTHD_R::new(((self.bits >> 16) & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - TS1_LITTHD"] #[inline(always)] pub fn ts1_litthd(&mut self) -> TS1_LITTHD_W { TS1_LITTHD_W { w: self } } #[doc = "Bits 16:31 - TS1_HITTHD"] #[inline(always)] pub fn ts1_hitthd(&mut self) -> TS1_HITTHD_W { TS1_HITTHD_W { w: self } } }
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // 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. #[macro_use] extern crate log; extern crate env_logger; extern crate time; extern crate petgraph; extern crate walkdir; extern crate habitat_core as hab_core; extern crate builder_core as bldr_core; extern crate habitat_builder_protocol as protocol; extern crate habitat_builder_db as db; extern crate habitat_net as hab_net; extern crate clap; extern crate postgres; extern crate protobuf; extern crate r2d2; pub mod data_store; pub mod error; use std::io::{self, Write}; use clap::{Arg, App}; use time::PreciseTime; use bldr_core::package_graph::PackageGraph; use data_store::DataStore; fn main() { env_logger::init().unwrap(); let matches = App::new("hab-spider") .version("0.1.0") .about("Habitat package graph builder") .arg(Arg::with_name("URL") .help("The DB connection URL") .required(true) .index(1)) .get_matches(); let connection_url = matches.value_of("URL").unwrap(); println!("Connecting to {}", connection_url); let datastore = DataStore::new(connection_url).unwrap(); datastore.setup().unwrap(); println!("Building graph... please wait."); let mut graph = PackageGraph::new(); let packages = datastore.get_packages().unwrap(); let start_time = PreciseTime::now(); let (ncount, ecount) = graph.build(packages.into_iter()); let end_time = PreciseTime::now(); println!("OK: {} nodes, {} edges ({} sec)", ncount, ecount, start_time.to(end_time)); println!("\nAvailable commands: help, stats, top, find, resolve, rdeps, exit\n"); let mut done = false; while !done { print!("spider> "); io::stdout() .flush() .ok() .expect("Could not flush stdout"); let mut cmd = String::new(); io::stdin().read_line(&mut cmd).unwrap(); let v: Vec<&str> = cmd.trim_right().split_whitespace().collect(); if v.len() > 0 { match v[0].to_lowercase().as_str() { "help" => do_help(), "stats" => do_stats(&graph), "top" => { let count = if v.len() < 2 { 10 } else { v[1].parse::<usize>().unwrap() }; do_top(&graph, count); } "find" => { if v.len() < 2 { println!("Missing search term\n") } else { let max = if v.len() > 2 { v[2].parse::<usize>().unwrap() } else { 10 }; do_find(&graph, v[1].to_lowercase().as_str(), max) } } "resolve" => { if v.len() < 2 { println!("Missing package name\n") } else { do_resolve(&graph, v[1].to_lowercase().as_str()) } } "rdeps" => { if v.len() < 2 { println!("Missing package name\n") } else { let max = if v.len() > 2 { v[2].parse::<usize>().unwrap() } else { 10 }; do_rdeps(&graph, v[1].to_lowercase().as_str(), max) } } "exit" => done = true, _ => println!("Unknown command\n"), } } } } fn do_help() { println!("COMMANDS:"); println!(" help Print this message"); println!(" stats Print graph statistics"); println!(" top [<count>] Print nodes with the most reverse dependencies"); println!(" resolve <name> Find the most recent version of the package 'origin/name'"); println!(" find <term> [<max>] Find packages that match the search term, up to max items"); println!(" rdeps <name> [<max>] Print the reverse dependencies for the package, up to max"); println!(" exit Exit the application\n"); } fn do_stats(graph: &PackageGraph) { let stats = graph.stats(); println!("Node count: {}", stats.node_count); println!("Edge count: {}", stats.edge_count); println!("Connected components: {}", stats.connected_comp); println!("Is cyclic: {}\n", stats.is_cyclic); } fn do_top(graph: &PackageGraph, count: usize) { let start_time = PreciseTime::now(); let top = graph.top(count); let end_time = PreciseTime::now(); println!("OK: {} items ({} sec)\n", top.len(), start_time.to(end_time)); for (name, count) in top { println!("{}: {}", name, count); } println!(""); } fn do_find(graph: &PackageGraph, phrase: &str, max: usize) { let start_time = PreciseTime::now(); let mut v = graph.search(phrase); let end_time = PreciseTime::now(); println!("OK: {} items ({} sec)\n", v.len(), start_time.to(end_time)); if v.is_empty() { println!("No matching packages found") } else { if v.len() > max { v.drain(max..); } for s in v { println!("{}", s); } } println!(""); } fn do_resolve(graph: &PackageGraph, name: &str) { let start_time = PreciseTime::now(); let result = graph.resolve(name); let end_time = PreciseTime::now(); println!("OK: ({} sec)\n", start_time.to(end_time)); match result { Some(s) => println!("{}", s), None => println!("No matching packages found"), } println!(""); } fn do_rdeps(graph: &PackageGraph, name: &str, max: usize) { let start_time = PreciseTime::now(); match graph.rdeps(name) { Some(mut rdeps) => { let end_time = PreciseTime::now(); println!("OK: {} items ({} sec)\n", rdeps.len(), start_time.to(end_time)); if rdeps.len() > max { rdeps.drain(max..); } for s in rdeps { println!("{}", s); } } None => println!("No entries found"), } println!(""); }
// Copyright (c) 2017 The Noise-rs Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT // or http://opensource.org/licenses/MIT>, at your option. All files in the // project carrying such notice may not be copied, modified, or distributed // except according to those terms. // TODO: Use PrimInt + Signed instead of SignedInt + NumCast once num has // PrimInt implementations use math; use num_traits::{NumCast, PrimInt, Signed}; use rand::{Rand, Rng, SeedableRng, XorShiftRng}; use std::fmt; const TABLE_SIZE: usize = 256; /// A seed table, required by all noise functions. /// /// Table creation is expensive, so in most circumstances you'll only want to /// create one of these per generator. #[derive(Copy)] #[deprecated(since="0.3.0", note="will be made private by 1.0; noise generator structs (e.g. Perlin) now store permutation table internally, so if you were storing PermutationTable for performance reasons, store the noise generator object instead")] pub struct PermutationTable { values: [u8; TABLE_SIZE], } impl Rand for PermutationTable { /// Generates a PermutationTable using a random seed. /// /// # Examples /// /// ```rust /// extern crate noise; /// extern crate rand; /// /// use noise::PermutationTable; /// /// # fn main() { /// let perm_table = rand::random::<PermutationTable>(); /// # } /// ``` /// /// ```rust /// extern crate noise; /// extern crate rand; /// /// use noise::PermutationTable; /// use rand::{SeedableRng, Rng, XorShiftRng}; /// /// # fn main() { /// let mut rng: XorShiftRng = SeedableRng::from_seed([1, 2, 3, 4]); /// let perm_table = rng.gen::<PermutationTable>(); /// # } /// ``` fn rand<R: Rng>(rng: &mut R) -> PermutationTable { let mut seq: Vec<u8> = (0..TABLE_SIZE).map(|x| x as u8).collect(); rng.shuffle(&mut *seq); // It's unfortunate that this double-initializes the array, but Rust // doesn't currently provide a clean way to do this in one pass. Hopefully // it won't matter, as Seed creation will usually be a one-time event. let mut perm_table = PermutationTable { values: [0; TABLE_SIZE] }; let seq_it = seq.iter(); for (x, y) in perm_table.values.iter_mut().zip(seq_it) { *x = *y } perm_table } } impl PermutationTable { /// Deterministically generates a new permutation table based on a `u32` seed value. /// /// Internally this uses a `XorShiftRng`, but we don't really need to worry /// about cryptographic security when working with procedural noise. /// /// # Example /// /// ```rust /// use noise::PermutationTable; /// /// let perm_table = PermutationTable::new(12); /// ``` pub fn new(seed: u32) -> PermutationTable { let mut rng: XorShiftRng = SeedableRng::from_seed([1, seed, seed, seed]); rng.gen() } #[inline(always)] pub fn get1<T: Signed + PrimInt + NumCast>(&self, x: T) -> usize { let x: usize = math::cast(x & math::cast(0xff)); self.values[x] as usize } #[inline(always)] pub fn get2<T: Signed + PrimInt + NumCast>(&self, pos: math::Point2<T>) -> usize { let y: usize = math::cast(pos[1] & math::cast(0xff)); self.values[self.get1(pos[0]) ^ y] as usize } #[inline(always)] pub fn get3<T: Signed + PrimInt + NumCast>(&self, pos: math::Point3<T>) -> usize { let z: usize = math::cast(pos[2] & math::cast(0xff)); self.values[self.get2([pos[0], pos[1]]) ^ z] as usize } #[inline(always)] pub fn get4<T: Signed + PrimInt + NumCast>(&self, pos: math::Point4<T>) -> usize { let w: usize = math::cast(pos[3] & math::cast(0xff)); self.values[self.get3([pos[0], pos[1], pos[2]]) ^ w] as usize } } impl Clone for PermutationTable { fn clone(&self) -> PermutationTable { PermutationTable { values: self.values } } } impl fmt::Debug for PermutationTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "PermutationTable {{ .. }}") } } #[cfg(test)] mod tests { use super::PermutationTable; use perlin::perlin3; use rand::random; #[test] fn test_random_seed() { let _ = perlin3::<f32>(&random(), &[1.0, 2.0, 3.0]); } #[test] fn test_negative_params() { let _ = perlin3::<f32>(&PermutationTable::new(0), &[-1.0, 2.0, 3.0]); } }
use super::*; use std::collections::HashMap; use std::path::Path; pub fn traverse_reduce(path: impl AsRef<Path>) -> Result<String, Error> { use std::path::Component::*; let path = path.as_ref(); let mut input = String::new(); if path.parent().is_none() { input.push_str(&path.to_string_lossy()); fix_trailing(&mut input); return Ok(input); } let mut buf = vec![]; // initial buf.push(path.file_stem().unwrap().to_string_lossy().to_string()); fn head(s: impl AsRef<str>) -> char { s.as_ref().chars().next().unwrap() } let mut path = path; while let Some(parent) = path.parent() { if let Some(RootDir) = parent.components().next() { break; } let base = path.file_stem().expect("valid file stem"); path = parent; let map = std::fs::read_dir(&parent) .map_err(|err| Error { kind: ErrorKind::InvalidDirectory(parent.to_string_lossy().to_string()), inner: err.to_string(), })? .flatten() .filter_map(|d| d.file_type().ok().and_then(|ft| ft.is_dir().as_opt(d))) .filter_map(|d| { d.path() .file_stem() .map(|s| s.to_string_lossy().to_string()) }) .fold(HashMap::<char, usize>::default(), |mut map, s| { *map.entry(head(s).to_ascii_lowercase()).or_default() += 1; map }); let base = base.to_string_lossy(); let h = head(&base).to_ascii_lowercase(); if *map.get(&h).unwrap() == 1 { buf.push(h.to_string()); } else { buf.push(base.to_string()) } } let mut pb = path.to_path_buf(); for el in buf.into_iter().rev() { pb = pb.join(el) } input.push_str(&pb.to_string_lossy()); fix_trailing(&mut input); Ok(input) }
use crate::{imp, io}; use io_lifetimes::OwnedFd; #[cfg(any( linux_raw, all( libc, not(any(target_os = "ios", target_os = "macos", target_os = "wasi")) ) ))] pub use imp::io::PipeFlags; /// `pipe()`—Creates a pipe. /// /// This function creates a pipe and returns two file descriptors, for the /// reading and writing ends of the pipe, respectively. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pipe.html /// [Linux]: https://man7.org/linux/man-pages/man2/pipe.2.html #[cfg(any(target_os = "ios", target_os = "macos"))] #[inline] pub fn pipe() -> io::Result<(OwnedFd, OwnedFd)> { imp::syscalls::pipe() } /// `pipe2(flags)`—Creates a pipe, with flags. /// /// This function creates a pipe and returns two file descriptors, for the /// reading and writing ends of the pipe, respectively. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/pipe2.2.html #[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "wasi")))] #[inline] #[doc(alias = "pipe2")] pub fn pipe_with(flags: PipeFlags) -> io::Result<(OwnedFd, OwnedFd)> { imp::syscalls::pipe_with(flags) }
#[macro_use] extern crate cached; extern crate pathfinding; use failure::Error; use pathfinding::prelude::{absdiff, astar}; // Should be large enough to find the best path... const GRID_SIZE: usize = 2048; // Example input. // const DEPTH: usize = 510; // const TARGET: (usize, usize) = (10, 10); // Puzzle input. const DEPTH: usize = 11109; const TARGET: (usize, usize) = (9, 731); #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum RegionType { Rocky, Narrow, Wet, } cached! { GEO_INDEX; fn geologic_index(x: usize, y: usize) -> usize = { match (x, y) { (0, 0) => 0, TARGET => 0, (x, 0) => x * 16807, (0, y) => y * 48271, _ => erosion_level(x - 1, y) * erosion_level(x, y - 1), } } } fn erosion_level(x: usize, y: usize) -> usize { (geologic_index(x, y) + DEPTH) % 20183 } fn region_type(x: usize, y: usize) -> RegionType { match erosion_level(x, y) % 3 { 0 => RegionType::Rocky, 1 => RegionType::Wet, 2 => RegionType::Narrow, _ => unreachable!(), } } fn draw(grid: &Vec<Vec<RegionType>>) { for y in 0..16 { for x in 0..16 { print!( "{}", match grid[y][x] { RegionType::Rocky => '.', RegionType::Wet => '=', RegionType::Narrow => '|', } ); } print!("\n"); } } fn risk_level( grid: &Vec<Vec<RegionType>>, top_left: (usize, usize), bottom_right: (usize, usize), ) -> usize { let mut risk = 0; for y in top_left.1..=bottom_right.1 { for x in top_left.0..=bottom_right.0 { risk += match grid[y][x] { RegionType::Rocky => 0, RegionType::Wet => 1, RegionType::Narrow => 2, } } } risk } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] enum Tool { Torch, ClimbingGear, Neither, } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] struct State { x: usize, y: usize, tool: Tool, } impl State { fn heuristic(&self, other: &State) -> usize { absdiff(self.x, other.x) + absdiff(self.y, other.y) + if self.tool != other.tool { 7 } else { 0 } } fn successors(&self, grid: &Vec<Vec<RegionType>>) -> Vec<(State, usize)> { let mut successors = Vec::new(); // We can stay in place and change tool. for &tool in &[Tool::Torch, Tool::ClimbingGear, Tool::Neither] { if tool != self.tool { successors.push((State { tool, ..*self }, 7)); } } // Or we can keep our current tool, but try to move. let x = self.x; let y = self.y; for target in &[(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] { if target.0 > GRID_SIZE || target.1 > GRID_SIZE { continue; } match (grid[target.1][target.0], self.tool) { (RegionType::Rocky, Tool::Torch) | (RegionType::Rocky, Tool::ClimbingGear) | (RegionType::Wet, Tool::ClimbingGear) | (RegionType::Wet, Tool::Neither) | (RegionType::Narrow, Tool::Torch) | (RegionType::Narrow, Tool::Neither) => { successors.push(( State { x: target.0, y: target.1, ..*self }, 1, )); } _ => (), } } successors } } fn solve(grid: &Vec<Vec<RegionType>>) -> usize { let start = State { x: 0, y: 0, tool: Tool::Torch, }; let goal = State { x: TARGET.0, y: TARGET.1, tool: Tool::Torch, }; let result = astar( &start, |n| n.successors(&grid), |n| n.heuristic(&goal), |n| *n == goal, ); if let Some((_, total_cost)) = result { return total_cost; } panic!("a-star failed"); } fn main() -> Result<(), Error> { let mut grid = vec![vec![RegionType::Rocky; GRID_SIZE]; GRID_SIZE]; for y in 0..2048 { for x in 0..2048 { grid[y][x] = region_type(x, y); } } //draw(&grid); println!("risk level: {}", risk_level(&grid, (0, 0), TARGET)); println!("shortest path: {}", solve(&grid)); Ok(()) }
use std::collections::HashMap; use std::fs::read_dir; use std::path::{Path, PathBuf}; use std::sync::Arc; use fluent_bundle::concurrent::FluentBundle; use fluent_bundle::{FluentResource, FluentValue}; use crate::error::LoaderError; pub use unic_langid::{langid, langids, LanguageIdentifier}; /// A builder pattern struct for constructing `ArcLoader`s. pub struct ArcLoaderBuilder<'a, 'b> { location: &'a Path, fallback: LanguageIdentifier, shared: Option<&'b [PathBuf]>, customize: Option<fn(&mut FluentBundle<Arc<FluentResource>>)>, } impl<'a, 'b> ArcLoaderBuilder<'a, 'b> { /// Adds Fluent resources that are shared across all localizations. pub fn shared_resources(mut self, shared: Option<&'b [PathBuf]>) -> Self { self.shared = shared; self } /// Allows you to customise each `FluentBundle`. pub fn customize(mut self, customize: fn(&mut FluentBundle<Arc<FluentResource>>)) -> Self { self.customize = Some(customize); self } /// Constructs an `ArcLoader` from the settings provided. pub fn build(self) -> Result<ArcLoader, Box<dyn std::error::Error>> { let mut resources = HashMap::new(); for entry in read_dir(self.location)? { let entry = entry?; if entry.file_type()?.is_dir() { if let Ok(lang) = entry.file_name().into_string() { let lang_resources = crate::fs::read_from_dir(entry.path())? .into_iter() .map(Arc::new) .collect::<Vec<_>>(); resources.insert(lang.parse::<LanguageIdentifier>()?, lang_resources); } } } let mut bundles = HashMap::new(); for (lang, v) in resources.iter() { let mut bundle = FluentBundle::new(vec![lang.clone()]); for shared_resource in self.shared.as_deref().unwrap_or(&[]) { bundle .add_resource(Arc::new(crate::fs::read_from_file(shared_resource)?)) .map_err(|errors| LoaderError::FluentBundle { errors })?; } for res in v { bundle .add_resource(res.clone()) .map_err(|errors| LoaderError::FluentBundle { errors })?; } if let Some(customize) = self.customize { (customize)(&mut bundle); } bundles.insert(lang.clone(), bundle); } let fallbacks = super::build_fallbacks(&*resources.keys().cloned().collect::<Vec<_>>()); Ok(ArcLoader { bundles, fallbacks, fallback: self.fallback, }) } } /// A loader that uses `Arc<FluentResource>` as its backing storage. This is /// mainly useful for when you need to load fluent at run time. You can /// configure the initialisation with `ArcLoaderBuilder`. /// ```no_run /// use fluent_templates::ArcLoader; /// /// let loader = ArcLoader::builder("locales/", unic_langid::langid!("en-US")) /// .shared_resources(Some(&["locales/core.ftl".into()])) /// .customize(|bundle| bundle.set_use_isolating(false)) /// .build() /// .unwrap(); /// ``` pub struct ArcLoader { bundles: HashMap<LanguageIdentifier, FluentBundle<Arc<FluentResource>>>, fallback: LanguageIdentifier, fallbacks: HashMap<LanguageIdentifier, Vec<LanguageIdentifier>>, } impl super::Loader for ArcLoader { // Traverse the fallback chain, fn lookup_complete<T: AsRef<str>>( &self, lang: &LanguageIdentifier, text_id: &str, args: Option<&HashMap<T, FluentValue>>, ) -> String { if let Some(fallbacks) = self.fallbacks.get(lang) { for l in fallbacks { if let Some(val) = self.lookup_single_language(l, text_id, args) { return val; } } } if *lang != self.fallback { if let Some(val) = self.lookup_single_language(&self.fallback, text_id, args) { return val; } } format!("Unknown localization {}", text_id) } fn locales(&self) -> Box<dyn Iterator<Item = &LanguageIdentifier> + '_> { Box::new(self.fallbacks.keys()) } } impl ArcLoader { /// Creates a new `ArcLoaderBuilder` pub fn builder<P: AsRef<Path> + ?Sized>( location: &P, fallback: LanguageIdentifier, ) -> ArcLoaderBuilder { ArcLoaderBuilder { location: location.as_ref(), fallback, shared: None, customize: None, } } /// Convenience function to look up a string for a single language pub fn lookup_single_language<T: AsRef<str>>( &self, lang: &LanguageIdentifier, text_id: &str, args: Option<&HashMap<T, FluentValue>>, ) -> Option<String> { super::shared::lookup_single_language(&self.bundles, lang, text_id, args) } /// Convenience function to look up a string without falling back to the /// default fallback language pub fn lookup_no_default_fallback<S: AsRef<str>>( &self, lang: &LanguageIdentifier, text_id: &str, args: Option<&HashMap<S, FluentValue>>, ) -> Option<String> { super::shared::lookup_no_default_fallback( &self.bundles, &self.fallbacks, lang, text_id, args, ) } }
//https://ptrace.fefe.de/wp/wpopt.rs // gcc -o lines lines.c // tar xzf llvm-8.0.0.src.tar.xz // find llvm-8.0.0.src -type f | xargs cat | tr -sc 'a-zA-Z0-9_' '\n' | perl -ne 'print unless length($_) > 1000;' | ./lines > words.txt //#![feature(impl_trait_in_bindings)] use std::fmt::Write; use std::io; use std::iter::FromIterator; use bytes::{BufMut, Bytes, BytesMut}; use futures::future; use futures::stream; use futures::Stream; use tokio::codec::{BytesCodec, FramedRead, FramedWrite}; use tokio::prelude::*; use tokio::runtime::Runtime; use word_count::util::*; use tokio::sync::mpsc::{channel, Receiver}; use std::cmp::max; use parallel_stream::{StreamExt, ParallelStream}; use tokio::sync::mpsc::error::SendError; const BUFFER_SIZE: usize = 4; //use futures::sync::mpsc::channel; const CHUNKS_CAPACITY: usize = 256; fn reduce_task<InItem, OutItem, S, FBuildPipeline, OutFuture, E>( src: Receiver<InItem>, sink: S, builder: FBuildPipeline, ) -> impl Future<Item = (), Error = ()> where E: std::error::Error, S: Sink<SinkItem=OutItem, SinkError=SendError>, OutFuture: Future<Item = OutItem, Error = E>, FBuildPipeline: FnOnce(Receiver<InItem>) -> OutFuture, { future::lazy(move || { let task = builder(src) .and_then(|result| { sink.sink_map_err(|e| panic!("join send error: {}", e)) .send(result) }) .map(|_sink| ()) .map_err(|e| panic!("pipe_err:{:?}", e)); task }) } fn forward_task<InItem, OutItem, S, FBuildPipeline, OutStream, E>( src: Receiver<InItem>, sink: S, builder: FBuildPipeline, ) -> impl Future<Item = (), Error = ()> where E: std::error::Error, S: Sink<SinkItem=OutItem, SinkError=SendError>, OutStream: Stream<Item = OutItem, Error = E>, FBuildPipeline: FnOnce(Receiver<InItem>) -> OutStream, { future::lazy(move || { let task = builder(src) .forward(sink.sink_map_err(|e| panic!("join send error: {}", e))) .map(|(_src, _sink)| ()) .map_err(|e| panic!("pipe_err:{:?}", e)); task }) } #[inline(never)] fn count_fn(stream: Receiver<Bytes>) -> impl Stream<Item=(Bytes, u64), Error = io::Error> { let item_stream = stream .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("recv error: {:#?}", e))) .fold(FreqTable::new(), |mut frequency, text| { count_bytes(&mut frequency, &text); future::ok::<FreqTable, io::Error>(frequency) }) .map(move |frequency|{ stream::iter_ok(frequency) }) .flatten_stream(); item_stream } #[inline(never)] fn acc_fn(stream: Receiver<(Bytes, u64)>) -> impl Future<Item=Vec<(Bytes, u64)>, Error = io::Error> { let part = stream .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("recv error: {:#?}", e))) .fold(FreqTable::new(), |mut frequency, (word, count)| { *frequency.entry(word).or_insert(0) += count; future::ok::<FreqTable, io::Error>(frequency) }).map(move |mut sub_table| Vec::from_iter(sub_table.drain()) ); part } fn main() -> io::Result<()> { let conf = parse_args("word count parallel buf"); let mut runtime = Runtime::new()?; let (input, output) = open_io_async(&conf); let input_stream = FramedRead::new(input, WholeWordsCodec::new()); let output_stream = FramedWrite::new(output, BytesCodec::new()); let pipe_threads = max(1, conf.threads); let (fork, join) = { let mut senders = Vec::new(); //let mut join = Join::new(|(_word, count)| { *count}); let mut sort_inputs = Vec::with_capacity(pipe_threads); let (out_tx, out_rx) = channel::<Vec<(Bytes, u64)>>(pipe_threads); for _i in 0..pipe_threads { let (tx, rx) = channel::<(Bytes, u64)>(pipe_threads); sort_inputs.push(tx); let sort_task = reduce_task(rx, out_tx.clone(), acc_fn); runtime.spawn(sort_task); } let mut shuffle = Shuffle::new( |(word, _count)| word.len() , sort_inputs); //let (out_tx, out_rx) = channel::<FreqTable>(pipe_threads); for _i in 0..pipe_threads { let (in_tx, in_rx) = channel::<Bytes>(BUFFER_SIZE); senders.push(in_tx); let sort_tx = shuffle.create_input(); let pipe = forward_task(in_rx, sort_tx, count_fn); runtime.spawn(pipe); //join.add(out_rx); } let fork = ForkRR::new(senders); (fork, out_rx) }; let file_reader = input_stream .forward(fork.sink_map_err(|e| { io::Error::new(io::ErrorKind::Other, format!("fork send error: {}", e)) })) .map(|(_in, _out)| ()) .map_err(|e| { eprintln!("error: {}", e); panic!() }); runtime.spawn(file_reader); let sub_table_stream /*: impl Stream<Item=HashMap<Vec<u8>, u64>, Error=io::Error> + Send*/ = join .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("recv error: {:#?}", e))); let file_writer = sub_table_stream .fold(Vec::new(), |mut frequency, mut part| { frequency.append(&mut part); future::ok::<Vec<(Bytes, u64)>, io::Error>(frequency) }) .map(|mut frequency| { frequency.sort_by(|&(_, a), &(_, b)| b.cmp(&a)); stream::iter_ok(frequency).chunks(CHUNKS_CAPACITY) // <- TODO performance? }) .flatten_stream() .map(|chunk| { let mut buffer = BytesMut::with_capacity(CHUNKS_CAPACITY * 15); for (word_raw, count) in chunk { let word = utf8(&word_raw).expect("UTF8 encoding error"); let max_len = word_raw.len() + 15; if buffer.remaining_mut() < max_len { buffer.reserve(10 * max_len); } buffer .write_fmt(format_args!("{} {}\n", word, count)) .expect("Formating error"); } buffer.freeze() }) .forward(output_stream); let (_word_stream, _out_file) = runtime.block_on(file_writer)?; runtime.shutdown_on_idle(); Ok(()) }
//! Utility to transliterate texts into ascii characters. //! This utility depends of the iconv utility installed in the SO. //! You want to have glibc with the correct locales installed. //! //! For example. If you want to transliterate from german, you need to //! have install the "de_DE.UTF-8" locale in your SO. //! //! You can do it with https://askubuntu.com/questions/76013/how-do-i-add-locale-to-ubuntu-server //! //! Iconv uses the thread locale in order to decide transliteration table to use. //! Prefer to use TextTransliterateOffThread as it will isolate the side effects of the uselocale C function mod iconv; mod locale_ffi; mod transliterate; mod transliterate_off_thread; pub use transliterate::TextTransliterate; pub use transliterate_off_thread::TextTransliterateOffThread;
use std::{mem, time}; use std::io::{Error, ErrorKind, Result}; use crate::kv::storage::crc64::{as_ne_bytes, kv_crc64}; use crate::kv::storage::kvdb::kvdb_s; fn usage() { println!("{}{}{}{}{}{}{}{}", " kv help -- this message \n", " kv get <key> -- get a key\n", " kv put <key> <val> -- set key\n", " kv del <key> -- delete a key\n", " kv list -- list all key in the db\n", " kv ins <start_key> <num> -- insert records in batch mode\n", " kv clr -- remove all records in the database\n", " kv verify -- get all records and verify them\n"); } struct cmd_s { cmd: &'static str, func: fn(db: &mut kvdb_s, args: Vec<String>) -> Result<()>, } const cmds: [cmd_s; 8] = [ cmd_s { cmd: "get", func: fn_get }, cmd_s { cmd: "put", func: fn_put }, cmd_s { cmd: "del", func: fn_del }, cmd_s { cmd: "list", func: fn_list }, cmd_s { cmd: "dump", func: fn_dump }, cmd_s { cmd: "ins", func: fn_ins }, cmd_s { cmd: "clr", func: fn_clr }, cmd_s { cmd: "verify", func: fn_verify }, ]; fn args_err(error: &str) -> Error { Error::new(ErrorKind::InvalidInput, error) } fn assert_args(args: &Vec<String>, count: usize) -> Result<()> { if args.len() != count { return Result::Err(args_err(format!("number of args must be {}", count).as_str())) } Ok(()) } fn parse_u64(args: &Vec<String>, index: usize) -> Result<u64> { args[index].parse().map_err(|e| args_err(format!("type of the {} args must be u64", index).as_str())) } fn fn_get(db: &mut kvdb_s, args: Vec<String>) -> Result<()> { assert_args(&args, 3)?; let k: u64 = parse_u64(&args, 2)?; match db.get(k) { Ok(v) => println!("found, key = {}, value = {}", k, v), Err(e) => eprintln!("record not found: {}", e), } return Ok(()); } fn fn_put(db: &mut kvdb_s, args: Vec<String>) -> Result<()> { assert_args(&args, 4)?; let k: u64 = parse_u64(&args, 2)?; let v: u64 = parse_u64(&args, 3)?; db.put(k, v) } fn fn_del(db: &mut kvdb_s, args: Vec<String>) -> Result<()> { assert_args(&args, 3)?; let k: u64 = parse_u64(&args, 2)?; match db.del(k) { Ok(_) => println!("deletion success"), Err(e) => eprintln!("deletion failed: {}", e), } Ok(()) } fn fn_list(db: &mut kvdb_s, args: Vec<String>) -> Result<()> { assert_args(&args, 2)?; let k: u64 = parse_u64(&args, 2)?; for (k, v) in db.iter(0, u64::MAX)? { println!("k = {:>5}, v = {:>21}", k, v); } Ok(()) } fn fn_dump(db: &mut kvdb_s, args: Vec<String>) -> Result<()> { assert_args(&args, 2)?; db.dump() } fn fn_ins(db: &mut kvdb_s, args: Vec<String>) -> Result<()> { assert_args(&args, 4)?; let start_k = parse_u64(&args, 2)?; let n = parse_u64(&args, 3)?; let mut last_i = 0_u64; let t0 = time::Instant::now(); let mut last = t0.clone(); let mut seq; for i in 0..n { seq = start_k + i; let k = kv_crc64(as_ne_bytes(&seq)); let v = kv_crc64(as_ne_bytes(&k)); db.put(k, v)?; if (i % 100) == 0 { let now = time::Instant::now(); if (now - last).as_secs() >= 1 { let us0 = 1000000 * (now - last); let us1 = 1000000 * (now - t0); println!("total: {} in {} sec, avarage: {} us/record", i, (now - t0).as_secs(), us1.as_secs() / i); println!("last {} sec: {}, avarage: {} us/record", i - last_i, (now - last).as_secs(), us0.as_secs() / (i - last_i + 1)); last = now; last_i = i; } } } Ok(()) } fn fn_clr(db: &mut kvdb_s, args: Vec<String>) -> Result<()> { Ok(()) } fn fn_verify(db: &mut kvdb_s, args: Vec<String>) -> Result<()> { Ok(()) } fn exec(args: Vec<String>) -> Result<()> { // struct cmd_s *c; if args.len() < 2 { usage(); return Ok(()); } let mut db = kvdb_s::open("aaa.db")?; let mut found = false; for c in &cmds { if c.cmd == args[1] { (c.func)(&mut db, args); found = true; break; } } if !found { usage(); } return Ok(()); }
extern crate dmbc; extern crate exonum; extern crate exonum_testkit; extern crate hyper; extern crate iron; extern crate iron_test; extern crate mount; extern crate serde_json; pub mod dmbc_testkit; use dmbc_testkit::{DmbcTestApiBuilder, DmbcTestKitApi}; use exonum::crypto; use exonum::messages::Message; use hyper::status::StatusCode; use dmbc::currency::api::error::ApiError; use dmbc::currency::api::transaction::TransactionResponse; use dmbc::currency::assets::{AssetBundle, AssetInfo, MetaAsset}; use dmbc::currency::configuration::{Configuration, TransactionFees, TransactionPermissions}; use dmbc::currency::error::Error; use dmbc::currency::transactions::builders::transaction; use dmbc::currency::wallet::Wallet; #[test] fn add_assets_mine_new_asset_to_receiver_empty_wallet() { let fixed = 10; let meta_data = "asset"; let units = 3; let balance = 100_000; let transaction_fee = 10; let per_asset_fee = 4; let config_fees = TransactionFees::with_default_key(transaction_fee, per_asset_fee, 0, 0, 0, 0); let permissions = TransactionPermissions::default(); let (creator_public_key, creator_secret_key) = crypto::gen_keypair(); let (receiver_key, _) = crypto::gen_keypair(); let mut testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_wallet_value(&creator_public_key, Wallet::new(balance, vec![])) .create(); let api = testkit.api(); // post the transaction let meta_asset = MetaAsset::new( &receiver_key, meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), ); let tx_add_assets = transaction::Builder::new() .keypair(creator_public_key, creator_secret_key) .tx_add_assets() .add_asset_value(meta_asset) .seed(85) .build(); let tx_hash = tx_add_assets.hash(); let (status, response) = api.post_tx(&tx_add_assets); testkit.create_block(); // check post response assert_eq!(status, StatusCode::Created); assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash }))); let (_, tx_status) = api.get_tx_status(&tx_add_assets); assert_eq!(tx_status, Ok(Ok(()))); // check creator wallet let creator = api.get_wallet(&creator_public_key); let expected_balance = balance - transaction_fee - per_asset_fee * units; assert_eq!(creator.balance, expected_balance); assert!(creator.assets_count == 0); // create asset's equivalents created by tx execution let (asset, info) = dmbc_testkit::create_asset2( meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_public_key, &tx_hash, ); // check receiver wallet let receivers_assets = api.get_wallet_assets(&receiver_key); let assets: Vec<AssetBundle> = receivers_assets.iter().map(|a| a.into()).collect(); assert_eq!(assets, vec![asset.clone()]); // compare asset info from blockchain let asset_info: Vec<AssetInfo> = receivers_assets .iter() .map(|a| a.clone().meta_data.unwrap()) .collect(); assert_eq!(asset_info, vec![info]); } #[test] fn add_assets_mine_existing_asset_to_receivers_non_empty_wallet() { let fixed = 10; let meta_data = "asset"; let units = 3; let balance = 100_000; let transaction_fee = 10; let per_asset_fee = 4; let config_fees = TransactionFees::with_default_key(transaction_fee, per_asset_fee, 0, 0, 0, 0); let permissions = TransactionPermissions::default(); let (creator_public_key, creator_secret_key) = crypto::gen_keypair(); let (receiver_key, _) = crypto::gen_keypair(); let meta_asset = MetaAsset::new( &receiver_key, meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), ); let (asset, info) = dmbc_testkit::create_asset( meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_public_key, ); let mut testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_wallet_value(&creator_public_key, Wallet::new(balance, vec![])) .add_asset_to_wallet(&receiver_key, (asset.clone(), info.clone())) .create(); let api = testkit.api(); let tx_add_assets = transaction::Builder::new() .keypair(creator_public_key, creator_secret_key) .tx_add_assets() .add_asset_value(meta_asset) .seed(85) .build(); let tx_hash = tx_add_assets.hash(); let (status, response) = api.post_tx(&tx_add_assets); testkit.create_block(); // check post response assert_eq!(status, StatusCode::Created); assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash }))); let (_, tx_status) = api.get_tx_status(&tx_add_assets); assert_eq!(tx_status, Ok(Ok(()))); // check creator wallet let creator = api.get_wallet(&creator_public_key); let expected_balance = balance - transaction_fee - per_asset_fee * units; assert_eq!(creator.balance, expected_balance); assert!(creator.assets_count == 0); let updated_asset = AssetBundle::new(asset.id(), asset.amount() * 2); let updated_info = AssetInfo::new( info.creator(), info.origin(), info.amount() * 2, info.fees(), info.data(), ); // check receiver wallet let receiver_assets = api.get_wallet_assets(&receiver_key); let assets: Vec<AssetBundle> = receiver_assets.iter().map(|a| a.into()).collect(); assert_eq!(assets, vec![updated_asset.clone()]); // compare asset info from blockchain let assets_infos: Vec<AssetInfo> = receiver_assets .iter() .map(|a| a.clone().meta_data.unwrap()) .collect(); assert_eq!(assets_infos, vec![updated_info]); } #[test] fn add_assets_mine_existing_asset_to_creators_empty_wallet() { let fixed = 10; let meta_data = "asset"; let units = 3; let balance = 100_000; let transaction_fee = 10; let per_asset_fee = 4; let config_fees = TransactionFees::with_default_key(transaction_fee, per_asset_fee, 0, 0, 0, 0); let permissions = TransactionPermissions::default(); let (creator_public_key, creator_secret_key) = crypto::gen_keypair(); let (receiver_key, _) = crypto::gen_keypair(); let (asset, info) = dmbc_testkit::create_asset( meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_public_key, ); let mut testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_wallet_value(&creator_public_key, Wallet::new(balance, vec![])) .add_asset_to_wallet(&receiver_key, (asset.clone(), info.clone())) .create(); let api = testkit.api(); let meta_asset = MetaAsset::new( &creator_public_key, meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), ); let tx_add_assets = transaction::Builder::new() .keypair(creator_public_key, creator_secret_key) .tx_add_assets() .add_asset_value(meta_asset) .seed(85) .build(); let tx_hash = tx_add_assets.hash(); let (status, response) = api.post_tx(&tx_add_assets); testkit.create_block(); // check post response assert_eq!(status, StatusCode::Created); assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash }))); let (_, tx_status) = api.get_tx_status(&tx_add_assets); assert_eq!(tx_status, Ok(Ok(()))); // check creator wallet let asset = AssetBundle::new(asset.id(), asset.amount()); let updated_info = AssetInfo::new( info.creator(), info.origin(), info.amount() * 2, info.fees(), info.data(), ); let creator = api.get_wallet(&creator_public_key); let creators_assets = api.get_wallet_assets(&creator_public_key); let assets: Vec<AssetBundle> = creators_assets.iter().map(|a| a.into()).collect(); let expected_balance = balance - transaction_fee - per_asset_fee * units; assert_eq!(creator.balance, expected_balance); assert_eq!(assets, vec![asset.clone()]); // check receiver wallet let receivers_assets = api.get_wallet_assets(&receiver_key); let assets: Vec<AssetBundle> = receivers_assets.iter().map(|a| a.into()).collect(); assert_eq!(assets, vec![asset.clone()]); // compare asset info from blockchain let assets_infos: Vec<AssetInfo> = receivers_assets .iter() .map(|a| a.clone().meta_data.unwrap()) .collect(); assert_eq!(assets_infos, vec![updated_info]); } #[test] fn add_assets_mine_existing_asset_to_creator_and_receiver() { let fixed = 10; let meta_data = "asset"; let units = 3; let balance = 100_000; let transaction_fee = 10; let per_asset_fee = 4; let config_fees = TransactionFees::with_default_key(transaction_fee, per_asset_fee, 0, 0, 0, 0); let permissions = TransactionPermissions::default(); let (creator_public_key, creator_secret_key) = crypto::gen_keypair(); let (receiver_key, _) = crypto::gen_keypair(); let (asset, info) = dmbc_testkit::create_asset( meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_public_key, ); let mut testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_wallet_value(&creator_public_key, Wallet::new(balance, vec![])) .add_asset_to_wallet(&receiver_key, (asset.clone(), info.clone())) .create(); let api = testkit.api(); let meta_asset_for_creator = MetaAsset::new( &creator_public_key, meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), ); let meta_asset_for_receiver = MetaAsset::new( &receiver_key, meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), ); let tx_add_assets = transaction::Builder::new() .keypair(creator_public_key, creator_secret_key) .tx_add_assets() .add_asset_value(meta_asset_for_creator) .add_asset_value(meta_asset_for_receiver) .seed(85) .build(); let tx_hash = tx_add_assets.hash(); let (status, response) = api.post_tx(&tx_add_assets); testkit.create_block(); // check post response assert_eq!(status, StatusCode::Created); assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash }))); let (_, tx_status) = api.get_tx_status(&tx_add_assets); assert_eq!(tx_status, Ok(Ok(()))); // check creator wallet let creators_asset = AssetBundle::new(asset.id(), asset.amount()); let receiver_asset = AssetBundle::new(asset.id(), asset.amount() * 2); let updated_info = AssetInfo::new( info.creator(), info.origin(), info.amount() * 3, info.fees(), info.data(), ); let creator = api.get_wallet(&creator_public_key); let creators_assets = api.get_wallet_assets(&creator_public_key); let assets: Vec<AssetBundle> = creators_assets.iter().map(|a| a.into()).collect(); let expected_balance = balance - transaction_fee - per_asset_fee * units * 2; assert_eq!(creator.balance, expected_balance); assert_eq!(assets, vec![creators_asset]); // check receiver wallet let receivers_assets = api.get_wallet_assets(&receiver_key); let assets: Vec<AssetBundle> = receivers_assets.iter().map(|a| a.into()).collect(); assert_eq!(assets, vec![receiver_asset]); // compare asset info from blockchain let assets_infos: Vec<AssetInfo> = receivers_assets .iter() .map(|a| a.clone().meta_data.unwrap()) .collect(); assert_eq!(assets_infos, vec![updated_info]); } #[test] fn add_assets_mine_existing_asset_to_receivers_wallet_with_different_asset() { let fixed = 10; let meta_data = "asset"; let new_meta_data = "new_asset"; let units = 3; let balance = 100_000; let transaction_fee = 10; let per_asset_fee = 4; let config_fees = TransactionFees::with_default_key(transaction_fee, per_asset_fee, 0, 0, 0, 0); let permissions = TransactionPermissions::default(); let (creator_public_key, creator_secret_key) = crypto::gen_keypair(); let (receiver_key, _) = crypto::gen_keypair(); let (asset, info) = dmbc_testkit::create_asset( meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_public_key, ); let mut testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_wallet_value(&creator_public_key, Wallet::new(balance, vec![])) .add_asset_to_wallet(&receiver_key, (asset.clone(), info.clone())) .create(); let api = testkit.api(); let meta_asset_for_receiver = MetaAsset::new( &receiver_key, new_meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), ); let tx_add_assets = transaction::Builder::new() .keypair(creator_public_key, creator_secret_key) .tx_add_assets() .add_asset_value(meta_asset_for_receiver) .seed(85) .build(); let tx_hash = tx_add_assets.hash(); let (status, response) = api.post_tx(&tx_add_assets); testkit.create_block(); // check post response assert_eq!(status, StatusCode::Created); assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash }))); let (_, tx_status) = api.get_tx_status(&tx_add_assets); assert_eq!(tx_status, Ok(Ok(()))); // check creator wallet let (new_asset, new_info) = dmbc_testkit::create_asset2( new_meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_public_key, &tx_hash, ); // let creator = testkit.fetch_wallet(&creator_public_key); let creator = api.get_wallet(&creator_public_key); let expected_balance = balance - transaction_fee - per_asset_fee * units; assert_eq!(creator.balance, expected_balance); assert!(creator.assets_count == 0); // check receiver wallet let receivers_assets = api.get_wallet_assets(&receiver_key); let assets: Vec<AssetBundle> = receivers_assets.iter().map(|a| a.into()).collect(); assert_eq!(assets, vec![asset, new_asset.clone()]); // compare asset info from blockchain let assets_infos: Vec<AssetInfo> = receivers_assets .iter() .map(|a| a.clone().meta_data.unwrap()) .collect(); assert_eq!(assets_infos[1], new_info); } #[test] fn add_assets_mine_existing_asset_with_different_fees() { let fixed1 = 10; let fixed2 = 20; let meta_data = "asset"; let units = 3; let balance = 100_000; let transaction_fee = 10; let per_asset_fee = 4; let config_fees = TransactionFees::with_default_key(transaction_fee, per_asset_fee, 0, 0, 0, 0); let permissions = TransactionPermissions::default(); let (public_key, secret_key) = crypto::gen_keypair(); let (asset, info) = dmbc_testkit::create_asset( meta_data, units, dmbc_testkit::asset_fees(fixed1, "0.0".parse().unwrap()), &public_key, ); let mut testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_wallet_value(&public_key, Wallet::new(balance, vec![])) .add_asset_to_wallet(&public_key, (asset.clone(), info.clone())) .create(); let api = testkit.api(); let tx_add_assets = transaction::Builder::new() .keypair(public_key, secret_key.clone()) .tx_add_assets() .add_asset( meta_data, units, dmbc_testkit::asset_fees(fixed2, "0.0".parse().unwrap()), ) .seed(85) .build(); let tx_hash = tx_add_assets.hash(); let (status, response) = api.post_tx(&tx_add_assets); testkit.create_block(); // check post response assert_eq!(status, StatusCode::Created); assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash }))); let (_, tx_status) = api.get_tx_status(&tx_add_assets); assert_eq!(tx_status, Ok(Err(Error::InvalidAssetInfo))); let wallet = api.get_wallet(&public_key); let wallet_assets = api.get_wallet_assets(&public_key); let assets: Vec<AssetBundle> = wallet_assets.iter().map(|a| a.into()).collect(); let expected_balance = balance - transaction_fee; assert_eq!(wallet.balance, expected_balance); assert_eq!(assets, vec![asset.clone()]); let assets_infos: Vec<AssetInfo> = wallet_assets .iter() .map(|a| a.clone().meta_data.unwrap()) .collect(); assert_eq!(assets_infos, vec![info]); } #[test] fn add_assets_insufficient_funds() { let fixed = 10; let meta_data = "asset"; let units = 3; let transaction_fee = 10; let per_asset_fee = 4; let config_fees = TransactionFees::with_default_key(transaction_fee, per_asset_fee, 0, 0, 0, 0); let permissions = TransactionPermissions::default(); let (public_key, secret_key) = crypto::gen_keypair(); let mut testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .create(); let api = testkit.api(); let tx_add_assets = transaction::Builder::new() .keypair(public_key, secret_key.clone()) .tx_add_assets() .add_asset( meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), ) .seed(99) .build(); let tx_hash = tx_add_assets.hash(); let (status, response) = api.post_tx(&tx_add_assets); testkit.create_block(); // check post response assert_eq!(status, StatusCode::Created); assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash }))); let (_, tx_status) = api.get_tx_status(&tx_add_assets); assert_eq!(tx_status, Ok(Err(Error::InsufficientFunds))); } #[test] fn add_assets_transaction_too_large() { let fixed = 10; let meta_data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; let units = 1; let kinds = 100; let balance = 100_000; let transaction_fee = 10; let per_asset_fee = 4; let config_fees = TransactionFees::with_default_key(transaction_fee, per_asset_fee, 0, 0, 0, 0); let permissions = TransactionPermissions::default(); let (creator_public_key, creator_secret_key) = crypto::gen_keypair(); let (receiver_key, _) = crypto::gen_keypair(); let mut testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_wallet_value(&creator_public_key, Wallet::new(balance, vec![])) .create(); let api = testkit.api(); // post the transaction let mut tx_add_assets = transaction::Builder::new() .keypair(creator_public_key, creator_secret_key) .tx_add_assets() .seed(85); for n in 0..kinds { let meta_data_kind = meta_data.to_string() + &n.to_string(); let meta_asset = MetaAsset::new( &receiver_key, &meta_data_kind, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), ); tx_add_assets = tx_add_assets.add_asset_value(meta_asset); } let tx_add_assets = tx_add_assets.build(); let (status, response) = api.post_tx(&tx_add_assets); testkit.create_block(); // check post response assert_eq!(status, StatusCode::BadRequest); assert_eq!(response, Ok(Err(Error::InvalidTransaction))); let (_, tx_status) = api.get_tx_status(&tx_add_assets); assert_eq!(tx_status, Err(ApiError::TransactionNotFound)); }
use crate::components::transistor::Transistor; use crate::components::wire::wiring; pub struct AndGate { t1: Transistor, t2: Transistor, pub input1: wiring::Wire, pub input2: wiring::Wire, pub output: wiring::Wire, } impl Default for AndGate { fn default() -> Self { let mut t1 = Transistor::default(); let mut t2 = Transistor::default(); wiring::set_high(&mut t1.collector); wiring::connect(&mut t2.collector, t1.emitter.clone()); AndGate { input1: t1.base.clone(), input2: t2.base.clone(), output: t2.emitter.clone(), t2: t2, t1: t1, } } } impl AndGate { pub fn settle(&mut self) { self.t1.tick(); self.t2.tick(); } } #[cfg(test)] mod tests { use super::*; #[test] fn false_and_false() { let mut and_gate = AndGate::default(); wiring::set_low(&mut and_gate.input1); wiring::set_low(&mut and_gate.input2); and_gate.settle(); let output_lock = and_gate.output.lock().unwrap(); assert_eq!(*output_lock, false); } #[test] fn true_and_false() { let mut and_gate = AndGate::default(); wiring::set_high(&mut and_gate.input1); wiring::set_low(&mut and_gate.input2); and_gate.settle(); let output_lock = and_gate.output.lock().unwrap(); assert_eq!(*output_lock, false); } #[test] fn false_and_true() { let mut and_gate = AndGate::default(); wiring::set_low(&mut and_gate.input1); wiring::set_high(&mut and_gate.input2); and_gate.settle(); let output_lock = and_gate.output.lock().unwrap(); assert_eq!(*output_lock, false); } #[test] fn true_and_true() { let mut and_gate = AndGate::default(); wiring::set_high(&mut and_gate.input1); wiring::set_high(&mut and_gate.input2); and_gate.settle(); let output_lock = and_gate.output.lock().unwrap(); assert_eq!(*output_lock, true); } }
use serde_json::{ json, Value as JsonValue, }; use crate::lib::{ types::Result, constants::TOOL_VERSION, }; pub fn get_tool_version_info() -> Result<JsonValue> { Ok(json!({"version": TOOL_VERSION })) }
#[no_mangle] fn clear_screen() {} #[no_mangle] fn draw_player(_: f64, _: f64, _: f64) {} #[no_mangle] fn draw_bullet(_: f64, _: f64) {} #[no_mangle] fn draw_player_bullet(_: f64, _: f64) {} #[no_mangle] fn draw_particle(_: f64, _: f64, _: f64, _: i32) {} #[no_mangle] fn draw_ufo(_: f64, _: f64) {} #[no_mangle] fn draw_hud(_: i32, _: i32, _: i32) {} #[no_mangle] fn draw_intro() {} #[no_mangle] fn draw_game_over(_: i32) {} #[no_mangle] fn draw_shield(_: i32, _: f64, _: f64, _: f64) {} #[no_mangle] fn draw_sprite(_: u32, _: u32, _: u32, _: u32) {} #[no_mangle] fn update_local_score(_: u32, _: u32, _: i32, _: *mut u8) {} #[no_mangle] fn new_session(); #[no_mangle] fn clear_leaderboard() {} #[no_mangle] fn init_shield(_: i32) {} #[no_mangle] fn add_shield_state(_: i32, _: i32, _: i32) {} #[no_mangle] fn update_shield(_: i32, _: i32, _: i32) {}
/*! An implementation of the [Longest increasing subsequence algorithm](https://en.wikipedia.org/wiki/Longest_increasing_subsequence). # Examples The main trait exposed by this crate is [`LisExt`], which is implemented for, inter alia, arrays: ``` use lis::LisExt; assert_eq!([2, 1, 4, 3, 5].longest_increasing_subsequence(), [1, 3, 4]); ``` Diffing two lists can be done with [`diff_by_key`]: ``` use lis::{diff_by_key, DiffCallback}; struct Cb; impl DiffCallback<usize, usize> for Cb { fn inserted(&mut self, new: usize) { assert_eq!(new, 2); } fn removed(&mut self, old: usize) {} fn unchanged(&mut self, old: usize, new: usize) { assert_eq!(old, 1); assert_eq!(new, 1); } } diff_by_key(1..2, |x| x, 1..3, |x| x, &mut Cb); ``` */ #![deny(missing_docs, missing_debug_implementations)] use fxhash::FxHashMap; use std::cmp::Ordering::{self, Greater, Less}; use std::hash::Hash; /// Extends `AsRef<[T]>` with methods for generating longest increasing subsequences. pub trait LisExt<T>: AsRef<[T]> { /// Returns indices of the longest increasing subsequence. /// /// See [`longest_increasing_subsequence_by`]. /// /// [`longest_increasing_subsequence_by`]: #method.longest_increasing_subsequence_by #[inline] fn longest_increasing_subsequence(&self) -> Vec<usize> where T: Ord, { self.longest_increasing_subsequence_by(|a, b| a.cmp(b), |_| true) } /// Returns indices of the longest increasing subsequence with a comparator function. /// /// The closure `filter` is called on each element. If it returns `false` the element is /// skipped, however indices are left intact. /// /// This is `O(n log n)` worst-case and allocates at most `2 * size_of<usize>() * n` bytes. /// It is based on the method described by Michael L. Fredman (1975) in [*On computing the /// length of longest increasing subsequences*](https://doi.org/10.1016/0012-365X(75)90103-X). /// /// # Example /// /// ``` /// use lis::LisExt; /// assert_eq!([2, 1, 4, 3, 5].longest_increasing_subsequence_by(|a, b| a.cmp(b), |_| true), [1, 3, 4]); /// ``` fn longest_increasing_subsequence_by<F, P>(&self, mut f: F, mut filter: P) -> Vec<usize> where F: FnMut(&T, &T) -> Ordering, P: FnMut(&T) -> bool, { let a = self.as_ref(); let (mut p, mut m) = (vec![0; a.len()], Vec::with_capacity(a.len())); let mut it = a.iter().enumerate().filter(|(_, x)| filter(x)); m.push(if let Some((i, _)) = it.next() { i } else { return Vec::new(); // The array was empty }); for (i, x) in it { // Test whether a[i] can extend the current sequence if f(&a[*m.last().unwrap()], x) == Less { p[i] = *m.last().unwrap(); m.push(i); continue; } // Binary search for largest j ≤ m.len() such that a[m[j]] < a[i] let j = match m.binary_search_by(|&j| f(&a[j], x).then(Greater)) { Ok(j) | Err(j) => j, }; if j > 0 { p[i] = m[j - 1]; } m[j] = i; } // Reconstruct the longest increasing subsequence let mut k = *m.last().unwrap(); for i in (0..m.len()).rev() { m[i] = k; k = p[k]; } m } } impl<S, T> LisExt<T> for S where S: AsRef<[T]> + ?Sized {} /// Extends `Iterator` with an adapter that is peekable from both ends. trait IteratorExt: Iterator { fn de_peekable(self) -> DoubleEndedPeekable<Self> where Self: Sized + DoubleEndedIterator, { DoubleEndedPeekable { iter: self, front: None, back: None, } } } impl<T: Iterator> IteratorExt for T {} /// A double ended iterator that is peekable. #[derive(Clone, Debug)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] struct DoubleEndedPeekable<I: Iterator> { iter: I, front: Option<Option<I::Item>>, back: Option<Option<I::Item>>, } impl<I: Iterator> DoubleEndedPeekable<I> { #[inline] fn peek(&mut self) -> Option<&I::Item> { if self.front.is_none() { self.front = Some( self.iter .next() .or_else(|| self.back.take().unwrap_or(None)), ); } match self.front { Some(Some(ref value)) => Some(value), Some(None) => None, _ => unreachable!(), } } #[inline] fn peek_back(&mut self) -> Option<&I::Item> where I: DoubleEndedIterator, { if self.back.is_none() { self.back = Some( self.iter .next_back() .or_else(|| self.front.take().unwrap_or(None)), ); } match self.back { Some(Some(ref value)) => Some(value), Some(None) => None, _ => unreachable!(), } } } impl<I: Iterator> Iterator for DoubleEndedPeekable<I> { type Item = I::Item; #[inline] fn next(&mut self) -> Option<I::Item> { self.front .take() .unwrap_or_else(|| self.iter.next()) .or_else(|| self.back.take().unwrap_or(None)) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let peek_len = match self.front { Some(None) => return (0, Some(0)), Some(Some(_)) => 1, None => 0, } + match self.back { Some(None) => return (0, Some(0)), Some(Some(_)) => 1, None => 0, }; let (lo, hi) = self.iter.size_hint(); ( lo.saturating_add(peek_len), hi.and_then(|x| x.checked_add(peek_len)), ) } } impl<I: DoubleEndedIterator> DoubleEndedIterator for DoubleEndedPeekable<I> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { self.back .take() .unwrap_or_else(|| self.iter.next_back()) .or_else(|| self.front.take().unwrap_or(None)) } } impl<I: std::iter::ExactSizeIterator> std::iter::ExactSizeIterator for DoubleEndedPeekable<I> {} impl<I: std::iter::FusedIterator> std::iter::FusedIterator for DoubleEndedPeekable<I> {} /// Gets notified for each step of the diffing process. pub trait DiffCallback<S, T> { /// Called when a new element was inserted. fn inserted(&mut self, new: T); /// Called when an element stayed in place. fn unchanged(&mut self, old: S, new: T); /// Called when an element was removed. fn removed(&mut self, old: S); /// Called when an element was moved. /// /// The default definition reduces to calls to [`removed`] and [`inserted`]. fn moved(&mut self, old: S, new: T) { self.removed(old); self.inserted(new); } } /// Computes the difference between the two iterators with key extraction functions. /// /// Keys have to be unique. After testing for common prefixes and suffixes, returns removals in /// forward order and then insertions/moves in reverse order. Guaranteed not to allocate if the /// changeset is entirely contiguous insertions or removals. Result stores `S`/`T`:s instead of /// indices; use [enumerate] if preferable. /// /// # Panics /// /// May panic if `a` contains duplicate keys. /// /// [enumerate]: std::iter::Iterator::enumerate pub fn diff_by_key<S, T, K: Eq + Hash>( a: impl IntoIterator<Item = S, IntoIter = impl DoubleEndedIterator<Item = S>>, mut f: impl FnMut(&S) -> &K, b: impl IntoIterator<Item = T, IntoIter = impl DoubleEndedIterator<Item = T>>, mut g: impl FnMut(&T) -> &K, cb: &mut impl DiffCallback<S, T>, ) { let (mut a, mut b) = (a.into_iter().de_peekable(), b.into_iter().de_peekable()); // Sync nodes with same key at start while a .peek() .and_then(|a| b.peek().filter(|&b| f(a) == g(b))) .is_some() { cb.unchanged(a.next().unwrap(), b.next().unwrap()); } // Sync nodes with same key at end while a .peek_back() .and_then(|a| b.peek_back().filter(|&b| f(a) == g(b))) .is_some() { cb.unchanged(a.next_back().unwrap(), b.next_back().unwrap()); } if a.peek().is_none() { return b.rev().for_each(|x| cb.inserted(x)); // If all of a was synced, add remaining in b } else if b.peek().is_none() { return a.for_each(|x| cb.removed(x)); // If all of b was synced, remove remaining in a } let (b, mut sources): (Vec<_>, Vec<_>) = b.map(|x| (x, None)).unzip(); let (mut last_j, mut moved) = (0, false); // Associate elements in `a` to their counterparts in `b`, or remove if nonexistant let assoc = |(i, (j, a_elem)): (_, (Option<usize>, _))| { if let Some(j) = j { debug_assert!(sources[j].is_none(), "Duplicate key"); // Catch some instances of dupes sources[j] = Some((i, a_elem)); if j < last_j { moved = true; } last_j = j; } else { cb.removed(a_elem); } }; // If size is small just loop through if b.len() < 4 || a.size_hint().1.map_or(false, |hi| hi | b.len() < 32) { a.map(|a_elem| (b.iter().position(|b_elem| f(&a_elem) == g(b_elem)), a_elem)) .enumerate() .for_each(assoc); } else { // Map of keys in b to their respective indices let key_index: FxHashMap<_, _> = b.iter().enumerate().map(|(j, ref x)| (g(x), j)).collect(); a.map(|a_elem| (key_index.get(&f(&a_elem)).copied(), a_elem)) .enumerate() .for_each(assoc); } if moved { // Find longest sequence that can remain stationary let mut seq = sources .longest_increasing_subsequence_by( |a, b| a.as_ref().unwrap().0.cmp(&b.as_ref().unwrap().0), Option::is_some, ) .into_iter() .rev() .peekable(); for (i, (b, source)) in b.into_iter().zip(sources).enumerate().rev() { if let Some((_, a)) = source { if Some(&i) == seq.peek() { seq.next(); cb.unchanged(a, b); } else { cb.moved(a, b); } } else { cb.inserted(b); } } } else { for (b, source) in b.into_iter().zip(sources).rev() { if let Some((_, a)) = source { cb.unchanged(a, b); } else { cb.inserted(b); }; } } } #[cfg(test)] mod tests { use super::*; fn powerset<T: Clone>(a: &[T]) -> Vec<Vec<T>> { (0..2usize.pow(a.len() as u32)) .map(|i| { a.iter() .enumerate() .filter(|&(t, _)| (i >> t) % 2 == 1) .map(|(_, element)| element.clone()) .collect() }) .collect() } fn run_diff<T: Copy + Eq + Hash>(a: &[T], b: &[T]) -> Vec<T> { struct Cb<T> { v: Vec<T>, idx: usize, last_add_one: usize, } impl<T: Copy + Eq> DiffCallback<(usize, &T), (usize, &T)> for Cb<T> { fn inserted(&mut self, (_j, new): (usize, &T)) { self.v.insert(self.idx, *new); } fn removed(&mut self, (_i, old): (usize, &T)) { let remove_idx = self.v.iter().position(|x| x == old).unwrap(); self.v.remove(remove_idx); if remove_idx < self.idx { self.idx -= 1; } } fn unchanged(&mut self, (i, _old): (usize, &T), (j, new): (usize, &T)) { if i == self.last_add_one && i == j { self.last_add_one += 1; } else { self.idx = self.v.iter().position(|x| x == new).unwrap(); } } fn moved(&mut self, (_i, old): (usize, &T), (_j, new): (usize, &T)) { let remove_idx = self.v.iter().position(|x| x == old).unwrap(); self.v.remove(remove_idx); if remove_idx < self.idx { self.idx -= 1; } self.v.insert(self.idx, *new); } } let mut cb = Cb { v: a.to_vec(), idx: a.len(), last_add_one: 0, }; diff_by_key( a.iter().enumerate(), |x| x.1, b.iter().enumerate(), |x| x.1, &mut cb, ); cb.v } #[test] fn test_diff_powerset_seven() { let (a, b): (Vec<_>, Vec<_>) = ((0..7).collect(), vec![5, 3, 6, 1, 2, 4, 0]); for a in powerset(&a) { for b in powerset(&b) { let v = run_diff(&a, &b); assert_eq!(v, b); } } } #[test] fn len_zero() { assert!(<[i32]>::longest_increasing_subsequence(&[]).is_empty()); } #[test] fn len_one() { assert_eq!(([5, 4, 3, 2, 1]).longest_increasing_subsequence().len(), 1); assert_eq!([0, 0, 0, 0].longest_increasing_subsequence().len(), 1); } #[test] fn lis_test() { assert_eq!( [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15].longest_increasing_subsequence(), [0, 4, 6, 9, 13, 15] ); assert_eq!( [2, 3, 4, 3, 5].longest_increasing_subsequence(), [0, 1, 2, 4] ); } }
use jsonrpc_core::{Error as RpcError, Params, Result as RpcResult, Value}; use log::debug; use serde::de::DeserializeOwned; use serde_json::from_value; pub fn parse_params<D: DeserializeOwned + std::fmt::Debug + 'static>( param: Params, ) -> RpcResult<D> { debug!("In-> {:?}", param); let value = match param { Params::None => Value::Array(Vec::new()), Params::Array(mut vec) => match vec.len() { 0 => Value::Array(Vec::new()), 1 => vec.remove(0), _ => Value::Array(vec), }, Params::Map(map) => Value::Object(map), }; debug!("Thru-> {:?}", value); from_value::<D>(value) .map(|out| { debug!("Out-> {:?}", out); out }) .map_err(|err| { debug!("Err-> expected {}", err); RpcError::invalid_params(format!("expected {}", err)) }) }
use std::fs::File; use std::io::{Error, BufReader, BufRead}; use std::path::Path; fn main() { match solve() { Ok((sum1, sum2)) => println!("Part 1: {} | Part 2: {}", sum1, sum2), Err(err) => println!("/!\\ Error! {}", err.to_string()), } } fn solve() -> Result<(usize, usize), Error> { let f = File::open(Path::new("input/day5.txt"))?; let file = BufReader::new(&f); let v: Vec<isize> = file.lines() .filter_map(|x| x.unwrap().parse().ok()) .collect(); let sum1 = journey(v.clone(), |x| x + 1); let sum2 = journey(v.clone(), |x| if x > 2 { x - 1 } else { x + 1 }); Ok((sum1, sum2)) } fn journey<F>(mut v: Vec<isize>, mut f: F) -> usize where F: FnMut(isize) -> isize, { let mut steps = 0; let mut pos: isize = 0; let n = v.len(); while pos >= 0 && pos < n as isize { let x = v[pos as usize]; v[pos as usize] = f(x); pos += x; steps += 1; } steps } #[cfg(test)] mod tests { use super::*; #[test] fn solve1_test() { let inputs = [ vec![1], vec![-1], vec![0], vec![0, -1], vec![0, 3, 0, 1, -3], ]; let solutions = [1, 1, 2, 4, 5]; for (input, solution) in inputs.iter().zip(solutions.iter()) { assert_eq!(journey(input.clone(), |x| x + 1), *solution) } } #[test] fn solve2_test() { let inputs = [ vec![1], vec![-1], vec![0], vec![0, -1], vec![0, 3, 0, 1, -3], ]; let solutions = [1, 1, 2, 4, 10]; for (input, solution) in inputs.iter().zip(solutions.iter()) { assert_eq!( journey(input.clone(), |x| if x > 2 { x - 1 } else { x + 1 }), *solution ) } } }
use serde::Deserialize; use super::super::{Operation, RunOn}; use crate::{ bson::{Bson, Document}, options::ClientOptions, test::FailPoint, }; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct TestFile { pub(crate) run_on: Option<Vec<RunOn>>, pub(crate) data: Vec<Document>, pub(crate) tests: Vec<TestCase>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct TestCase { pub(crate) description: String, pub(crate) client_options: Option<ClientOptions>, pub(crate) use_multiple_mongoses: Option<bool>, pub(crate) fail_point: Option<FailPoint>, pub(crate) operation: Operation, pub(crate) outcome: Outcome, } #[derive(Debug, Deserialize)] pub(crate) struct Outcome { pub(crate) error: Option<bool>, pub(crate) result: Option<TestResult>, pub(crate) collection: CollectionOutcome, } #[derive(Debug, Deserialize)] #[serde(untagged)] pub(crate) enum TestResult { Labels(Labels), Value(Bson), } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct Labels { pub(crate) error_labels_contain: Option<Vec<String>>, pub(crate) error_labels_omit: Option<Vec<String>>, } #[derive(Debug, Deserialize)] pub(crate) struct CollectionOutcome { pub(crate) name: Option<String>, pub(crate) data: Vec<Document>, }
use serde::{Deserialize, Serialize}; /// Wikipedia category label. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Category(pub String); impl Category { /// Get the fully qualified name of a category. pub fn fqn(&self) -> String { format!("Category:{}", self.0) } }
extern crate colored; extern crate termion; extern crate ultrastar_txt; mod errors { error_chain!{} } use crate::errors::*; use colored::*; use pitch_calc::*; pub fn generate_screen( line: &ultrastar_txt::Line, beat: f32, dominant_note: Option<LetterOctave>, ) -> Result<String> { let (term_width, _term_height) = termion::terminal_size().chain_err(|| "could not get terminal size")?; let note_lines = draw_notelines(line, beat, term_width)?; let lyric_line = gen_lyric_line(line, beat, term_width, dominant_note); Ok(format!("{}{}", note_lines, lyric_line,)) } fn draw_notelines(line: &ultrastar_txt::Line, beat: f32, term_width: u16) -> Result<String> { // spacin between note lines let line_spacing = 2; // space to leave at the top (ex for progrss bar) let top_offset = 2; let mut output = String::new(); let first_note_start = if let Some(note) = line.notes.first() { match note { &ultrastar_txt::Note::Regular { start, duration: _, pitch: _, text: _, } => start, &ultrastar_txt::Note::Golden { start, duration: _, pitch: _, text: _, } => start, &ultrastar_txt::Note::Freestyle { start, duration: _, pitch: _, text: _, } => start, &ultrastar_txt::Note::PlayerChange { player: _ } => 0, // TODO: this is bad find better solution } } else { return Err("line has no first note???".into()); }; let last_note_end = if let Some(note) = line.notes.last() { match note { &ultrastar_txt::Note::Regular { start, duration, pitch: _, text: _, } => start + duration, &ultrastar_txt::Note::Golden { start, duration, pitch: _, text: _, } => start + duration, &ultrastar_txt::Note::Freestyle { start, duration, pitch: _, text: _, } => start + duration, &ultrastar_txt::Note::PlayerChange { player: _ } => 0, // TODO: this is bad find better solution } } else { return Err("line has no last note???".into()); }; let chars_per_beat = term_width as f32 / (last_note_end - first_note_start) as f32; for note in line.notes.iter() { let (start, duration, pitch, note_type) = match note { &ultrastar_txt::Note::Regular { start, duration, pitch, text: _, } => (start, duration, Step(pitch as f32), NoteType::Regular), &ultrastar_txt::Note::Golden { start, duration, pitch, text: _, } => (start, duration, Step(pitch as f32), NoteType::Golden), &ultrastar_txt::Note::Freestyle { start, duration, pitch, text: _, } => (start, duration, Step(pitch as f32), NoteType::Freestyle), _ => continue, }; // calculate position of current note // terminal goto starts at 1 let note_hpos = ((start - first_note_start) as f32 * chars_per_beat) as u16 + 1; let note_vpos = (top_offset + 17 * line_spacing) - letter_to_pos(pitch.letter()) * line_spacing + 1; let color_note = match note_type { NoteType::Golden => { Box::new(|note: &str| note.yellow().to_string()) as Box<Fn(&str) -> String> } NoteType::Regular => { Box::new(|note: &str| note.bright_blue().to_string()) as Box<Fn(&str) -> String> } NoteType::Freestyle => { Box::new(|note: &str| note.red().to_string()) as Box<Fn(&str) -> String> } }; let color_played_note = match note_type { NoteType::Golden => { Box::new(|note: &str| note.bright_yellow().to_string()) as Box<Fn(&str) -> String> } NoteType::Regular => { Box::new(|note: &str| note.white().to_string()) as Box<Fn(&str) -> String> } NoteType::Freestyle => { Box::new(|note: &str| note.bright_red().to_string()) as Box<Fn(&str) -> String> } }; // note is current note or allready played if beat >= start as f32 { // draw progress bar let times = (beat - start as f32) * chars_per_beat; if beat <= last_note_end as f32 { let bar = "#".repeat(times.floor() as usize); // terminal goto starts with 1 output.push_str(format!("{}{}", termion::cursor::Goto(1, 1), bar).as_ref()); } // note is current note -> hightlight it if (start + duration) as f32 >= beat { let marked = (beat - start as f32) * chars_per_beat; let note_line_str = color_note( "#".repeat((duration as f32 * chars_per_beat) as usize) .as_ref(), ); let marked_line_str = color_played_note("#".repeat(marked as usize).as_ref()); output.push_str( format!( "{}{}{}{}{}{:?}", termion::cursor::Goto(note_hpos, note_vpos), note_line_str, termion::cursor::Goto(note_hpos, note_vpos), marked_line_str, termion::cursor::Goto(note_hpos, note_vpos), pitch.letter(), ).as_ref(), ); } // note has been played else { let played_line_str = color_played_note( "#".repeat((duration as f32 * chars_per_beat) as usize) .as_ref(), ); output.push_str( format!( "{}{}{}{:?}", termion::cursor::Goto(note_hpos, note_vpos), played_line_str, termion::cursor::Goto(note_hpos, note_vpos), pitch.letter(), ).as_ref(), ); } // note has not been played yet } else { let note_line_str = color_note( "#".repeat((duration as f32 * chars_per_beat) as usize) .as_ref(), ); output.push_str( format!( "{}{}{}{:?}", termion::cursor::Goto(note_hpos, note_vpos), note_line_str, termion::cursor::Goto(note_hpos, note_vpos), pitch.letter(), ).as_ref(), ); } } Ok(output) } fn line_to_str(line: &ultrastar_txt::Line) -> String { let mut line_str = String::new(); for note in line.notes.iter() { match note { &ultrastar_txt::Note::Regular { start: _, duration: _, pitch: _, ref text, } => line_str.push_str(text), &ultrastar_txt::Note::Golden { start: _, duration: _, pitch: _, ref text, } => line_str.push_str(text), &ultrastar_txt::Note::Freestyle { start: _, duration: _, pitch: _, ref text, } => line_str.push_str(text), _ => continue, }; } line_str } #[derive(PartialEq)] enum NoteType { Regular, Golden, Freestyle, } fn gen_lyric_line( line: &ultrastar_txt::Line, beat: f32, term_width: u16, dominant_note: Option<LetterOctave>, ) -> String { let uncolored_line = line_to_str(line); // terminal goto starts at 1 let line_vpos = (term_width - uncolored_line.len() as u16) / 2 + 1; let line_hpos = 2 + 17 * 2 + 10 + 1; // TODO this is below the lines but should not be a magic number let mut lyric = format!("{}", termion::cursor::Goto(line_vpos, line_hpos)); for note in line.notes.iter() { let (start, duration, _pitch, text, note_type) = match note { &ultrastar_txt::Note::Regular { start, duration, pitch, ref text, } => (start, duration, pitch, text, NoteType::Regular), &ultrastar_txt::Note::Golden { start, duration, pitch, ref text, } => (start, duration, pitch, text, NoteType::Golden), &ultrastar_txt::Note::Freestyle { start, duration, pitch, ref text, } => (start, duration, pitch, text, NoteType::Freestyle), _ => continue, }; // note is current note or allready played if beat >= start as f32 { // note is current note -> hightlight it if (start + duration) as f32 >= beat { if note_type == NoteType::Golden { lyric.push_str(&text.black().on_bright_yellow().to_string()); } else { lyric.push_str(&text.black().on_bright_white().to_string()); } } // note has been played else { if note_type == NoteType::Golden { lyric.push_str(&text.yellow().to_string()); } else { lyric.push_str(&text.white().to_string()); } } } else { if note_type == NoteType::Golden { lyric.push_str(&text.bright_yellow().to_string()); } else { lyric.push_str(&text.bright_blue().to_string()); } } } // add current note under the line let note = match dominant_note { Some(n) => format!("{:?}", n), None => format!(" "), }; let line_hpos = 2 + 17 * 2 + 10 + 3; // TODO this is below the lines but should not be a magic number let line_vpos = (term_width - note.len() as u16) / 2 + 1; lyric.push_str(format!("{}{}", termion::cursor::Goto(line_vpos, line_hpos), note).as_ref()); lyric } fn letter_to_pos(letter: Letter) -> u16 { match letter { Letter::C => 0, Letter::Csh => 1, Letter::Db => 2, Letter::D => 3, Letter::Dsh => 4, Letter::Eb => 5, Letter::E => 6, Letter::F => 7, Letter::Fsh => 8, Letter::Gb => 9, Letter::G => 10, Letter::Gsh => 11, Letter::Ab => 12, Letter::A => 13, Letter::Ash => 14, Letter::Bb => 15, Letter::B => 16, } }
#[macro_use] extern crate from_repr_enum_derive; #[repr(u8)] #[derive(FromReprEnum, Debug, PartialEq)] enum Foo { X = 1, Y = 2, Unknown = 255, } #[test] fn test_from() { let x = Foo::from(1); assert_eq!(Foo::X, x); let y = Foo::from(2); assert_eq!(Foo::Y, y); let u = Foo::from(99); assert_eq!(Foo::Unknown, u); } #[repr(u8)] #[derive(FromReprEnum, Debug, PartialEq)] #[ReprEnumDefault = "NotFound"] enum Bar { X = 1, Y = 2, NotFound = 255, } #[test] fn test_from_with_default() { let x = Bar::from(1); assert_eq!(Bar::X, x); let y = Bar::from(2); assert_eq!(Bar::Y, y); let u = Bar::from(99); assert_eq!(Bar::NotFound, u); } #[repr(u64)] #[derive(FromReprEnum, Debug, PartialEq)] enum Foo64 { X = 1, Y = 5, Unknown = 255, } #[test] fn test_from_64() { let x = Foo64::from(1); assert_eq!(Foo64::X, x); let y = Foo64::from(5); assert_eq!(Foo64::Y, y); let u = Foo64::from(99); assert_eq!(Foo64::Unknown, u); }
fn main() { println!("Hello, world!"); use std::thread; use std::time::Duration; let handle = thread::spawn(|| { for i in 11..50 { println!("{}", i); thread::sleep(Duration::from_millis(1)); } }); for i in 6..10 { println!("{}", i); thread::sleep(Duration::from_millis(2)); } // 强制等待线程执行完毕 handle.join().unwrap(); // 可以在参数列表前使用 move 关键字强制闭包获取其使用的环境值的所有权。这个技巧在创建新线程将值的所有权从一个线程移动到另一个线程时最为实用。 let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("{:?}", v); }); // drop(v); // println!("{:?}", v); handle.join().unwrap(); println!("----------消息传递----------"); // 使用消息传递在线程间传送数据 use std::sync::mpsc; let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("Hi"); tx.send(val).unwrap(); }); // loop { // 不会用,看不懂 // let remsg = rx.try_recv().unwrap(); // println!("remsg: {}", remsg); // } let received = rx.recv().unwrap(); println!("{}", received); println!("----------消息传递2----------"); let (tx, rx) = mpsc::channel(); let tx_clone = tx.clone(); 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)); } }); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("thread"), ]; for val in vals { tx_clone.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); let mut v1 = rx.iter(); let a = v1.next(); println!("{:?}", a); for received in rx { println!("Got: {}", received); } // 共享状态并发互斥器 use std::sync::{Mutex, Arc}; 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!("count: {}", *counter.lock().unwrap()); // 死锁尝试 let a = Arc::new(Mutex::new("left".to_string())); let b = Arc::new(Mutex::new("right".to_string())); let a_ = Arc::clone(&a); let b_ = Arc::clone(&b); let handle_a = thread::spawn(move || { let mut got_a = a.lock().unwrap(); println!("获取a正在等待b"); thread::sleep(Duration::from_secs(1)); let mut got_b = b.lock().unwrap(); // let mut got_b = b.try_lock().unwrap(); }); let handle_b = thread::spawn(move || { let mut got_a = b_.lock().unwrap(); println!("获取b正在等待a"); thread::sleep(Duration::from_secs(1)); let mut got_b = a_.lock().unwrap(); }); handle_a.join().unwrap(); handle_b.join().unwrap(); }
extern crate connect_4; use connect_4::Connect4; use connect_4::Player; use connect_4::State; #[test] fn it_starts_blank() { let game = Connect4::new(); assert_eq!("\n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n1|2|3|4|5|6|7\n", game.to_string()); } #[test] fn can_play_first_go_as_red() { let mut game = Connect4::new(); game.play(Player::Red, 4).unwrap(); assert_eq!("\n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n | | |\x1b[31mO\x1b[0m| | | \n1|2|3|4|5|6|7\n", game.to_string()); } #[test] fn can_play_first_go_as_yellow() { let mut game = Connect4::new(); game.play(Player::Yellow, 4).unwrap(); assert_eq!("\n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n | | |\x1b[33mO\x1b[0m| | | \n1|2|3|4|5|6|7\n", game.to_string()); } #[test] fn can_play_in_any_column() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(1, 2, 3, 4, 5, 6, 7)); assert_eq!("\n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n\x1b[33mO\x1b[0m|\x1b[31mO\x1b[0m|\x1b[33mO\x1b[0m|\x1b[31mO\x1b[0m|\x1b[33mO\x1b[0m|\x1b[31mO\x1b[0m|\x1b[33mO\x1b[0m\n1|2|3|4|5|6|7\n", game.to_string()); } #[test] fn can_play_on_top_of_another_counter() { let mut game = Connect4::new(); game.play(Player::Yellow, 4).unwrap(); game.play(Player::Red, 4).unwrap(); assert_eq!("\n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n | | |\x1b[31mO\x1b[0m| | | \n | | |\x1b[33mO\x1b[0m| | | \n1|2|3|4|5|6|7\n", game.to_string()); } #[test] fn cannot_play_as_the_same_player_twice_in_a_row() { let mut game = Connect4::new(); game.play(Player::Yellow, 4).unwrap(); assert_eq!(game.play(Player::Yellow, 4), Err("You can't have two goes.")); } #[test] fn cannot_play_out_the_top() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(4, 4, 4, 4, 4, 4)); assert_eq!(game.play(Player::Yellow, 4), Err("No more space in that column.")); } #[test] fn game_starts_in_play() { let game = Connect4::new(); assert_eq!(game.state(), State::InPlay); } #[test] fn full_board_is_stalemate() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!( 1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 7, 1, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 7, 1, 1, 2, 3, 4, 5, 6, 7)); assert_eq!(game.state(), State::Stalemate, "\nExpected Stalemate; game board was: {}and game winner was: {:?}\n", game.to_string(), game.winner); } #[test] fn can_win_horizontally() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(1, 1, 2, 2, 3, 3, 4)); assert_eq!(game.state(), State::Won, "\nExpected Won; game board was: {}and game winner was: {:?}\n", game.to_string(), game.winner); } #[test] fn can_win_vertically() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(1, 2, 1, 2, 1, 2, 1)); assert_eq!(game.state(), State::Won, "\nExpected Won; game board was: {}and game winner was: {:?}\n", game.to_string(), game.winner); } #[test] fn can_win_diagonally() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(1, 2, 2, 3, 4, 3, 3, 4, 4, 5, 4)); assert_eq!(game.state(), State::Won, "\nExpected Won; game board was: {}and game winner was: {:?}\n", game.to_string(), game.winner); } #[test] fn cannot_play_out_of_the_board() { let mut game = Connect4::new(); assert_eq!(game.play(Player::Red, 9), Err("That's not in the board.")); } #[test] fn can_try_again_after_playing_out_of_top() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(1, 1, 1, 1, 1, 1)); assert_eq!(game.play(Player::Yellow, 1), Err("No more space in that column.")); assert_eq!(game.play(Player::Yellow, 2), Ok("Played a turn.")); } #[test] fn a_winning_line_is_asterisks() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(1, 1, 2, 2, 3, 3, 4)); assert_eq!("\n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n\x1b[31mO\x1b[0m|\x1b[31mO\x1b[0m|\x1b[31mO\x1b[0m| | | | \n\x1b[33m*\x1b[0m|\x1b[33m*\x1b[0m|\x1b[33m*\x1b[0m|\x1b[33m*\x1b[0m| | | \n1|2|3|4|5|6|7\n", game.to_string()); } #[test] fn winning_with_the_last_move_on_the_left_of_the_line_wins() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(7, 7, 6, 6, 5, 5, 4)); assert_eq!(State::Won, game.state()); } #[test] fn a_winning_line_of_more_than_4_counters_are_all_asterisks() { let mut game = Connect4::new(); play_in_columns(&mut game, vec!(1, 1, 2, 2, 3, 3, 5, 5, 6, 6, 7, 7, 4)); assert_eq!("\n | | | | | | \n | | | | | | \n | | | | | | \n | | | | | | \n\u{1b}[31mO\u{1b}[0m|\u{1b}[31mO\u{1b}[0m|\u{1b}[31mO\u{1b}[0m| |\u{1b}[31mO\u{1b}[0m|\u{1b}[31mO\u{1b}[0m|\u{1b}[31mO\u{1b}[0m\n\u{1b}[33m*\u{1b}[0m|\u{1b}[33m*\u{1b}[0m|\u{1b}[33m*\u{1b}[0m|\u{1b}[33m*\u{1b}[0m|\u{1b}[33m*\u{1b}[0m|\u{1b}[33m*\u{1b}[0m|\u{1b}[33m*\u{1b}[0m\n1|2|3|4|5|6|7\n", game.to_string()); } fn play_in_columns(game: &mut Connect4, columns: Vec<usize>) { let mut player = Player::Yellow; for column in columns { game.play(player, column).unwrap(); player = match player { Player::Red => Player::Yellow, Player::Yellow => Player::Red, }; } }
#![allow(unused)] use crate::openxr_module::OpenXR; use crate::parser::*; use crate::SCALE; use glium::texture::{DepthFormat, DepthTexture2d, MipmapsOption, UncompressedFloatFormat}; use glium::{vertex::VertexBufferAny, Display, DrawParameters, Frame, Program, Surface, Texture2d}; use nalgebra::{Matrix4, Translation3, UnitQuaternion}; use std::collections::HashMap; use std::ffi::{c_void, CString}; use std::os::raw::*; use std::rc::Rc; use x11::{glx, xlib}; pub mod backend; pub mod camera; pub mod shaders; pub struct Window { pub context: Rc<glium::backend::Context>, pub xr: OpenXR, pub shaders: HashMap<String, Program>, pub models: HashMap<String, VertexBufferAny>, pub textures: HashMap<String, Texture2d>, pub depth_textures: Option<(DepthTexture2d, DepthTexture2d)>, } impl Window { pub fn new() -> Self { let mut backend = backend::Backend::new(); let xr = OpenXR::new(&mut backend); let context = unsafe { glium::backend::Context::new(backend, false, Default::default()) }.unwrap(); Self { context, xr, depth_textures: None, shaders: HashMap::new(), models: HashMap::new(), textures: HashMap::new(), } } pub fn create_depth_textures(&mut self) { let depth_texture_left = DepthTexture2d::empty_with_format( &self.context, DepthFormat::F32, MipmapsOption::EmptyMipmaps, self.xr.swapchains.resolution_left.0, self.xr.swapchains.resolution_left.1, ) .unwrap(); let depth_texture_right = DepthTexture2d::empty_with_format( &self.context, DepthFormat::F32, MipmapsOption::EmptyMipmaps, self.xr.swapchains.resolution_right.0, self.xr.swapchains.resolution_right.1, ) .unwrap(); self.depth_textures = Some((depth_texture_left, depth_texture_right)); } pub fn draw(&mut self) { let swapchain_image = self.xr.swapchains.get_images(); if let Some((swapchain_image_left, swapchain_image_right)) = swapchain_image { if self.depth_textures.is_none() { self.create_depth_textures(); } let depth_textures = self.depth_textures.as_ref().unwrap(); self.xr.frame_stream_begin(); let texture_left = unsafe { glium::texture::texture2d::Texture2d::from_id( &self.context, glium::texture::UncompressedFloatFormat::U8U8U8U8, swapchain_image_left, false, glium::texture::MipmapsOption::NoMipmap, glium::texture::Dimensions::Texture2d { width: self.xr.swapchains.resolution_left.0, height: self.xr.swapchains.resolution_left.1, }, ) }; let texture_right = unsafe { glium::texture::texture2d::Texture2d::from_id( &self.context, glium::texture::UncompressedFloatFormat::U8U8U8U8, swapchain_image_right, false, glium::texture::MipmapsOption::NoMipmap, glium::texture::Dimensions::Texture2d { width: self.xr.swapchains.resolution_right.0, height: self.xr.swapchains.resolution_right.1, }, ) }; let mut target = glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.context, &texture_left, &depth_textures.0, ) .unwrap(); target.clear_color_and_depth((0.6, 0.0, 0.0, 1.0), 1.0); let mut target = glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.context, &texture_right, &depth_textures.1, ) .unwrap(); target.clear_color_and_depth((0.0, 0.0, 0.6, 1.0), 1.0); self.xr.swapchains.release_images(); self.xr.frame_stream_end(); } } fn draw_image() {} pub fn update_xr(&mut self) { self.xr.update(); } pub fn compile_shaders(&mut self) { use shaders::*; println!("Compiling shaders..."); let simple = glium::Program::from_source( &self.context, SHADER_SIMPLE_VERT, SHADER_SIMPLE_FRAG, None, ) .unwrap(); self.shaders.insert("simple".to_string(), simple); } pub fn load_default_models(&mut self) { use crate::obj_loader::load_obj; self.models.insert( "block".to_string(), load_obj("./assets/models/block.obj", &self.context), ); self.models.insert( "cube".to_string(), load_obj("./assets/models/cube.obj", &self.context), ); } pub fn load_default_textures(&mut self) { use crate::textures::load_texture; self.textures.insert( "dev".to_string(), load_texture("./assets/textures/dev.png".to_string(), &self.context), ); self.textures.insert( "mine".to_string(), load_texture("./assets/textures/mine.png".to_string(), &self.context), ); self.textures.insert( "note_red".to_string(), load_texture("./assets/textures/note_red.png".to_string(), &self.context), ); self.textures.insert( "obstacle".to_string(), load_texture("./assets/textures/obstacle.png".to_string(), &self.context), ); self.textures.insert( "note_blue".to_string(), load_texture("./assets/textures/note_blue.png".to_string(), &self.context), ); self.textures.insert( "note_middle_red".to_string(), load_texture( "./assets/textures/note_middle_red.png".to_string(), &self.context, ), ); self.textures.insert( "note_middle_blue".to_string(), load_texture( "./assets/textures/note_middle_blue.png".to_string(), &self.context, ), ); } } #[derive(Copy, Clone)] pub struct Vertex { pub position: [f32; 3], pub normal: [f32; 3], pub tex_coords: [f32; 2], } implement_vertex!(Vertex, position, normal, tex_coords); pub fn calc_transform( scale: (f32, f32, f32), position: Translation3<f32>, rotation: UnitQuaternion<f32>, ) -> Matrix4<f32> { let scale_matrix: Matrix4<f32> = Matrix4::new( scale.0, 0.0, 0.0, 0.0, 0.0, scale.1, 0.0, 0.0, 0.0, 0.0, scale.2, 0.0, 0.0, 0.0, 0.0, 1.0, ); let translation_matrix = position.to_homogeneous(); let rotation_matrix = rotation.to_homogeneous(); translation_matrix * rotation_matrix * scale_matrix } pub fn get_params() -> DrawParameters<'static> { use glium::{draw_parameters, Depth, DepthTest}; DrawParameters { depth: Depth { test: DepthTest::IfLess, write: true, ..Default::default() }, backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise, blend: draw_parameters::Blend::alpha_blending(), ..Default::default() } }
use ast_types::Path as RacerPath; use ast_types::{ self, GenericsArgs, ImplHeader, PathAlias, PathAliasKind, PathSearch, TraitBounds, Ty, }; use core::{self, BytePos, ByteRange, Match, MatchType, Scope, Session, SessionExt}; use nameres::{self, resolve_path_with_str}; use scopes; use typeinf; use std::path::Path; use std::rc::Rc; use syntax::ast::{ self, ExprKind, FunctionRetTy, ItemKind, LitKind, PatKind, TyKind, UseTree, UseTreeKind, }; use syntax::errors::{emitter::ColorConfig, Handler}; use syntax::parse::parser::Parser; use syntax::parse::{self, ParseSess}; use syntax::source_map::{self, FileName, SourceMap, Span}; use syntax::{self, visit}; /// construct parser from string // From syntax/util/parser_testing.rs pub fn string_to_parser(ps: &ParseSess, source_str: String) -> Parser { parse::new_parser_from_source_str(ps, FileName::Custom("racer-file".to_owned()), source_str) } /// Get parser from string s and then apply closure f to it // TODO: use Result insated of Option pub fn with_error_checking_parse<F, T>(s: String, f: F) -> Option<T> where F: FnOnce(&mut Parser) -> Option<T>, { syntax::with_globals(|| { let codemap = Rc::new(SourceMap::new(source_map::FilePathMapping::empty())); // setting of how we display errors in console // here we set can_emit_warnings=false, treat_err_as_bug=false let handler = Handler::with_tty_emitter(ColorConfig::Never, false, false, Some(codemap.clone())); let parse_sess = ParseSess::with_span_handler(handler, codemap); let mut p = string_to_parser(&parse_sess, s); f(&mut p) }) } /// parse string source_str as statement and then apply f to it /// return false if we can't parse s as statement // TODO: make F FnOnce(&ast::Stmt) -> Result<Something, Error> pub fn with_stmt<F>(source_str: String, f: F) -> bool where F: FnOnce(&ast::Stmt), { with_error_checking_parse(source_str, |p| { let stmt = match p.parse_stmt() { Ok(Some(stmt)) => stmt, _ => return None, }; f(&stmt); Some(()) }).is_some() } pub(crate) fn destruct_span(span: Span) -> (u32, u32) { let source_map::BytePos(lo) = span.lo(); let source_map::BytePos(hi) = span.hi(); (lo, hi) } pub(crate) fn get_span_start(span: Span) -> u32 { let source_map::BytePos(lo) = span.lo(); lo } /// collect paths from syntax::ast::UseTree #[derive(Debug)] pub struct UseVisitor { pub path_list: Vec<PathAlias>, pub contains_glob: bool, } impl<'ast> visit::Visitor<'ast> for UseVisitor { fn visit_item(&mut self, i: &ast::Item) { // collect items from use tree recursively // returns (Paths, contains_glab) fn collect_nested_items( use_tree: &UseTree, parent_path: Option<&ast_types::Path>, ) -> (Vec<PathAlias>, bool) { let mut res = vec![]; let mut path = if let Some(parent) = parent_path { let relative_path = RacerPath::from_ast(&use_tree.prefix); let mut path = parent.clone(); path.extend(relative_path); path } else { RacerPath::from_ast(&use_tree.prefix) }; let mut contains_glob = false; match use_tree.kind { UseTreeKind::Simple(_, _, _) => { let ident = use_tree.ident().name.to_string(); let kind = if let Some(last_seg) = path.segments.last() { //` self` is treated normaly in libsyntax, // but we distinguish it here to make completion easy if last_seg.name == "self" { PathAliasKind::Self_(ident) } else { PathAliasKind::Ident(ident) } } else { PathAliasKind::Ident(ident) }; if let PathAliasKind::Self_(_) = kind { path.segments.pop(); } res.push(PathAlias { kind, path }); } UseTreeKind::Nested(ref nested) => { nested.iter().for_each(|(ref tree, _)| { let (items, has_glob) = collect_nested_items(tree, Some(&path)); res.extend(items); contains_glob |= has_glob; }); } UseTreeKind::Glob => { res.push(PathAlias { kind: PathAliasKind::Glob, path, }); contains_glob = true; } } (res, contains_glob) } if let ItemKind::Use(ref use_tree) = i.node { let (path_list, contains_glob) = collect_nested_items(use_tree, None); self.path_list = path_list; self.contains_glob = contains_glob; } } } pub struct PatBindVisitor { ident_points: Vec<ByteRange>, } impl<'ast> visit::Visitor<'ast> for PatBindVisitor { fn visit_local(&mut self, local: &ast::Local) { // don't visit the RHS (init) side of the let stmt self.visit_pat(&local.pat); } fn visit_expr(&mut self, ex: &ast::Expr) { // don't visit the RHS or block of an 'if let' or 'for' stmt match ex.node { ExprKind::IfLet(ref pat, ..) | ExprKind::WhileLet(ref pat, ..) => { pat.iter().for_each(|pat| self.visit_pat(pat)) } ExprKind::ForLoop(ref pat, ..) => self.visit_pat(pat), _ => visit::walk_expr(self, ex), } } fn visit_pat(&mut self, p: &ast::Pat) { match p.node { PatKind::Ident(_, ref spannedident, _) => { self.ident_points.push(spannedident.span.into()); } _ => { visit::walk_pat(self, p); } } } } pub struct PatVisitor { ident_points: Vec<ByteRange>, } impl<'ast> visit::Visitor<'ast> for PatVisitor { fn visit_pat(&mut self, p: &ast::Pat) { match p.node { PatKind::Ident(_, ref spannedident, _) => { self.ident_points.push(spannedident.span.into()); } _ => { visit::walk_pat(self, p); } } } } fn point_is_in_span(point: BytePos, span: &Span) -> bool { let point: u32 = point.0 as u32; let (lo, hi) = destruct_span(*span); point >= lo && point < hi } // The point must point to an ident within the pattern. fn destructure_pattern_to_ty( pat: &ast::Pat, point: BytePos, ty: &Ty, scope: &Scope, session: &Session, ) -> Option<Ty> { debug!( "destructure_pattern_to_ty point {:?} ty {:?} pat: {:?}", point, ty, pat.node ); match pat.node { PatKind::Ident(_, ref spannedident, _) => { if point_is_in_span(point, &spannedident.span) { debug!("destructure_pattern_to_ty matched an ident!"); Some(ty.clone()) } else { panic!( "Expecting the point to be in the patident span. pt: {:?}", point ); } } PatKind::Tuple(ref tuple_elements, _) => match *ty { Ty::Tuple(ref typeelems) => { let mut res = None; for (i, p) in tuple_elements.iter().enumerate() { if point_is_in_span(point, &p.span) { let ty = &typeelems[i]; res = destructure_pattern_to_ty(p, point, ty, scope, session); break; } } res } _ => panic!("Expecting TyTuple"), }, PatKind::TupleStruct(ref path, ref children, _) => { let m = resolve_ast_path(path, &scope.filepath, scope.point, session); let contextty = path_to_match(ty.clone(), session); if let Some(m) = m { let mut res = None; for (i, p) in children.iter().enumerate() { if point_is_in_span(point, &p.span) { res = typeinf::get_tuplestruct_field_type(i, &m, session) .and_then(|ty| // if context ty is a match, use its generics if let Some(Ty::Match(ref contextmatch)) = contextty { path_to_match_including_generics(ty, contextmatch, session) } else { path_to_match(ty, session) }) .and_then(|ty| destructure_pattern_to_ty(p, point, &ty, scope, session)); break; } } res } else { None } } PatKind::Struct(ref path, ref children, _) => { let m = resolve_ast_path(path, &scope.filepath, scope.point, session); let contextty = path_to_match(ty.clone(), session); if let Some(m) = m { let mut res = None; for child in children { if point_is_in_span(point, &child.span) { res = typeinf::get_struct_field_type( &child.node.ident.name.as_str(), &m, session, ).and_then(|ty| { if let Some(Ty::Match(ref contextmatch)) = contextty { path_to_match_including_generics(ty, contextmatch, session) } else { path_to_match(ty, session) } }).and_then(|ty| { destructure_pattern_to_ty(&child.node.pat, point, &ty, scope, session) }); break; } } res } else { None } } _ => { debug!("Could not destructure pattern {:?}", pat); None } } } struct LetTypeVisitor<'c: 's, 's> { scope: Scope, session: &'s Session<'c>, srctxt: String, pos: BytePos, // pos is relative to the srctxt, scope is global result: Option<Ty>, } impl<'c, 's, 'ast> visit::Visitor<'ast> for LetTypeVisitor<'c, 's> { fn visit_expr(&mut self, ex: &ast::Expr) { match ex.node { ExprKind::IfLet(ref pattern, ref expr, _, _) | ExprKind::WhileLet(ref pattern, ref expr, _, _) => { let mut v = ExprTypeVisitor { scope: self.scope.clone(), result: None, session: self.session, }; v.visit_expr(expr); // TODO: too ugly self.result = v .result .and_then(|ty| { pattern .iter() .filter_map(|pat| { destructure_pattern_to_ty( pat, self.pos, &ty, &self.scope, self.session, ) }).nth(0) }).and_then(|ty| path_to_match(ty, self.session)); } _ => visit::walk_expr(self, ex), } } fn visit_local(&mut self, local: &ast::Local) { let mut ty = None; if let Some(ref local_ty) = local.ty { ty = Ty::from_ast(local_ty, &self.scope); } if ty.is_none() { // oh, no type in the let expr. Try evalling the RHS ty = local.init.as_ref().and_then(|initexpr| { debug!("init node is {:?}", initexpr.node); let mut v = ExprTypeVisitor { scope: self.scope.clone(), result: None, session: self.session, }; v.visit_expr(initexpr); v.result }); } debug!( "LetTypeVisitor: ty is {:?}. pos is {:?}, src is |{}|", ty, self.pos, self.srctxt ); self.result = ty .and_then(|ty| { destructure_pattern_to_ty(&local.pat, self.pos, &ty, &self.scope, self.session) }).and_then(|ty| path_to_match(ty, self.session)); } } struct MatchTypeVisitor<'c: 's, 's> { scope: Scope, session: &'s Session<'c>, pos: BytePos, // pos is relative to the srctxt, scope is global result: Option<Ty>, } impl<'c, 's, 'ast> visit::Visitor<'ast> for MatchTypeVisitor<'c, 's> { fn visit_expr(&mut self, ex: &ast::Expr) { if let ExprKind::Match(ref subexpression, ref arms) = ex.node { debug!("PHIL sub expr is {:?}", subexpression); let mut v = ExprTypeVisitor { scope: self.scope.clone(), result: None, session: self.session, }; v.visit_expr(subexpression); debug!("PHIL sub type is {:?}", v.result); for arm in arms { for pattern in &arm.pats { if point_is_in_span(self.pos, &pattern.span) { debug!("PHIL point is in pattern |{:?}|", pattern); self.result = v .result .as_ref() .and_then(|ty| { destructure_pattern_to_ty( pattern, self.pos, ty, &self.scope, self.session, ) }).and_then(|ty| path_to_match(ty, self.session)); } } } } } } fn resolve_ast_path( path: &ast::Path, filepath: &Path, pos: BytePos, session: &Session, ) -> Option<Match> { let path = RacerPath::from_ast(path); debug!("resolve_ast_path {:?}", path); nameres::resolve_path_with_str( &path, filepath, pos, core::SearchType::ExactMatch, core::Namespace::Both, session, ).nth(0) } fn path_to_match(ty: Ty, session: &Session) -> Option<Ty> { match ty { Ty::PathSearch(ref path, ref scope) => { find_type_match(path, &scope.filepath, scope.point, session) } Ty::RefPtr(ty) => path_to_match(*ty, session), _ => Some(ty), } } fn find_type_match(path: &RacerPath, fpath: &Path, pos: BytePos, session: &Session) -> Option<Ty> { debug!("find_type_match {:?}, {:?}", path, fpath); let mut res = resolve_path_with_str( path, fpath, pos, core::SearchType::ExactMatch, core::Namespace::Type, session, ).nth(0) .and_then(|m| match m.mtype { MatchType::Type => get_type_of_typedef(&m, session), _ => Some(m), })?; // TODO: 'Type' support // if res is Enum/Struct and has a generic type paramter, let's resolve it. for (mut param, typ) in res.generics_mut().zip(path.generic_types()) { param.resolve(PathSearch { path: typ.clone(), filepath: fpath.to_owned(), point: pos, }) } Some(Ty::Match(res)) } pub(crate) fn get_type_of_typedef(m: &Match, session: &Session) -> Option<Match> { debug!("get_type_of_typedef match is {:?}", m); let msrc = session.load_source_file(&m.filepath); let blobstart = m.point - BytePos(5); // 5 == "type ".len() let blob = msrc.get_src_from_start(blobstart); blob.iter_stmts() .nth(0) .and_then(|range| { let blob = msrc[range.shift(blobstart).to_range()].to_owned(); debug!("get_type_of_typedef blob string {}", blob); let res = parse_type(blob); debug!("get_type_of_typedef parsed type {:?}", res.type_); res.type_ }).and_then(|type_| { let src = session.load_source_file(&m.filepath); let scope_start = scopes::scope_start(src.as_src(), m.point); // Type of TypeDef cannot be inside the impl block so look outside let outer_scope_start = scope_start .0 .checked_sub(1) .map(|sub| scopes::scope_start(src.as_src(), sub.into())) .and_then(|s| { let blob = src.get_src_from_start(s); let blob = blob.trim_left(); if blob.starts_with("impl") || blob.starts_with("trait") || blob.starts_with("pub trait") { Some(s) } else { None } }); nameres::resolve_path_with_str( &type_, &m.filepath, outer_scope_start.unwrap_or(scope_start), core::SearchType::ExactMatch, core::Namespace::Type, session, ).nth(0) }) } struct ExprTypeVisitor<'c: 's, 's> { scope: Scope, session: &'s Session<'c>, result: Option<Ty>, } impl<'c, 's, 'ast> visit::Visitor<'ast> for ExprTypeVisitor<'c, 's> { fn visit_expr(&mut self, expr: &ast::Expr) { debug!( "ExprTypeVisitor::visit_expr {:?}(kind: {:?})", expr, expr.node ); //walk_expr(self, ex, e) match expr.node { ExprKind::Unary(_, ref expr) | ExprKind::AddrOf(_, ref expr) => { self.visit_expr(expr); } ExprKind::Path(_, ref path) => { let source_map::BytePos(lo) = path.span.lo(); self.result = resolve_ast_path( path, &self.scope.filepath, self.scope.point + lo.into(), self.session, ).and_then(|m| { let msrc = self.session.load_source_file(&m.filepath); typeinf::get_type_of_match(m, msrc.as_src(), self.session) }); } ExprKind::Call(ref callee_expression, _ /*ref arguments*/) => { self.visit_expr(callee_expression); self.result = self.result.take().and_then(|m| { if let Ty::Match(m) = m { match m.mtype { MatchType::Function | MatchType::Method(_) => { typeinf::get_return_type_of_function(&m, &m, self.session) .and_then(|ty| path_to_match(ty, self.session)) } MatchType::Struct(_) | MatchType::Enum(_) => Some(Ty::Match(m)), _ => { debug!( "ExprTypeVisitor: Cannot handle ExprCall of {:?} type", m.mtype ); None } } } else { None } }); } ExprKind::Struct(ref path, _, _) => { let pathvec = RacerPath::from_ast(path); self.result = find_type_match( &pathvec, &self.scope.filepath, self.scope.point, self.session, ); } ExprKind::MethodCall(ref method_def, ref arguments) => { let methodname = method_def.ident.name.as_str(); debug!("method call ast name {}", methodname); // arguments[0] is receiver(e.g. self) let objexpr = &arguments[0]; self.visit_expr(objexpr); self.result = self.result.as_ref().and_then(|contextm| match contextm { Ty::Match(contextm) => { let omethod = nameres::search_for_impl_methods( contextm, &methodname, contextm.point, &contextm.filepath, contextm.local, core::SearchType::ExactMatch, self.session, ); omethod .map(|method| { typeinf::get_return_type_of_function( &method, contextm, self.session, ) }).filter_map(|ty| { ty.and_then(|ty| { path_to_match_including_generics(ty, contextm, self.session) }) }).nth(0) } _ => None, }); } ExprKind::Field(ref subexpression, spannedident) => { let fieldname = spannedident.name.to_string(); debug!("exprfield {}", fieldname); self.visit_expr(subexpression); self.result = self.result.as_ref().and_then(|structm| match *structm { Ty::Match(ref structm) => { typeinf::get_struct_field_type(&fieldname, structm, self.session).and_then( |fieldtypepath| { find_type_match_including_generics( &fieldtypepath, &structm.filepath, structm.point, structm, self.session, ) }, ) } _ => None, }); } ExprKind::Tup(ref exprs) => { let mut v = Vec::new(); for expr in exprs { self.visit_expr(expr); match self.result { Some(ref t) => v.push(t.clone()), None => { self.result = None; return; } }; } self.result = Some(Ty::Tuple(v)); } ExprKind::Lit(ref lit) => { let ty_path = match lit.node { LitKind::Str(_, _) => Some(RacerPath::from_vec(false, vec!["str"])), // See https://github.com/phildawes/racer/issues/727 for // information on why other literals aren't supported. _ => None, }; self.result = if let Some(lit_path) = ty_path { find_type_match( &lit_path, &self.scope.filepath, self.scope.point, self.session, ) } else { Some(Ty::Unsupported) }; } ExprKind::Try(ref expr) => { self.visit_expr(&expr); debug!("ExprKind::Try result: {:?} expr: {:?}", self.result, expr); self.result = if let Some(&Ty::Match(ref m)) = self.result.as_ref() { // HACK for speed up (kngwyu) // Yeah there're many corner cases but it'll work well in most cases if m.matchstr == "Result" || m.matchstr == "Option" { debug!("Option or Result: {:?}", m); m.resolved_generics().next().and_then(|ok_param| { find_type_match( &ok_param.path, &ok_param.filepath, ok_param.point, self.session, ) }) } else { debug!("Unable to desugar Try expression; type was {:?}", m); None } } else { None }; } ExprKind::Match(_, ref arms) => { debug!("match expr"); for arm in arms { self.visit_expr(&arm.body); // All match arms need to return the same result, so if we found a result // we can end the search. if self.result.is_some() { break; } } } ExprKind::If(_, ref block, ref else_block) | ExprKind::IfLet(_, _, ref block, ref else_block) => { debug!("if/iflet expr"); visit::walk_block(self, &block); // if the block does not resolve to a type, try the else block if self.result.is_none() && else_block.is_some() { self.visit_expr(&else_block.as_ref().unwrap()); } } ExprKind::Block(ref block, ref _label) => { debug!("block expr"); visit::walk_block(self, &block); } _ => { debug!("- Could not match expr node type: {:?}", expr.node); } }; } fn visit_mac(&mut self, mac: &ast::Mac) { // Just do nothing if we see a macro, but also prevent the panic! in the default impl. debug!("ignoring visit_mac: {:?}", mac); } } // gets generics info from the context match fn path_to_match_including_generics(ty: Ty, contextm: &Match, session: &Session) -> Option<Ty> { debug!("path_to_match_including_generics: {:?} {:?}", ty, contextm); match ty { Ty::PathSearch(ref fieldtypepath, ref scope) => { if fieldtypepath.segments.len() == 1 { let typename = &fieldtypepath.segments[0].name; // could have generic args! - try and resolve them let mut typepath = fieldtypepath.to_owned(); let mut gentypefound = false; for type_param in contextm.generics() { let resolved = try_continue!(type_param.resolved()); if type_param.name() == typename { return find_type_match( &resolved.path, &resolved.filepath, resolved.point, session, ); } for typ in &mut typepath.segments[0].types { if type_param.name() == &typ.segments[0].name { *typ = resolved.path.clone(); gentypefound = true; } } } if gentypefound { let mut out = find_type_match(&typepath, &scope.filepath, scope.point, session); // Fix the paths on the generic types in out // TODO(kngwyu): I DON'T KNOW WHAT THIS CODE DO COMPLETELY if let Some(Ty::Match(ref mut m)) = out { for type_search in contextm.resolved_generics() { for gen_param in m.generics_mut() { debug!( "gen_param: {:?}, type_search: {:?}", gen_param, type_search ); let same_name = gen_param.resolved().map_or(false, |typ| { typ.path.segments[0].name == type_search.path.segments[0].name }); if same_name { gen_param.resolve(type_search.to_owned()); } } } } return out; } } find_type_match(fieldtypepath, &scope.filepath, scope.point, session) } _ => Some(ty), } } fn find_type_match_including_generics( fieldtype: &Ty, filepath: &Path, pos: BytePos, structm: &Match, session: &Session, ) -> Option<Ty> { assert_eq!(&structm.filepath, filepath); let fieldtypepath = match *fieldtype { Ty::PathSearch(ref path, _) => path, Ty::RefPtr(ref ty) => match *ty.as_ref() { Ty::PathSearch(ref path, _) => path, _ => { debug!( "EXPECTING A PATH!! Cannot handle other types yet. {:?}", fieldtype ); return None; } }, _ => { debug!( "EXPECTING A PATH!! Cannot handle other types yet. {:?}", fieldtype ); return None; } }; if fieldtypepath.segments.len() == 1 { // could be a generic arg! - try and resolve it let typename = &fieldtypepath.segments[0].name; for type_param in structm.generics() { if let Some(type_search) = type_param.resolved() { if type_param.name() == typename { return find_type_match( &type_search.path, &type_search.filepath, type_search.point, session, ); } } } } find_type_match(fieldtypepath, filepath, pos, session) } struct StructVisitor { pub scope: Scope, pub fields: Vec<(String, BytePos, Option<Ty>)>, } impl<'ast> visit::Visitor<'ast> for StructVisitor { fn visit_variant_data( &mut self, struct_definition: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId, _: Span, ) { for field in struct_definition.fields() { let source_map::BytePos(point) = field.span.lo(); let ty = Ty::from_ast(&field.ty, &self.scope); let name = match field.ident { Some(ref ident) => ident.to_string(), // name unnamed field by its ordinal, since self.0 works None => format!("{}", self.fields.len()), }; self.fields.push((name, point.into(), ty)); } } } #[derive(Debug)] pub struct TypeVisitor { pub name: Option<String>, pub type_: Option<RacerPath>, } impl<'ast> visit::Visitor<'ast> for TypeVisitor { fn visit_item(&mut self, item: &ast::Item) { if let ItemKind::Ty(ref ty, _) = item.node { self.name = Some(item.ident.name.to_string()); let typepath = match ty.node { TyKind::Rptr(_, ref ty) => match ty.ty.node { TyKind::Path(_, ref path) => { let type_ = RacerPath::from_ast(path); debug!("type type is {:?}", type_); Some(type_) } _ => None, }, TyKind::Path(_, ref path) => { let type_ = RacerPath::from_ast(path); debug!("type type is {:?}", type_); Some(type_) } _ => None, }; self.type_ = typepath; debug!("typevisitor type is {:?}", self.type_); } } } pub struct TraitVisitor { pub name: Option<String>, } impl<'ast> visit::Visitor<'ast> for TraitVisitor { fn visit_item(&mut self, item: &ast::Item) { if let ItemKind::Trait(..) = item.node { self.name = Some(item.ident.name.to_string()); } } } #[derive(Debug)] pub struct ImplVisitor<'p> { pub result: Option<ImplHeader>, filepath: &'p Path, offset: BytePos, block_start: BytePos, // the point { appears local: bool, } impl<'p> ImplVisitor<'p> { fn new(filepath: &'p Path, offset: BytePos, local: bool, block_start: BytePos) -> Self { ImplVisitor { result: None, filepath, offset, block_start, local, } } } impl<'ast, 'p> visit::Visitor<'ast> for ImplVisitor<'p> { fn visit_item(&mut self, item: &ast::Item) { if let ItemKind::Impl(_, _, _, ref generics, ref otrait, ref self_typ, _) = item.node { let impl_start = self.offset + get_span_start(item.span).into(); self.result = ImplHeader::new( generics, self.filepath, otrait, self_typ, self.offset, self.local, impl_start, self.block_start, ); } } } pub struct ModVisitor { pub name: Option<String>, } impl<'ast> visit::Visitor<'ast> for ModVisitor { fn visit_item(&mut self, item: &ast::Item) { if let ItemKind::Mod(_) = item.node { self.name = Some(item.ident.name.to_string()); } } } pub struct ExternCrateVisitor { pub name: Option<String>, pub realname: Option<String>, } impl<'ast> visit::Visitor<'ast> for ExternCrateVisitor { fn visit_item(&mut self, item: &ast::Item) { if let ItemKind::ExternCrate(ref optional_s) = item.node { self.name = Some(item.ident.name.to_string()); if let Some(ref istr) = *optional_s { self.realname = Some(istr.to_string()); } } } } #[derive(Debug)] struct GenericsVisitor<P> { result: GenericsArgs, filepath: P, } impl<'ast, P: AsRef<Path>> visit::Visitor<'ast> for GenericsVisitor<P> { fn visit_generics(&mut self, g: &ast::Generics) { let path = &self.filepath; if !self.result.0.is_empty() { warn!("[visit_generics] called for multiple generics!"); } self.result.extend(GenericsArgs::from_generics(g, path, 0)); } } pub struct EnumVisitor { pub name: String, pub values: Vec<(String, BytePos)>, } impl<'ast> visit::Visitor<'ast> for EnumVisitor { fn visit_item(&mut self, i: &ast::Item) { if let ItemKind::Enum(ref enum_definition, _) = i.node { self.name = i.ident.name.to_string(); //visitor.visit_generics(type_parameters, env.clone()); //visit::walk_enum_def(self, enum_definition, type_parameters, e) let (point1, point2) = destruct_span(i.span); debug!("name point is {} {}", point1, point2); for variant in &enum_definition.variants { let source_map::BytePos(point) = variant.span.lo(); self.values .push((variant.node.ident.to_string(), point.into())); } } } } pub fn parse_use(s: String) -> UseVisitor { let mut v = UseVisitor { path_list: Vec::new(), contains_glob: false, }; // visit::walk_crate can be panic so we don't use it here with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v } pub fn parse_pat_bind_stmt(s: String) -> Vec<ByteRange> { let mut v = PatBindVisitor { ident_points: Vec::new(), }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.ident_points } pub fn parse_struct_fields(s: String, scope: Scope) -> Vec<(String, BytePos, Option<Ty>)> { let mut v = StructVisitor { scope, fields: Vec::new(), }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.fields } pub fn parse_impl( s: String, path: &Path, offset: BytePos, local: bool, scope_start: BytePos, ) -> Option<ImplHeader> { let mut v = ImplVisitor::new(path, offset, local, scope_start); with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.result } pub fn parse_trait(s: String) -> TraitVisitor { let mut v = TraitVisitor { name: None }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v } /// parse traits and collect inherited traits as TraitBounds pub fn parse_inherited_traits<P: AsRef<Path>>( s: String, filepath: P, offset: i32, ) -> Option<TraitBounds> { let mut v = InheritedTraitsVisitor { result: None, file_path: filepath, offset: offset, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.result } pub fn parse_generics(s: String, filepath: &Path) -> GenericsArgs { let mut v = GenericsVisitor { result: GenericsArgs::default(), filepath: filepath, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.result } pub fn parse_type(s: String) -> TypeVisitor { let mut v = TypeVisitor { name: None, type_: None, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v } pub fn parse_fn_args(s: String) -> Vec<ByteRange> { parse_pat_idents(s) } pub fn parse_pat_idents(s: String) -> Vec<ByteRange> { let mut v = PatVisitor { ident_points: Vec::new(), }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); debug!("ident points are {:?}", v.ident_points); v.ident_points } pub fn parse_fn_output(s: String, scope: Scope) -> Option<Ty> { let mut v = FnOutputVisitor { result: None, scope, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.result } pub fn parse_fn_arg_type( s: String, argpos: BytePos, scope: Scope, session: &Session, offset: i32, ) -> Option<Ty> { debug!("parse_fn_arg {:?} |{}|", argpos, s); let mut v = FnArgTypeVisitor { argpos, scope, session, generics: GenericsArgs::default(), offset, result: None, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.result } pub fn parse_mod(s: String) -> ModVisitor { let mut v = ModVisitor { name: None }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v } pub fn parse_extern_crate(s: String) -> ExternCrateVisitor { let mut v = ExternCrateVisitor { name: None, realname: None, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v } pub fn parse_enum(s: String) -> EnumVisitor { let mut v = EnumVisitor { name: String::new(), values: Vec::new(), }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v } pub fn get_type_of(s: String, fpath: &Path, pos: BytePos, session: &Session) -> Option<Ty> { let startscope = Scope { filepath: fpath.to_path_buf(), point: pos, }; let mut v = ExprTypeVisitor { scope: startscope, result: None, session, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.result } // pos points to an ident in the lhs of the stmtstr pub fn get_let_type(s: String, pos: BytePos, scope: Scope, session: &Session) -> Option<Ty> { let mut v = LetTypeVisitor { scope, session, srctxt: s.clone(), pos, result: None, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.result } pub fn get_match_arm_type(s: String, pos: BytePos, scope: Scope, session: &Session) -> Option<Ty> { let mut v = MatchTypeVisitor { scope, session, pos, result: None, }; with_stmt(s, |stmt| visit::walk_stmt(&mut v, stmt)); v.result } pub struct FnOutputVisitor { scope: Scope, pub result: Option<Ty>, } impl<'ast> visit::Visitor<'ast> for FnOutputVisitor { fn visit_fn( &mut self, _: visit::FnKind, fd: &ast::FnDecl, _: source_map::Span, _: ast::NodeId, ) { self.result = match fd.output { FunctionRetTy::Ty(ref ty) => Ty::from_ast(ty, &self.scope), FunctionRetTy::Default(_) => None, }; } } /// Visitor to detect type of fnarg pub struct FnArgTypeVisitor<'c: 's, 's> { /// the code point arg appears in search string argpos: BytePos, scope: Scope, session: &'s Session<'c>, generics: GenericsArgs, /// the code point search string starts /// use i32 for the case `impl blah {` is inserted offset: i32, pub result: Option<Ty>, } impl<'c, 's, 'ast> visit::Visitor<'ast> for FnArgTypeVisitor<'c, 's> { fn visit_generics(&mut self, g: &'ast ast::Generics) { let filepath = &self.scope.filepath; let generics = GenericsArgs::from_generics(g, filepath, self.offset); debug!( "[FnArgTypeVisitor::visit_generics] {:?}", self.generics.get_idents() ); self.generics.extend(generics); } fn visit_fn( &mut self, _fk: visit::FnKind, fd: &ast::FnDecl, _: source_map::Span, _: ast::NodeId, ) { debug!("[FnArgTypeVisitor::visit_fn] inputs: {:?}", fd.inputs); // Get generics arguments here (just for speed up) self.result = fd .inputs .iter() .find(|arg| point_is_in_span(self.argpos, &arg.pat.span)) .and_then(|arg| { debug!("[FnArgTypeVisitor::visit_fn] type {:?} was found", arg.ty); let ty = Ty::from_ast(&arg.ty, &self.scope) .and_then(|ty| { destructure_pattern_to_ty( &arg.pat, self.argpos, &ty, &self.scope, self.session, ) }).map(destruct_ty_refptr)?; if let Ty::PathSearch(ref path, ref scope) = ty { let segments = &path.segments; // now we want to get 'T' from fn f<T>(){}, so segments.len() == 1 if segments.len() == 1 { let name = &segments[0].name; if let Some(bounds) = self.generics.find_type_param(name) { let res = bounds.to_owned().into_match()?; return Some(Ty::Match(res)); } } find_type_match(path, &scope.filepath, scope.point, self.session) } else { Some(ty) } }); } } fn destruct_ty_refptr(ty_arg: Ty) -> Ty { if let Ty::RefPtr(ty) = ty_arg { destruct_ty_refptr(*ty) } else { ty_arg } } /// Visitor to collect Inherited Traits pub struct InheritedTraitsVisitor<P> { /// search result(list of Inherited Traits) result: Option<TraitBounds>, /// the file trait appears file_path: P, /// thecode point 'trait' statement starts offset: i32, } impl<'ast, P> visit::Visitor<'ast> for InheritedTraitsVisitor<P> where P: AsRef<Path>, { fn visit_item(&mut self, item: &ast::Item) { if let ItemKind::Trait(_, _, _, ref bounds, _) = item.node { self.result = Some(TraitBounds::from_generic_bounds( bounds, &self.file_path, self.offset, )); } } }
pub mod primes; pub mod fibonacci; pub mod euclid; pub mod pythagorean_triples;
use std::{rc::Rc, sync::{Arc, RwLock}}; use coingecko_requests::data::{Coin, VsCurrency}; use iced::{Button, Clipboard, Column, Command, HorizontalAlignment, Length, PickList, Row, Scrollable, Text, TextInput, button, pick_list, scrollable, text_input}; pub struct Flags { pub coins: Rc<Vec<coingecko_requests::data::Coin>>, pub currencies: Rc<Vec<coingecko_requests::data::VsCurrency>>, pub settings: Arc<RwLock<crate::settings::Settings>>, } #[derive(Debug, Clone)] pub enum Message { TriggersUpdated(Vec<coingecko_requests::data::Trigger>), SaveTriggerClicked, CoinPicked(coingecko_requests::data::Coin), CurrencyPicked(coingecko_requests::data::VsCurrency), PriceInputChanged(String), TriggersAdded, DeleteTriggerClicked(i64), TriggerDeleted } #[derive(Debug, Clone)] pub struct Gui { coins: Rc<Vec<coingecko_requests::data::Coin>>, currencies: Rc<Vec<coingecko_requests::data::VsCurrency>>, settings: Arc<RwLock<crate::settings::Settings>>, triggers: Vec<coingecko_requests::data::Trigger>, picked_coin: coingecko_requests::data::Coin, coin_picklist_state: pick_list::State<coingecko_requests::data::Coin>, picked_currency: coingecko_requests::data::VsCurrency, currency_picklist_state: pick_list::State<coingecko_requests::data::VsCurrency>, price_input_state: text_input::State, price_value: String, save_trigger_state: button::State, scrollable_state: scrollable::State, delete_button_states: Vec<button::State>, } impl Gui { pub fn new(flags: Flags) -> (Self, Command<Message>) { let picked_coin = flags.coins.iter().find(|coin| coin.raw.id == "bitcoin").cloned().unwrap(); let picked_currency = flags.currencies.iter().find(|currency| currency.raw.name == "usd").cloned().unwrap(); (Self{ coins: flags.coins, currencies: flags.currencies, settings: flags.settings, triggers: Vec::new(), coin_picklist_state: Default::default(), picked_coin: picked_coin.clone(), picked_currency: picked_currency.clone(), currency_picklist_state: Default::default(), price_input_state: Default::default(), price_value: Default::default(), save_trigger_state: Default::default(), scrollable_state: Default::default(), delete_button_states: Vec::new(), }, Command::perform(update_triggers(), |result| Message::TriggersUpdated(result.unwrap()))) } pub fn update(&mut self, message: Message, _clipboard: &mut Clipboard) -> Command<Message> { match message { Message::TriggersUpdated(vec) => { println!("Triggers updated. len = {}", vec.len()); self.triggers = vec; } Message::PriceInputChanged(value) => { self.price_value = value; } Message::CoinPicked(picked) => { self.picked_coin = picked; } Message::CurrencyPicked(picked) => { self.picked_currency = picked; } Message::SaveTriggerClicked => { if let Ok(value) = self.price_value.parse::<f64>() { return Command::perform(add_trigger(self.picked_coin.clone(), self.picked_currency.clone(), value), |x| { x.unwrap(); Message::TriggersAdded }); } } Message::TriggersAdded => { return Command::perform(update_triggers(), |result| Message::TriggersUpdated(result.unwrap())); } Message::DeleteTriggerClicked(id) => { return Command::perform(delete_trigger(id), |result| { result.unwrap(); Message::TriggerDeleted }); } Message::TriggerDeleted => { return Command::perform(update_triggers(), |result| Message::TriggersUpdated(result.unwrap())); } } Command::none() } pub fn view(&mut self) -> iced::Element<'_, Message> { let lock = self.settings.read().unwrap(); let theme = lock.theme; let show_all_coins = lock.show_all_coins; let show_all_currencies = lock.show_all_currencies; let coins = if show_all_coins { self.coins.as_ref().clone() } else { self.coins.iter().filter(|coin| coin.favourite).cloned().collect() }; let currencies = if show_all_currencies { self.currencies.as_ref().clone() } else { self.currencies.iter().filter(|coin| coin.favourite).cloned().collect() }; self.delete_button_states = vec![Default::default(); self.triggers.len()]; let mut delete_button_states = self.delete_button_states.iter_mut().collect::<Vec<_>>(); let mut main_column = Column::new() .spacing(5) .width(Length::Fill) .height(Length::Fill); let mut trigger_settings_row = Row::new() .spacing(5) .width(Length::Shrink) .height(Length::Shrink); let mut coin_column = Column::new() .spacing(5) .width(Length::FillPortion(1)); coin_column = coin_column.push(Text::new("Coin")); let coin_picklist = PickList::new(&mut self.coin_picklist_state, coins, Some(self.picked_coin.clone()), Message::CoinPicked).width(Length::Fill).style(theme); coin_column = coin_column.push(coin_picklist); let mut vs_currency_column = Column::new() .spacing(5) .width(Length::FillPortion(1)); vs_currency_column = vs_currency_column.push(Text::new("Currency")); let vs_currency_picklist = PickList::new(&mut self.currency_picklist_state, currencies, Some(self.picked_currency.clone()), Message::CurrencyPicked).width(Length::Fill).style(theme); vs_currency_column = vs_currency_column.push(vs_currency_picklist); let mut price_input_column = Column::new() .spacing(5) .width(Length::FillPortion(1)); price_input_column = price_input_column.push(Text::new("Enter a value")); let text_input_price = TextInput::new(&mut self.price_input_state,"200",&mut self.price_value ,Message::PriceInputChanged).width(Length::Fill).padding(5).style(theme); price_input_column = price_input_column.push(text_input_price); trigger_settings_row = trigger_settings_row.push(coin_column); trigger_settings_row = trigger_settings_row.push(vs_currency_column); trigger_settings_row = trigger_settings_row.push(price_input_column); trigger_settings_row = trigger_settings_row.push(Button::new(&mut self.save_trigger_state, Text::new("Save").horizontal_alignment(HorizontalAlignment::Center)).on_press(Message::SaveTriggerClicked).width(Length::Fill).padding(17).style(theme)); main_column = main_column.push(trigger_settings_row); let mut scrollable = Scrollable::new(&mut self.scrollable_state) .width(Length::Fill) .height(Length::Fill); for trigger in self.triggers.iter() { let coin = self.coins.iter().find(|coin| coin.rowid == trigger.coin_id).cloned().unwrap(); let currency = self.currencies.iter().find(|currency| currency.rowid == trigger.currency_id).cloned().unwrap(); let initial_price = trigger.initial_price; let target_price = trigger.target_price; let mut trigger_row = Row::new().padding(5).spacing(5).width(Length::Fill); trigger_row = trigger_row.push(Button::new(delete_button_states.pop().unwrap(), Text::new("delete")).on_press(Message::DeleteTriggerClicked(trigger.rowid)).style(theme)); trigger_row = trigger_row.push(Text::new(format!("Trigger #{}: coin: {}, currency: {} from {} to {}", trigger.rowid, coin.raw.id, currency.raw.name, initial_price, target_price))); scrollable = scrollable.push(trigger_row); } main_column = main_column.push(scrollable); main_column.into() } } pub async fn update_triggers() -> Result<Vec<coingecko_requests::data::Trigger>, Box<dyn std::error::Error>> { let api_client = coingecko_requests::api_client::Client::new(); let client = coingecko_requests::caching_client::Client::new(api_client).await?; Ok(client.get_all_triggers().await?) } pub async fn add_trigger(coin: Coin, currency: VsCurrency, value: f64) -> Result<(), Box<dyn std::error::Error>> { let api_client = coingecko_requests::api_client::Client::new(); let client = coingecko_requests::caching_client::Client::new(api_client).await?; let data = client.price(&[coin.raw.id.as_str()], &[currency.raw.name.as_str()]).await?; client.add_trigger(coin.rowid, currency.rowid, data[&coin.raw.id][&currency.raw.name], value).await?; Ok(()) } pub async fn delete_trigger(trigger_id: i64) -> Result<(), Box<dyn std::error::Error>> { let api_client = coingecko_requests::api_client::Client::new(); let client = coingecko_requests::caching_client::Client::new(api_client).await?; client.delete_trigger(trigger_id).await?; Ok(()) }
pub mod recursive; pub mod tagsfile; use std::path::PathBuf; use anyhow::Result; use itertools::Itertools; use structopt::StructOpt; use crate::app::Params; use crate::paths::AbsPathBuf; const EXCLUDE: &str = ".git,*.json,node_modules,target,_build"; /// Generate ctags recursively given the directory. #[derive(StructOpt, Debug, Clone)] pub(self) struct SharedParams { /// The directory for executing the ctags command. #[structopt(long, parse(from_os_str))] dir: Option<PathBuf>, /// Specify the language. #[structopt(long)] languages: Option<String>, /// Exclude files and directories matching 'pattern'. /// /// Will be translated into ctags' option: --exclude=pattern. #[structopt( long, default_value = EXCLUDE, use_delimiter = true )] exclude: Vec<String>, /// Specify the input files. // - notify the tags update on demand. #[structopt(long)] files: Vec<AbsPathBuf>, } impl SharedParams { pub fn exclude_opt(&self) -> String { self.exclude .iter() .map(|x| format!("--exclude={}", x)) .join(" ") } pub fn dir(&self) -> Result<PathBuf> { let dir = match self.dir { Some(ref d) => d.clone(), None => std::env::current_dir()?, }; Ok(dir) } } /// Ctags command. #[derive(StructOpt, Debug, Clone)] pub enum Ctags { RecursiveTags(recursive::RecursiveTags), TagsFile(tagsfile::TagsFile), } impl Ctags { pub fn run(&self, params: Params) -> Result<()> { match self { Self::RecursiveTags(recursive_tags) => recursive_tags.run(params), Self::TagsFile(tags_file) => tags_file.run(params), } } }
pub struct PascalsTriangle { num_rows: u32 } impl PascalsTriangle { pub fn new(row_count: u32) -> Self { PascalsTriangle{ num_rows: row_count } } pub fn rows(&self) -> Vec<Vec<u32>> { (0..self.num_rows).map( |n| (0..n + 1).map( |k| combination(n, k) ).collect() ).collect() } } fn factorial(num: u32) -> u32 { (1..num+1).product() } fn combination(n: u32, k: u32) -> u32 { factorial(n) / (factorial(k) * factorial(n-k)) }
use std::rc::Rc; // shared pointer use std::cell::RefCell; // mutability type NodePtr<T> = Rc<RefCell<Node<T>>>; struct Node<T> { value: T, prev: Option<NodePtr<T>>, next: Option<NodePtr<T>> } pub struct DoublyLinkedList<T> { first: Option<NodePtr<T>>, last: Option<NodePtr<T>>, curr_iter: Option<NodePtr<T>> } impl<T> Node<T> { pub fn new_ptr(new_value: T) -> NodePtr<T> { return Rc::new(RefCell::new(Node { value: new_value, prev: None, next: None, })) } pub fn set_next(&mut self, last: Option<NodePtr<T>>) { self.next = last; } pub fn set_prev(&mut self, prev: Option<NodePtr<T>>) { self.prev = prev; } pub fn get_next(&self) -> Option<NodePtr<T>> { if let Some(next_node) = &self.next { return Some(next_node.clone()) } None } } impl<T> DoublyLinkedList<T> where T: Copy, T: PartialEq { pub fn new() -> DoublyLinkedList<T>{ return DoublyLinkedList { first: None, last: None, curr_iter: None } } pub fn insert(&mut self, new_value: T) { if let Some(prev_last_ptr) = &self.last { let new_last_ptr = Node::new_ptr(new_value); prev_last_ptr.borrow_mut().set_next(Some(new_last_ptr.clone())); new_last_ptr.borrow_mut().set_prev(Some(prev_last_ptr.clone())); self.last = Some(new_last_ptr); return; } let node_ptr = Node::new_ptr(new_value); self.first = Some(node_ptr.clone()); self.last = Some(node_ptr.clone()); self.curr_iter = Some(node_ptr.clone()); } fn find(&self, value: T) -> Option<NodePtr<T>>{ let mut next_node_option = None; if let Some(first_node) = &self.first { next_node_option = Some(first_node.clone()); } while let Some(next_node) = next_node_option { if next_node.borrow().value == value { return Some(next_node.clone()) } next_node_option = next_node.borrow().get_next(); } None } pub fn contains(&self, value: T) -> bool { match self.find(value) { Some(_) => true, None => false, } } } impl<T> Iterator for DoublyLinkedList<T> where T: Copy { type Item = T; fn next(&mut self) -> Option<T> { if let Some(curr_iter_ptr) = self.curr_iter.clone() { match &curr_iter_ptr.borrow().next { Some(next_iter_ptr) => { self.curr_iter = Some(next_iter_ptr.clone()); return Some(curr_iter_ptr.borrow().value); } None => { self.curr_iter = None; return Some(curr_iter_ptr.borrow().value); } } } return None; } } #[test] fn insert_test() { let mut list: DoublyLinkedList<i8> = DoublyLinkedList::new(); let vector_from_range: Vec<i8> = (1..20).collect(); let mut vector_from_list: Vec<i8> = Vec::new(); for i in 1..20 { list.insert(i) } for j in list { vector_from_list.push(j) } assert_eq!(vector_from_range, vector_from_range) } #[test] fn contains_test() { let mut list: DoublyLinkedList<i8> = DoublyLinkedList::new(); for i in 1..20 { list.insert(i) } assert_eq!(list.contains(3), true); assert_eq!(list.contains(19), true); assert_ne!(list.contains(20), true); assert_eq!(list.contains(21), false); } fn main () { }
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! MultiAddress type that is union of index and id for an account. use sp_runtime::traits::Member; use codec::{Encode, Decode}; use sp_runtime::RuntimeDebug; use core::fmt; use sp_std::vec::Vec; /// A multi-format address wrapper for on-chain accounts. #[derive(Encode, Decode, PartialEq, Eq, Clone, sp_runtime::RuntimeDebug)] #[cfg_attr(feature = "std", derive(Hash))] pub enum MultiAddress<AccountId, AccountIndex> { /// It's an account ID (pubkey). Id(AccountId), /// It's an account index. Index(#[codec(compact)] AccountIndex), /// It's some arbitrary raw bytes. Raw(Vec<u8>), /// It's a 32 byte representation. / this is friendly name Address32([u8; 32]), /// Its a 20 byte representation. / this is another friendly name Address20([u8; 20]), } #[cfg(feature = "std")] impl<AccountId, AccountIndex> fmt::Display for MultiAddress<AccountId, AccountIndex> where AccountId: fmt::Debug, AccountIndex: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } impl<AccountId, AccountIndex> From<AccountId> for MultiAddress<AccountId, AccountIndex> { fn from(a: AccountId) -> Self { MultiAddress::Id(a) } } impl<AccountId: Default, AccountIndex> Default for MultiAddress<AccountId, AccountIndex> { fn default() -> Self { MultiAddress::Id(Default::default()) } }
// i8 i16 i32 i64 isize // u8 u16 u32 u64 usize // bool // str --- more later #[derive(Debug, PartialEq, Clone)] pub struct Point { x: i32, y: i32, } #[derive(Debug, PartialEq)] pub struct Ship { location: Point, status: ShipStatus, } #[derive(Debug, PartialEq)] pub enum ShipStatus { Engaged, Waiting, Firing(Point), Heading(Point), } #[derive(Debug, PartialEq)] pub enum Action { Shot { from: Point, at: Point }, Move { from: Point, to: Point }, } impl Point { pub fn new(x: i32, y: i32) -> Self { Point { x, y } } pub fn transpose(&mut self, p: &Point) { self.x += p.x; self.y += p.y; } } impl Ship { pub fn attack(&mut self, p: Point) { self.status = ShipStatus::Firing(p) } pub fn time_step(&mut self, v: &mut Vec<Action>) { use std::cmp::Ordering::*; //an enum match &self.status { ShipStatus::Heading(p) => { let nx = match p.x.cmp(&self.location.x) { Greater => self.location.x + 1, Less => self.location.x - 1, Equal => self.location.x, }; let ny = match p.y.cmp(&self.location.y) { Greater => self.location.y + 1, Less => self.location.y - 1, Equal => self.location.y, }; v.push(Action::Move { from: self.location.clone(), to: Point::new(nx, ny), }); } ShipStatus::Firing(p) => v.push(Action::Shot { from: self.location.clone(), at: p.clone(), }), _ => {} } } } fn main() { let mut ship = Ship { location: Point { x: 10, y: 10 }, status: ShipStatus::Waiting, }; ship.location.x += 10; println!("ship location = ({},{})", ship.location.x, ship.location.y); println!("ship = {:?}", ship); let mut a = Point::new(10, 4); let b = Point::new(20, -4); //a becomes self a.transpose(&b); // panics if not equal and ends the program immediately assert_eq!(a, Point::new(30, 0)); ship.attack(b); println!("Attacking Ship = {:?}", ship); let mut actions: Vec<Action> = Vec::new(); ship.time_step(&mut actions); println!("actions = {:?}", actions); if let ShipStatus::Firing(p) = ship.status { println!("the ship will fire at {:?}", p); } }
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CFGG { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `GPIO49INTD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GPIO49INTDR { #[doc = "FNCSEL = 0x1 - nCE polarity active low value."] NCELOW, #[doc = "FNCSEL = 0x1 - nCE polarity active high value."] NCEHIGH, } impl GPIO49INTDR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { GPIO49INTDR::NCELOW => false, GPIO49INTDR::NCEHIGH => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> GPIO49INTDR { match value { false => GPIO49INTDR::NCELOW, true => GPIO49INTDR::NCEHIGH, } } #[doc = "Checks if the value of the field is `NCELOW`"] #[inline] pub fn is_n_celow(&self) -> bool { *self == GPIO49INTDR::NCELOW } #[doc = "Checks if the value of the field is `NCEHIGH`"] #[inline] pub fn is_n_cehigh(&self) -> bool { *self == GPIO49INTDR::NCEHIGH } } #[doc = "Possible values of the field `GPIO49OUTCFG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GPIO49OUTCFGR { #[doc = "FNCSEL = 0x3 - Output disabled value."] DIS, #[doc = "FNCSEL = 0x3 - Output is push-pull value."] PUSHPULL, #[doc = "FNCSEL = 0x3 - Output is open drain value."] OD, #[doc = "FNCSEL = 0x3 - Output is tri-state value."] TS, } impl GPIO49OUTCFGR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { GPIO49OUTCFGR::DIS => 0, GPIO49OUTCFGR::PUSHPULL => 1, GPIO49OUTCFGR::OD => 2, GPIO49OUTCFGR::TS => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> GPIO49OUTCFGR { match value { 0 => GPIO49OUTCFGR::DIS, 1 => GPIO49OUTCFGR::PUSHPULL, 2 => GPIO49OUTCFGR::OD, 3 => GPIO49OUTCFGR::TS, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == GPIO49OUTCFGR::DIS } #[doc = "Checks if the value of the field is `PUSHPULL`"] #[inline] pub fn is_pushpull(&self) -> bool { *self == GPIO49OUTCFGR::PUSHPULL } #[doc = "Checks if the value of the field is `OD`"] #[inline] pub fn is_od(&self) -> bool { *self == GPIO49OUTCFGR::OD } #[doc = "Checks if the value of the field is `TS`"] #[inline] pub fn is_ts(&self) -> bool { *self == GPIO49OUTCFGR::TS } } #[doc = "Possible values of the field `GPIO49INCFG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GPIO49INCFGR { #[doc = "Read the GPIO pin data value."] READ, #[doc = "INTD = 0 - Readback will always be zero value."] RDZERO, } impl GPIO49INCFGR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { GPIO49INCFGR::READ => false, GPIO49INCFGR::RDZERO => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> GPIO49INCFGR { match value { false => GPIO49INCFGR::READ, true => GPIO49INCFGR::RDZERO, } } #[doc = "Checks if the value of the field is `READ`"] #[inline] pub fn is_read(&self) -> bool { *self == GPIO49INCFGR::READ } #[doc = "Checks if the value of the field is `RDZERO`"] #[inline] pub fn is_rdzero(&self) -> bool { *self == GPIO49INCFGR::RDZERO } } #[doc = "Possible values of the field `GPIO48INTD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GPIO48INTDR { #[doc = "FNCSEL = 0x1 - nCE polarity active low value."] NCELOW, #[doc = "FNCSEL = 0x1 - nCE polarity active high value."] NCEHIGH, } impl GPIO48INTDR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { GPIO48INTDR::NCELOW => false, GPIO48INTDR::NCEHIGH => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> GPIO48INTDR { match value { false => GPIO48INTDR::NCELOW, true => GPIO48INTDR::NCEHIGH, } } #[doc = "Checks if the value of the field is `NCELOW`"] #[inline] pub fn is_n_celow(&self) -> bool { *self == GPIO48INTDR::NCELOW } #[doc = "Checks if the value of the field is `NCEHIGH`"] #[inline] pub fn is_n_cehigh(&self) -> bool { *self == GPIO48INTDR::NCEHIGH } } #[doc = "Possible values of the field `GPIO48OUTCFG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GPIO48OUTCFGR { #[doc = "FNCSEL = 0x3 - Output disabled value."] DIS, #[doc = "FNCSEL = 0x3 - Output is push-pull value."] PUSHPULL, #[doc = "FNCSEL = 0x3 - Output is open drain value."] OD, #[doc = "FNCSEL = 0x3 - Output is tri-state value."] TS, } impl GPIO48OUTCFGR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { GPIO48OUTCFGR::DIS => 0, GPIO48OUTCFGR::PUSHPULL => 1, GPIO48OUTCFGR::OD => 2, GPIO48OUTCFGR::TS => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> GPIO48OUTCFGR { match value { 0 => GPIO48OUTCFGR::DIS, 1 => GPIO48OUTCFGR::PUSHPULL, 2 => GPIO48OUTCFGR::OD, 3 => GPIO48OUTCFGR::TS, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == GPIO48OUTCFGR::DIS } #[doc = "Checks if the value of the field is `PUSHPULL`"] #[inline] pub fn is_pushpull(&self) -> bool { *self == GPIO48OUTCFGR::PUSHPULL } #[doc = "Checks if the value of the field is `OD`"] #[inline] pub fn is_od(&self) -> bool { *self == GPIO48OUTCFGR::OD } #[doc = "Checks if the value of the field is `TS`"] #[inline] pub fn is_ts(&self) -> bool { *self == GPIO48OUTCFGR::TS } } #[doc = "Possible values of the field `GPIO48INCFG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GPIO48INCFGR { #[doc = "Read the GPIO pin data value."] READ, #[doc = "INTD = 0 - Readback will always be zero value."] RDZERO, } impl GPIO48INCFGR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { GPIO48INCFGR::READ => false, GPIO48INCFGR::RDZERO => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> GPIO48INCFGR { match value { false => GPIO48INCFGR::READ, true => GPIO48INCFGR::RDZERO, } } #[doc = "Checks if the value of the field is `READ`"] #[inline] pub fn is_read(&self) -> bool { *self == GPIO48INCFGR::READ } #[doc = "Checks if the value of the field is `RDZERO`"] #[inline] pub fn is_rdzero(&self) -> bool { *self == GPIO48INCFGR::RDZERO } } #[doc = "Values that can be written to the field `GPIO49INTD`"] pub enum GPIO49INTDW { #[doc = "FNCSEL = 0x1 - nCE polarity active low value."] NCELOW, #[doc = "FNCSEL = 0x1 - nCE polarity active high value."] NCEHIGH, } impl GPIO49INTDW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { GPIO49INTDW::NCELOW => false, GPIO49INTDW::NCEHIGH => true, } } } #[doc = r" Proxy"] pub struct _GPIO49INTDW<'a> { w: &'a mut W, } impl<'a> _GPIO49INTDW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: GPIO49INTDW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "FNCSEL = 0x1 - nCE polarity active low value."] #[inline] pub fn n_celow(self) -> &'a mut W { self.variant(GPIO49INTDW::NCELOW) } #[doc = "FNCSEL = 0x1 - nCE polarity active high value."] #[inline] pub fn n_cehigh(self) -> &'a mut W { self.variant(GPIO49INTDW::NCEHIGH) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `GPIO49OUTCFG`"] pub enum GPIO49OUTCFGW { #[doc = "FNCSEL = 0x3 - Output disabled value."] DIS, #[doc = "FNCSEL = 0x3 - Output is push-pull value."] PUSHPULL, #[doc = "FNCSEL = 0x3 - Output is open drain value."] OD, #[doc = "FNCSEL = 0x3 - Output is tri-state value."] TS, } impl GPIO49OUTCFGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { GPIO49OUTCFGW::DIS => 0, GPIO49OUTCFGW::PUSHPULL => 1, GPIO49OUTCFGW::OD => 2, GPIO49OUTCFGW::TS => 3, } } } #[doc = r" Proxy"] pub struct _GPIO49OUTCFGW<'a> { w: &'a mut W, } impl<'a> _GPIO49OUTCFGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: GPIO49OUTCFGW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "FNCSEL = 0x3 - Output disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(GPIO49OUTCFGW::DIS) } #[doc = "FNCSEL = 0x3 - Output is push-pull value."] #[inline] pub fn pushpull(self) -> &'a mut W { self.variant(GPIO49OUTCFGW::PUSHPULL) } #[doc = "FNCSEL = 0x3 - Output is open drain value."] #[inline] pub fn od(self) -> &'a mut W { self.variant(GPIO49OUTCFGW::OD) } #[doc = "FNCSEL = 0x3 - Output is tri-state value."] #[inline] pub fn ts(self) -> &'a mut W { self.variant(GPIO49OUTCFGW::TS) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `GPIO49INCFG`"] pub enum GPIO49INCFGW { #[doc = "Read the GPIO pin data value."] READ, #[doc = "INTD = 0 - Readback will always be zero value."] RDZERO, } impl GPIO49INCFGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { GPIO49INCFGW::READ => false, GPIO49INCFGW::RDZERO => true, } } } #[doc = r" Proxy"] pub struct _GPIO49INCFGW<'a> { w: &'a mut W, } impl<'a> _GPIO49INCFGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: GPIO49INCFGW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Read the GPIO pin data value."] #[inline] pub fn read(self) -> &'a mut W { self.variant(GPIO49INCFGW::READ) } #[doc = "INTD = 0 - Readback will always be zero value."] #[inline] pub fn rdzero(self) -> &'a mut W { self.variant(GPIO49INCFGW::RDZERO) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `GPIO48INTD`"] pub enum GPIO48INTDW { #[doc = "FNCSEL = 0x1 - nCE polarity active low value."] NCELOW, #[doc = "FNCSEL = 0x1 - nCE polarity active high value."] NCEHIGH, } impl GPIO48INTDW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { GPIO48INTDW::NCELOW => false, GPIO48INTDW::NCEHIGH => true, } } } #[doc = r" Proxy"] pub struct _GPIO48INTDW<'a> { w: &'a mut W, } impl<'a> _GPIO48INTDW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: GPIO48INTDW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "FNCSEL = 0x1 - nCE polarity active low value."] #[inline] pub fn n_celow(self) -> &'a mut W { self.variant(GPIO48INTDW::NCELOW) } #[doc = "FNCSEL = 0x1 - nCE polarity active high value."] #[inline] pub fn n_cehigh(self) -> &'a mut W { self.variant(GPIO48INTDW::NCEHIGH) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `GPIO48OUTCFG`"] pub enum GPIO48OUTCFGW { #[doc = "FNCSEL = 0x3 - Output disabled value."] DIS, #[doc = "FNCSEL = 0x3 - Output is push-pull value."] PUSHPULL, #[doc = "FNCSEL = 0x3 - Output is open drain value."] OD, #[doc = "FNCSEL = 0x3 - Output is tri-state value."] TS, } impl GPIO48OUTCFGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { GPIO48OUTCFGW::DIS => 0, GPIO48OUTCFGW::PUSHPULL => 1, GPIO48OUTCFGW::OD => 2, GPIO48OUTCFGW::TS => 3, } } } #[doc = r" Proxy"] pub struct _GPIO48OUTCFGW<'a> { w: &'a mut W, } impl<'a> _GPIO48OUTCFGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: GPIO48OUTCFGW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "FNCSEL = 0x3 - Output disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(GPIO48OUTCFGW::DIS) } #[doc = "FNCSEL = 0x3 - Output is push-pull value."] #[inline] pub fn pushpull(self) -> &'a mut W { self.variant(GPIO48OUTCFGW::PUSHPULL) } #[doc = "FNCSEL = 0x3 - Output is open drain value."] #[inline] pub fn od(self) -> &'a mut W { self.variant(GPIO48OUTCFGW::OD) } #[doc = "FNCSEL = 0x3 - Output is tri-state value."] #[inline] pub fn ts(self) -> &'a mut W { self.variant(GPIO48OUTCFGW::TS) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `GPIO48INCFG`"] pub enum GPIO48INCFGW { #[doc = "Read the GPIO pin data value."] READ, #[doc = "INTD = 0 - Readback will always be zero value."] RDZERO, } impl GPIO48INCFGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { GPIO48INCFGW::READ => false, GPIO48INCFGW::RDZERO => true, } } } #[doc = r" Proxy"] pub struct _GPIO48INCFGW<'a> { w: &'a mut W, } impl<'a> _GPIO48INCFGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: GPIO48INCFGW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Read the GPIO pin data value."] #[inline] pub fn read(self) -> &'a mut W { self.variant(GPIO48INCFGW::READ) } #[doc = "INTD = 0 - Readback will always be zero value."] #[inline] pub fn rdzero(self) -> &'a mut W { self.variant(GPIO48INCFGW::RDZERO) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 7 - GPIO49 interrupt direction."] #[inline] pub fn gpio49intd(&self) -> GPIO49INTDR { GPIO49INTDR::_from({ const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 5:6 - GPIO49 output configuration."] #[inline] pub fn gpio49outcfg(&self) -> GPIO49OUTCFGR { GPIO49OUTCFGR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 4 - GPIO49 input enable."] #[inline] pub fn gpio49incfg(&self) -> GPIO49INCFGR { GPIO49INCFGR::_from({ const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 3 - GPIO48 interrupt direction."] #[inline] pub fn gpio48intd(&self) -> GPIO48INTDR { GPIO48INTDR::_from({ const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 1:2 - GPIO48 output configuration."] #[inline] pub fn gpio48outcfg(&self) -> GPIO48OUTCFGR { GPIO48OUTCFGR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 0 - GPIO48 input enable."] #[inline] pub fn gpio48incfg(&self) -> GPIO48INCFGR { GPIO48INCFGR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 7 - GPIO49 interrupt direction."] #[inline] pub fn gpio49intd(&mut self) -> _GPIO49INTDW { _GPIO49INTDW { w: self } } #[doc = "Bits 5:6 - GPIO49 output configuration."] #[inline] pub fn gpio49outcfg(&mut self) -> _GPIO49OUTCFGW { _GPIO49OUTCFGW { w: self } } #[doc = "Bit 4 - GPIO49 input enable."] #[inline] pub fn gpio49incfg(&mut self) -> _GPIO49INCFGW { _GPIO49INCFGW { w: self } } #[doc = "Bit 3 - GPIO48 interrupt direction."] #[inline] pub fn gpio48intd(&mut self) -> _GPIO48INTDW { _GPIO48INTDW { w: self } } #[doc = "Bits 1:2 - GPIO48 output configuration."] #[inline] pub fn gpio48outcfg(&mut self) -> _GPIO48OUTCFGW { _GPIO48OUTCFGW { w: self } } #[doc = "Bit 0 - GPIO48 input enable."] #[inline] pub fn gpio48incfg(&mut self) -> _GPIO48INCFGW { _GPIO48INCFGW { w: self } } }
extern crate iptables; use std::panic; #[test] fn test_new() { nat(iptables::new(false).unwrap(), "NATNEW", "NATNEW2"); filter(iptables::new(false).unwrap(), "FILTERNEW"); } #[test] fn test_old() { nat( iptables::IPTables { cmd: "iptables", has_wait: false, has_check: false, is_numeric: false, }, "NATOLD", "NATOLD2", ); filter( iptables::IPTables { cmd: "iptables", has_wait: false, has_check: false, is_numeric: false, }, "FILTEROLD", ); } fn nat(ipt: iptables::IPTables, old_name: &str, new_name: &str) { assert!(ipt.new_chain("nat", old_name).is_ok()); assert!(ipt.rename_chain("nat", old_name, new_name).is_ok()); assert!(ipt.append("nat", new_name, "-j ACCEPT").is_ok()); assert!(ipt.exists("nat", new_name, "-j ACCEPT").unwrap()); assert!(ipt.delete("nat", new_name, "-j ACCEPT").is_ok()); assert!(ipt.insert("nat", new_name, "-j ACCEPT", 1).is_ok()); assert!(ipt .append( "nat", new_name, "-m comment --comment \"double-quoted comment\" -j ACCEPT" ) .is_ok(),); assert!(ipt .exists( "nat", new_name, "-m comment --comment \"double-quoted comment\" -j ACCEPT" ) .unwrap(),); assert!(ipt .append( "nat", new_name, "-m comment --comment 'single-quoted comment' -j ACCEPT" ) .is_ok(),); // The following `exists`-check has to use double-quotes, since the iptables output (if it // doesn't have the check-functionality) will use double quotes. assert!(ipt .exists( "nat", new_name, "-m comment --comment \"single-quoted comment\" -j ACCEPT" ) .unwrap(),); assert!(ipt.flush_chain("nat", new_name).is_ok()); assert!(!ipt.exists("nat", new_name, "-j ACCEPT").unwrap()); assert!(ipt .execute("nat", &format!("-A {} -j ACCEPT", new_name)) .is_ok()); assert!(ipt.exists("nat", new_name, "-j ACCEPT").unwrap()); assert!(ipt.flush_chain("nat", new_name).is_ok()); assert!(ipt.chain_exists("nat", new_name).unwrap()); assert!(ipt.delete_chain("nat", new_name).is_ok()); assert!(!ipt.chain_exists("nat", new_name).unwrap()); } fn filter(ipt: iptables::IPTables, name: &str) { assert!(ipt.new_chain("filter", name).is_ok()); assert!(ipt.insert("filter", name, "-j ACCEPT", 1).is_ok()); assert!(ipt.replace("filter", name, "-j DROP", 1).is_ok()); assert!(ipt.exists("filter", name, "-j DROP").unwrap()); assert!(!ipt.exists("filter", name, "-j ACCEPT").unwrap()); assert!(ipt.delete("filter", name, "-j DROP").is_ok()); assert_eq!(ipt.list("filter", name).unwrap().len(), 1); assert!(ipt .execute("filter", &format!("-A {} -j ACCEPT", name)) .is_ok()); assert!(ipt.exists("filter", name, "-j ACCEPT").unwrap()); assert!(ipt .append( "filter", name, "-m comment --comment \"double-quoted comment\" -j ACCEPT" ) .is_ok(),); assert!(ipt .exists( "filter", name, "-m comment --comment \"double-quoted comment\" -j ACCEPT" ) .unwrap()); assert!(ipt .append( "filter", name, "-m comment --comment 'single-quoted comment' -j ACCEPT" ) .is_ok(),); // The following `exists`-check has to use double-quotes, since the iptables output (if it // doesn't have the check-functionality) will use double quotes. assert!(ipt .exists( "filter", name, "-m comment --comment \"single-quoted comment\" -j ACCEPT" ) .unwrap(),); assert!(ipt.flush_chain("filter", name).is_ok()); assert!(ipt.chain_exists("filter", name).unwrap()); assert!(ipt.delete_chain("filter", name).is_ok()); assert!(!ipt.chain_exists("filter", name).unwrap()); } #[test] fn test_get_policy() { let ipt = iptables::new(false).unwrap(); // filter assert!(ipt.get_policy("filter", "INPUT").is_ok()); assert!(ipt.get_policy("filter", "FORWARD").is_ok()); assert!(ipt.get_policy("filter", "OUTPUT").is_ok()); // mangle assert!(ipt.get_policy("mangle", "PREROUTING").is_ok()); assert!(ipt.get_policy("mangle", "OUTPUT").is_ok()); assert!(ipt.get_policy("mangle", "INPUT").is_ok()); assert!(ipt.get_policy("mangle", "FORWARD").is_ok()); assert!(ipt.get_policy("mangle", "POSTROUTING").is_ok()); // nat assert!(ipt.get_policy("nat", "PREROUTING").is_ok()); assert!(ipt.get_policy("nat", "POSTROUTING").is_ok()); assert!(ipt.get_policy("nat", "OUTPUT").is_ok()); // raw assert!(ipt.get_policy("raw", "PREROUTING").is_ok()); assert!(ipt.get_policy("raw", "OUTPUT").is_ok()); // security assert!(ipt.get_policy("security", "INPUT").is_ok()); assert!(ipt.get_policy("security", "OUTPUT").is_ok()); assert!(ipt.get_policy("security", "FORWARD").is_ok()); // Wrong table assert!(ipt.get_policy("not_existant", "_").is_err()); // Wrong chain assert!(ipt.get_policy("filter", "_").is_err()); } #[test] #[ignore] fn test_set_policy() { let ipt = iptables::new(false).unwrap(); // Since we can only set policies on built-in chains, we have to retain the policy of the chain // before setting it, to restore it to its original state. let current_policy = ipt.get_policy("mangle", "FORWARD").unwrap(); // If the following assertions fail or any other panic occurs, we still have to ensure not to // change the policy for the user. let result = panic::catch_unwind(|| { assert!(ipt.set_policy("mangle", "FORWARD", "DROP").is_ok()); assert_eq!(ipt.get_policy("mangle", "FORWARD").unwrap(), "DROP"); }); // Reset the policy to the retained value ipt.set_policy("mangle", "FORWARD", &current_policy) .unwrap(); // "Rethrow" a potential caught panic assert!(result.is_ok()); }
use aoc2019::intcode::IntCodeCpu; use std::fs; use std::io; fn main() -> io::Result<()> { let code = fs::read_to_string("./input/day09.in")?; let mut cpu = IntCodeCpu::from_code(&code); cpu.input.push_back(1); cpu.run(); println!("p1: {}", cpu.output.pop_back().unwrap()); cpu = IntCodeCpu::from_code(&code); cpu.input.push_back(2); cpu.run(); println!("p2: {}", cpu.output.pop_back().unwrap()); Ok(()) }
use crate::prelude::*; use poly::*; /// Constant-time extended euclidean algorithm to compute the inverse of x in yℤ\[x\] /// x.len() and degree of y are assumed to be public /// See recipx in Figure 6.1 of https://eprint.iacr.org/2019/266 #[inline] #[cfg_attr(feature = "use_attributes", unsafe_hacspec)] pub(crate) fn extended_euclid_internal<T: Integer + Copy>( x: &[T], y: &[T], n: T, ) -> Result<Vec<T>, &'static str> { let (yd, _) = leading_coefficient(y); let (xd, _) = leading_coefficient(x); debug_assert!(yd >= xd); debug_assert!(yd > 0); let mut f = make_fixed_length(y, yd + 1); f.reverse(); let mut g = make_fixed_length(x, yd); g.reverse(); let (delta, f, _g, v) = divstepsx(2 * yd - 1, 2 * yd - 1, &f, &g, n); if delta != 0 { return Err("Could not invert the polynomial"); } let t = monomial(f[0].inv(n), 2 * yd - 2 - v.1); let mut rr = poly_mul(&t, &v.0, n); rr = make_fixed_length(&rr, yd); rr.reverse(); Ok(rr) } /// Iterate division steps in the constant-time polynomial inversion algorithm /// See Figure 5.1 from https://eprint.iacr.org/2019/266 /// Instead of returning M2kx((u,v,q,r)) in last component, only return v fn divstepsx<T: Integer + Copy>( nn: usize, t: usize, fin: &[T], gin: &[T], n: T, ) -> (i128, Vec<T>, Vec<T>, (Vec<T>, usize)) { debug_assert!(t >= nn); let mut f = fin.to_vec(); let mut g = gin.to_vec(); let mut delta = 1; // Each of u,v,q,r in (f, i) represents quotient f/x^i // u,v,q,r = 1,0,0,1 let mut u = (vec![T::ONE(); 1], 0); let mut v = (vec![T::ZERO(); 1], 0); let mut q = (vec![T::ZERO(); 1], 0); let mut r = (vec![T::ONE(); 1], 0); for i in 0..nn { // Bring u,v,q,r back to fixed precision t u.0 = make_fixed_length(&u.0, t); v.0 = make_fixed_length(&v.0, t); q.0 = make_fixed_length(&q.0, t); r.0 = make_fixed_length(&r.0, t); // Decrease precision of f and g in each iteration f = make_fixed_length(&f, nn - i); g = make_fixed_length(&g, nn - i); // TODO: make swap constant time if delta > 0 && !g[0].equal(T::ZERO()) { delta = -delta; core::mem::swap(&mut f, &mut g); core::mem::swap(&mut q, &mut u); core::mem::swap(&mut r, &mut v); } delta = delta + 1; let f0 = monomial(f[0], 0); let g0 = monomial(g[0], 0); // g = (f0*g-g0*f)/x let t0 = poly_mul(&f0, &g, n); let t1 = poly_mul(&g0, &f, n); g = poly_sub(&t0, &t1, n); g = poly_divx(&g); // q = (f0*q-g0*u)/x let t0 = poly_mul(&f0, &q.0, n); let t1 = poly_mul(&g0, &u.0, n); q = quot_sub(&t0, q.1, &t1, u.1, n); q.1 += 1; // r = (f0*r-g0*v)/x let t0 = poly_mul(&f0, &r.0, n); let t1 = poly_mul(&g0, &v.0, n); r = quot_sub(&t0, r.1, &t1, v.1, n); r.1 += 1; } (delta, f, g, v) } /// Divide a by x assuming a is a multiple of x (shift right by one) fn poly_divx<T: Numeric + Copy>(v: &[T]) -> Vec<T> { let mut out = vec![T::default(); v.len() - 1]; for (a, &b) in out.iter_mut().zip(v.iter().skip(1)) { *a = b; } out } /// Subtract quotient (bn/x^bd) from (an/x^ad) fn quot_sub<T: Integer + Copy>(an: &[T], ad: usize, bn: &[T], bd: usize, n: T) -> (Vec<T>, usize) { let cd = core::cmp::max(ad, bd); let x = monomial(T::ONE(), 1); let mut a = an.to_vec(); let mut b = bn.to_vec(); for _ in 0..cd - ad { //XXX: Any way to write this more nicely? a = poly_mul(&a, &x, n); } for _ in 0..cd - bd { //XXX: Any way to write this more nicely? b = poly_mul(&b, &x, n); } (poly_sub(&a, &b, n), cd) }
#[doc = "Register `HWCFGR1` reader"] pub type R = crate::R<HWCFGR1_SPEC>; #[doc = "Field `NUM_DMA_STREAMS` reader - number of DMA request line multiplexer (output) channels"] pub type NUM_DMA_STREAMS_R = crate::FieldReader; #[doc = "Field `NUM_DMA_PERIPH_REQ` reader - number of DMA request lines from peripherals"] pub type NUM_DMA_PERIPH_REQ_R = crate::FieldReader; #[doc = "Field `NUM_DMA_TRIG` reader - number of synchronization inputs"] pub type NUM_DMA_TRIG_R = crate::FieldReader; #[doc = "Field `NUM_DMA_REQGEN` reader - number of DMA request generator channels"] pub type NUM_DMA_REQGEN_R = crate::FieldReader; impl R { #[doc = "Bits 0:7 - number of DMA request line multiplexer (output) channels"] #[inline(always)] pub fn num_dma_streams(&self) -> NUM_DMA_STREAMS_R { NUM_DMA_STREAMS_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - number of DMA request lines from peripherals"] #[inline(always)] pub fn num_dma_periph_req(&self) -> NUM_DMA_PERIPH_REQ_R { NUM_DMA_PERIPH_REQ_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:23 - number of synchronization inputs"] #[inline(always)] pub fn num_dma_trig(&self) -> NUM_DMA_TRIG_R { NUM_DMA_TRIG_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 24:31 - number of DMA request generator channels"] #[inline(always)] pub fn num_dma_reqgen(&self) -> NUM_DMA_REQGEN_R { NUM_DMA_REQGEN_R::new(((self.bits >> 24) & 0xff) as u8) } } #[doc = "DMAMUX hardware configuration 1 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hwcfgr1::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct HWCFGR1_SPEC; impl crate::RegisterSpec for HWCFGR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`hwcfgr1::R`](R) reader structure"] impl crate::Readable for HWCFGR1_SPEC {} #[doc = "`reset()` method sets HWCFGR1 to value 0x0417_3907"] impl crate::Resettable for HWCFGR1_SPEC { const RESET_VALUE: Self::Ux = 0x0417_3907; }
//! [Graceful Shutdown and Cleanup] //! //! [graceful shutdown and cleanup]: https://doc.rust-lang.org/book/ch20-03-graceful-shutdown-and-cleanup.html use std::{ env, error::Error, fmt::Debug, fs, io::{self, Read, Write}, net::{TcpListener, TcpStream, ToSocketAddrs}, thread, time::Duration, }; use tracing::{error, info, instrument, warn}; use the_book::ch20::ThreadPool; static SERVER: &str = "127.0.0.1:7880"; #[instrument] fn main() -> Result<(), Box<dyn Error>> { tracing_subscriber::fmt::init(); let mut args = env::args().skip(1); let addr = args.next().unwrap_or(SERVER.to_string()); let count = args .next() .map(|num| num.parse().unwrap_or(num_cpus::get())) .unwrap_or(num_cpus::get()); let max = args .next() .map(|num| num.parse().unwrap_or(std::usize::MAX)) .unwrap_or(std::usize::MAX); server(addr, count, max) } #[instrument] fn server<A: ToSocketAddrs + Debug>( addr: A, count: usize, max: usize, ) -> Result<(), Box<dyn Error>> { let pool = ThreadPool::new(count); let server = TcpListener::bind(addr)?; info!("listen on {}", server.local_addr()?); for s in server.incoming().take(max) { match s { Err(err) => warn!("accept error: {}", err), Ok(s) => { if let Err(err) = pool.execute(|| handler(s)) { error!("pool execution error: {}", err); } } } } Ok(()) } #[instrument] fn handler(mut s: TcpStream) -> io::Result<()> { let mut buf = [0; 512]; s.read(&mut buf)?; let get = b"GET / HTTP/1.1"; let sleep = b"GET /sleep HTTP/1.1"; let (status, file) = if buf.starts_with(get) { ("200 OK", "hello.html") } else if buf.starts_with(sleep) { thread::sleep(Duration::from_secs(5)); ("200 OK", "hello.html") } else { ("404 NOT FOUND", "404.html") }; let body = fs::read_to_string(format!("examples/{}", file))?; s.write_fmt(format_args!("HTTP/1.1 {}\r\n\r\n{}", status, body))?; s.flush() }
use core::cell::UnsafeCell; use core::mem::MaybeUninit; use core::sync::atomic::{AtomicBool, Ordering}; use futures::task::AtomicWaker; pub struct Oneshot<T> { message: UnsafeCell<MaybeUninit<T>>, waker: AtomicWaker, has_message: AtomicBool, } pub struct Sender<'a, T>(&'a Oneshot<T>); pub struct Receiver<'a, T>(&'a Oneshot<T>); impl<T> Oneshot<T> { pub const fn new() -> Self { Self { message: UnsafeCell::new(MaybeUninit::uninit()), waker: AtomicWaker::new(), has_message: AtomicBool::new(false), } } /// NOTE(unsafe): This function must not be used when the oneshot might /// contain a message or a `Sender` exists referencing this oneshot. This /// means it can't be used concurrently with itself or the latter to run /// will violate that constraint. pub unsafe fn put(&self, message: T) { self.message.get().write(MaybeUninit::new(message)); self.has_message.store(true, Ordering::Release); self.waker.wake(); } /// NOTE(unsafe): This function must not be used concurrently with itself, /// but it can be used concurrently with put. pub unsafe fn take(&self) -> Option<T> { if self.has_message.load(Ordering::Acquire) { let message = self.message.get().read().assume_init(); self.has_message.store(false, Ordering::Release); Some(message) } else { None } } /// Split the Oneshot into a Sender and a Receiver. The Sender can send one /// message. The Receiver is a Future and can be used to await that message. /// If the Receiver is dropped before taking the message, the message is /// dropped as well. This function can be called again after the lifetimes /// of the Sender and Receiver end in order to send a new message. pub fn split<'a>(&'a mut self) -> (Sender<'a, T>, Receiver<'a, T>) { unsafe { self.take() }; (Sender(self), Receiver(self)) } /// NOTE(unsafe): There must be no more than one `Receiver` at a time. /// `take` should not be called while a `Receiver` exists. pub unsafe fn recv<'a>(&'a self) -> Receiver<'a, T> { Receiver(self) } /// NOTE(unsafe): There must be no more than one `Sender` at a time. `put` /// should not be called while a `Sender` exists. The `Oneshot` must be /// empty when the `Sender` is created. pub unsafe fn send<'a>(&'a self) -> Sender<'a, T> { Sender(self) } pub fn is_empty(&self) -> bool { !self.has_message.load(Ordering::AcqRel) } } impl<T> Drop for Oneshot<T> { fn drop(&mut self) { unsafe { self.take() }; } } impl <'a, T> Sender<'a, T>{ pub fn send(self, message: T){ unsafe {self.0.put(message)}; } } use core::future::Future; use core::pin::Pin; use core::task::{Context, Poll}; impl<'a, T> Future for Receiver<'a, T>{ type Output = T; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> { self.0.waker.register(cx.waker()); if let Some(message) = unsafe { self.0.take()}{ Poll::Ready(message) } else{ Poll::Pending } } } impl<'a, T> Drop for Receiver<'a, T>{ fn drop(&mut self){ unsafe{ self.0.take()}; } }
//! // mod admin; mod conn; mod dialer; mod listener; mod node; mod ports; mod services; // #[doc(inline)] // pub use admin::Admin; #[doc(inline)] pub use conn::Conn; #[doc(inline)] pub use dialer::Dialer; #[doc(inline)] pub use listener::Listener; #[doc(inline)] pub use node::Node; #[doc(inline)] pub use ports::*; #[doc(inline)] pub use services::*; use crate::{error::Error, Config}; use std::{fmt::Debug, sync::Arc}; use xactor::{Actor, Addr, Handler}; /// #[async_trait::async_trait] pub trait Core: Debug where Self: Actor, Self: Handler<messages::GetConfig>, { /// type Conn: Conn; /// type Dialer: Dialer<Self>; /// type Listener: Listener<Self>; /// type LinkManager: LinkManager<Self>; /// type PeerManager: PeerManager<Self>; /// type Router: Router<Self>; /// type Switch: Switch<Self>; /// async fn current_config(core: &mut Addr<Self>) -> Result<Arc<Config>, Error> { Ok(core.call(messages::GetConfig).await?) } /// async fn dialer(core: &mut Addr<Self>) -> Result<Addr<Self::Listener>, Error>; /// async fn listener(core: &mut Addr<Self>) -> Result<Addr<Self::Listener>, Error>; /// async fn peer_manager(core: &mut Addr<Self>) -> Result<Addr<Self::PeerManager>, Error>; /// async fn router(core: &mut Addr<Self>) -> Result<Addr<Self::Router>, Error>; /// async fn switch(core: &mut Addr<Self>) -> Result<Addr<Self::Switch>, Error>; } pub mod messages { use crate::Config; use std::sync::Arc; #[xactor::message(result = "Arc<Config>")] pub struct GetConfig; #[xactor::message(result = "Arc<Config>")] pub struct Reconfigure; } // #[async_trait] // pub trait NodeAPI: Node { // /// TODO // async fn get_peers(self: Arc<Self>) -> Result<(), Error>; // /// TODO // async fn get_switch_peers(self: Arc<Self>) -> Result<(), Error>; // /// TODO // async fn get_dht(self: Arc<Self>) -> Result<(), Error>; // /// TODO // async fn get_switch_queues(self: Arc<Self>) -> Result<(), Error>; // /// TODO // async fn get_sessions(self: Arc<Self>) -> Result<(), Error>; // // /// TODO // // async fn get_dialer(self: Arc<Self>) -> Result<(), Error>; // // /// TODO // // async fn get_listener(self: Arc<Self>) -> Result<(), Error>; // /// TODO // async fn get_tcp_listener(self: Arc<Self>) -> Result<(), Error>; // }
use crate::prelude::*; use crate::requests::*; use azure_core::HttpClient; use azure_storage::core::clients::StorageClient; use std::sync::Arc; pub trait AsPopReceiptClient { /// Implement this trait to convert the calling client into a /// `PopReceiptClient`. This trait is used to make sure the /// returned client is wrapped in an `Arc` to avoid /// unnecessary copying while keeping the clients /// type signature simple (without lifetimes). fn as_pop_receipt_client(&self, pop_receipt: impl Into<PopReceipt>) -> Arc<PopReceiptClient>; } impl AsPopReceiptClient for Arc<QueueClient> { /// Pass a valid `PopReceipt` to a `QueueClient` /// to obtain a `PopReceiptClient` back. The `PopReceiptClient` /// can then delete or update the message /// referenced by the passed `PopReceipt`. fn as_pop_receipt_client(&self, pop_receipt: impl Into<PopReceipt>) -> Arc<PopReceiptClient> { PopReceiptClient::new(self.clone(), pop_receipt) } } #[derive(Debug, Clone)] pub struct PopReceiptClient { queue_client: Arc<QueueClient>, pop_receipt: PopReceipt, } impl PopReceiptClient { pub(crate) fn new( queue_client: Arc<QueueClient>, pop_receipt: impl Into<PopReceipt>, ) -> Arc<Self> { Arc::new(Self { queue_client, pop_receipt: pop_receipt.into(), }) } pub(crate) fn storage_client(&self) -> &StorageClient { self.queue_client.storage_client() } pub(crate) fn http_client(&self) -> &dyn HttpClient { self.queue_client .storage_client() .storage_account_client() .http_client() } pub(crate) fn pop_receipt_url(&self) -> Result<url::Url, url::ParseError> { let mut url = self.queue_client.url_with_segments( ["messages", self.pop_receipt.message_id()] .iter() .map(std::ops::Deref::deref), )?; url.query_pairs_mut() .append_pair("popreceipt", self.pop_receipt.pop_receipt()); Ok(url) } /// Deletes the message. The message must not have been /// made visible again or this call would fail. pub fn delete(&self) -> DeleteMessageBuilder { DeleteMessageBuilder::new(self) } /// Updates the message. /// The message must not have been /// made visible again or this call would fail. pub fn update(&self, visibility_timeout: impl Into<VisibilityTimeout>) -> UpdateMessageBuilder { UpdateMessageBuilder::new(self, visibility_timeout) } }
// Copyright 2017 pdb Developers // // 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 crate::common::*; // OFFCB: #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Slice { pub offset: i32, // technically a "long", but... 32 bits for life? pub size: u32, } // HDR: // https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/tpi.h#L45 #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Header { pub version: u32, pub header_size: u32, pub minimum_index: u32, pub maximum_index: u32, pub gprec_size: u32, pub tpi_hash_stream: u16, pub tpi_hash_pad_stream: u16, pub hash_key_size: u32, pub hash_bucket_size: u32, pub hash_values: Slice, pub ti_off: Slice, pub hash_adj: Slice, // "offcb of hash head list, maps (hashval,ti), where ti is the head of the hashval chain." } impl Header { pub(crate) fn empty() -> Self { let empty_slice = Slice { offset: 0, size: 0 }; Self { version: 0, header_size: 0, minimum_index: 0, maximum_index: 0, gprec_size: 0, tpi_hash_stream: 0, tpi_hash_pad_stream: 0, hash_key_size: 0, hash_bucket_size: 0, hash_values: empty_slice, ti_off: empty_slice, hash_adj: empty_slice, } } pub(crate) fn parse(buf: &mut ParseBuffer<'_>) -> Result<Self> { debug_assert!(buf.pos() == 0); if buf.is_empty() { // Special case when the buffer is completely empty. This indicates a missing TPI or IPI // stream. In this case, `ItemInformation` acts like an empty shell that never resolves // any types. return Ok(Self::empty()); } let header = Self { version: buf.parse()?, header_size: buf.parse()?, minimum_index: buf.parse()?, maximum_index: buf.parse()?, gprec_size: buf.parse()?, tpi_hash_stream: buf.parse()?, tpi_hash_pad_stream: buf.parse()?, hash_key_size: buf.parse()?, hash_bucket_size: buf.parse()?, hash_values: Slice { offset: buf.parse()?, size: buf.parse()?, }, ti_off: Slice { offset: buf.parse()?, size: buf.parse()?, }, hash_adj: Slice { offset: buf.parse()?, size: buf.parse()?, }, }; // we read 56 bytes // make sure that's okay let bytes_read = buf.pos() as u32; if header.header_size < bytes_read { return Err(Error::InvalidTypeInformationHeader( "header size is impossibly small", )); } else if header.header_size > 1024 { return Err(Error::InvalidTypeInformationHeader( "header size is unreasonably large", )); } // consume anything else the header says belongs to the header buf.take((header.header_size - bytes_read) as usize)?; // do some final validations if header.minimum_index < 4096 { return Err(Error::InvalidTypeInformationHeader( "minimum type index is < 4096", )); } if header.maximum_index < header.minimum_index { return Err(Error::InvalidTypeInformationHeader( "maximum type index is < minimum type index", )); } // success Ok(header) } }
use common_failures::Result; use std::convert::From; use std::io::Read; pub trait TokenStream<T> { fn next(&mut self) -> Result<Option<T>>; } pub struct ByteStream<R: Read> { read: R, buffer: [u8; 1], } impl<R: Read> From<R> for ByteStream<R> { fn from(from: R) -> ByteStream<R> { ByteStream { read: from, buffer: [0], } } } impl<R: Read> TokenStream<u8> for ByteStream<R> { fn next(&mut self) -> Result<Option<u8>> { match self.read.read(&mut self.buffer)? { 0 => Ok(None), 1 => Ok(Some(self.buffer[0])), _ => Err(format_err!("")), } } } pub struct TokenBuffer<T, S: TokenStream<T>> { pub(crate) stream: S, pub(crate) buffer: Vec<T>, } impl<R: Read> From<R> for TokenBuffer<u8, ByteStream<R>> { fn from(from: R) -> TokenBuffer<u8, ByteStream<R>> { TokenBuffer { stream: ByteStream::from(from), buffer: Vec::new(), } } } impl<T, S: TokenStream<T>> TokenBuffer<T, S> { pub fn pop(&mut self) -> Result<Option<T>> { let token; if self.buffer.is_empty() { token = self.stream.next()?; } else { token = Some(self.buffer.remove(0)); } Ok(token) } pub fn push(&mut self, token: T) { self.buffer.insert(0, token); } pub fn push_tokens(&mut self, mut tokens: Vec<T>) { for i in 0..tokens.len() { self.buffer.insert(i, tokens.remove(0)); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_from() { let mut tb = TokenBuffer::from("Hello World".as_bytes()); let mut word1: Vec<u8> = Vec::new(); word1.push(tb.pop().unwrap().unwrap()); word1.push(tb.pop().unwrap().unwrap()); word1.push(tb.pop().unwrap().unwrap()); word1.push(tb.pop().unwrap().unwrap()); word1.push(tb.pop().unwrap().unwrap()); let mut blank: Vec<u8> = Vec::new(); blank.push(tb.pop().unwrap().unwrap()); let mut word2: Vec<u8> = Vec::new(); word2.push(tb.pop().unwrap().unwrap()); word2.push(tb.pop().unwrap().unwrap()); word2.push(tb.pop().unwrap().unwrap()); word2.push(tb.pop().unwrap().unwrap()); word2.push(tb.pop().unwrap().unwrap()); assert_eq!(None, tb.pop().unwrap()); tb.push_tokens(word2); tb.push_tokens(blank); tb.push_tokens(word1); let foo = tb.buffer; println!("{:?}", foo) } }
use std::fmt::{Display, Result, Formatter}; #[derive(Debug, Clone)] pub struct Position { line: usize, pub col: usize, file: String } impl Position { pub fn new(file: String) -> Position { Position { line: 1, col: 1, file: file } } pub fn next_line(&mut self) { self.line += 1; self.col = 1; } } impl Display for Position { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "\"{}\":{}:{}", self.file, self.line, self.col) } }
use std::fmt; use castnow::KeyCommand; #[derive(Debug, Clone, Copy)] pub enum State { Initial, Loading, Loaded, Playing, Stopping, Stopped, Pausing, Paused, Error } impl State { pub fn next(current: &State, success: bool) -> State { if !success { return State::Error; } let new_state = match *current { State::Loading => State::Loaded, State::Stopping => State::Stopped, State::Pausing => State::Paused, _ => { println!("Unexpected state transition {:?}", *current); State::Error } }; println!("{:?} -> {:?}", current, new_state); new_state } } impl fmt::Display for State { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) } }
use std::default::Default; use test::{Bencher, black_box}; use super::utils::Countable; use StdQueue = std::collections::PriorityQueue; // Gotta make our own trait since libcollections doesn't yet! pub trait PriorityQueue <T> : Mutable { fn push (&mut self, val: T); fn pop (&mut self) -> Option<T>; fn peek <'a> (&'a self) -> Option<&'a T>; } // Impl it for std, because we're nice like that mod hack { use std::collections::PriorityQueue; #[inline] pub fn push <T:Ord> (queue: &mut PriorityQueue<T>, val: T) { queue.push(val); } #[inline] pub fn pop <T:Ord> (queue: &mut PriorityQueue<T>) -> Option<T> { queue.pop() } } impl <T: Ord> PriorityQueue <T> for StdQueue <T> { #[inline] fn push (&mut self, val: T) { hack::push(self, val); } #[inline] fn pop (&mut self) -> Option<T> { hack::pop(self) } #[inline] fn peek <'a> (&'a self) -> Option<&'a T> { self.top() } } // Testing pub fn test_push <Q: PriorityQueue<uint> + Default + Collection> () { let mut queue: Q = Default::default(); queue.push(1); assert_eq!(queue.len(), 1); queue.push(2); assert_eq!(queue.len(), 2); } pub fn test_pop <Q: PriorityQueue<uint> + Default + Collection> () { let mut queue: Q = Default::default(); queue.push(3); queue.push(2); queue.push(4); assert_eq!(queue.pop(), Some(2)); assert_eq!(queue.len(), 2); assert_eq!(queue.pop(), Some(3)); assert_eq!(queue.len(), 1); assert_eq!(queue.pop(), Some(4)); assert_eq!(queue.len(), 0); //empty pop assert_eq!(queue.pop(), None); assert_eq!(queue.len(), 0); } pub fn test_peek <Q: PriorityQueue<uint> + Default + Collection> () { let mut queue: Q = Default::default(); assert_eq!(queue.peek(), None); queue.push(3); queue.push(2); queue.push(4); assert_eq!(queue.peek(), Some(&2)); } // Benching // iteratively inserts all elements, and then iteratively pops them all off pub fn bench_fill_and_drain <Q: PriorityQueue<N> + Default, N:Countable, I:Iterator<N> + Clone> (seq: I, bencher: &mut Bencher) { bencher.iter(||{ let mut queue:Q = Default::default(); for item in seq.clone() { queue.push(item); } while !queue.is_empty() { black_box(queue.pop()); } }); } // iteratively inserts all elements, and then pops one value off pub fn bench_fill_and_pop <Q: PriorityQueue<N> + Default, N:Countable, I:Iterator<N> + Clone> (seq: I, bencher: &mut Bencher) { bencher.iter(||{ let mut queue:Q = Default::default(); for item in seq.clone() { queue.push(item); } black_box(queue.pop()); }); } // alternates between pushing 2 elements, and poppping 1 pub fn bench_mixed_access <Q: PriorityQueue<N> + Default, N:Countable, I:Iterator<N> + Clone> (seq: I, bencher: &mut Bencher) { bencher.iter(||{ let mut queue:Q = Default::default(); let mut count = 0u; for item in seq.clone() { count += 1; if count > 2 { count = 0; black_box(queue.pop()); } else { queue.push(item); } } }); } #[macro_export] macro_rules! bench_priorityqueue( ($queue_type:ty) => ( type ToTest = $queue_type; #[bench] fn from_iter_ord_small (bencher: &mut Bencher) { collection::bench_from_iter::<ToTest, _, _>(utils::ordered_sequence::<uint>(2), bencher); } #[bench] fn from_iter_ord_big (bencher: &mut Bencher) { collection::bench_from_iter::<ToTest, _, _>(utils::ordered_sequence::<uint>(4), bencher); } #[bench] fn from_iter_unord_small (bencher: &mut Bencher) { collection::bench_from_iter::<ToTest, _, _>(utils::unordered_sequence::<uint>(2), bencher); } #[bench] fn from_iter_unord_big (bencher: &mut Bencher) { collection::bench_from_iter::<ToTest, _, _>(utils::unordered_sequence::<uint>(4), bencher); } #[bench] fn fill_and_pop_ord_small (bencher: &mut Bencher) { priorityqueue::bench_fill_and_pop::<ToTest, _, _>(utils::ordered_sequence::<uint>(2), bencher); } #[bench] fn fill_and_pop_ord_big (bencher: &mut Bencher) { priorityqueue::bench_fill_and_pop::<ToTest, _, _>(utils::ordered_sequence::<uint>(4), bencher); } #[bench] fn fill_and_pop_unord_small (bencher: &mut Bencher) { priorityqueue::bench_fill_and_pop::<ToTest, _, _>(utils::unordered_sequence::<uint>(2), bencher); } #[bench] fn fill_and_pop_unord_big (bencher: &mut Bencher) { priorityqueue::bench_fill_and_pop::<ToTest, _, _>(utils::unordered_sequence::<uint>(4), bencher); } #[bench] fn fill_and_drain_ord_small (bencher: &mut Bencher) { priorityqueue::bench_fill_and_drain::<ToTest, _, _>(utils::ordered_sequence::<uint>(2), bencher); } #[bench] fn fill_and_drain_ord_big (bencher: &mut Bencher) { priorityqueue::bench_fill_and_drain::<ToTest, _, _>(utils::ordered_sequence::<uint>(4), bencher); } #[bench] fn fill_and_drain_unord_small (bencher: &mut Bencher) { priorityqueue::bench_fill_and_drain::<ToTest, _, _>(utils::unordered_sequence::<uint>(2), bencher); } #[bench] fn fill_and_drain_unord_big (bencher: &mut Bencher) { priorityqueue::bench_fill_and_drain::<ToTest, _, _>(utils::unordered_sequence::<uint>(4), bencher); } #[bench] fn mixed_access_ord_small (bencher: &mut Bencher) { priorityqueue::bench_mixed_access::<ToTest, _, _>(utils::ordered_sequence::<uint>(2), bencher); } #[bench] fn mixed_access_ord_big (bencher: &mut Bencher) { priorityqueue::bench_mixed_access::<ToTest, _, _>(utils::ordered_sequence::<uint>(4), bencher); } #[bench] fn mixed_access_unord_small (bencher: &mut Bencher) { priorityqueue::bench_mixed_access::<ToTest, _, _>(utils::unordered_sequence::<uint>(2), bencher); } #[bench] fn mixed_access_unord_big (bencher: &mut Bencher) { priorityqueue::bench_mixed_access::<ToTest, _, _>(utils::unordered_sequence::<uint>(4), bencher); } ); ) #[cfg(test)] mod bench { use super::super::priorityqueue; use super::super::collection; use super::super::utils; use test::Bencher; use std::collections::PriorityQueue; bench_priorityqueue!(PriorityQueue<uint>) }
#![no_std] extern crate alloc; mod consts; #[cfg(not(feature = "minimal"))] mod default; #[cfg(feature = "minimal")] mod minimal; #[cfg(not(feature = "minimal"))] pub use default::Md2; #[cfg(feature = "minimal")] pub use minimal::Md2; #[cfg(test)] mod tests { use super::Md2; use dev_util::impl_test; const OFFICIAL: [(&[u8], &str); 6] = [ // https://tools.ietf.org/html/rfc1319 ("".as_bytes(), "8350e5a3e24c153df2275c9f80692773"), ("a".as_bytes(), "32ec01ec4a6dac72c0ab96fb34c0b5d1"), ( "message digest".as_bytes(), "ab4f496bfb2a530b219ff33031fe06b0", ), ( "abcdefghijklmnopqrstuvwxyz".as_bytes(), "4e8ddff3650292ab5a4108c3aa47940b", ), ( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".as_bytes(), "da33def2a42df13975352846c30338cd", ), ( "12345678901234567890123456789012345678901234567890123456789012345678901234567890" .as_bytes(), "d5976f79d83d3a0dc9806c3c66f3efd8", ), ]; impl_test!(Md2, md2_official, OFFICIAL, Md2::default()); }
pub mod rcc; pub mod gpioa; pub mod gpiob; pub mod usart1; pub mod flash; pub mod stk; pub mod spi1; pub mod afio; pub mod adc1;
#![feature(prelude_import)] #![no_std] #[prelude_import] use std::prelude::v1::*; #[macro_use] extern crate std as std; #[macro_use] extern crate inherit; fn main() {} trait Node { fn source_location(&self) -> (usize, usize); } struct Expr { source_location: (usize, usize), } impl Node for Expr { fn source_location(&self) -> (usize, usize) { self.source_location } }
extern crate whenever; use std::env; use whenever::parser; fn main() { let args: Vec<String> = env::args().collect(); let arg = match args.len() { 2 => args[1].clone(), _ => "today".to_string(), }; let dt = parser::parse_date(&arg); match dt { Some(d) => println!("{}", d), None => println!("Could not parse {}", arg), } }
use std::io::{self, Write}; use std::process; use std::process::Command; fn main() { if !cfg!(target_os = "windows") { println!("Incompatible target os, need Microsoft Windows 10"); process::exit(0); } let output = { Command::new("x410.exe") .args(&["/desktop"]) .output() .expect("failed to execute prcess x410.exe") }; println!("status: {} | start /B x410.exe /desktop", output.status); io::stdout().write_all(&output.stdout).unwrap(); io::stderr().write_all(&output.stderr).unwrap(); let output = { Command::new("ubuntu2004.exe") .args(&["run", "~/runx11.sh"]) .output() .expect("failed to execute prcess ubuntu2004.exe") }; println!("status: {} | ubuntu2004.exe ru", output.status); io::stdout().write_all(&output.stdout).unwrap(); io::stderr().write_all(&output.stderr).unwrap(); }
use crate::*; use rider_themes::predef::*; use rider_themes::Theme; use std::fs; use std::path::PathBuf; pub fn create(directories: &Directories) -> std::io::Result<()> { fs::create_dir_all(directories.themes_dir.clone())?; for theme in default_styles() { write_theme(&theme, directories)?; } Ok(()) } fn write_theme(theme: &Theme, directories: &Directories) -> std::io::Result<()> { let mut theme_path = PathBuf::new(); theme_path.push(directories.themes_dir.clone()); theme_path.push(format!("{}.json", theme.name())); let contents = serde_json::to_string_pretty(&theme).unwrap(); fs::write(&theme_path, contents)?; Ok(()) } fn default_styles() -> Vec<Theme> { vec![default::build_theme(), railscasts::build_theme()] } #[cfg(test)] mod tests { use super::*; use std::fs::create_dir_all; use std::path::Path; use uuid::Uuid; #[test] fn assert_default_styles() { assert_eq!(default_styles().len(), 2); } #[cfg(test)] fn join(a: String, b: String) -> String { vec![a, b].join("/") } #[test] fn assert_create_default() { let uniq = Uuid::new_v4(); let test_path = join("/tmp/rider-tests".to_owned(), uniq.to_string()); create_dir_all(test_path.clone()).unwrap(); let directories = Directories::new(Some(test_path.clone()), None); let rider_dir = join(test_path.clone(), "rider".to_owned()); assert_eq!( Path::new(join(rider_dir.clone(), "themes/default.json".to_owned()).as_str()).exists(), false ); assert_eq!(create(&directories).is_ok(), true); assert_eq!( Path::new(join(rider_dir.clone(), "themes/default.json".to_owned()).as_str()).exists(), true ); } #[test] fn assert_create_railscasts() { let uniq = Uuid::new_v4(); let test_path = join("/tmp/rider-tests".to_owned(), uniq.to_string()); create_dir_all(test_path.clone()).unwrap(); let directories = Directories::new(Some(test_path.clone()), None); let rider_dir = join(test_path.clone(), "rider".to_owned()); assert_eq!( Path::new(join(rider_dir.clone(), "themes/default.json".to_owned()).as_str()).exists(), false ); assert_eq!(create(&directories).is_ok(), true); assert_eq!( Path::new(join(rider_dir.clone(), "themes/railscasts.json".to_owned()).as_str()) .exists(), true ); } }
// The problem_factory module is a class implementing a classic factory pattern // to instantiate problem solutions // get_solution is the factory method for creating a solution to each problem pub fn get_solution(problem_number: i32) -> String { match problem_number { 1 => super::multiple_3or5::compute(), 2 => super::even_fibonacci::compute(), 3 => super::largest_prime_factor::compute(), 4 => super::largest_palindrome_product::compute(), 5 => super::smallest_multiple::compute(), 6 => super::sum_square_difference::compute(), 7 => super::prime10001::compute(), 8 => super::largest_product_series::compute(), 9 => super::pythagorean_triplet::compute(), 10 => super::summation_primes::compute(), 11 => super::largest_product_grid::compute(), 12 => super::highly_divisible_triangle::compute(), 13 => super::large_sum::compute(), _ => "Problem ".to_owned() + &problem_number.to_string() + " is not solved.", } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::{format_err, Result}; use libra_types::{ account_config::{account_struct_tag, AccountResource}, language_storage::StructTag, }; use vm_runtime_types::{ loaded_data::{struct_def::StructDef, types::Type}, value::{Struct, Value}, }; /// resolve StructDef by StructTag. pub trait StructDefResolve { fn resolve(&self, tag: &StructTag) -> Result<StructDef>; } #[derive(Clone, Debug)] pub struct Resource(StructTag, Struct); impl Resource { pub fn new(tag: StructTag, value: Struct) -> Self { Self(tag, value) } pub fn tag(&self) -> &StructTag { &self.0 } pub fn new_from_account_resource(account_resource: AccountResource) -> Self { //this serialize and decode should never fail, so use unwrap. let out: Vec<u8> = lcs::to_bytes(&account_resource).unwrap(); Self::decode(account_struct_tag(), get_account_struct_def(), &out).expect("decode fail.") } pub fn decode(tag: StructTag, def: StructDef, bytes: &[u8]) -> Result<Self> { let struct_value = Value::simple_deserialize(bytes, def) .map_err(|vm_error| format_err!("decode resource fail:{:?}", vm_error)) .and_then(|value| value.value_as().map_err(Into::into))?; Ok(Self::new(tag, struct_value)) } pub fn encode(&self) -> Vec<u8> { Into::<Value>::into(self) .simple_serialize() .expect("serialize should not fail.") } } impl Into<Value> for Resource { fn into(self) -> Value { Value::struct_(self.1) } } impl Into<Value> for &Resource { fn into(self) -> Value { self.clone().into() } } impl std::cmp::PartialEq for Resource { fn eq(&self, other: &Self) -> bool { //TODO optimize self.encode() == other.encode() } } impl Into<(StructTag, Struct)> for Resource { fn into(self) -> (StructTag, Struct) { (self.0, self.1) } } pub fn get_account_struct_def() -> StructDef { let int_type = Type::U64; let byte_array_type = Type::ByteArray; let coin = Type::Struct(get_coin_struct_def()); let event_handle = Type::Struct(get_event_handle_struct_def()); StructDef::new(vec![ byte_array_type, coin, Type::Bool, Type::Bool, event_handle.clone(), event_handle.clone(), int_type.clone(), ]) } pub fn get_coin_struct_def() -> StructDef { let int_type = Type::U64; StructDef::new(vec![int_type.clone()]) } pub fn get_event_handle_struct_def() -> StructDef { StructDef::new(vec![Type::U64, Type::ByteArray]) }
use aoc_lib::{Input, Solver}; #[derive(Debug)] pub(crate) struct Day1 {} impl Day1 { fn get_sorted(input: Input) -> Vec<u32> { let mut x = input.lines.iter().fold(vec![0], |mut acc, x| { if x.is_empty() { acc.push(0_u32); acc } else { let l = acc.len(); acc[l - 1] += x.parse::<u32>().unwrap_or(0); acc } }); x.sort_by(|a, b| b.cmp(a)); x } } impl Solver for Day1 { type OutputPart1 = u32; type OutputPart2 = u32; fn day() -> u8 { 1 } fn solution_part1(input: Input) -> Option<Self::OutputPart1> { let x = Day1::get_sorted(input); x.first().copied() } fn solution_part2(input: Input) -> Option<Self::OutputPart2> { let x = Day1::get_sorted(input); x.split_at(3).0.iter().copied().reduce(|a, b| a + b) } }
extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn log(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) { log(&format!("Hello, {}!", name)); }
use specs::prelude::*; use types::*; use component::flag::IsMissile; use component::reference::PlayerRef; use component::time::*; use airmash_protocol::server::{PlayerFire, PlayerFireProjectile}; use airmash_protocol::{to_bytes, ServerPacket}; use websocket::OwnedMessage; pub struct MissileFireHandler; #[derive(SystemData)] pub struct MissileFireHandlerData<'a> { pub ents: Entities<'a>, pub pos: WriteStorage<'a, Position>, pub vel: WriteStorage<'a, Velocity>, pub rot: ReadStorage<'a, Rotation>, pub plane: ReadStorage<'a, Plane>, pub teams: WriteStorage<'a, Team>, pub keystate: ReadStorage<'a, KeyState>, pub energy: WriteStorage<'a, Energy>, pub config: Read<'a, Config>, pub flags: WriteStorage<'a, IsMissile>, pub mobs: WriteStorage<'a, Mob>, pub owner: WriteStorage<'a, PlayerRef>, pub conns: Read<'a, Connections>, pub starttime: Read<'a, StartTime>, pub thisframe: Read<'a, ThisFrame>, pub spawntime: WriteStorage<'a, MobSpawnTime>, pub lastshot: WriteStorage<'a, LastShotTime>, } impl<'a> System<'a> for MissileFireHandler { type SystemData = MissileFireHandlerData<'a>; fn run(&mut self, data: Self::SystemData) { let clock = (data.thisframe.0 - data.starttime.0).to_clock(); let thisframe = data.thisframe; let MissileFireHandlerData { ents, mut pos, mut vel, rot, keystate, plane, mut teams, mut energy, config, mut flags, mut mobs, mut owner, conns, mut spawntime, mut lastshot, .. } = data; let new = ( &*ents, &pos, &vel, &rot, &keystate, &mut energy, &plane, &teams, &mut lastshot, ).par_join() .filter_map( |(ent, pos, vel, rot, keystate, energy, plane, team, lastshot)| { let ref info = config.planes[*plane]; let ref missile = config.mobs[info.missile_type].missile.unwrap(); if thisframe.0 - lastshot.0 < info.fire_delay || !keystate.fire || *energy < info.fire_energy { return None; } // Rotate starting angle 90 degrees so that // it's inline with the plane. Change this // and missiles will shoot sideways :) let m_dir = Vector2::new(rot.sin(), -rot.cos()); // Component of velocity parallel to direction let vel_par = Vector2::dot(m_dir, *vel).max(Speed::new(0.0)); let m_vel = m_dir * (vel_par * missile.speed_factor + missile.base_speed); let m_accel = m_dir * missile.accel; let m_ent = ents.create(); let m_pos = *pos + m_dir * info.missile_offset; *energy -= info.fire_energy; *lastshot = LastShotTime(thisframe.0); let packet = PlayerFire { clock: clock, id: ent, energy: *energy, energy_regen: info.energy_regen, projectiles: vec![PlayerFireProjectile { id: m_ent, accel: m_accel, pos: m_pos, speed: m_vel, ty: info.missile_type, max_speed: missile.max_speed, }], }; conns.send_to_all(OwnedMessage::Binary( to_bytes(&ServerPacket::PlayerFire(packet)).unwrap(), )); return Some((m_ent, info.missile_type, m_pos, m_vel, *team, ent)); }, ) .collect::<Vec<(Entity, Mob, Position, Velocity, Team, Entity)>>(); for v in new { trace!( target: "", "Fired missile: {:?}", v ); pos.insert(v.0, v.2).unwrap(); vel.insert(v.0, v.3).unwrap(); mobs.insert(v.0, v.1).unwrap(); flags.insert(v.0, IsMissile {}).unwrap(); teams.insert(v.0, v.4).unwrap(); owner.insert(v.0, PlayerRef(v.5)).unwrap(); spawntime.insert(v.0, MobSpawnTime(thisframe.0)).unwrap(); } } } use dispatch::SystemInfo; use systems::PositionUpdate; impl SystemInfo for MissileFireHandler { type Dependencies = PositionUpdate; fn name() -> &'static str { concat!(module_path!(), "::", line!()) } fn new() -> Self { Self {} } }
use actix_cors::Cors; use actix_web::{web, App, HttpServer}; use chrono::prelude::*; use config::Config; use lazy_static; use serde_json; use std::collections::HashMap; use std::thread; use std::time::Duration; mod event; mod order; mod utils; pub const ADDR: &str = "0.0.0.0:9004"; lazy_static::lazy_static! { static ref SECRETS: HashMap<String, String> = { let mut config = Config::default(); config.merge(config::File::with_name("secrets")).unwrap(); config.try_into::<HashMap<String, String>>().unwrap() }; } #[async_std::main] async fn main() { println!("Listening on {}", ADDR); async_std::task::spawn(update_orders()); HttpServer::new(|| { App::new() .wrap(Cors::new()) .service(web::scope("/orders").route("", web::get().to(order::get::get_received))) }) .bind(ADDR) .unwrap() .run() .unwrap(); } async fn update_orders() { use event::*; let mut event_store_conn = utils::get_event_store_db_connection().unwrap(); let mut tracked_orders = HashMap::<String, NaiveDateTime>::new(); let mut order_query_conn = utils::get_order_query_db_connection().unwrap(); order_query_conn .execute( r#"CREATE TABLE IF NOT EXISTS "order" ( id SERIAL PRIMARY KEY, entity_id TEXT NOT NULL, customer_id TEXT NOT NULL, date DATE, frame_color TEXT, frame_id TEXT NOT NULL, owner_id TEXT NOT NULL, quantity INT, total REAL, processed BOOLEAN NOT NULL DEFAULT FALSE, rejected BOOLEAN NOT NULL DEFAULT FALSE, updated_at TIMESTAMP(6) NOT NULL )"#, &[], ) .unwrap(); let order_rows = &order_query_conn .query(r#"SELECT entity_id, updated_at FROM "order""#, &[]) .unwrap(); for row in order_rows { let order_id = row.get(0); let updated_at: NaiveDateTime = row.get(1); tracked_orders.insert(order_id, updated_at); } loop { let recent = tracked_orders.iter().max_by(|p, q| p.1.cmp(q.1)); let updated_at: NaiveDateTime = if let Some(max_pair) = recent { max_pair.1.clone() } else { NaiveDateTime::new(NaiveDate::from_yo(1970, 1), NaiveTime::from_hms(0, 0, 0)) }; dbg!(&updated_at); let read_res = (|| { let event_rows = &event_store_conn .query( r#"SELECT entity_id, body, inserted_at, type FROM "order" WHERE inserted_at > $1"#, &[&updated_at], ) .map_err(|e| e.to_string())?; for row in event_rows { let entity_id: String = row.get(0); dbg!(&entity_id); let body: String = row.get(1); dbg!(&body); let inserted_at: NaiveDateTime = row.get(2); dbg!(&inserted_at); let r#type: String = row.get(3); dbg!(&r#type); let persist_res = (|| { match r#type.as_str() { "OrderPlaced" => { let body: OrderPlacedData = serde_json::from_str(&body).map_err(|e| e.to_string())?; // Save order in Postgres order_query_conn .execute( r#"INSERT INTO "order" (entity_id, customer_id, date, frame_color, frame_id, owner_id, quantity, total, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)"#, &[ &entity_id, &body.customer_id, &body.date, &body.frame_color, &body.frame_id, &body.owner_id, &body.quantity, &body.total, &inserted_at, ], ) .map_err(|e| e.to_string())?; Ok::<(), String>(()) } "OrderProcessed" => { order_query_conn .execute( r#"UPDATE "order" SET processed = $1, rejected = $2, updated_at = $3 WHERE entity_id = $4 "#, &[&true, &false, &inserted_at, &entity_id], ) .map_err(|e| e.to_string())?; Ok::<(), String>(()) } "OrderRejected" => { order_query_conn .execute( r#"UPDATE "order" SET processed = $1, rejected = $2, updated_at = $3 WHERE entity_id = $4 "#, &[&false, &true, &inserted_at, &entity_id], ) .map_err(|e| e.to_string())?; Ok::<(), String>(()) } other => { println!("Unknown event type {}", other); Ok::<(), String>(()) } } })(); persist_res.unwrap(); tracked_orders.insert(entity_id, inserted_at); } Ok::<(), String>(()) })(); if read_res.is_err() { dbg!("{}", read_res.unwrap_err()); } thread::sleep(Duration::from_secs(30)); } }
//! Registry authentication support. use crate::sources::CRATES_IO_REGISTRY; use crate::util::{config, CargoResult, Config}; use anyhow::{bail, format_err, Context as _}; use cargo_util::ProcessError; use std::io::{Read, Write}; use std::path::PathBuf; use std::process::{Command, Stdio}; use super::RegistryConfig; enum Action { Get, Store(String), Erase, } /// Returns the token to use for the given registry. pub(super) fn auth_token( config: &Config, cli_token: Option<&str>, credential: &RegistryConfig, registry_name: Option<&str>, api_url: &str, ) -> CargoResult<String> { let token = match (cli_token, credential) { (None, RegistryConfig::None) => { bail!("no upload token found, please run `cargo login` or pass `--token`"); } (Some(cli_token), _) => cli_token.to_string(), (None, RegistryConfig::Token(config_token)) => config_token.to_string(), (None, RegistryConfig::Process(process)) => { let registry_name = registry_name.unwrap_or(CRATES_IO_REGISTRY); run_command(config, process, registry_name, api_url, Action::Get)?.unwrap() } }; Ok(token) } /// Saves the given token. pub(super) fn login( config: &Config, token: String, credential_process: Option<&(PathBuf, Vec<String>)>, registry_name: Option<&str>, api_url: &str, ) -> CargoResult<()> { if let Some(process) = credential_process { let registry_name = registry_name.unwrap_or(CRATES_IO_REGISTRY); run_command( config, process, registry_name, api_url, Action::Store(token), )?; } else { config::save_credentials(config, Some(token), registry_name)?; } Ok(()) } /// Removes the token for the given registry. pub(super) fn logout( config: &Config, credential_process: Option<&(PathBuf, Vec<String>)>, registry_name: Option<&str>, api_url: &str, ) -> CargoResult<()> { if let Some(process) = credential_process { let registry_name = registry_name.unwrap_or(CRATES_IO_REGISTRY); run_command(config, process, registry_name, api_url, Action::Erase)?; } else { config::save_credentials(config, None, registry_name)?; } Ok(()) } fn run_command( config: &Config, process: &(PathBuf, Vec<String>), name: &str, api_url: &str, action: Action, ) -> CargoResult<Option<String>> { let cred_proc; let (exe, args) = if process.0.to_str().unwrap_or("").starts_with("cargo:") { cred_proc = sysroot_credential(config, process)?; &cred_proc } else { process }; if !args.iter().any(|arg| arg.contains("{action}")) { let msg = |which| { format!( "credential process `{}` cannot be used to {}, \ the credential-process configuration value must pass the \ `{{action}}` argument in the config to support this command", exe.display(), which ) }; match action { Action::Get => {} Action::Store(_) => bail!(msg("log in")), Action::Erase => bail!(msg("log out")), } } let action_str = match action { Action::Get => "get", Action::Store(_) => "store", Action::Erase => "erase", }; let args: Vec<_> = args .iter() .map(|arg| { arg.replace("{action}", action_str) .replace("{name}", name) .replace("{api_url}", api_url) }) .collect(); let mut cmd = Command::new(&exe); cmd.args(args) .env("CARGO", config.cargo_exe()?) .env("CARGO_REGISTRY_NAME", name) .env("CARGO_REGISTRY_API_URL", api_url); match action { Action::Get => { cmd.stdout(Stdio::piped()); } Action::Store(_) => { cmd.stdin(Stdio::piped()); } Action::Erase => {} } let mut child = cmd.spawn().with_context(|| { let verb = match action { Action::Get => "fetch", Action::Store(_) => "store", Action::Erase => "erase", }; format!( "failed to execute `{}` to {} authentication token for registry `{}`", exe.display(), verb, name ) })?; let mut token = None; match &action { Action::Get => { let mut buffer = String::new(); log::debug!("reading into buffer"); child .stdout .as_mut() .unwrap() .read_to_string(&mut buffer) .with_context(|| { format!( "failed to read token from registry credential process `{}`", exe.display() ) })?; if let Some(end) = buffer.find('\n') { if buffer.len() > end + 1 { bail!( "credential process `{}` returned more than one line of output; \ expected a single token", exe.display() ); } buffer.truncate(end); } token = Some(buffer); } Action::Store(token) => { writeln!(child.stdin.as_ref().unwrap(), "{}", token).with_context(|| { format!( "failed to send token to registry credential process `{}`", exe.display() ) })?; } Action::Erase => {} } let status = child.wait().with_context(|| { format!( "registry credential process `{}` exit failure", exe.display() ) })?; if !status.success() { let msg = match action { Action::Get => "failed to authenticate to registry", Action::Store(_) => "failed to store token to registry", Action::Erase => "failed to erase token from registry", }; return Err(ProcessError::new( &format!( "registry credential process `{}` {} `{}`", exe.display(), msg, name ), Some(status), None, ) .into()); } Ok(token) } /// Gets the path to the libexec processes in the sysroot. fn sysroot_credential( config: &Config, process: &(PathBuf, Vec<String>), ) -> CargoResult<(PathBuf, Vec<String>)> { let cred_name = process.0.to_str().unwrap().strip_prefix("cargo:").unwrap(); let cargo = config.cargo_exe()?; let root = cargo .parent() .and_then(|p| p.parent()) .ok_or_else(|| format_err!("expected cargo path {}", cargo.display()))?; let exe = root.join("libexec").join(format!( "cargo-credential-{}{}", cred_name, std::env::consts::EXE_SUFFIX )); let mut args = process.1.clone(); if !args.iter().any(|arg| arg == "{action}") { args.push("{action}".to_string()); } Ok((exe, args)) }
// Copyright 2015 The GeoRust Developers // // 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::str::FromStr; use rustc_serialize::json::{self, ToJson}; use ::{Error, Geometry, Feature, FeatureCollection, FromObject}; /// GeoJSON Objects /// /// [GeoJSON Format Specification § 2] /// (http://geojson.org/geojson-spec.html#geojson-objects) #[derive(Clone, Debug, PartialEq)] pub enum GeoJson { Geometry(Geometry), Feature(Feature), FeatureCollection(FeatureCollection), } impl<'a> From<&'a GeoJson> for json::Object { fn from(geojson: &'a GeoJson) -> json::Object { return match *geojson { GeoJson::Geometry(ref geometry) => geometry.into(), GeoJson::Feature(ref feature) => feature.into(), GeoJson::FeatureCollection(ref fc) => fc.into(), }; } } impl FromObject for GeoJson { fn from_object(object: &json::Object) -> Result<Self, Error> { let type_ = expect_string!(expect_property!(object, "type", "Missing 'type' field")); return match &type_ as &str { "Point" | "MultiPoint" | "LineString" | "MultiLineString" | "Polygon" | "MultiPolygon" => Geometry::from_object(object).map(GeoJson::Geometry), "Feature" => Feature::from_object(object).map(GeoJson::Feature), "FeatureCollection" => FeatureCollection::from_object(object).map(GeoJson::FeatureCollection), _ => Err(Error::new("Encountered unknown GeoJSON type")), }; } } impl json::ToJson for GeoJson { fn to_json(&self) -> json::Json { return json::Json::Object(self.into()); } } impl FromStr for GeoJson { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let decoded_json = match json::Json::from_str(s) { Ok(j) => j, Err(..) => return Err(Error::new("Encountered malformed JSON")), }; let object = match decoded_json { json::Json::Object(object) => object, _ => return Err(Error::new("Attempted to create GeoJSON from JSON that is not an object")), }; return GeoJson::from_object(&object); } } impl ToString for GeoJson { fn to_string(&self) -> String { return self.to_json().to_string(); } }
//! File-based cache for `DirEntry` structures. //! //! The cache persists scan results between `userscan` invocations so that unchanged files don't //! need to be scanned again. It is currently saved as compressed MessagePack file. use super::{Lookup, StorePaths}; use crate::cachemap::*; use crate::errors::*; use crate::output::p2s; use crate::system::ExecutionContext; use colored::Colorize; use ignore::DirEntry; use std::fs; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::RwLock; #[derive(Debug, Default)] pub struct Cache { map: RwLock<CacheMap>, filename: PathBuf, file: Option<fs::File>, dirty: AtomicBool, hits: AtomicUsize, misses: AtomicUsize, limit: usize, } impl Cache { pub fn new(limit: Option<usize>) -> Self { Cache { limit: limit.unwrap_or(0), ..Self::default() } } pub fn open<P: AsRef<Path>>(mut self, path: P, ctx: &ExecutionContext) -> Result<Self> { self.filename = path.as_ref().to_path_buf(); info!("Loading cache {}", p2s(&self.filename)); self.file = ctx.with_dropped_privileges::<_, UErr, _>(|| { if let Some(p) = path.as_ref().parent() { fs::create_dir_all(p).map_err(|e| UErr::Create(p.to_owned(), e))?; } let mut cachefile = open_locked(&path).map_err(|e| UErr::LoadCache(self.filename.clone(), e))?; if cachefile.metadata().map_err(UErr::from)?.len() > 0 { let map = CacheMap::load(&mut cachefile, &self.filename) .map_err(|e| UErr::LoadCache(self.filename.clone(), e))?; debug!("loaded {} entries from cache", map.len()); self.map = RwLock::new(map); self.dirty = AtomicBool::new(false); } else { debug!("creating new cache {}", p2s(&path)); self.map.write().expect("tainted lock").clear(); self.dirty = AtomicBool::new(true); } Ok(Some(cachefile)) })?; Ok(self) } pub fn commit(&mut self, ctx: &ExecutionContext) -> Result<()> { if let Some(ref mut file) = self.file { if !self.dirty.compare_and_swap(true, false, Ordering::SeqCst) { return Ok(()); } ctx.drop_privileges()?; let mut map = self.map.write().expect("tainted lock"); map.retain(|_, ref mut v| v.used); debug!("writing {} entries to cache", map.len()); map.save(file) .map_err(|e| UErr::SaveCache(self.filename.clone(), e))?; ctx.regain_privileges()?; } Ok(()) } fn get(&self, dent: &DirEntry) -> Option<(Vec<PathBuf>, fs::Metadata)> { let ino = dent.ino()?; let mut map = self.map.write().expect("tainted lock"); let c = map.get_mut(&ino)?; let meta = dent.metadata().ok()?; if c.ctime == meta.ctime() && c.ctime_nsec == meta.ctime_nsec() as u8 { c.used = true; Some((c.refs.clone(), meta)) } else { None } } pub fn lookup(&self, dent: DirEntry) -> Lookup { if let Some(ft) = dent.file_type() { if ft.is_dir() { return Lookup::Dir(StorePaths { dent, refs: vec![], cached: true, bytes_scanned: 0, metadata: None, }); } } match self.get(&dent) { Some((refs, metadata)) => { self.hits.fetch_add(1, Ordering::Relaxed); Lookup::Hit(StorePaths { dent, refs, cached: true, bytes_scanned: 0, metadata: Some(metadata), }) } None => { self.misses.fetch_add(1, Ordering::Relaxed); Lookup::Miss(dent) } } } pub fn insert(&self, sp: &mut StorePaths) -> Result<()> { if sp.cached { return Ok(()); } let meta = sp.metadata()?; let mut map = self.map.write().expect("tainted lock"); if self.limit > 0 && map.len() >= self.limit { return Err(UErr::CacheFull(self.limit)); } map.insert( sp.ino()?, CacheLine::new(meta.ctime(), meta.ctime_nsec() as u8, &sp.refs), ); self.dirty.store(true, Ordering::Release); Ok(()) } /* statistics */ pub fn len(&self) -> usize { self.map.read().expect("tainted lock").len() } pub fn hit_ratio(&self) -> f32 { let h = self.hits.load(Ordering::SeqCst); let m = self.misses.load(Ordering::SeqCst); if h == 0 { 0.0 } else { h as f32 / (h as f32 + m as f32) } } pub fn log_statistics(&self) { if self.file.is_some() { info!( "Cache saved to {}, {} entries, hit ratio {}%", p2s(&self.filename), self.len().to_string().cyan(), ((self.hit_ratio() * 100.0) as u32).to_string().cyan() ) } } } #[cfg(test)] mod tests { use super::Lookup::*; use super::*; use crate::tests::{dent, FIXTURES}; use std::fs; use tempfile::TempDir; fn sp_dummy() -> StorePaths { let dent = tests::dent("dir2/lftp"); StorePaths { dent, refs: vec![PathBuf::from("q3wx1gab2ysnk5nyvyyg56ana2v4r2ar-glibc-2.24")], cached: false, bytes_scanned: 0, metadata: None, } } fn sp_fixture<P: AsRef<Path>>(path: P) -> StorePaths { StorePaths { dent: tests::dent(path), refs: vec![], cached: false, bytes_scanned: 0, metadata: None, } } #[test] fn insert_cacheline() { let c = Cache::new(None); c.insert(&mut sp_fixture("dir1/proto-http.la")) .expect("insert failed"); let dent = tests::dent("dir1/proto-http.la"); let map = c.map.read().unwrap(); let entry = map .get(&dent.ino().unwrap()) .expect("cache entry not found"); assert_eq!( entry.ctime, fs::metadata("dir1/proto-http.la").unwrap().ctime() ); } #[test] fn insert_should_fail_on_limit() { let c = Cache::new(Some(2)); c.insert(&mut sp_fixture("dir1/proto-http.la")).expect("ok"); c.insert(&mut sp_fixture("dir2/lftp")).expect("ok"); assert!(c.insert(&mut sp_fixture("dir2/lftp.offset")).is_err()); } #[test] fn lookup_should_miss_on_changed_metadata() { let c = Cache::new(None); let ino = tests::dent("dir2/lftp").ino().unwrap(); c.insert(&mut sp_dummy()).expect("insert failed"); match c.lookup(tests::dent("dir2/lftp")) { Hit(sp) => assert_eq!( vec![PathBuf::from("q3wx1gab2ysnk5nyvyyg56ana2v4r2ar-glibc-2.24")], sp.refs ), _ => panic!("test failure: did not find dir2/lftp in cache"), } c.map.write().unwrap().get_mut(&ino).unwrap().ctime = 6674; match c.lookup(tests::dent("dir2/lftp")) { Miss(_) => (), _ => panic!("should not hit: dir2/lftp"), } } #[test] fn load_save_cache() { let td = TempDir::new().unwrap(); let cache_file = td.path().join("cache.mp"); fs::copy(FIXTURES.join("cache.mp"), &cache_file).unwrap(); let mut c = Cache::new(None) .open(&cache_file, &ExecutionContext::new()) .unwrap(); assert_eq!(12, c.len()); assert!(!c.dirty.load(Ordering::SeqCst)); for ref cl in c.map.read().unwrap().values() { assert!(!cl.used); } c.insert(&mut sp_dummy()).unwrap(); assert!(c.dirty.load(Ordering::SeqCst)); // exactly the newly inserted cacheline should have the "used" flag set assert_eq!( 1, c.map .read() .unwrap() .values() .filter(|cl| cl.used) .collect::<Vec<_>>() .len() ); c.commit(&ExecutionContext::new()).unwrap(); assert_eq!(1, c.len()); let cache_len = fs::metadata(&cache_file).unwrap().len(); assert!(cache_len > 60); } }
#![allow(non_snake_case)] use failure::{ ensure, Fallible, }; use iota_lib_rs::prelude::iota_client; use iota_streams::app::{ message::HasLink }; use iota_streams::app::transport::{ Transport, tangle::client::* }; use iota_streams::app_channels::{ api::tangle::{ Address, Author, Subscriber }, message, }; use iota_streams::core::tbits::Tbits; use iota_streams::protobuf3::types::Trytes; use std::str::FromStr; fn example() -> Fallible<()> { let mut client = iota_client::Client::new("https://nodes.devnet.iota.org:443"); let mut send_opt = SendTrytesOptions::default(); send_opt.min_weight_magnitude = 10; let recv_opt = (); let mut author = Author::new("DE9OVLDWFLNTKCYPVMRRKMYOEBLBWHFRQERUHAECFSCHSDZODGRDVXPVJJVGKEZOVVHWENPLWFVZWZUNG", 2, true); //println!("Channel address = {}", author.channel_address()); let public_payload = Trytes(Tbits::from_str("PUBLICPAYLOAD").unwrap()); let masked_payload = Trytes(Tbits::from_str("MASKEDPAYLOAD").unwrap()); println!("announce"); let (announcement_address, announcement_tag) = { let msg = &author.announce()?; println!(" {}", msg.link.msgid.to_string()); client.send_message_with_options(&msg, send_opt)?; (msg.link.appinst.to_string(), msg.link.msgid.to_string()) }; let announcement_link = Address::from_str(&announcement_address, &announcement_tag).unwrap(); println!("sign packet"); let signed_packet = { let msg = author.sign_packet(&announcement_link, &public_payload, &masked_payload)?; println!(" {}", msg.link.msgid.to_string()); client.send_message_with_options(&msg, send_opt)?; (msg.link.appinst.to_string(), msg.link.msgid.to_string()) }; let signed_packet_link= Address::from_str(&signed_packet.0, &signed_packet.1).unwrap(); println!(" at {}", signed_packet_link.rel()); println!("share keyload for everyone"); let keyload= { let msg = author.share_keyload_for_everyone(&announcement_link)?; println!(" {}", msg.link.msgid); client.send_message_with_options(&msg, send_opt)?; (msg.link.appinst.to_string(), msg.link.msgid.to_string()) }; let keyload_link= Address::from_str(&keyload.0, &keyload.1).unwrap(); println!("tag packet"); let tagged_packet_link = { let msg = author.tag_packet(&keyload_link, &public_payload, &masked_payload)?; println!(" {}", msg.link.msgid); client.send_message_with_options(&msg, send_opt)?; msg.link.clone() }; println!("change key"); let change_key_link = { let msg = author.change_key(&announcement_link)?; println!(" {}", msg.link.msgid); client.send_message_with_options(&msg, send_opt)?; msg.link }; Ok(()) } fn main() { let _result = dbg!(example()); }
fn main() { println!("cargo:rerun-if-changed=lib/jlinker/bin/libjlinker.a"); println!("cargo:rustc-link-search=./lib/jlinker/bin/"); println!("cargo:rustc-link-search=./lib/keystone/build/llvm/lib"); println!("cargo:rustc-link-lib=jlinker"); println!("cargo:rustc-link-lib=keystone"); println!("cargo:rustc-link-lib=stdc++"); println!("cargo:rustc-link-lib=m"); println!("cargo:rustc-link-lib=bfd"); }