text
stringlengths
8
4.13M
use std::fmt::{self, Display}; use std::ops::Deref; use std::sync::Arc; use crate::erts::term::pid::InvalidPidError; use crate::erts::term::prelude::{TermDecodingError, TermEncodingError, TypeError}; #[derive(Clone)] pub struct ArcError(Arc<anyhow::Error>); impl ArcError { pub fn new(err: anyhow::Error) -> Self { Self(Arc::new(err)) } pub fn from_err<E>(err: E) -> Self where E: std::error::Error + Send + Sync + 'static, { Self(Arc::new(anyhow::Error::new(err))) } pub fn context<C>(&self, context: C) -> Self where C: Display + Send + Sync + 'static, { Self::new(anyhow::Error::new(self.clone()).context(context)) } } impl Deref for ArcError { type Target = anyhow::Error; fn deref(&self) -> &Self::Target { self.0.deref() } } impl fmt::Debug for ArcError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.0) } } impl fmt::Display for ArcError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl std::error::Error for ArcError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { self.0.source() } } impl From<anyhow::Error> for ArcError { fn from(err: anyhow::Error) -> Self { Self::new(err) } } impl From<InvalidPidError> for ArcError { fn from(err: InvalidPidError) -> Self { Self::from_err(err) } } impl From<TermDecodingError> for ArcError { fn from(err: TermDecodingError) -> Self { Self::from_err(err) } } impl From<TermEncodingError> for ArcError { fn from(err: TermEncodingError) -> Self { Self::from_err(err) } } impl From<TypeError> for ArcError { fn from(err: TypeError) -> Self { Self::from_err(err) } }
use std::str::FromStr; use async_graphql::http::{WebSocketProtocols, WsMessage, ALL_WEBSOCKET_PROTOCOLS}; use async_graphql::{Data, ObjectType, Schema, SubscriptionType}; use futures_util::future::{self, Ready}; use futures_util::{Future, SinkExt, StreamExt}; use poem::web::websocket::{Message, WebSocket}; use poem::{http, Endpoint, FromRequest, IntoResponse, Request, Response, Result}; /// A GraphQL subscription endpoint. /// /// # Example /// /// ``` /// use poem::{Route, get}; /// use async_graphql_poem::GraphQLSubscription; /// use async_graphql::{EmptyMutation, Object, Schema, Subscription}; /// use futures_util::{Stream, stream}; /// /// struct Query; /// /// #[Object] /// impl Query { /// async fn value(&self) -> i32 { /// 100 /// } /// } /// /// struct Subscription; /// /// #[Subscription] /// impl Subscription { /// async fn values(&self) -> impl Stream<Item = i32> { /// stream::iter(vec![1, 2, 3, 4, 5]) /// } /// } /// /// type MySchema = Schema<Query, EmptyMutation, Subscription>; /// /// let schema = Schema::new(Query, EmptyMutation, Subscription); /// let app = Route::new().at("/ws", get(GraphQLSubscription::new(schema))); /// ``` pub struct GraphQLSubscription<Query, Mutation, Subscription, F> { schema: Schema<Query, Mutation, Subscription>, initializer: F, } impl<Query, Mutation, Subscription> GraphQLSubscription< Query, Mutation, Subscription, fn(serde_json::Value) -> Ready<async_graphql::Result<Data>>, > { /// Create a GraphQL subscription endpoint. pub fn new(schema: Schema<Query, Mutation, Subscription>) -> Self { Self { schema, initializer: |_| futures_util::future::ready(Ok(Default::default())), } } } impl<Query, Mutation, Subscription, F> GraphQLSubscription<Query, Mutation, Subscription, F> { /// With a data initialization function. pub fn with_initializer<F2, R>( self, initializer: F2, ) -> GraphQLSubscription<Query, Mutation, Subscription, F2> where F2: FnOnce(serde_json::Value) -> R + Clone + Send + Sync + 'static, R: Future<Output = Result<Data>> + Send + 'static, { GraphQLSubscription { schema: self.schema, initializer, } } } #[poem::async_trait] impl<Query, Mutation, Subscription, F, R> Endpoint for GraphQLSubscription<Query, Mutation, Subscription, F> where Query: ObjectType + 'static, Mutation: ObjectType + 'static, Subscription: SubscriptionType + 'static, F: FnOnce(serde_json::Value) -> R + Clone + Send + Sync + 'static, R: Future<Output = async_graphql::Result<Data>> + Send + 'static, { type Output = Result<Response>; async fn call(&self, req: Request) -> Self::Output { let (req, mut body) = req.split(); let websocket = WebSocket::from_request(&req, &mut body).await?; let protocol = req .headers() .get(http::header::SEC_WEBSOCKET_PROTOCOL) .and_then(|value| value.to_str().ok()) .and_then(|protocols| { protocols .split(',') .find_map(|p| WebSocketProtocols::from_str(p.trim()).ok()) }) .unwrap_or(WebSocketProtocols::SubscriptionsTransportWS); let schema = self.schema.clone(); let initializer = self.initializer.clone(); let resp = websocket .protocols(ALL_WEBSOCKET_PROTOCOLS) .on_upgrade(move |socket| async move { let (mut sink, stream) = socket.split(); let stream = stream .take_while(|res| future::ready(res.is_ok())) .map(Result::unwrap) .filter_map(|msg| { if msg.is_text() || msg.is_binary() { future::ready(Some(msg)) } else { future::ready(None) } }) .map(Message::into_bytes) .boxed(); let mut stream = async_graphql::http::WebSocket::with_data( schema, stream, initializer, protocol, ) .map(|msg| match msg { WsMessage::Text(text) => Message::text(text), WsMessage::Close(code, status) => Message::close_with(code, status), }); while let Some(item) = stream.next().await { let _ = sink.send(item).await; } }) .into_response(); Ok(resp) } }
use std::path::PathBuf; use std::io; mod data; mod index; mod test_utils; use self::data::*; use self::index::*; #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct Metadata { pub offset: u64, pub length: u32, pub hash: [u8; 32], } pub struct Storage { data: Data, index: Index, } impl Storage { // TODO: consider asRef here as the case in the std File::create pub fn new(dir: &PathBuf) -> io::Result<Self> { Ok(Self { data: Data::new(dir.join("rkv-data"))?, index: Index::new(dir.join("rkv-index"))?, }) } pub fn set(&mut self, val: &[u8]) -> io::Result<String> { let metadata = self.data.insert(val)?; self.index.insert(metadata) } pub fn get(&mut self, val: &[u8]) -> io::Result<Vec<u8>> { let mut array = [0u8; 32]; for (&x, p) in val.iter().zip(array.iter_mut()) { *p = x; } if let Some(r) = self.index.get(array) { return Ok(self.data.fetch(r)?); } else { return Err(io::Error::new(io::ErrorKind::Other, "Value is not found")); } } }
use side::{Side, BLACK}; use std::fmt; #[cfg(test)] use rand; pub type Internal = usize; /// Represents a square on the chessboard #[derive(PartialEq, PartialOrd, Copy, Clone)] pub struct Square(pub Internal); const NAMES: [&'static str; 64] = [ "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8", ]; #[allow(dead_code)] pub const A1: Square = Square(0); #[allow(dead_code)] pub const B1: Square = Square(1); #[allow(dead_code)] pub const C1: Square = Square(2); #[allow(dead_code)] pub const D1: Square = Square(3); #[allow(dead_code)] pub const E1: Square = Square(4); #[allow(dead_code)] pub const F1: Square = Square(5); #[allow(dead_code)] pub const G1: Square = Square(6); #[allow(dead_code)] pub const H1: Square = Square(7); #[allow(dead_code)] pub const A2: Square = Square(8); #[allow(dead_code)] pub const B2: Square = Square(9); #[allow(dead_code)] pub const C2: Square = Square(10); #[allow(dead_code)] pub const D2: Square = Square(11); #[allow(dead_code)] pub const E2: Square = Square(12); #[allow(dead_code)] pub const F2: Square = Square(13); #[allow(dead_code)] pub const G2: Square = Square(14); #[allow(dead_code)] pub const H2: Square = Square(15); #[allow(dead_code)] pub const A3: Square = Square(16); #[allow(dead_code)] pub const B3: Square = Square(17); #[allow(dead_code)] pub const C3: Square = Square(18); #[allow(dead_code)] pub const D3: Square = Square(19); #[allow(dead_code)] pub const E3: Square = Square(20); #[allow(dead_code)] pub const F3: Square = Square(21); #[allow(dead_code)] pub const G3: Square = Square(22); #[allow(dead_code)] pub const H3: Square = Square(23); #[allow(dead_code)] pub const A4: Square = Square(24); #[allow(dead_code)] pub const B4: Square = Square(25); #[allow(dead_code)] pub const C4: Square = Square(26); #[allow(dead_code)] pub const D4: Square = Square(27); #[allow(dead_code)] pub const E4: Square = Square(28); #[allow(dead_code)] pub const F4: Square = Square(29); #[allow(dead_code)] pub const G4: Square = Square(30); #[allow(dead_code)] pub const H4: Square = Square(31); #[allow(dead_code)] pub const A5: Square = Square(32); #[allow(dead_code)] pub const B5: Square = Square(33); #[allow(dead_code)] pub const C5: Square = Square(34); #[allow(dead_code)] pub const D5: Square = Square(35); #[allow(dead_code)] pub const E5: Square = Square(36); #[allow(dead_code)] pub const F5: Square = Square(37); #[allow(dead_code)] pub const G5: Square = Square(38); #[allow(dead_code)] pub const H5: Square = Square(39); #[allow(dead_code)] pub const A6: Square = Square(40); #[allow(dead_code)] pub const B6: Square = Square(41); #[allow(dead_code)] pub const C6: Square = Square(42); #[allow(dead_code)] pub const D6: Square = Square(43); #[allow(dead_code)] pub const E6: Square = Square(44); #[allow(dead_code)] pub const F6: Square = Square(45); #[allow(dead_code)] pub const G6: Square = Square(46); #[allow(dead_code)] pub const H6: Square = Square(47); #[allow(dead_code)] pub const A7: Square = Square(48); #[allow(dead_code)] pub const B7: Square = Square(49); #[allow(dead_code)] pub const C7: Square = Square(50); #[allow(dead_code)] pub const D7: Square = Square(51); #[allow(dead_code)] pub const E7: Square = Square(52); #[allow(dead_code)] pub const F7: Square = Square(53); #[allow(dead_code)] pub const G7: Square = Square(54); #[allow(dead_code)] pub const H7: Square = Square(55); #[allow(dead_code)] pub const A8: Square = Square(56); #[allow(dead_code)] pub const B8: Square = Square(57); #[allow(dead_code)] pub const C8: Square = Square(58); #[allow(dead_code)] pub const D8: Square = Square(59); #[allow(dead_code)] pub const E8: Square = Square(60); #[allow(dead_code)] pub const F8: Square = Square(61); #[allow(dead_code)] pub const G8: Square = Square(62); #[allow(dead_code)] pub const H8: Square = Square(63); impl Square { #[inline] pub fn new(s: Internal) -> Square { Square(s) } #[inline] pub const fn to_u8(&self) -> u8 { self.0 as u8 } #[inline] pub fn to_i32(&self) -> i32 { self.0 as i32 } #[inline] pub fn to_u32(&self) -> u32 { self.0 as u32 } #[inline] pub fn raw(&self) -> Internal { self.0 } #[inline] #[allow(dead_code)] pub fn diagonal(&self) -> usize { ((self.row() - self.col()) & 15) as usize } #[inline] #[allow(dead_code)] pub fn anti_diagonal(&self) -> usize { ((self.row() + self.col()) & 7) as usize } #[inline] pub fn inc(&mut self) { self.0 += 1 } #[inline] pub fn to_usize(&self) -> usize { self.0 as usize } // Gives square from perspective of side // ie, flips if black #[inline] pub fn from_side(&self, side: Side) -> Square { Square(self.0 ^ if side == BLACK { 56 } else { 0 }) } #[inline] pub fn flip(&self) -> Square { Square(self.0 ^ 56) } #[inline] pub fn rotate_right(&self, amount: Internal) -> Square { Square((self.0 + (64 - amount)) & 63) } #[inline] pub fn rotate_left(&self, amount: Internal) -> Square { Square((self.0 + amount) & 63) } pub fn to_str(&self) -> &'static str { NAMES[self.0 as usize] } pub fn to_string(&self) -> String { self.to_str().to_string() } #[inline] #[cfg(test)] pub fn random() -> Square { Square(rand::random::<Internal>() % 64) } // returns a square at the same row as self, and the same col as another square #[inline] pub fn along_row_with_col(&self, other: Square) -> Square { Square((self.0 & 56) | (other.0 & 7)) } #[inline] pub fn change_row(&self, row: Internal) -> Square { Square((self.0 & 7) | (row * 8)) } #[inline] pub fn row(&self) -> Internal { self.0 >> 3 } #[inline] pub fn rowx8(&self) -> Internal { self.0 & 56 } #[inline] pub fn col(&self) -> Internal { self.0 & 7 } #[inline] pub fn from(row: Internal, col: Internal) -> Square { Square(row * 8 + col) } pub fn parse(s: &str) -> Result<Option<Square>, String> { if s == "-" { return Ok(None); } if s.len() < 2 { return Err("String too short".to_string()); } let col_char = s.chars().nth(0).unwrap() as Internal; let row_char = s.chars().nth(1).unwrap() as Internal; let col = col_char - 'a' as Internal; let row = row_char - '1' as Internal; if col > 7 { return Err(format!("Bad column identifier: {}", col_char)); } if row > 7 { return Err(format!("Bad row identifier: {}", row_char)); } Ok(Some(Square::from(row, col))) } } impl fmt::Display for Square { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_string()) } } impl fmt::Debug for Square { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_string()) } } #[cfg(test)] mod test { use super::*; #[test] fn along_row_with_col() { assert_eq!(A5.along_row_with_col(B6), B5); } #[test] fn flip() { assert_eq!(H8.flip(), H1); assert_eq!(C3.flip(), C6); assert_eq!(B2.flip(), B7); } #[test] fn rotate_left() { assert_eq!(A1.rotate_left(1), B1); assert_eq!(H8.rotate_left(1), A1); assert_eq!(C3.rotate_left(16), C5); } #[test] fn raw() { assert_eq!(H8.raw(), 63); assert_eq!(B3.raw(), 17); } #[test] fn to_string() { assert_eq!(A1.to_string(), "a1"); assert_eq!(F8.to_string(), "f8"); } #[test] fn col() { assert_eq!(A2.col(), 0); assert_eq!(C6.col(), 2); } #[test] fn row() { assert_eq!(A2.row(), 1); assert_eq!(C6.row(), 5); } }
pub mod draw; pub mod profile; pub mod serdeflate;
pub use VkDebugReportErrorEXT::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkDebugReportErrorEXT { VK_DEBUG_REPORT_ERROR_NONE_EXT = 0, VK_DEBUG_REPORT_ERROR_CALLBACK_REF_EXT = 1, }
#![deny(warnings)] #![feature(abi_msp430_interrupt)] #![feature(proc_macro)] #![no_std] extern crate msp430; extern crate msp430g2553; #[macro_use(task)] extern crate msp430_rtfm as rtfm; use msp430::asm; use rtfm::app; app! { device: msp430g2553, tasks: { TIMER0_A1: { resources: [PORT_1_2, TIMER0_A3], }, }, } // This initialization function runs first and has full access to all the // resources (peripherals and data) // This function runs with interrupts disabled and *can't* be preempted fn init(p: init::Peripherals) { // Disable watchdog p.WATCHDOG_TIMER.wdtctl.write(|w| unsafe { const PASSWORD: u16 = 0x5A00; w.bits(PASSWORD).wdthold().set_bit() }); p.PORT_1_2 .p1dir .modify(|_, w| w.p0().set_bit().p6().set_bit()); p.PORT_1_2 .p1out .modify(|_, w| w.p0().set_bit().p6().clear_bit()); p.SYSTEM_CLOCK.bcsctl3.modify(|_, w| w.lfxt1s().lfxt1s_2()); p.SYSTEM_CLOCK.bcsctl1.modify(|_, w| w.diva().diva_1()); p.TIMER0_A3.ta0ccr0.write(|w| unsafe { w.bits(1200) }); p.TIMER0_A3 .ta0ctl .modify(|_, w| w.tassel().tassel_1().mc().mc_1()); p.TIMER0_A3.ta0cctl1.modify(|_, w| w.ccie().set_bit()); p.TIMER0_A3.ta0ccr1.write(|w| unsafe { w.bits(600) }); } // The idle function runs right after `init` // The interrupts are enabled at this point and `idle` and can be preempted fn idle() -> ! { loop { // NOTE it seems this infinite loop gets optimized to `undef` if the NOP // is removed asm::nop() } } task!(TIMER0_A1, periodic); // A task has access to the resources declared in the `rtfm!` macro fn periodic(r: TIMER0_A1::Resources) { r.TIMER0_A3.ta0cctl1.modify(|_, w| w.ccifg().clear_bit()); r.PORT_1_2 .p1out .modify(|r, w| w.p0().bit(!r.p0().bit()) .p6().bit(!r.p6().bit())); }
#![deny(rustdoc::broken_intra_doc_links, rustdoc::bare_urls, rust_2018_idioms)] #![warn( missing_copy_implementations, missing_debug_implementations, clippy::explicit_iter_loop, // See https://github.com/influxdata/influxdb_iox/pull/1671 clippy::future_not_send, clippy::clone_on_ref_ptr, clippy::todo, clippy::dbg_macro, unused_crate_dependencies )] // Workaround for "unused crate" lint false positives. #[cfg(test)] use once_cell as _; #[cfg(test)] use parking_lot as _; #[cfg(test)] use regex as _; use workspace_hack as _; use observability_deps::tracing::{ self, field::{Field, Visit}, subscriber::Interest, Id, Level, Subscriber, }; use std::borrow::Cow; use std::{io::Write, time::SystemTime}; use tracing_subscriber::{fmt::MakeWriter, layer::Context, registry::LookupSpan, Layer}; /// Implements a `tracing_subscriber::Layer` which generates /// [logfmt] formatted log entries, suitable for log ingestion /// /// At time of writing, I could find no good existing crate /// /// <https://github.com/mcountryman/logfmt_logger> from @mcountryman /// looked very small and did not (obviously) work with the tracing subscriber /// /// [logfmt]: https://brandur.org/logfmt #[derive(Debug)] pub struct LogFmtLayer<W> where W: for<'writer> MakeWriter<'writer>, { writer: W, display_target: bool, } impl<W> LogFmtLayer<W> where W: for<'writer> MakeWriter<'writer>, { /// Create a new logfmt Layer to pass into tracing_subscriber /// /// Note this layer simply formats and writes to the specified writer. It /// does not do any filtering for levels itself. Filtering can be done /// using a EnvFilter /// /// For example: /// ``` /// use logfmt::LogFmtLayer; /// use tracing_subscriber::{EnvFilter, prelude::*, self}; /// /// // setup debug logging level /// std::env::set_var("RUST_LOG", "debug"); /// /// // setup formatter to write to stderr /// let formatter = /// LogFmtLayer::new(std::io::stderr); /// /// tracing_subscriber::registry() /// .with(EnvFilter::from_default_env()) /// .with(formatter) /// .init(); /// ``` pub fn new(writer: W) -> Self { Self { writer, display_target: true, } } /// Control whether target and location attributes are displayed (on by default). /// /// Note: this API mimics that of other fmt layers in tracing-subscriber crate. pub fn with_target(self, display_target: bool) -> Self { Self { display_target, ..self } } } impl<S, W> Layer<S> for LogFmtLayer<W> where W: for<'writer> MakeWriter<'writer> + 'static, S: Subscriber + for<'a> LookupSpan<'a>, { fn register_callsite( &self, _metadata: &'static tracing::Metadata<'static>, ) -> tracing::subscriber::Interest { Interest::always() } fn on_new_span(&self, attrs: &tracing::span::Attributes<'_>, id: &Id, ctx: Context<'_, S>) { let writer = self.writer.make_writer(); let metadata = ctx.metadata(id).expect("span should have metadata"); let mut p = FieldPrinter::new(writer, metadata.level(), self.display_target); p.write_span_name(metadata.name()); attrs.record(&mut p); p.write_span_id(id); p.write_timestamp(); } fn max_level_hint(&self) -> Option<tracing::metadata::LevelFilter> { None } fn on_event(&self, event: &tracing::Event<'_>, ctx: Context<'_, S>) { let writer = self.writer.make_writer(); let mut p = FieldPrinter::new(writer, event.metadata().level(), self.display_target); // record fields event.record(&mut p); if let Some(span) = ctx.lookup_current() { p.write_span_id(&span.id()) } // record source information p.write_source_info(event); p.write_timestamp(); } } /// This thing is responsible for actually printing log information to /// a writer struct FieldPrinter<W: Write> { writer: W, display_target: bool, } impl<W: Write> FieldPrinter<W> { fn new(mut writer: W, level: &Level, display_target: bool) -> Self { let level_str = match *level { Level::TRACE => "trace", Level::DEBUG => "debug", Level::INFO => "info", Level::WARN => "warn", Level::ERROR => "error", }; write!(writer, r#"level={level_str}"#).ok(); Self { writer, display_target, } } fn write_span_name(&mut self, value: &str) { write!(self.writer, " span_name=\"{}\"", quote_and_escape(value)).ok(); } fn write_source_info(&mut self, event: &tracing::Event<'_>) { if !self.display_target { return; } let metadata = event.metadata(); write!( self.writer, " target=\"{}\"", quote_and_escape(metadata.target()) ) .ok(); if let Some(module_path) = metadata.module_path() { if metadata.target() != module_path { write!(self.writer, " module_path=\"{module_path}\"").ok(); } } if let (Some(file), Some(line)) = (metadata.file(), metadata.line()) { write!(self.writer, " location=\"{file}:{line}\"").ok(); } } fn write_span_id(&mut self, id: &Id) { write!(self.writer, " span={}", id.into_u64()).ok(); } fn write_timestamp(&mut self) { let ns_since_epoch = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .expect("System time should have been after the epoch") .as_nanos(); write!(self.writer, " time={ns_since_epoch:?}").ok(); } } impl<W: Write> Drop for FieldPrinter<W> { fn drop(&mut self) { // finish the log line writeln!(self.writer).ok(); } } impl<W: Write> Visit for FieldPrinter<W> { fn record_i64(&mut self, field: &Field, value: i64) { write!( self.writer, " {}={}", translate_field_name(field.name()), value ) .ok(); } fn record_u64(&mut self, field: &Field, value: u64) { write!( self.writer, " {}={}", translate_field_name(field.name()), value ) .ok(); } fn record_bool(&mut self, field: &Field, value: bool) { write!( self.writer, " {}={}", translate_field_name(field.name()), value ) .ok(); } fn record_str(&mut self, field: &Field, value: &str) { write!( self.writer, " {}={}", translate_field_name(field.name()), quote_and_escape(value) ) .ok(); } fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) { let field_name = translate_field_name(field.name()); let debug_formatted = format!("{value:?}"); write!( self.writer, " {}={:?}", field_name, quote_and_escape(&debug_formatted) ) .ok(); let display_formatted = format!("{value}"); write!( self.writer, " {}.display={}", field_name, quote_and_escape(&display_formatted) ) .ok(); } fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { // Note this appears to be invoked via `debug!` and `info! macros let formatted_value = format!("{value:?}"); write!( self.writer, " {}={}", translate_field_name(field.name()), quote_and_escape(&formatted_value) ) .ok(); } } /// return true if the string value already starts/ends with quotes and is /// already properly escaped (all spaces escaped) fn needs_quotes_and_escaping(value: &str) -> bool { // mismatches beginning / end quotes if value.starts_with('"') != value.ends_with('"') { return true; } // ignore beginning/ending quotes, if any let pre_quoted = value.len() >= 2 && value.starts_with('"') && value.ends_with('"'); let value = if pre_quoted { &value[1..value.len() - 1] } else { value }; // unescaped quotes let c0 = value.chars(); let c1 = value.chars().skip(1); if c0.zip(c1).any(|(c0, c1)| c0 != '\\' && c1 == '"') { return true; } // Quote any strings that contain a literal '=' which the logfmt parser // interprets as a key/value separator. if value.chars().any(|c| c == '=') && !pre_quoted { return true; } if value.bytes().any(|b| b <= b' ') && !pre_quoted { return true; } false } /// escape any characters in name as needed, otherwise return string as is fn quote_and_escape(value: &'_ str) -> Cow<'_, str> { if needs_quotes_and_escaping(value) { Cow::Owned(format!("{value:?}")) } else { Cow::Borrowed(value) } } // Translate the field name from tracing into the logfmt style fn translate_field_name(name: &str) -> &str { if name == "message" { "msg" } else { name } } #[cfg(test)] mod test { use super::*; #[test] fn quote_and_escape_len0() { assert_eq!(quote_and_escape(""), ""); } #[test] fn quote_and_escape_len1() { assert_eq!(quote_and_escape("f"), "f"); } #[test] fn quote_and_escape_len2() { assert_eq!(quote_and_escape("fo"), "fo"); } #[test] fn quote_and_escape_len3() { assert_eq!(quote_and_escape("foo"), "foo"); } #[test] fn quote_and_escape_len3_1quote_start() { assert_eq!(quote_and_escape("\"foo"), "\"\\\"foo\""); } #[test] fn quote_and_escape_len3_1quote_end() { assert_eq!(quote_and_escape("foo\""), "\"foo\\\"\""); } #[test] fn quote_and_escape_len3_2quote() { assert_eq!(quote_and_escape("\"foo\""), "\"foo\""); } #[test] fn quote_and_escape_space() { assert_eq!(quote_and_escape("foo bar"), "\"foo bar\""); } #[test] fn quote_and_escape_space_prequoted() { assert_eq!(quote_and_escape("\"foo bar\""), "\"foo bar\""); } #[test] fn quote_and_escape_space_prequoted_but_not_escaped() { assert_eq!(quote_and_escape("\"foo \"bar\""), "\"\\\"foo \\\"bar\\\"\""); } #[test] fn quote_and_escape_quoted_quotes() { assert_eq!(quote_and_escape("foo:\"bar\""), "\"foo:\\\"bar\\\"\""); } #[test] fn quote_and_escape_nested_1() { assert_eq!(quote_and_escape(r#"a "b" c"#), r#""a \"b\" c""#); } #[test] fn quote_and_escape_nested_2() { assert_eq!( quote_and_escape(r#"a "0 \"1\" 2" c"#), r#""a \"0 \\\"1\\\" 2\" c""# ); } #[test] fn quote_not_printable() { assert_eq!(quote_and_escape("foo\nbar"), r#""foo\nbar""#); assert_eq!(quote_and_escape("foo\r\nbar"), r#""foo\r\nbar""#); assert_eq!(quote_and_escape("foo\0bar"), r#""foo\0bar""#); } #[test] fn not_quote_unicode_unnecessarily() { assert_eq!(quote_and_escape("mikuličić"), "mikuličić"); } #[test] // https://github.com/influxdata/influxdb_iox/issues/4352 fn test_uri_quoted() { assert_eq!(quote_and_escape("/api/v2/write?bucket=06fddb4f912a0d7f&org=9df0256628d1f506&orgID=9df0256628d1f506&precision=ns"), r#""/api/v2/write?bucket=06fddb4f912a0d7f&org=9df0256628d1f506&orgID=9df0256628d1f506&precision=ns""#); } }
use test_deps::deps; use tokio::time::{self, Duration}; static mut COUNTER_RET_RESULT: usize = 0; #[deps(RET_RESULT_000)] #[tokio::test] async fn tokio_ret_result_000() -> Result<(), ()> { time::sleep(Duration::from_secs_f64(0.1)).await; unsafe { assert_eq!(0, COUNTER_RET_RESULT); COUNTER_RET_RESULT = COUNTER_RET_RESULT + 1; } Ok(()) } #[deps(RET_RESULT_001: RET_RESULT_000)] #[tokio::test] async fn tokio_ret_result_001() -> Result<(), ()> { time::sleep(Duration::from_secs_f64(0.05)).await; unsafe { assert_eq!(1, COUNTER_RET_RESULT); COUNTER_RET_RESULT = COUNTER_RET_RESULT + 1; } Ok(()) } #[deps(RET_RESULT_002: RET_RESULT_001)] #[tokio::test] async fn tokio_ret_result_002() -> Result<(), ()> { time::sleep(Duration::from_secs_f64(0.025)).await; unsafe { assert_eq!(2, COUNTER_RET_RESULT); COUNTER_RET_RESULT = COUNTER_RET_RESULT + 1; } Ok(()) } static mut COUNTER_MT_RUNTIME: usize = 0; #[deps(MT_RUNTIME_000)] #[tokio::test(flavor = "multi_thread", worker_threads = 8)] async fn tokio_mt_runtime_000() { time::sleep(Duration::from_secs_f64(0.1)).await; unsafe { assert_eq!(0, COUNTER_MT_RUNTIME); COUNTER_MT_RUNTIME = COUNTER_MT_RUNTIME + 1; } } #[deps(MT_RUNTIME_001: MT_RUNTIME_000)] #[tokio::test(flavor = "multi_thread", worker_threads = 8)] async fn tokio_mt_runtime_001() { time::sleep(Duration::from_secs_f64(0.05)).await; unsafe { assert_eq!(1, COUNTER_MT_RUNTIME); COUNTER_MT_RUNTIME = COUNTER_MT_RUNTIME + 1; } } #[deps(MT_RUNTIME_002: MT_RUNTIME_001)] #[tokio::test(flavor = "multi_thread", worker_threads = 8)] async fn tokio_mt_runtime_002() { time::sleep(Duration::from_secs_f64(0.025)).await; unsafe { assert_eq!(2, COUNTER_MT_RUNTIME); COUNTER_MT_RUNTIME = COUNTER_MT_RUNTIME + 1; } }
use std::env; use std::io; use std::io::BufRead; fn main() { let input: String = match env::args().nth(1) { None => { eprintln!("Usage: {} [input_string | -]", env::args().nth(0).unwrap()); eprintln!("If - is given as argument, read from stdin."); std::process::exit(0); }, Some(input) => input, }; if "-".eq(&input) { let stdin = io::stdin(); let handle = stdin.lock(); handle.lines().for_each(|line_res| { match line_res { Ok(line) => run_compute(&line), Err(err) => eprintln!("Could not read input: {}", err), } }); } else { run_compute(&input) } } fn run_compute(input: &str) { let result = compute(&input); match result { Ok(result) => println!("{}", result), Err(err) => eprintln!("Error: {}", err), } } fn compute(input: &str) -> Result<u32, String> { // operating on bytes because we need digits '0'..'9' only let len = input.len(); let mut next_it = input.bytes().enumerate().cycle().skip(len / 2); let mut sum = 0; for (pos, b) in input.bytes().enumerate() { let cur = to_digit(b, pos)?; let (pos_next, b_next) = next_it.next().unwrap(); let next = to_digit(b_next, pos_next)?; if cur == next { sum += cur; } } Ok(sum) } fn to_digit(b: u8, pos: usize) -> Result<u32, String> { if b < b'0' || b > b'9' { return Err(format!("unexpected input at character position {}", pos)); } Ok((b - b'0') as u32) } #[cfg(test)] mod tests { use super::*; #[test] fn it_works_1() { assert_eq!(Ok(6), compute("1212")); } #[test] fn it_works_2() { assert_eq!(Ok(0), compute("1221")); } #[test] fn it_works_3() { assert_eq!(Ok(4), compute("123425")); } #[test] fn it_works_4() { assert_eq!(Ok(12), compute("123123")); } #[test] fn it_works_5() { assert_eq!(Ok(4), compute("12131415")); } #[test] fn illegal_input() { assert!(compute("x1234").is_err()); assert!(compute("Hello").is_err()); assert!(compute("1234foo").is_err()); } }
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #![allow(non_snake_case)] extern crate astro; use astro::*; #[test] fn nutation() { let (nut_in_long, nut_in_oblq) = nutation::nutation(2446895.5); let (d1, m1, s1) = angle::dms_frm_deg(nut_in_long.to_degrees()); assert_eq!((d1, m1, util::round_upto_digits(s1, 3)), (0, 0, -3.788)); let (d2, m2, s2) = angle::dms_frm_deg(nut_in_oblq.to_degrees()); assert_eq!((d2, m2, util::round_upto_digits(s2, 3)), (0, 0, 9.443)); } #[test] fn nutation_in_eq_coords() { let eq_point = coords::EqPoint { asc: 41.5555635_f64.to_radians(), dec: 49.3503415_f64.to_radians() }; let (a, b) = nutation::nutation_in_eq_coords( &eq_point, angle::deg_frm_dms(0, 0, 14.861).to_radians(), angle::deg_frm_dms(0, 0, 2.705).to_radians(), 23.436_f64.to_radians() ); assert_eq!(util::round_upto_digits(a.to_degrees(), 7), 0.0044011); assert_eq!(util::round_upto_digits(b.to_degrees(), 7), 0.001727); }
// Copyright (c) 2020 zenoxygen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. extern crate clap; use clap::{App, Arg}; /// Parse arguments. pub fn parse_args<'a>() -> clap::ArgMatches<'a> { let args_conflicts = ["file"]; App::new("roof") .version("0.6.0") .about("A minimalist, fast and reliable utility to share files.") .author("zenoxygen <zenoxygen@protonmail.com>") .arg( Arg::with_name("file") .help("The file/directory to serve or the URL to download from") .required_unless("serve") .number_of_values(1), ) .arg( Arg::with_name("count") .short("c") .long("count") .help("How many times the file/directory will be served") .number_of_values(1) .default_value("1"), ) .arg( Arg::with_name("ip_addr") .short("i") .long("ip_addr") .help("The address to serve the file/directory from") .number_of_values(1) .default_value("127.0.0.1"), ) .arg( Arg::with_name("port") .short("p") .long("port") .help("The port to serve the file/directory from") .number_of_values(1) .default_value("8080"), ) .arg( Arg::with_name("serve") .short("s") .long("serve") .help("When specified, roof will serve itself") .conflicts_with_all(&args_conflicts) .empty_values(true), ) .get_matches() }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GuidanceAudioMeasurementSystem(pub i32); impl GuidanceAudioMeasurementSystem { pub const Meters: GuidanceAudioMeasurementSystem = GuidanceAudioMeasurementSystem(0i32); pub const MilesAndYards: GuidanceAudioMeasurementSystem = GuidanceAudioMeasurementSystem(1i32); pub const MilesAndFeet: GuidanceAudioMeasurementSystem = GuidanceAudioMeasurementSystem(2i32); } impl ::core::convert::From<i32> for GuidanceAudioMeasurementSystem { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GuidanceAudioMeasurementSystem { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GuidanceAudioMeasurementSystem { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.Guidance.GuidanceAudioMeasurementSystem;i4)"); } impl ::windows::core::DefaultType for GuidanceAudioMeasurementSystem { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GuidanceAudioNotificationKind(pub i32); impl GuidanceAudioNotificationKind { pub const Maneuver: GuidanceAudioNotificationKind = GuidanceAudioNotificationKind(0i32); pub const Route: GuidanceAudioNotificationKind = GuidanceAudioNotificationKind(1i32); pub const Gps: GuidanceAudioNotificationKind = GuidanceAudioNotificationKind(2i32); pub const SpeedLimit: GuidanceAudioNotificationKind = GuidanceAudioNotificationKind(3i32); pub const Traffic: GuidanceAudioNotificationKind = GuidanceAudioNotificationKind(4i32); pub const TrafficCamera: GuidanceAudioNotificationKind = GuidanceAudioNotificationKind(5i32); } impl ::core::convert::From<i32> for GuidanceAudioNotificationKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GuidanceAudioNotificationKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GuidanceAudioNotificationKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.Guidance.GuidanceAudioNotificationKind;i4)"); } impl ::windows::core::DefaultType for GuidanceAudioNotificationKind { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceAudioNotificationRequestedEventArgs(pub ::windows::core::IInspectable); impl GuidanceAudioNotificationRequestedEventArgs { pub fn AudioNotification(&self) -> ::windows::core::Result<GuidanceAudioNotificationKind> { let this = self; unsafe { let mut result__: GuidanceAudioNotificationKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceAudioNotificationKind>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn AudioFilePaths(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } pub fn AudioText(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for GuidanceAudioNotificationRequestedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceAudioNotificationRequestedEventArgs;{ca2aa24a-c7c2-4d4c-9d7c-499576bceddb})"); } unsafe impl ::windows::core::Interface for GuidanceAudioNotificationRequestedEventArgs { type Vtable = IGuidanceAudioNotificationRequestedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca2aa24a_c7c2_4d4c_9d7c_499576bceddb); } impl ::windows::core::RuntimeName for GuidanceAudioNotificationRequestedEventArgs { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceAudioNotificationRequestedEventArgs"; } impl ::core::convert::From<GuidanceAudioNotificationRequestedEventArgs> for ::windows::core::IUnknown { fn from(value: GuidanceAudioNotificationRequestedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceAudioNotificationRequestedEventArgs> for ::windows::core::IUnknown { fn from(value: &GuidanceAudioNotificationRequestedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceAudioNotificationRequestedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceAudioNotificationRequestedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceAudioNotificationRequestedEventArgs> for ::windows::core::IInspectable { fn from(value: GuidanceAudioNotificationRequestedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&GuidanceAudioNotificationRequestedEventArgs> for ::windows::core::IInspectable { fn from(value: &GuidanceAudioNotificationRequestedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceAudioNotificationRequestedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceAudioNotificationRequestedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceAudioNotificationRequestedEventArgs {} unsafe impl ::core::marker::Sync for GuidanceAudioNotificationRequestedEventArgs {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GuidanceAudioNotifications(pub u32); impl GuidanceAudioNotifications { pub const None: GuidanceAudioNotifications = GuidanceAudioNotifications(0u32); pub const Maneuver: GuidanceAudioNotifications = GuidanceAudioNotifications(1u32); pub const Route: GuidanceAudioNotifications = GuidanceAudioNotifications(2u32); pub const Gps: GuidanceAudioNotifications = GuidanceAudioNotifications(4u32); pub const SpeedLimit: GuidanceAudioNotifications = GuidanceAudioNotifications(8u32); pub const Traffic: GuidanceAudioNotifications = GuidanceAudioNotifications(16u32); pub const TrafficCamera: GuidanceAudioNotifications = GuidanceAudioNotifications(32u32); } impl ::core::convert::From<u32> for GuidanceAudioNotifications { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GuidanceAudioNotifications { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GuidanceAudioNotifications { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.Guidance.GuidanceAudioNotifications;u4)"); } impl ::windows::core::DefaultType for GuidanceAudioNotifications { type DefaultType = Self; } impl ::core::ops::BitOr for GuidanceAudioNotifications { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for GuidanceAudioNotifications { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for GuidanceAudioNotifications { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for GuidanceAudioNotifications { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for GuidanceAudioNotifications { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceLaneInfo(pub ::windows::core::IInspectable); impl GuidanceLaneInfo { pub fn LaneMarkers(&self) -> ::windows::core::Result<GuidanceLaneMarkers> { let this = self; unsafe { let mut result__: GuidanceLaneMarkers = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceLaneMarkers>(result__) } } pub fn IsOnRoute(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for GuidanceLaneInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceLaneInfo;{8404d114-6581-43b7-ac15-c9079bf90df1})"); } unsafe impl ::windows::core::Interface for GuidanceLaneInfo { type Vtable = IGuidanceLaneInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8404d114_6581_43b7_ac15_c9079bf90df1); } impl ::windows::core::RuntimeName for GuidanceLaneInfo { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceLaneInfo"; } impl ::core::convert::From<GuidanceLaneInfo> for ::windows::core::IUnknown { fn from(value: GuidanceLaneInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceLaneInfo> for ::windows::core::IUnknown { fn from(value: &GuidanceLaneInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceLaneInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceLaneInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceLaneInfo> for ::windows::core::IInspectable { fn from(value: GuidanceLaneInfo) -> Self { value.0 } } impl ::core::convert::From<&GuidanceLaneInfo> for ::windows::core::IInspectable { fn from(value: &GuidanceLaneInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceLaneInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceLaneInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceLaneInfo {} unsafe impl ::core::marker::Sync for GuidanceLaneInfo {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GuidanceLaneMarkers(pub u32); impl GuidanceLaneMarkers { pub const None: GuidanceLaneMarkers = GuidanceLaneMarkers(0u32); pub const LightRight: GuidanceLaneMarkers = GuidanceLaneMarkers(1u32); pub const Right: GuidanceLaneMarkers = GuidanceLaneMarkers(2u32); pub const HardRight: GuidanceLaneMarkers = GuidanceLaneMarkers(4u32); pub const Straight: GuidanceLaneMarkers = GuidanceLaneMarkers(8u32); pub const UTurnLeft: GuidanceLaneMarkers = GuidanceLaneMarkers(16u32); pub const HardLeft: GuidanceLaneMarkers = GuidanceLaneMarkers(32u32); pub const Left: GuidanceLaneMarkers = GuidanceLaneMarkers(64u32); pub const LightLeft: GuidanceLaneMarkers = GuidanceLaneMarkers(128u32); pub const UTurnRight: GuidanceLaneMarkers = GuidanceLaneMarkers(256u32); pub const Unknown: GuidanceLaneMarkers = GuidanceLaneMarkers(4294967295u32); } impl ::core::convert::From<u32> for GuidanceLaneMarkers { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GuidanceLaneMarkers { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GuidanceLaneMarkers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.Guidance.GuidanceLaneMarkers;u4)"); } impl ::windows::core::DefaultType for GuidanceLaneMarkers { type DefaultType = Self; } impl ::core::ops::BitOr for GuidanceLaneMarkers { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for GuidanceLaneMarkers { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for GuidanceLaneMarkers { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for GuidanceLaneMarkers { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for GuidanceLaneMarkers { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceManeuver(pub ::windows::core::IInspectable); impl GuidanceManeuver { #[cfg(feature = "Devices_Geolocation")] pub fn StartLocation(&self) -> ::windows::core::Result<super::super::super::Devices::Geolocation::Geopoint> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Devices::Geolocation::Geopoint>(result__) } } pub fn DistanceFromRouteStart(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn DistanceFromPreviousManeuver(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn DepartureRoadName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn NextRoadName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn DepartureShortRoadName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn NextShortRoadName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Kind(&self) -> ::windows::core::Result<GuidanceManeuverKind> { let this = self; unsafe { let mut result__: GuidanceManeuverKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceManeuverKind>(result__) } } pub fn StartAngle(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn EndAngle(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn RoadSignpost(&self) -> ::windows::core::Result<GuidanceRoadSignpost> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceRoadSignpost>(result__) } } pub fn InstructionText(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for GuidanceManeuver { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceManeuver;{fc09326c-ecc9-4928-a2a1-7232b99b94a1})"); } unsafe impl ::windows::core::Interface for GuidanceManeuver { type Vtable = IGuidanceManeuver_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfc09326c_ecc9_4928_a2a1_7232b99b94a1); } impl ::windows::core::RuntimeName for GuidanceManeuver { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceManeuver"; } impl ::core::convert::From<GuidanceManeuver> for ::windows::core::IUnknown { fn from(value: GuidanceManeuver) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceManeuver> for ::windows::core::IUnknown { fn from(value: &GuidanceManeuver) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceManeuver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceManeuver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceManeuver> for ::windows::core::IInspectable { fn from(value: GuidanceManeuver) -> Self { value.0 } } impl ::core::convert::From<&GuidanceManeuver> for ::windows::core::IInspectable { fn from(value: &GuidanceManeuver) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceManeuver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceManeuver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceManeuver {} unsafe impl ::core::marker::Sync for GuidanceManeuver {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GuidanceManeuverKind(pub i32); impl GuidanceManeuverKind { pub const None: GuidanceManeuverKind = GuidanceManeuverKind(0i32); pub const GoStraight: GuidanceManeuverKind = GuidanceManeuverKind(1i32); pub const UTurnRight: GuidanceManeuverKind = GuidanceManeuverKind(2i32); pub const UTurnLeft: GuidanceManeuverKind = GuidanceManeuverKind(3i32); pub const TurnKeepRight: GuidanceManeuverKind = GuidanceManeuverKind(4i32); pub const TurnLightRight: GuidanceManeuverKind = GuidanceManeuverKind(5i32); pub const TurnRight: GuidanceManeuverKind = GuidanceManeuverKind(6i32); pub const TurnHardRight: GuidanceManeuverKind = GuidanceManeuverKind(7i32); pub const KeepMiddle: GuidanceManeuverKind = GuidanceManeuverKind(8i32); pub const TurnKeepLeft: GuidanceManeuverKind = GuidanceManeuverKind(9i32); pub const TurnLightLeft: GuidanceManeuverKind = GuidanceManeuverKind(10i32); pub const TurnLeft: GuidanceManeuverKind = GuidanceManeuverKind(11i32); pub const TurnHardLeft: GuidanceManeuverKind = GuidanceManeuverKind(12i32); pub const FreewayEnterRight: GuidanceManeuverKind = GuidanceManeuverKind(13i32); pub const FreewayEnterLeft: GuidanceManeuverKind = GuidanceManeuverKind(14i32); pub const FreewayLeaveRight: GuidanceManeuverKind = GuidanceManeuverKind(15i32); pub const FreewayLeaveLeft: GuidanceManeuverKind = GuidanceManeuverKind(16i32); pub const FreewayKeepRight: GuidanceManeuverKind = GuidanceManeuverKind(17i32); pub const FreewayKeepLeft: GuidanceManeuverKind = GuidanceManeuverKind(18i32); pub const TrafficCircleRight1: GuidanceManeuverKind = GuidanceManeuverKind(19i32); pub const TrafficCircleRight2: GuidanceManeuverKind = GuidanceManeuverKind(20i32); pub const TrafficCircleRight3: GuidanceManeuverKind = GuidanceManeuverKind(21i32); pub const TrafficCircleRight4: GuidanceManeuverKind = GuidanceManeuverKind(22i32); pub const TrafficCircleRight5: GuidanceManeuverKind = GuidanceManeuverKind(23i32); pub const TrafficCircleRight6: GuidanceManeuverKind = GuidanceManeuverKind(24i32); pub const TrafficCircleRight7: GuidanceManeuverKind = GuidanceManeuverKind(25i32); pub const TrafficCircleRight8: GuidanceManeuverKind = GuidanceManeuverKind(26i32); pub const TrafficCircleRight9: GuidanceManeuverKind = GuidanceManeuverKind(27i32); pub const TrafficCircleRight10: GuidanceManeuverKind = GuidanceManeuverKind(28i32); pub const TrafficCircleRight11: GuidanceManeuverKind = GuidanceManeuverKind(29i32); pub const TrafficCircleRight12: GuidanceManeuverKind = GuidanceManeuverKind(30i32); pub const TrafficCircleLeft1: GuidanceManeuverKind = GuidanceManeuverKind(31i32); pub const TrafficCircleLeft2: GuidanceManeuverKind = GuidanceManeuverKind(32i32); pub const TrafficCircleLeft3: GuidanceManeuverKind = GuidanceManeuverKind(33i32); pub const TrafficCircleLeft4: GuidanceManeuverKind = GuidanceManeuverKind(34i32); pub const TrafficCircleLeft5: GuidanceManeuverKind = GuidanceManeuverKind(35i32); pub const TrafficCircleLeft6: GuidanceManeuverKind = GuidanceManeuverKind(36i32); pub const TrafficCircleLeft7: GuidanceManeuverKind = GuidanceManeuverKind(37i32); pub const TrafficCircleLeft8: GuidanceManeuverKind = GuidanceManeuverKind(38i32); pub const TrafficCircleLeft9: GuidanceManeuverKind = GuidanceManeuverKind(39i32); pub const TrafficCircleLeft10: GuidanceManeuverKind = GuidanceManeuverKind(40i32); pub const TrafficCircleLeft11: GuidanceManeuverKind = GuidanceManeuverKind(41i32); pub const TrafficCircleLeft12: GuidanceManeuverKind = GuidanceManeuverKind(42i32); pub const Start: GuidanceManeuverKind = GuidanceManeuverKind(43i32); pub const End: GuidanceManeuverKind = GuidanceManeuverKind(44i32); pub const TakeFerry: GuidanceManeuverKind = GuidanceManeuverKind(45i32); pub const PassTransitStation: GuidanceManeuverKind = GuidanceManeuverKind(46i32); pub const LeaveTransitStation: GuidanceManeuverKind = GuidanceManeuverKind(47i32); } impl ::core::convert::From<i32> for GuidanceManeuverKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GuidanceManeuverKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GuidanceManeuverKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.Guidance.GuidanceManeuverKind;i4)"); } impl ::windows::core::DefaultType for GuidanceManeuverKind { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceMapMatchedCoordinate(pub ::windows::core::IInspectable); impl GuidanceMapMatchedCoordinate { #[cfg(feature = "Devices_Geolocation")] pub fn Location(&self) -> ::windows::core::Result<super::super::super::Devices::Geolocation::Geopoint> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Devices::Geolocation::Geopoint>(result__) } } pub fn CurrentHeading(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn CurrentSpeed(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn IsOnStreet(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn Road(&self) -> ::windows::core::Result<GuidanceRoadSegment> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceRoadSegment>(result__) } } } unsafe impl ::windows::core::RuntimeType for GuidanceMapMatchedCoordinate { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceMapMatchedCoordinate;{b7acb168-2912-4a99-aff1-798609b981fe})"); } unsafe impl ::windows::core::Interface for GuidanceMapMatchedCoordinate { type Vtable = IGuidanceMapMatchedCoordinate_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb7acb168_2912_4a99_aff1_798609b981fe); } impl ::windows::core::RuntimeName for GuidanceMapMatchedCoordinate { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceMapMatchedCoordinate"; } impl ::core::convert::From<GuidanceMapMatchedCoordinate> for ::windows::core::IUnknown { fn from(value: GuidanceMapMatchedCoordinate) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceMapMatchedCoordinate> for ::windows::core::IUnknown { fn from(value: &GuidanceMapMatchedCoordinate) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceMapMatchedCoordinate { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceMapMatchedCoordinate { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceMapMatchedCoordinate> for ::windows::core::IInspectable { fn from(value: GuidanceMapMatchedCoordinate) -> Self { value.0 } } impl ::core::convert::From<&GuidanceMapMatchedCoordinate> for ::windows::core::IInspectable { fn from(value: &GuidanceMapMatchedCoordinate) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceMapMatchedCoordinate { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceMapMatchedCoordinate { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceMapMatchedCoordinate {} unsafe impl ::core::marker::Sync for GuidanceMapMatchedCoordinate {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GuidanceMode(pub i32); impl GuidanceMode { pub const None: GuidanceMode = GuidanceMode(0i32); pub const Simulation: GuidanceMode = GuidanceMode(1i32); pub const Navigation: GuidanceMode = GuidanceMode(2i32); pub const Tracking: GuidanceMode = GuidanceMode(3i32); } impl ::core::convert::From<i32> for GuidanceMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GuidanceMode { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GuidanceMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.Guidance.GuidanceMode;i4)"); } impl ::windows::core::DefaultType for GuidanceMode { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceNavigator(pub ::windows::core::IInspectable); impl GuidanceNavigator { pub fn StartNavigating<'a, Param0: ::windows::core::IntoParam<'a, GuidanceRoute>>(&self, route: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), route.into_param().abi()).ok() } } pub fn StartSimulating<'a, Param0: ::windows::core::IntoParam<'a, GuidanceRoute>>(&self, route: Param0, speedinmeterspersecond: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), route.into_param().abi(), speedinmeterspersecond).ok() } } pub fn StartTracking(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() } } pub fn Pause(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() } } pub fn Resume(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() } } pub fn Stop(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() } } pub fn RepeatLastAudioNotification(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() } } pub fn AudioMeasurementSystem(&self) -> ::windows::core::Result<GuidanceAudioMeasurementSystem> { let this = self; unsafe { let mut result__: GuidanceAudioMeasurementSystem = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceAudioMeasurementSystem>(result__) } } pub fn SetAudioMeasurementSystem(&self, value: GuidanceAudioMeasurementSystem) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value).ok() } } pub fn AudioNotifications(&self) -> ::windows::core::Result<GuidanceAudioNotifications> { let this = self; unsafe { let mut result__: GuidanceAudioNotifications = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceAudioNotifications>(result__) } } pub fn SetAudioNotifications(&self, value: GuidanceAudioNotifications) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn GuidanceUpdated<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<GuidanceNavigator, GuidanceUpdatedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveGuidanceUpdated<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn DestinationReached<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<GuidanceNavigator, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveDestinationReached<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn Rerouting<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<GuidanceNavigator, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveRerouting<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn Rerouted<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<GuidanceNavigator, GuidanceReroutedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveRerouted<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn RerouteFailed<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<GuidanceNavigator, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveRerouteFailed<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn UserLocationLost<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<GuidanceNavigator, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveUserLocationLost<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn UserLocationRestored<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<GuidanceNavigator, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveUserLocationRestored<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn SetGuidanceVoice<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, voiceid: i32, voicefolder: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), voiceid, voicefolder.into_param().abi()).ok() } } #[cfg(feature = "Devices_Geolocation")] pub fn UpdateUserLocation<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Devices::Geolocation::Geocoordinate>>(&self, userlocation: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), userlocation.into_param().abi()).ok() } } #[cfg(feature = "Devices_Geolocation")] pub fn UpdateUserLocationWithPositionOverride<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Devices::Geolocation::Geocoordinate>, Param1: ::windows::core::IntoParam<'a, super::super::super::Devices::Geolocation::BasicGeoposition>>(&self, userlocation: Param0, positionoverride: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), userlocation.into_param().abi(), positionoverride.into_param().abi()).ok() } } pub fn GetCurrent() -> ::windows::core::Result<GuidanceNavigator> { Self::IGuidanceNavigatorStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceNavigator>(result__) }) } #[cfg(feature = "Foundation")] pub fn AudioNotificationRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<GuidanceNavigator, GuidanceAudioNotificationRequestedEventArgs>>>(&self, value: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = &::windows::core::Interface::cast::<IGuidanceNavigator2>(self)?; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveAudioNotificationRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IGuidanceNavigator2>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn IsGuidanceAudioMuted(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IGuidanceNavigator2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIsGuidanceAudioMuted(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IGuidanceNavigator2>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } pub fn UseAppProvidedVoice() -> ::windows::core::Result<bool> { Self::IGuidanceNavigatorStatics2(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) }) } pub fn IGuidanceNavigatorStatics<R, F: FnOnce(&IGuidanceNavigatorStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<GuidanceNavigator, IGuidanceNavigatorStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IGuidanceNavigatorStatics2<R, F: FnOnce(&IGuidanceNavigatorStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<GuidanceNavigator, IGuidanceNavigatorStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for GuidanceNavigator { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceNavigator;{08f17ef7-8e3f-4d9a-be8a-108f9a012c67})"); } unsafe impl ::windows::core::Interface for GuidanceNavigator { type Vtable = IGuidanceNavigator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08f17ef7_8e3f_4d9a_be8a_108f9a012c67); } impl ::windows::core::RuntimeName for GuidanceNavigator { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceNavigator"; } impl ::core::convert::From<GuidanceNavigator> for ::windows::core::IUnknown { fn from(value: GuidanceNavigator) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceNavigator> for ::windows::core::IUnknown { fn from(value: &GuidanceNavigator) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceNavigator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceNavigator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceNavigator> for ::windows::core::IInspectable { fn from(value: GuidanceNavigator) -> Self { value.0 } } impl ::core::convert::From<&GuidanceNavigator> for ::windows::core::IInspectable { fn from(value: &GuidanceNavigator) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceNavigator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceNavigator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceNavigator {} unsafe impl ::core::marker::Sync for GuidanceNavigator {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceReroutedEventArgs(pub ::windows::core::IInspectable); impl GuidanceReroutedEventArgs { pub fn Route(&self) -> ::windows::core::Result<GuidanceRoute> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceRoute>(result__) } } } unsafe impl ::windows::core::RuntimeType for GuidanceReroutedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceReroutedEventArgs;{115d4008-d528-454e-bb94-a50341d2c9f1})"); } unsafe impl ::windows::core::Interface for GuidanceReroutedEventArgs { type Vtable = IGuidanceReroutedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x115d4008_d528_454e_bb94_a50341d2c9f1); } impl ::windows::core::RuntimeName for GuidanceReroutedEventArgs { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceReroutedEventArgs"; } impl ::core::convert::From<GuidanceReroutedEventArgs> for ::windows::core::IUnknown { fn from(value: GuidanceReroutedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceReroutedEventArgs> for ::windows::core::IUnknown { fn from(value: &GuidanceReroutedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceReroutedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceReroutedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceReroutedEventArgs> for ::windows::core::IInspectable { fn from(value: GuidanceReroutedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&GuidanceReroutedEventArgs> for ::windows::core::IInspectable { fn from(value: &GuidanceReroutedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceReroutedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceReroutedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceReroutedEventArgs {} unsafe impl ::core::marker::Sync for GuidanceReroutedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceRoadSegment(pub ::windows::core::IInspectable); impl GuidanceRoadSegment { pub fn RoadName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn ShortRoadName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SpeedLimit(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } #[cfg(feature = "Foundation")] pub fn TravelTime(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Devices_Geolocation")] pub fn Path(&self) -> ::windows::core::Result<super::super::super::Devices::Geolocation::Geopath> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Devices::Geolocation::Geopath>(result__) } } pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn IsHighway(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsTunnel(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsTollRoad(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsScenic(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IGuidanceRoadSegment2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for GuidanceRoadSegment { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceRoadSegment;{b32758a6-be78-4c63-afe7-6c2957479b3e})"); } unsafe impl ::windows::core::Interface for GuidanceRoadSegment { type Vtable = IGuidanceRoadSegment_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb32758a6_be78_4c63_afe7_6c2957479b3e); } impl ::windows::core::RuntimeName for GuidanceRoadSegment { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceRoadSegment"; } impl ::core::convert::From<GuidanceRoadSegment> for ::windows::core::IUnknown { fn from(value: GuidanceRoadSegment) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceRoadSegment> for ::windows::core::IUnknown { fn from(value: &GuidanceRoadSegment) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceRoadSegment { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceRoadSegment { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceRoadSegment> for ::windows::core::IInspectable { fn from(value: GuidanceRoadSegment) -> Self { value.0 } } impl ::core::convert::From<&GuidanceRoadSegment> for ::windows::core::IInspectable { fn from(value: &GuidanceRoadSegment) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceRoadSegment { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceRoadSegment { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceRoadSegment {} unsafe impl ::core::marker::Sync for GuidanceRoadSegment {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceRoadSignpost(pub ::windows::core::IInspectable); impl GuidanceRoadSignpost { pub fn ExitNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Exit(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "UI")] pub fn BackgroundColor(&self) -> ::windows::core::Result<super::super::super::UI::Color> { let this = self; unsafe { let mut result__: super::super::super::UI::Color = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::UI::Color>(result__) } } #[cfg(feature = "UI")] pub fn ForegroundColor(&self) -> ::windows::core::Result<super::super::super::UI::Color> { let this = self; unsafe { let mut result__: super::super::super::UI::Color = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::UI::Color>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn ExitDirections(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } } unsafe impl ::windows::core::RuntimeType for GuidanceRoadSignpost { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceRoadSignpost;{f1a728b6-f77a-4742-8312-53300f9845f0})"); } unsafe impl ::windows::core::Interface for GuidanceRoadSignpost { type Vtable = IGuidanceRoadSignpost_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf1a728b6_f77a_4742_8312_53300f9845f0); } impl ::windows::core::RuntimeName for GuidanceRoadSignpost { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceRoadSignpost"; } impl ::core::convert::From<GuidanceRoadSignpost> for ::windows::core::IUnknown { fn from(value: GuidanceRoadSignpost) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceRoadSignpost> for ::windows::core::IUnknown { fn from(value: &GuidanceRoadSignpost) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceRoadSignpost { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceRoadSignpost { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceRoadSignpost> for ::windows::core::IInspectable { fn from(value: GuidanceRoadSignpost) -> Self { value.0 } } impl ::core::convert::From<&GuidanceRoadSignpost> for ::windows::core::IInspectable { fn from(value: &GuidanceRoadSignpost) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceRoadSignpost { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceRoadSignpost { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceRoadSignpost {} unsafe impl ::core::marker::Sync for GuidanceRoadSignpost {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceRoute(pub ::windows::core::IInspectable); impl GuidanceRoute { #[cfg(feature = "Foundation")] pub fn Duration(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } pub fn Distance(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Maneuvers(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<GuidanceManeuver>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<GuidanceManeuver>>(result__) } } #[cfg(feature = "Devices_Geolocation")] pub fn BoundingBox(&self) -> ::windows::core::Result<super::super::super::Devices::Geolocation::GeoboundingBox> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Devices::Geolocation::GeoboundingBox>(result__) } } #[cfg(feature = "Devices_Geolocation")] pub fn Path(&self) -> ::windows::core::Result<super::super::super::Devices::Geolocation::Geopath> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Devices::Geolocation::Geopath>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn RoadSegments(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<GuidanceRoadSegment>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<GuidanceRoadSegment>>(result__) } } pub fn ConvertToMapRoute(&self) -> ::windows::core::Result<super::MapRoute> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::MapRoute>(result__) } } pub fn CanCreateFromMapRoute<'a, Param0: ::windows::core::IntoParam<'a, super::MapRoute>>(maproute: Param0) -> ::windows::core::Result<bool> { Self::IGuidanceRouteStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), maproute.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } pub fn TryCreateFromMapRoute<'a, Param0: ::windows::core::IntoParam<'a, super::MapRoute>>(maproute: Param0) -> ::windows::core::Result<GuidanceRoute> { Self::IGuidanceRouteStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), maproute.into_param().abi(), &mut result__).from_abi::<GuidanceRoute>(result__) }) } pub fn IGuidanceRouteStatics<R, F: FnOnce(&IGuidanceRouteStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<GuidanceRoute, IGuidanceRouteStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for GuidanceRoute { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceRoute;{3a14545d-801a-40bd-a286-afb2010cce6c})"); } unsafe impl ::windows::core::Interface for GuidanceRoute { type Vtable = IGuidanceRoute_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3a14545d_801a_40bd_a286_afb2010cce6c); } impl ::windows::core::RuntimeName for GuidanceRoute { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceRoute"; } impl ::core::convert::From<GuidanceRoute> for ::windows::core::IUnknown { fn from(value: GuidanceRoute) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceRoute> for ::windows::core::IUnknown { fn from(value: &GuidanceRoute) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceRoute { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceRoute { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceRoute> for ::windows::core::IInspectable { fn from(value: GuidanceRoute) -> Self { value.0 } } impl ::core::convert::From<&GuidanceRoute> for ::windows::core::IInspectable { fn from(value: &GuidanceRoute) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceRoute { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceRoute { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceRoute {} unsafe impl ::core::marker::Sync for GuidanceRoute {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceTelemetryCollector(pub ::windows::core::IInspectable); impl GuidanceTelemetryCollector { pub fn Enabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetEnabled(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn ClearLocalData(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() } } pub fn SpeedTrigger(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn SetSpeedTrigger(&self, value: f64) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() } } pub fn UploadFrequency(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetUploadFrequency(&self, value: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() } } pub fn GetCurrent() -> ::windows::core::Result<GuidanceTelemetryCollector> { Self::IGuidanceTelemetryCollectorStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceTelemetryCollector>(result__) }) } pub fn IGuidanceTelemetryCollectorStatics<R, F: FnOnce(&IGuidanceTelemetryCollectorStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<GuidanceTelemetryCollector, IGuidanceTelemetryCollectorStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for GuidanceTelemetryCollector { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceTelemetryCollector;{db1f8da5-b878-4d92-98dd-347d23d38262})"); } unsafe impl ::windows::core::Interface for GuidanceTelemetryCollector { type Vtable = IGuidanceTelemetryCollector_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdb1f8da5_b878_4d92_98dd_347d23d38262); } impl ::windows::core::RuntimeName for GuidanceTelemetryCollector { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceTelemetryCollector"; } impl ::core::convert::From<GuidanceTelemetryCollector> for ::windows::core::IUnknown { fn from(value: GuidanceTelemetryCollector) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceTelemetryCollector> for ::windows::core::IUnknown { fn from(value: &GuidanceTelemetryCollector) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceTelemetryCollector { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceTelemetryCollector { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceTelemetryCollector> for ::windows::core::IInspectable { fn from(value: GuidanceTelemetryCollector) -> Self { value.0 } } impl ::core::convert::From<&GuidanceTelemetryCollector> for ::windows::core::IInspectable { fn from(value: &GuidanceTelemetryCollector) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceTelemetryCollector { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceTelemetryCollector { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceTelemetryCollector {} unsafe impl ::core::marker::Sync for GuidanceTelemetryCollector {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GuidanceUpdatedEventArgs(pub ::windows::core::IInspectable); impl GuidanceUpdatedEventArgs { pub fn Mode(&self) -> ::windows::core::Result<GuidanceMode> { let this = self; unsafe { let mut result__: GuidanceMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceMode>(result__) } } pub fn NextManeuver(&self) -> ::windows::core::Result<GuidanceManeuver> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceManeuver>(result__) } } pub fn NextManeuverDistance(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn AfterNextManeuver(&self) -> ::windows::core::Result<GuidanceManeuver> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceManeuver>(result__) } } pub fn AfterNextManeuverDistance(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn DistanceToDestination(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn ElapsedDistance(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } #[cfg(feature = "Foundation")] pub fn ElapsedTime(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn TimeToDestination(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } pub fn RoadName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Route(&self) -> ::windows::core::Result<GuidanceRoute> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceRoute>(result__) } } pub fn CurrentLocation(&self) -> ::windows::core::Result<GuidanceMapMatchedCoordinate> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GuidanceMapMatchedCoordinate>(result__) } } pub fn IsNewManeuver(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn LaneInfo(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<GuidanceLaneInfo>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<GuidanceLaneInfo>>(result__) } } } unsafe impl ::windows::core::RuntimeType for GuidanceUpdatedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.Guidance.GuidanceUpdatedEventArgs;{fdac160b-9e8d-4de3-a9fa-b06321d18db9})"); } unsafe impl ::windows::core::Interface for GuidanceUpdatedEventArgs { type Vtable = IGuidanceUpdatedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfdac160b_9e8d_4de3_a9fa_b06321d18db9); } impl ::windows::core::RuntimeName for GuidanceUpdatedEventArgs { const NAME: &'static str = "Windows.Services.Maps.Guidance.GuidanceUpdatedEventArgs"; } impl ::core::convert::From<GuidanceUpdatedEventArgs> for ::windows::core::IUnknown { fn from(value: GuidanceUpdatedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&GuidanceUpdatedEventArgs> for ::windows::core::IUnknown { fn from(value: &GuidanceUpdatedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GuidanceUpdatedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GuidanceUpdatedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GuidanceUpdatedEventArgs> for ::windows::core::IInspectable { fn from(value: GuidanceUpdatedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&GuidanceUpdatedEventArgs> for ::windows::core::IInspectable { fn from(value: &GuidanceUpdatedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GuidanceUpdatedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GuidanceUpdatedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GuidanceUpdatedEventArgs {} unsafe impl ::core::marker::Sync for GuidanceUpdatedEventArgs {} #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceAudioNotificationRequestedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceAudioNotificationRequestedEventArgs { type Vtable = IGuidanceAudioNotificationRequestedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca2aa24a_c7c2_4d4c_9d7c_499576bceddb); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceAudioNotificationRequestedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut GuidanceAudioNotificationKind) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceLaneInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceLaneInfo { type Vtable = IGuidanceLaneInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8404d114_6581_43b7_ac15_c9079bf90df1); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceLaneInfo_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut GuidanceLaneMarkers) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceManeuver(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceManeuver { type Vtable = IGuidanceManeuver_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfc09326c_ecc9_4928_a2a1_7232b99b94a1); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceManeuver_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut GuidanceManeuverKind) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceMapMatchedCoordinate(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceMapMatchedCoordinate { type Vtable = IGuidanceMapMatchedCoordinate_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb7acb168_2912_4a99_aff1_798609b981fe); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceMapMatchedCoordinate_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceNavigator(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceNavigator { type Vtable = IGuidanceNavigator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08f17ef7_8e3f_4d9a_be8a_108f9a012c67); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceNavigator_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, route: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, route: ::windows::core::RawPtr, speedinmeterspersecond: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut GuidanceAudioMeasurementSystem) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: GuidanceAudioMeasurementSystem) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut GuidanceAudioNotifications) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: GuidanceAudioNotifications) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, voiceid: i32, voicefolder: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, userlocation: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, userlocation: ::windows::core::RawPtr, positionoverride: super::super::super::Devices::Geolocation::BasicGeoposition) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceNavigator2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceNavigator2 { type Vtable = IGuidanceNavigator2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6cdc50d1_041c_4bf3_b633_a101fc2f6b57); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceNavigator2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceNavigatorStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceNavigatorStatics { type Vtable = IGuidanceNavigatorStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x00fd9513_4456_4e66_a143_3add6be08426); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceNavigatorStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceNavigatorStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceNavigatorStatics2 { type Vtable = IGuidanceNavigatorStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x54c5c3e2_7784_4c85_8c95_d0c6efb43965); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceNavigatorStatics2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceReroutedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceReroutedEventArgs { type Vtable = IGuidanceReroutedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x115d4008_d528_454e_bb94_a50341d2c9f1); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceReroutedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceRoadSegment(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceRoadSegment { type Vtable = IGuidanceRoadSegment_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb32758a6_be78_4c63_afe7_6c2957479b3e); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceRoadSegment_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceRoadSegment2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceRoadSegment2 { type Vtable = IGuidanceRoadSegment2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2474a61d_1723_49f1_895b_47a2c4aa9c55); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceRoadSegment2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceRoadSignpost(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceRoadSignpost { type Vtable = IGuidanceRoadSignpost_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf1a728b6_f77a_4742_8312_53300f9845f0); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceRoadSignpost_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "UI")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::UI::Color) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI"))] usize, #[cfg(feature = "UI")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::UI::Color) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceRoute(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceRoute { type Vtable = IGuidanceRoute_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3a14545d_801a_40bd_a286_afb2010cce6c); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceRoute_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceRouteStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceRouteStatics { type Vtable = IGuidanceRouteStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf56d926a_55ed_49c1_b09c_4b8223b50db3); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceRouteStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, maproute: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, maproute: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceTelemetryCollector(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceTelemetryCollector { type Vtable = IGuidanceTelemetryCollector_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdb1f8da5_b878_4d92_98dd_347d23d38262); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceTelemetryCollector_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceTelemetryCollectorStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceTelemetryCollectorStatics { type Vtable = IGuidanceTelemetryCollectorStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x36532047_f160_44fb_b578_94577ca05990); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceTelemetryCollectorStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGuidanceUpdatedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGuidanceUpdatedEventArgs { type Vtable = IGuidanceUpdatedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfdac160b_9e8d_4de3_a9fa_b06321d18db9); } #[repr(C)] #[doc(hidden)] pub struct IGuidanceUpdatedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut GuidanceMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, );
use intcode::*; fn main() { let program = parse_program(include_str!("../input/day_9.txt")); println!( "Part 1 => {}", IntcodeComputer::new(&program) .run(vec!(1)) .last() .unwrap() ); println!( "Part 2 => {}", IntcodeComputer::new(&program) .run(vec!(2)) .last() .unwrap() ); } #[test] fn part_1_complete() { let program = parse_program(include_str!("../input/day_9.txt")); assert_eq!( *IntcodeComputer::new(&program) .run(vec!(1)) .last() .unwrap(), 2518058886 ); } #[test] fn part_2_complete() { let program = parse_program(include_str!("../input/day_9.txt")); assert_eq!( *IntcodeComputer::new(&program) .run(vec!(2)) .last() .unwrap(), 44292 ); }
extern crate clap; extern crate hlife; use std::fs::File; use std::io::Read; use std::process::exit; use clap::{Arg, App}; use hlife::Hashlife; use hlife::global::Pattern; use hlife::format::write::format_rle; fn main() { let matches = App::new("Itai's Hashlife") .arg(Arg::with_name("INPUT-FILE") .required(true) .index(1)) .arg(Arg::with_name("GENERATIONS") .required(true) .index(2)) .get_matches(); let filename = matches.value_of("INPUT-FILE").expect("internal clap error"); let gens_string = matches.value_of("GENERATIONS").expect("internal clap\ error"); let gens = u64::from_str_radix(&gens_string, 10).unwrap_or_else(|_| { println!( "Error: Second argument gens must be a nonnegative integer: {}", &gens_string); exit(1); }); let mut in_file = File::open(&filename).unwrap_or_else(|_| { println!("Cannot open file {}", &filename); exit(1); }); let mut rle_buf = Vec::new(); in_file.read_to_end(&mut rle_buf).unwrap_or_else(|_| { println!("Error reading file {}", &filename); exit(1); }); Hashlife::with_new(|hl| { let block = hl.block_from_bytes(&rle_buf).unwrap_or_else(|_| { println!("Badly formatted RLE in {}", &filename); exit(1); }); let mut pattern = Pattern::new(block); pattern.step(gens); print!("{}", format_rle(&pattern.block())); }); }
#![feature(once_cell)] #![feature(option_result_unwrap_unchecked)] mod dyn_prefix; mod load_database; mod type_map_key; pub use dyn_prefix::*; pub use load_database::*; pub use type_map_key::*; use sqlx::{Pool, Postgres}; use std::lazy::SyncOnceCell as OnceCell; pub const DATABASE_ENABLED: bool = true; pub static PG_POOL: OnceCell<Pool<Postgres>> = OnceCell::new();
use std::{ future::Future, mem, pin::Pin, sync::{Arc, Condvar, Mutex}, task::{Context, Poll}, }; use cooked_waker::{IntoWaker, WakeRef}; use futures::pin_mut; // This is a naive implementation of a notifier which should already be available with any runtime // like Tokio #[derive(Debug, Default)] struct Notifier { // a simple Mutex guarding the condition for blocking was_notified: Mutex<bool>, // blocking the thread while waiting for an event (i.e. was_notified) to occur cv: Condvar, } impl Notifier { // blocking the thread until it is notified fn wait(&self) { let mut was_notified = self.was_notified.lock().expect("cannot acquire lock"); // waiting for the was_notified to be set to true while !*was_notified { eprintln!("Waiting for wake"); // the cv is blocking until a separate thread sends a signal (through the Notifier) was_notified = self .cv .wait(was_notified) .expect("cannot block the thread and waiting for notifications") } // setting it to false so other Futures can notify us again *was_notified = false; } } // implementing the WakeRef trait so Notifier can be awoken impl WakeRef for Notifier { fn wake_by_ref(&self) { let was_notified = { let mut lock = self .was_notified .lock() .expect("cannot lock was_notified mutex"); // only if it wasn't notified, only then we signal the Condvar. In fact, replace // mem::replace turns the was_notified to true while returning the old value mem::replace(&mut *lock, true) }; // if not already notified, signal the cv if !was_notified { eprintln!("Awoken"); self.cv.notify_one(); } } } pub fn run_future<F: Future>(future: F) -> F::Output { // this guarantees that whatever we have pinned to the stack, will remain pinned forever // the pin_mut macro basically takes care of the unsafe // essentially what it does is to shadow the variable with a pinned reference // so it is not possible to get the original object ever again (so the object cannot be moved // because we lost ownership of the reference here) pin_mut!(future); // wakers need to be cheaply clonable across the Futures, since the latters would probably have // to manage their own wakers in their logic. This is the reason why they are an Arc // on a struct like the Notifier let notifier = Arc::new(Notifier::default()); // into_waker is part of the WakeRef trait and deals with the raw pointers and // function pointers, etc let waker = notifier.clone().into_waker(); let mut cx = Context::from_waker(&waker); // when we poll the future... loop { // a pinned reference is not a normal movable reference, so when we call a function on it, // it cannot be moved, so `future` provides an `as_mut()` function, which is kinda like a // copy, but with a shorter lifetime which takes care of moving the pinned reference match future.as_mut().poll(&mut cx) { //...it might be ready, which means we are done and can return the output Poll::Ready(output) => return output, //...when instead it returns `Pending`, it means that it arranged for the `Waker` in the //context to be called when it wants to progress on. So all we have to do is block the //thread Poll::Pending => notifier.wait(), }; } }
pub struct Keypad{ pub keys: [bool; 16] } impl Keypad { pub fn new() -> Keypad { Keypad { keys: [false; 16] } } pub fn key_down(&mut self, index: u8){ self.keys[index as usize] = true; } pub fn key_up(&mut self, index: u8) { self.keys[index as usize] = false; } pub fn is_key_down(&self, index: u8) -> bool { self.keys[index as usize] } }
pub mod algorithms; pub mod data_structures; pub mod util;
use std::{ cell::RefCell, cmp, collections::{HashMap, HashSet}, }; use crate::core::{Part, Solution}; pub fn solve(part: Part, input: String) -> String { match part { Part::P1 => Day16::solve_part_one(input), Part::P2 => Day16::solve_part_two(input), } } #[derive(Debug)] struct Valve { name: String, flow: usize, adjacent: HashSet<String>, } impl From<&str> for Valve { fn from(scan: &str) -> Self { let (data, connections) = scan.split_once(';').unwrap(); let (valve, flow_str) = data.split_once(" has flow rate=").unwrap(); let name = valve.split_whitespace().last().unwrap().to_owned(); let flow = flow_str.parse::<usize>().unwrap(); let adjacent = connections .trim() .split_whitespace() .skip(4) .map(|t| t.trim_end_matches(',').to_owned()) .collect(); Self { name, flow, adjacent, } } } struct Day16; impl Solution for Day16 { fn solve_part_one(input: String) -> String { let valves: HashMap<String, Valve> = input .lines() .map(|scan| { let valve = Valve::from(scan); (valve.name.to_string(), valve) }) .collect(); let mut distances = HashMap::new(); for x in valves.keys() { for y in valves.keys() { if valves.get(x).unwrap().adjacent.contains(y) { distances .entry((x.clone(), y.clone())) .or_insert(RefCell::new(1)); } else { distances .entry((x.clone(), y.clone())) .or_insert(RefCell::new(i64::MAX)); } } } for x in valves.keys() { for y in valves.keys() { for z in valves.keys() { let y_to_z = get(&distances, y, z); let y_to_x = get(&distances, y, x); let x_to_z = get(&distances, x, z); distances.insert( (y.clone(), z.clone()), RefCell::new(match y_to_x == i64::MAX || x_to_z == i64::MAX { true => cmp::min(y_to_z, i64::MAX), false => cmp::min(y_to_z, y_to_x + x_to_z), }), ); } } } String::new() } fn solve_part_two(_input: String) -> String { String::new() } } fn get(distances: &HashMap<(String, String), RefCell<i64>>, x: &String, y: &String) -> i64 { *distances.get(&(x.clone(), y.clone())).unwrap().borrow() }
// All data taken from www.brucelindbloom.com. use xyz::Xyz; use xyy::XyY; pub trait NamedWhitePoint<T> { fn get_xyz() -> Xyz<T>; fn get_xy_chromaticity() -> XyY<T>; } pub mod deg_2; pub mod deg_10; pub use self::deg_2::*;
use amethyst::{ core::{ math::Vector2, timing::Time, transform::Transform }, ecs::prelude::{Entities, Join, Read, Write, ReadStorage, System, WriteStorage}, }; use nalgebra as na; use crate::{ collision_world::CollisionWorld, components }; const SPEED: f32 = 120.0; pub struct MotionSystem; impl<'s> System<'s> for MotionSystem { type SystemData = ( WriteStorage<'s, components::Player>, WriteStorage<'s, Transform>, WriteStorage<'s, components::Collider>, WriteStorage<'s, components::Motion>, Write<'s, CollisionWorld>, Read<'s, Time>, ); fn run(&mut self, ( mut player_storage, mut transform_storage, mut collider_storage, mut motion_storage, mut collision_world, time, ): Self::SystemData) { for ( mut player, mut transform, mut collider, mut motion, ) in ( &mut player_storage, &mut transform_storage, &mut collider_storage, &mut motion_storage, ).join() { motion.velocity.x = player.lr_input_state * SPEED; if player.snapback.x != 0.0 { motion.velocity = Vector2::new(-player.snapback.x, motion.velocity.y); collision_world.update_position(&mut transform, &mut collider, &mut motion, &time); } else { motion.velocity += motion.acceleration; motion.acceleration = na::zero(); collision_world.update_position(&mut transform, &mut collider, &mut motion, &time); } } } }
use crate::runtime::data::launches::structures::{Launch, Article}; use crate::languages::LanguagePack; use crate::runtime::renderer::render_help_menu; use crate::settings::Config; use crate::runtime::state::State; use std::io::Stdout; use tui::Terminal; use tui::backend::CrosstermBackend; use tui::layout::{Layout, Direction, Constraint}; use tui::widgets::Clear; use chrono::{Utc, DateTime, Local}; mod widgets; pub fn run( _language: &LanguagePack, out: &mut Terminal<CrosstermBackend<Stdout>>, launch_present: bool, i: &Option<Launch>, news: &Option<Vec<Article>>, log: &Vec<(DateTime<Local>, String, u8)>, mut state: State, _settings: &mut Config, ) { let mut news_dimensions = (0, 0); let mut update_dimensions = (0, 0); let _ = out.draw(|f| { let whole = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Ratio(8, 12), Constraint::Min(10), ] .as_ref(), ) .split(f.size()); let right = Layout::default().direction(Direction::Horizontal) .constraints( [ Constraint::Percentage(50), Constraint::Percentage(50), ] .as_ref(), ) .split(whole[0]); let right_status = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Percentage(75), Constraint::Percentage(25), ] .as_ref(), ) .split(right[1]); let left = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Percentage(50), Constraint::Percentage(50), ] .as_ref(), ) .split(right[0]); news_dimensions = (right_status[0].width, right_status[0].height); update_dimensions = (left[1].width, left[1].height); }); if launch_present { let launch = i.clone().unwrap(); let timespan = crate::utilities::countdown(launch.net.clone().unwrap_or(Utc::now().to_string())); let _ = out.draw(|f| { let whole = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Ratio(8, 12), Constraint::Min(10), ] .as_ref(), ) .split(f.size()); let right = Layout::default() .direction(Direction::Horizontal) .constraints( [ Constraint::Percentage(50), Constraint::Percentage(50), ] .as_ref(), ) .split(whole[0]); let right_status = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Percentage(75), Constraint::Percentage(25), ] .as_ref(), ) .split(right[1]); let left = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Percentage(50), Constraint::Percentage(50), ] .as_ref(), ) .split(right[0]); // Render launch widget ("Launch Info") f.render_widget(widgets::launch_info::render_dynamic(launch.clone()), left[0]); // Render logs widget ("Logs") f.render_widget(widgets::system_logs::render(log), right_status[1]); // Render dynamic countdown widget ("Countdown") f.render_widget(widgets::countdown::render_dynamic(timespan, launch.clone()), whole[1]); // Render dynamic news widget ("News") f.render_widget(Clear, right_status[0]); f.render_widget(widgets::news_articles::render(&mut state, news_dimensions, news.clone().unwrap_or(vec![])), right_status[0]); // Render dynamic launch update widget ("Updates") f.render_widget(Clear, left[1]); f.render_widget(widgets::launch_updates::render_list(&mut state, launch.clone()), left[1]); if state.render_help { render_help_menu(f); } }); } else { let _ = out.draw(|f| { let whole = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Ratio(7, 10), Constraint::Min(9), ] .as_ref(), ) .split(f.size()); let right = Layout::default() .direction(Direction::Horizontal) .constraints( [ Constraint::Percentage(50), Constraint::Percentage(50), ] .as_ref(), ) .split(whole[0]); let left = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Max(10), Constraint::Max(12), ] .as_ref(), ) .split(right[0]); f.render_widget(widgets::launch_info::render_missing(), left[0]); f.render_widget(Clear, right[1]); f.render_widget(widgets::news_articles::render(&mut state, news_dimensions, news.clone().unwrap_or(vec![])), right[1]); f.render_widget(widgets::system_logs::render(log), left[1]); f.render_widget(widgets::countdown::render_blank(), whole[1]); if state.render_help { render_help_menu(f); } }); } }
//! Persistent accounts are stored in below path location: //! <path>/<pid>/data/ //! //! The persistent store would allow for this mode of operation: //! - Concurrent single thread append with many concurrent readers. //! //! The underlying memory is memory mapped to a file. The accounts would be //! stored across multiple files and the mappings of file and offset of a //! particular account would be stored in a shared index. This will allow for //! concurrent commits without blocking reads, which will sequentially write //! to memory, ssd or disk, and should be as fast as the hardware allow for. //! The only required in memory data structure with a write lock is the index, //! which should be fast to update. //! //! AppendVec's only store accounts for single forks. To bootstrap the //! index from a persistent store of AppendVec's, the entries include //! a "write_version". A single global atomic `AccountsDB::write_version` //! tracks the number of commits to the entire data store. So the latest //! commit for each fork entry would be indexed. use crate::accounts_index::{AccountsIndex, Fork}; use crate::append_vec::{AppendVec, StorageMeta, StoredAccount}; use hashbrown::{HashMap, HashSet}; use log::*; use rand::{thread_rng, Rng}; use rayon::prelude::*; use solana_sdk::account::Account; use solana_sdk::pubkey::Pubkey; use std::fs::{create_dir_all, remove_dir_all}; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, RwLock}; const ACCOUNT_DATA_FILE_SIZE: u64 = 64 * 1024 * 1024; const ACCOUNT_DATA_FILE: &str = "data"; #[derive(Debug, Default)] pub struct ErrorCounters { pub account_not_found: usize, pub account_in_use: usize, pub account_loaded_twice: usize, pub blockhash_not_found: usize, pub blockhash_too_old: usize, pub reserve_blockhash: usize, pub insufficient_funds: usize, pub invalid_account_index: usize, pub duplicate_signature: usize, pub call_chain_too_deep: usize, pub missing_signature_for_fee: usize, } #[derive(Default, Clone)] pub struct AccountInfo { /// index identifying the append storage id: AppendVecId, /// offset into the storage offset: usize, /// lamports in the account used when squashing kept for optimization /// purposes to remove accounts with zero balance. lamports: u64, } /// An offset into the AccountsDB::storage vector type AppendVecId = usize; type AccountStorage = Vec<Arc<AccountStorageEntry>>; pub type AccountStorageSlice = [Arc<AccountStorageEntry>]; pub type InstructionAccounts = Vec<Account>; pub type InstructionLoaders = Vec<Vec<(Pubkey, Account)>>; #[derive(Debug, PartialEq)] pub enum AccountStorageStatus { StorageAvailable = 0, StorageFull = 1, } impl From<usize> for AccountStorageStatus { fn from(status: usize) -> Self { use self::AccountStorageStatus::*; match status { 0 => StorageAvailable, 1 => StorageFull, _ => unreachable!(), } } } /// Persistent storage structure holding the accounts pub struct AccountStorageEntry { fork_id: Fork, /// storage holding the accounts accounts: AppendVec, /// Keeps track of the number of accounts stored in a specific AppendVec. /// This is periodically checked to reuse the stores that do not have /// any accounts in it. count: AtomicUsize, /// status corresponding to the storage status: AtomicUsize, } impl AccountStorageEntry { pub fn new(path: &str, fork_id: Fork, id: usize, file_size: u64) -> Self { let p = format!("{}/{}", path, id); let path = Path::new(&p); let _ignored = remove_dir_all(path); create_dir_all(path).expect("Create directory failed"); let accounts = AppendVec::new(&path.join(ACCOUNT_DATA_FILE), true, file_size as usize); AccountStorageEntry { fork_id, accounts, count: AtomicUsize::new(0), status: AtomicUsize::new(AccountStorageStatus::StorageAvailable as usize), } } pub fn set_status(&self, status: AccountStorageStatus) { self.status.store(status as usize, Ordering::Relaxed); } pub fn get_status(&self) -> AccountStorageStatus { self.status.load(Ordering::Relaxed).into() } fn add_account(&self) { self.count.fetch_add(1, Ordering::Relaxed); } fn remove_account(&self) -> bool { if self.count.fetch_sub(1, Ordering::Relaxed) == 1 { self.accounts.reset(); self.set_status(AccountStorageStatus::StorageAvailable); true } else { false } } } // This structure handles the load/store of the accounts #[derive(Default)] pub struct AccountsDB { /// Keeps tracks of index into AppendVec on a per fork basis pub accounts_index: RwLock<AccountsIndex<AccountInfo>>, /// Account storage pub storage: RwLock<AccountStorage>, /// distribute the accounts across storage lists next_id: AtomicUsize, /// write version write_version: AtomicUsize, /// Set of storage paths to pick from paths: Vec<String>, /// Starting file size of appendvecs file_size: u64, } pub fn get_paths_vec(paths: &str) -> Vec<String> { paths.split(',').map(ToString::to_string).collect() } impl AccountsDB { pub fn new_with_file_size(paths: &str, file_size: u64) -> Self { let paths = get_paths_vec(&paths); AccountsDB { accounts_index: RwLock::new(AccountsIndex::default()), storage: RwLock::new(vec![]), next_id: AtomicUsize::new(0), write_version: AtomicUsize::new(0), paths, file_size, } } pub fn new(paths: &str) -> Self { Self::new_with_file_size(paths, ACCOUNT_DATA_FILE_SIZE) } fn new_storage_entry(&self, fork_id: Fork, path: &str) -> AccountStorageEntry { AccountStorageEntry::new( path, fork_id, self.next_id.fetch_add(1, Ordering::Relaxed), self.file_size, ) } pub fn has_accounts(&self, fork: Fork) -> bool { for x in self.storage.read().unwrap().iter() { if x.fork_id == fork && x.count.load(Ordering::Relaxed) > 0 { return true; } } false } /// Scan a specific fork through all the account storage in parallel with sequential read // PERF: Sequentially read each storage entry in parallel pub fn scan_account_storage<F, B>(&self, fork_id: Fork, scan_func: F) -> Vec<B> where F: Fn(&StoredAccount, &mut B) -> (), F: Send + Sync, B: Send + Default, { let storage_maps: Vec<Arc<AccountStorageEntry>> = self .storage .read() .unwrap() .iter() .filter(|store| store.fork_id == fork_id) .cloned() .collect(); storage_maps .into_par_iter() .map(|storage| { let accounts = storage.accounts.accounts(0); let mut retval = B::default(); accounts .iter() .for_each(|stored_account| scan_func(stored_account, &mut retval)); retval }) .collect() } pub fn load( storage: &AccountStorageSlice, ancestors: &HashMap<Fork, usize>, accounts_index: &AccountsIndex<AccountInfo>, pubkey: &Pubkey, ) -> Option<Account> { let info = accounts_index.get(pubkey, ancestors)?; //TODO: thread this as a ref storage .get(info.id) .and_then(|store| Some(store.accounts.get_account(info.offset)?.0.clone_account())) } pub fn load_slow(&self, ancestors: &HashMap<Fork, usize>, pubkey: &Pubkey) -> Option<Account> { let accounts_index = self.accounts_index.read().unwrap(); let storage = self.storage.read().unwrap(); Self::load(&storage, ancestors, &accounts_index, pubkey) } fn get_storage_id(&self, fork_id: Fork, start: usize, current: usize) -> usize { let mut id = current; let len: usize; { let stores = self.storage.read().unwrap(); len = stores.len(); if len > 0 { if id == std::usize::MAX { id = start % len; if stores[id].get_status() == AccountStorageStatus::StorageAvailable { return id; } } else { stores[id].set_status(AccountStorageStatus::StorageFull); } loop { id = (id + 1) % len; if fork_id == stores[id].fork_id && stores[id].get_status() == AccountStorageStatus::StorageAvailable { break; } if id == start % len { break; } } } } if len == 0 || id == start % len { let mut stores = self.storage.write().unwrap(); // check if new store was already created if stores.len() == len { let path_idx = thread_rng().gen_range(0, self.paths.len()); let storage = self.new_storage_entry(fork_id, &self.paths[path_idx]); stores.push(Arc::new(storage)); } id = stores.len() - 1; } id } fn append_account(&self, fork_id: Fork, pubkey: &Pubkey, account: &Account) -> (usize, usize) { let offset: usize; let start = self.next_id.fetch_add(1, Ordering::Relaxed); let mut id = self.get_storage_id(fork_id, start, std::usize::MAX); // Even if no lamports, need to preserve the account owner so // we can update the vote_accounts correctly if this account is purged // when squashing. let acc = &mut account.clone(); if account.lamports == 0 { acc.data.resize(0, 0); } loop { let result: Option<usize>; { let accounts = &self.storage.read().unwrap()[id]; let write_version = self.write_version.fetch_add(1, Ordering::Relaxed) as u64; let meta = StorageMeta { write_version, pubkey: *pubkey, data_len: account.data.len() as u64, }; result = accounts.accounts.append_account(meta, account); accounts.add_account(); } if let Some(val) = result { offset = val; break; } else { id = self.get_storage_id(fork_id, start, id); } } (id, offset) } pub fn purge_fork(&self, fork: Fork) { //add_root should be called first let is_root = self.accounts_index.read().unwrap().is_root(fork); trace!("PURGING {} {}", fork, is_root); if !is_root { self.storage.write().unwrap().retain(|x| { trace!("PURGING {} {}", x.fork_id, fork); x.fork_id != fork }); } } /// Store the account update. pub fn store(&self, fork_id: Fork, accounts: &[(&Pubkey, &Account)]) { //TODO; these blocks should be separate functions and unit tested let infos: Vec<_> = accounts .iter() .map(|(pubkey, account)| { let (id, offset) = self.append_account(fork_id, pubkey, account); AccountInfo { id, offset, lamports: account.lamports, } }) .collect(); let reclaims: Vec<(Fork, AccountInfo)> = { let mut index = self.accounts_index.write().unwrap(); let mut reclaims = vec![]; for (i, info) in infos.into_iter().enumerate() { let key = &accounts[i].0; reclaims.extend(index.insert(fork_id, key, info).into_iter()) } reclaims }; let dead_forks: HashSet<Fork> = { let stores = self.storage.read().unwrap(); let mut cleared_forks: HashSet<Fork> = HashSet::new(); for (fork_id, account_info) in reclaims { let cleared = stores[account_info.id].remove_account(); if cleared { cleared_forks.insert(fork_id); } } let live_forks: HashSet<Fork> = stores.iter().map(|x| x.fork_id).collect(); cleared_forks.difference(&live_forks).cloned().collect() }; { let mut index = self.accounts_index.write().unwrap(); for fork in dead_forks { index.cleanup_dead_fork(fork); } } } pub fn add_root(&self, fork: Fork) { self.accounts_index.write().unwrap().add_root(fork) } } #[cfg(test)] mod tests { // TODO: all the bank tests are bank specific, issue: 2194 use super::*; use rand::{thread_rng, Rng}; use solana_sdk::account::Account; fn cleanup_paths(paths: &str) { let paths = get_paths_vec(&paths); paths.iter().for_each(|p| { let _ignored = remove_dir_all(p); }); } struct TempPaths { pub paths: String, } impl Drop for TempPaths { fn drop(&mut self) { cleanup_paths(&self.paths); } } fn get_tmp_accounts_path(paths: &str) -> TempPaths { let vpaths = get_paths_vec(paths); let out_dir = std::env::var("OUT_DIR").unwrap_or_else(|_| "target".to_string()); let vpaths: Vec<_> = vpaths .iter() .map(|path| format!("{}/{}", out_dir, path)) .collect(); TempPaths { paths: vpaths.join(","), } } #[macro_export] macro_rules! tmp_accounts_name { () => { &format!("{}-{}", file!(), line!()) }; } #[macro_export] macro_rules! get_tmp_accounts_path { () => { get_tmp_accounts_path(tmp_accounts_name!()) }; } #[test] fn test_accountsdb_add_root() { solana_logger::setup(); let paths = get_tmp_accounts_path!(); let db = AccountsDB::new(&paths.paths); let key = Pubkey::default(); let account0 = Account::new(1, 0, &key); db.store(0, &[(&key, &account0)]); db.add_root(0); let ancestors = vec![(1, 1)].into_iter().collect(); assert_eq!(db.load_slow(&ancestors, &key), Some(account0)); } #[test] fn test_accountsdb_latest_ancestor() { solana_logger::setup(); let paths = get_tmp_accounts_path!(); let db = AccountsDB::new(&paths.paths); let key = Pubkey::default(); let account0 = Account::new(1, 0, &key); db.store(0, &[(&key, &account0)]); let account1 = Account::new(0, 0, &key); db.store(1, &[(&key, &account1)]); let ancestors = vec![(1, 1)].into_iter().collect(); assert_eq!(&db.load_slow(&ancestors, &key).unwrap(), &account1); let ancestors = vec![(1, 1), (0, 0)].into_iter().collect(); assert_eq!(&db.load_slow(&ancestors, &key).unwrap(), &account1); } #[test] fn test_accountsdb_latest_ancestor_with_root() { solana_logger::setup(); let paths = get_tmp_accounts_path!(); let db = AccountsDB::new(&paths.paths); let key = Pubkey::default(); let account0 = Account::new(1, 0, &key); db.store(0, &[(&key, &account0)]); let account1 = Account::new(0, 0, &key); db.store(1, &[(&key, &account1)]); db.add_root(0); let ancestors = vec![(1, 1)].into_iter().collect(); assert_eq!(&db.load_slow(&ancestors, &key).unwrap(), &account1); let ancestors = vec![(1, 1), (0, 0)].into_iter().collect(); assert_eq!(&db.load_slow(&ancestors, &key).unwrap(), &account1); } #[test] fn test_accountsdb_root_one_fork() { solana_logger::setup(); let paths = get_tmp_accounts_path!(); let db = AccountsDB::new(&paths.paths); let key = Pubkey::default(); let account0 = Account::new(1, 0, &key); // store value 1 in the "root", i.e. db zero db.store(0, &[(&key, &account0)]); // now we have: // // root0 -> key.lamports==1 // / \ // / \ // key.lamports==0 <- fork1 \ // fork2 -> key.lamports==1 // (via root0) // store value 0 in one child let account1 = Account::new(0, 0, &key); db.store(1, &[(&key, &account1)]); // masking accounts is done at the Accounts level, at accountsDB we see // original account (but could also accept "None", which is implemented // at the Accounts level) let ancestors = vec![(0, 0), (1, 1)].into_iter().collect(); assert_eq!(&db.load_slow(&ancestors, &key).unwrap(), &account1); // we should see 1 token in fork 2 let ancestors = vec![(0, 0), (2, 2)].into_iter().collect(); assert_eq!(&db.load_slow(&ancestors, &key).unwrap(), &account0); db.add_root(0); let ancestors = vec![(1, 1)].into_iter().collect(); assert_eq!(db.load_slow(&ancestors, &key), Some(account1)); let ancestors = vec![(2, 2)].into_iter().collect(); assert_eq!(db.load_slow(&ancestors, &key), Some(account0)); // original value } #[test] fn test_accountsdb_add_root_many() { let paths = get_tmp_accounts_path!(); let db = AccountsDB::new(&paths.paths); let mut pubkeys: Vec<Pubkey> = vec![]; create_account(&db, &mut pubkeys, 0, 100, 0, 0); for _ in 1..100 { let idx = thread_rng().gen_range(0, 99); let ancestors = vec![(0, 0)].into_iter().collect(); let account = db.load_slow(&ancestors, &pubkeys[idx]).unwrap(); let mut default_account = Account::default(); default_account.lamports = (idx + 1) as u64; assert_eq!(default_account, account); } db.add_root(0); // check that all the accounts appear with a new root for _ in 1..100 { let idx = thread_rng().gen_range(0, 99); let ancestors = vec![(0, 0)].into_iter().collect(); let account0 = db.load_slow(&ancestors, &pubkeys[idx]).unwrap(); let ancestors = vec![(1, 1)].into_iter().collect(); let account1 = db.load_slow(&ancestors, &pubkeys[idx]).unwrap(); let mut default_account = Account::default(); default_account.lamports = (idx + 1) as u64; assert_eq!(&default_account, &account0); assert_eq!(&default_account, &account1); } } #[test] #[ignore] fn test_accountsdb_count_stores() { let paths = get_tmp_accounts_path!(); let db = AccountsDB::new(&paths.paths); let mut pubkeys: Vec<Pubkey> = vec![]; create_account( &db, &mut pubkeys, 0, 2, ACCOUNT_DATA_FILE_SIZE as usize / 3, 0, ); assert!(check_storage(&db, 2)); let pubkey = Pubkey::new_rand(); let account = Account::new(1, ACCOUNT_DATA_FILE_SIZE as usize / 3, &pubkey); db.store(1, &[(&pubkey, &account)]); db.store(1, &[(&pubkeys[0], &account)]); { let stores = db.storage.read().unwrap(); assert_eq!(stores.len(), 2); assert_eq!(stores[0].count.load(Ordering::Relaxed), 2); assert_eq!(stores[1].count.load(Ordering::Relaxed), 2); } db.add_root(1); { let stores = db.storage.read().unwrap(); assert_eq!(stores.len(), 2); assert_eq!(stores[0].count.load(Ordering::Relaxed), 2); assert_eq!(stores[1].count.load(Ordering::Relaxed), 2); } } #[test] fn test_accounts_unsquashed() { let key = Pubkey::default(); // 1 token in the "root", i.e. db zero let paths = get_tmp_accounts_path!(); let db0 = AccountsDB::new(&paths.paths); let account0 = Account::new(1, 0, &key); db0.store(0, &[(&key, &account0)]); // 0 lamports in the child let account1 = Account::new(0, 0, &key); db0.store(1, &[(&key, &account1)]); // masking accounts is done at the Accounts level, at accountsDB we see // original account let ancestors = vec![(0, 0), (1, 1)].into_iter().collect(); assert_eq!(db0.load_slow(&ancestors, &key), Some(account1)); let ancestors = vec![(0, 0)].into_iter().collect(); assert_eq!(db0.load_slow(&ancestors, &key), Some(account0)); } fn create_account( accounts: &AccountsDB, pubkeys: &mut Vec<Pubkey>, fork: Fork, num: usize, space: usize, num_vote: usize, ) { for t in 0..num { let pubkey = Pubkey::new_rand(); let account = Account::new((t + 1) as u64, space, &Account::default().owner); pubkeys.push(pubkey.clone()); let ancestors = vec![(fork, 0)].into_iter().collect(); assert!(accounts.load_slow(&ancestors, &pubkey).is_none()); accounts.store(fork, &[(&pubkey, &account)]); } for t in 0..num_vote { let pubkey = Pubkey::new_rand(); let account = Account::new((num + t + 1) as u64, space, &solana_vote_api::id()); pubkeys.push(pubkey.clone()); let ancestors = vec![(fork, 0)].into_iter().collect(); assert!(accounts.load_slow(&ancestors, &pubkey).is_none()); accounts.store(fork, &[(&pubkey, &account)]); } } fn update_accounts(accounts: &AccountsDB, pubkeys: &Vec<Pubkey>, fork: Fork, range: usize) { for _ in 1..1000 { let idx = thread_rng().gen_range(0, range); let ancestors = vec![(fork, 0)].into_iter().collect(); if let Some(mut account) = accounts.load_slow(&ancestors, &pubkeys[idx]) { account.lamports = account.lamports + 1; accounts.store(fork, &[(&pubkeys[idx], &account)]); if account.lamports == 0 { let ancestors = vec![(fork, 0)].into_iter().collect(); assert!(accounts.load_slow(&ancestors, &pubkeys[idx]).is_none()); } else { let mut default_account = Account::default(); default_account.lamports = account.lamports; assert_eq!(default_account, account); } } } } fn check_storage(accounts: &AccountsDB, count: usize) -> bool { let stores = accounts.storage.read().unwrap(); assert_eq!(stores.len(), 1); assert_eq!( stores[0].get_status(), AccountStorageStatus::StorageAvailable ); stores[0].count.load(Ordering::Relaxed) == count } fn check_accounts(accounts: &AccountsDB, pubkeys: &Vec<Pubkey>, fork: Fork) { for _ in 1..100 { let idx = thread_rng().gen_range(0, 99); let ancestors = vec![(fork, 0)].into_iter().collect(); let account = accounts.load_slow(&ancestors, &pubkeys[idx]).unwrap(); let mut default_account = Account::default(); default_account.lamports = (idx + 1) as u64; assert_eq!(default_account, account); } } #[test] fn test_account_one() { let paths = get_tmp_accounts_path!(); let accounts = AccountsDB::new(&paths.paths); let mut pubkeys: Vec<Pubkey> = vec![]; create_account(&accounts, &mut pubkeys, 0, 1, 0, 0); let ancestors = vec![(0, 0)].into_iter().collect(); let account = accounts.load_slow(&ancestors, &pubkeys[0]).unwrap(); let mut default_account = Account::default(); default_account.lamports = 1; assert_eq!(default_account, account); } #[test] fn test_account_many() { let paths = get_tmp_accounts_path("many0,many1"); let accounts = AccountsDB::new(&paths.paths); let mut pubkeys: Vec<Pubkey> = vec![]; create_account(&accounts, &mut pubkeys, 0, 100, 0, 0); check_accounts(&accounts, &pubkeys, 0); } #[test] fn test_account_update() { let paths = get_tmp_accounts_path!(); let accounts = AccountsDB::new(&paths.paths); let mut pubkeys: Vec<Pubkey> = vec![]; create_account(&accounts, &mut pubkeys, 0, 100, 0, 0); update_accounts(&accounts, &pubkeys, 0, 99); assert_eq!(check_storage(&accounts, 100), true); } #[test] fn test_account_grow_many() { let paths = get_tmp_accounts_path("many2,many3"); let size = 4096; let accounts = AccountsDB::new_with_file_size(&paths.paths, size); let mut keys = vec![]; for i in 0..9 { let key = Pubkey::new_rand(); let account = Account::new(i + 1, size as usize / 4, &key); accounts.store(0, &[(&key, &account)]); keys.push(key); } for (i, key) in keys.iter().enumerate() { let ancestors = vec![(0, 0)].into_iter().collect(); assert_eq!( accounts.load_slow(&ancestors, &key).unwrap().lamports, (i as u64) + 1 ); } let mut append_vec_histogram = HashMap::new(); for storage in accounts.storage.read().unwrap().iter() { *append_vec_histogram.entry(storage.fork_id).or_insert(0) += 1; } for count in append_vec_histogram.values() { assert!(*count >= 2); } } #[test] #[ignore] fn test_account_grow() { let paths = get_tmp_accounts_path!(); let accounts = AccountsDB::new(&paths.paths); let count = [0, 1]; let status = [ AccountStorageStatus::StorageAvailable, AccountStorageStatus::StorageFull, ]; let pubkey1 = Pubkey::new_rand(); let account1 = Account::new(1, ACCOUNT_DATA_FILE_SIZE as usize / 2, &pubkey1); accounts.store(0, &[(&pubkey1, &account1)]); { let stores = accounts.storage.read().unwrap(); assert_eq!(stores.len(), 1); assert_eq!(stores[0].count.load(Ordering::Relaxed), 1); assert_eq!(stores[0].get_status(), status[0]); } let pubkey2 = Pubkey::new_rand(); let account2 = Account::new(1, ACCOUNT_DATA_FILE_SIZE as usize / 2, &pubkey2); accounts.store(0, &[(&pubkey2, &account2)]); { let stores = accounts.storage.read().unwrap(); assert_eq!(stores.len(), 2); assert_eq!(stores[0].count.load(Ordering::Relaxed), 1); assert_eq!(stores[0].get_status(), status[1]); assert_eq!(stores[1].count.load(Ordering::Relaxed), 1); assert_eq!(stores[1].get_status(), status[0]); } let ancestors = vec![(0, 0)].into_iter().collect(); assert_eq!(accounts.load_slow(&ancestors, &pubkey1).unwrap(), account1); assert_eq!(accounts.load_slow(&ancestors, &pubkey2).unwrap(), account2); for i in 0..25 { let index = i % 2; accounts.store(0, &[(&pubkey1, &account1)]); { let stores = accounts.storage.read().unwrap(); assert_eq!(stores.len(), 3); assert_eq!(stores[0].count.load(Ordering::Relaxed), count[index]); assert_eq!(stores[0].get_status(), status[0]); assert_eq!(stores[1].count.load(Ordering::Relaxed), 1); assert_eq!(stores[1].get_status(), status[1]); assert_eq!(stores[2].count.load(Ordering::Relaxed), count[index ^ 1]); assert_eq!(stores[2].get_status(), status[0]); } let ancestors = vec![(0, 0)].into_iter().collect(); assert_eq!(accounts.load_slow(&ancestors, &pubkey1).unwrap(), account1); assert_eq!(accounts.load_slow(&ancestors, &pubkey2).unwrap(), account2); } } #[test] fn test_purge_fork_not_root() { let paths = get_tmp_accounts_path!(); let accounts = AccountsDB::new(&paths.paths); let mut pubkeys: Vec<Pubkey> = vec![]; create_account(&accounts, &mut pubkeys, 0, 1, 0, 0); let ancestors = vec![(0, 0)].into_iter().collect(); assert!(accounts.load_slow(&ancestors, &pubkeys[0]).is_some());; accounts.purge_fork(0); assert!(accounts.load_slow(&ancestors, &pubkeys[0]).is_none());; } #[test] fn test_purge_fork_after_root() { let paths = get_tmp_accounts_path!(); let accounts = AccountsDB::new(&paths.paths); let mut pubkeys: Vec<Pubkey> = vec![]; create_account(&accounts, &mut pubkeys, 0, 1, 0, 0); let ancestors = vec![(0, 0)].into_iter().collect(); accounts.add_root(0); accounts.purge_fork(0); assert!(accounts.load_slow(&ancestors, &pubkeys[0]).is_some()); } }
/* * @lc app=leetcode.cn id=102 lang=rust * * [102] 二叉树的层次遍历 * * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/description/ * * algorithms * Medium (59.88%) * Likes: 356 * Dislikes: 0 * Total Accepted: 72.4K * Total Submissions: 119.7K * Testcase Example: '[3,9,20,null,null,15,7]' * * 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 * * 例如: * 给定二叉树: [3,9,20,null,null,15,7], * * ⁠ 3 * ⁠ / \ * ⁠ 9 20 * ⁠ / \ * ⁠ 15 7 * * * 返回其层次遍历结果: * * [ * ⁠ [3], * ⁠ [9,20], * ⁠ [15,7] * ] * * */ // @lc code=start // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { use std::collections::VecDeque; let mut ret = Vec::new(); if root.is_none() { return ret; } let mut sub_vec = Vec::new(); let mut queue = VecDeque::new(); let mut cur_level = 0; queue.push_back((0, root.clone())); while !queue.is_empty() { if let Some((lev, Some(node))) = queue.pop_front() { if lev > cur_level { ret.push(sub_vec.clone()); sub_vec.clear(); cur_level = lev; } sub_vec.push(node.borrow().val); queue.push_back((lev + 1, node.borrow().left.clone())); queue.push_back((lev + 1, node.borrow().right.clone())); } } if !sub_vec.is_empty() { ret.push(sub_vec); } ret } } // @lc code=end
mod display_name; pub(crate) mod email; mod matrix; pub(crate) mod twitter; pub use display_name::{DisplayNameHandler, VIOLATIONS_CAP}; pub use email::{EmailHandler, EmailId, EmailTransport, SmtpImapClientBuilder}; pub use matrix::{EventExtract, MatrixClient, MatrixHandler, MatrixTransport}; pub use twitter::{Twitter, TwitterBuilder, TwitterHandler, TwitterId, TwitterTransport};
#[derive(Copy, Clone, Debug)] struct Edge { to: usize, cost: u64, } fn dijkstra(g: &Vec<Vec<Edge>>, start: usize) -> (Vec<u64>, Vec<Option<usize>>) { use std::cmp::Reverse; use std::collections::BinaryHeap; let n = g.len(); let mut d = vec![std::u64::MAX; n]; let mut q = BinaryHeap::new(); let mut prev = vec![None; n]; d[start] = 0; q.push((Reverse(0), start)); while let Some((Reverse(c), cur)) = q.pop() { if c > d[cur] { continue; } for e in &g[cur] { if c + e.cost < d[e.to] { d[e.to] = c + e.cost; prev[e.to] = Some(cur); q.push((Reverse(d[e.to]), e.to)); } } } (d, prev) } fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let t: usize = rd.get(); let n: usize = rd.get(); let m: usize = rd.get(); let edges: Vec<(usize, usize, u64)> = (0..m) .map(|_| { let u: usize = rd.get(); let v: usize = rd.get(); let w: u64 = rd.get(); (u - 1, v - 1, w) }) .collect(); let solve0 = || { let mut ans = std::u64::MAX; for i in 0..m { let mut g = vec![vec![]; n]; for j in 0..m { if i == j { continue; } let (u, v, w) = edges[j]; g[u].push(Edge { to: v, cost: w }); g[v].push(Edge { to: u, cost: w }); } let (u, v, w) = edges[i]; let (d, _) = dijkstra(&g, v); ans = ans.min(d[u].saturating_add(w)); } ans }; let solve1 = || { let mut ans = std::u64::MAX; for i in 0..m { let mut g = vec![vec![]; n]; for j in 0..m { if i == j { continue; } let (u, v, w) = edges[j]; g[u].push(Edge { to: v, cost: w }); } let (u, v, w) = edges[i]; let (d, _) = dijkstra(&g, v); ans = ans.min(d[u].saturating_add(w)); } ans }; let ans = match t { 0 => solve0(), 1 => solve1(), _ => unreachable!(), }; if ans < std::u64::MAX { println!("{}", ans); } else { println!("{}", -1); } } pub struct ProconReader<R> { r: R, line: String, i: usize, } impl<R: std::io::BufRead> ProconReader<R> { pub fn new(reader: R) -> Self { Self { r: reader, line: 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.line.len()); assert_ne!(&self.line[self.i..=self.i], " "); let line = &self.line[self.i..]; let end = line.find(' ').unwrap_or_else(|| line.len()); let s = &line[..end]; self.i += end; s.parse() .unwrap_or_else(|_| panic!("parse error `{}`", self.line)) } fn skip_blanks(&mut self) { loop { let start = self.line[self.i..].find(|ch| ch != ' '); match start { Some(j) => { self.i += j; break; } None => { self.line.clear(); self.i = 0; let num_bytes = self.r.read_line(&mut self.line).unwrap(); assert!(num_bytes > 0, "reached EOF :("); self.line = self.line.trim_end_matches(&['\r', '\n'][..]).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() } }
#[allow(unused_imports)] use proconio::{marker::*, *}; #[fastout] fn main() { input! { n: i32, x: i32, a: [i32; n], } for a in a { if a == x { println!("Yes"); return; } } println!("No"); }
use super::*; #[derive(Clone, Eq, Ord, PartialEq, PartialOrd, Default)] pub struct Signature { pub kind: ElementType, pub pointers: usize, pub by_ref: bool, pub is_const: bool, pub is_array: bool, } impl Signature { pub fn is_blittable(&self) -> bool { self.pointers > 0 || self.kind.is_blittable() } pub fn is_udt(&self) -> bool { self.pointers == 0 && self.kind.is_udt() } pub fn has_explicit(&self) -> bool { self.pointers == 0 && self.kind.has_explicit() } pub fn is_packed(&self) -> bool { if self.pointers > 0 { return false; } match &self.kind { ElementType::TypeDef(def) => def.is_packed(), ElementType::Array((signature, _)) => signature.is_packed(), _ => false, } } pub fn size(&self) -> usize { if self.pointers > 0 { 1 } else { self.kind.size() } } }
test_stdout!(with_atom_returns_true, "true\n"); test_stdout!( without_atom_returns_false, "false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n" );
extern crate cc; extern crate cmake; fn main() { cc::Build::new() .file("./src/C/util.c") .file("./src/C/glad.c") .file("./src/C/qef_solver.cpp") .include("./src/H") .include("include") .compile("rsutil"); let dst = cmake::build("voxelized-3d-cuda"); println!("cargo:rustc-link-search=native={}", "./voxelized-3d-cuda/cmake-build-release"); //TODO println!("cargo:rustc-link-lib=static=stdc++"); println!("cargo:rustc-link-lib=static=voxelized3d"); }
//! Code generation for `#[graphql_union]` macro. use std::mem; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens as _}; use syn::{ext::IdentExt as _, parse_quote, spanned::Spanned as _}; use crate::common::{diagnostic, parse, path_eq_single, scalar, SpanContainer}; use super::{ all_variants_different, emerge_union_variants_from_attr, Attr, Definition, VariantAttr, VariantDefinition, }; /// [`diagnostic::Scope`] of errors for `#[graphql_union]` macro. const ERR: diagnostic::Scope = diagnostic::Scope::UnionAttr; /// Expands `#[graphql_union]` macro into generated code. pub fn expand(attr_args: TokenStream, body: TokenStream) -> syn::Result<TokenStream> { if let Ok(mut ast) = syn::parse2::<syn::ItemTrait>(body) { let trait_attrs = parse::attr::unite(("graphql_union", &attr_args), &ast.attrs); ast.attrs = parse::attr::strip("graphql_union", ast.attrs); return expand_on_trait(trait_attrs, ast); } Err(syn::Error::new( Span::call_site(), "#[graphql_union] attribute is applicable to trait definitions only", )) } /// Expands `#[graphql_union]` macro placed on a trait definition. fn expand_on_trait( attrs: Vec<syn::Attribute>, mut ast: syn::ItemTrait, ) -> syn::Result<TokenStream> { let attr = Attr::from_attrs("graphql_union", &attrs)?; let trait_span = ast.span(); let trait_ident = &ast.ident; let name = attr .name .clone() .map(SpanContainer::into_inner) .unwrap_or_else(|| trait_ident.unraw().to_string()); if !attr.is_internal && name.starts_with("__") { ERR.no_double_underscore( attr.name .as_ref() .map(SpanContainer::span_ident) .unwrap_or_else(|| trait_ident.span()), ); } let mut variants: Vec<_> = ast .items .iter_mut() .filter_map(|i| match i { syn::TraitItem::Method(m) => parse_variant_from_trait_method(m, trait_ident, &attr), _ => None, }) .collect(); proc_macro_error::abort_if_dirty(); emerge_union_variants_from_attr(&mut variants, attr.external_resolvers); if variants.is_empty() { ERR.emit_custom(trait_span, "expects at least one union variant"); } if !all_variants_different(&variants) { ERR.emit_custom( trait_span, "must have a different type for each union variant", ); } proc_macro_error::abort_if_dirty(); let context = attr .context .map(SpanContainer::into_inner) .or_else(|| variants.iter().find_map(|v| v.context.as_ref()).cloned()) .unwrap_or_else(|| parse_quote! { () }); let generated_code = Definition { name, ty: parse_quote! { #trait_ident }, is_trait_object: true, description: attr.description.map(SpanContainer::into_inner), context, scalar: scalar::Type::parse(attr.scalar.as_deref(), &ast.generics), generics: ast.generics.clone(), variants, }; Ok(quote! { #ast #generated_code }) } /// Parses given Rust trait `method` as [GraphQL union][1] variant. /// /// On failure returns [`None`] and internally fills up [`proc_macro_error`] /// with the corresponding errors. /// /// [1]: https://spec.graphql.org/October2021#sec-Unions fn parse_variant_from_trait_method( method: &mut syn::TraitItemMethod, trait_ident: &syn::Ident, trait_attr: &Attr, ) -> Option<VariantDefinition> { let method_attrs = method.attrs.clone(); // Remove repeated attributes from the method, to omit incorrect expansion. method.attrs = mem::take(&mut method.attrs) .into_iter() .filter(|attr| !path_eq_single(&attr.path, "graphql")) .collect(); let attr = VariantAttr::from_attrs("graphql", &method_attrs) .map_err(|e| proc_macro_error::emit_error!(e)) .ok()?; if let Some(rslvr) = attr.external_resolver { ERR.custom( rslvr.span_ident(), "cannot use #[graphql(with = ...)] attribute on a trait method", ) .note(String::from( "instead use #[graphql(ignore)] on the method with \ #[graphql_union(on ... = ...)] on the trait itself", )) .emit() } if attr.ignore.is_some() { return None; } let method_span = method.sig.span(); let method_ident = &method.sig.ident; let ty = parse::downcaster::output_type(&method.sig.output) .map_err(|span| { ERR.emit_custom( span, "expects trait method return type to be `Option<&VariantType>` only", ) }) .ok()?; let method_context_ty = parse::downcaster::context_ty(&method.sig) .map_err(|span| { ERR.emit_custom( span, "expects trait method to accept `&self` only and, optionally, `&Context`", ) }) .ok()?; if let Some(is_async) = &method.sig.asyncness { ERR.emit_custom( is_async.span(), "async downcast to union variants is not supported", ); return None; } let resolver_code = { if let Some(other) = trait_attr.external_resolvers.get(&ty) { ERR.custom( method_span, format!( "trait method `{method_ident}` conflicts with the external \ resolver function `{}` declared on the trait to resolve \ the variant type `{}`", other.to_token_stream(), ty.to_token_stream(), ), ) .note(String::from( "use `#[graphql(ignore)]` attribute to ignore this trait \ method for union variants resolution", )) .emit(); } if method_context_ty.is_some() { parse_quote! { #trait_ident::#method_ident(self, ::juniper::FromContext::from(context)) } } else { parse_quote! { #trait_ident::#method_ident(self) } } }; // Doing this may be quite an expensive, because resolving may contain some // heavy computation, so we're preforming it twice. Unfortunately, we have // no other options here, until the `juniper::GraphQLType` itself will allow // to do it in some cleverer way. let resolver_check = parse_quote! { ({ #resolver_code } as ::std::option::Option<&#ty>).is_some() }; Some(VariantDefinition { ty, resolver_code, resolver_check, context: method_context_ty, }) }
// 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. use crate::errors::{Error, ErrorKind, Result}; use crate::util::{get_source_kind, SourceKind}; use async_std::task; use clap::{App, ArgMatches}; use std::io::Write; use std::sync::atomic::Ordering; use tremor_api as api; use tremor_common::file; use tremor_runtime::system::World; use tremor_runtime::{self, version}; async fn handle_api_request< G: std::future::Future<Output = api::Result<tide::Response>>, F: Fn(api::Request) -> G, >( req: api::Request, handler_func: F, ) -> tide::Result { let resource_type = api::accept(&req); // Handle request. If any api error is returned, serialize it into a tide response // as well, respecting the requested resource type. (and if there's error during // this serialization, fall back to the error's conversion into tide response) handler_func(req).await.or_else(|api_error| { api::serialize_error(resource_type, api_error) .or_else(|e| Ok(Into::<tide::Response>::into(e))) }) } fn api_server(world: &World) -> tide::Server<api::State> { let mut app = tide::Server::with_state(api::State { world: world.clone(), }); app.at("/version") .get(|r| handle_api_request(r, api::version::get)); app.at("/binding") .get(|r| handle_api_request(r, api::binding::list_artefact)) .post(|r| handle_api_request(r, api::binding::publish_artefact)); app.at("/binding/:aid") .get(|r| handle_api_request(r, api::binding::get_artefact)) .delete(|r| handle_api_request(r, api::binding::unpublish_artefact)); app.at("/binding/:aid/:sid") .get(|r| handle_api_request(r, api::binding::get_servant)) .post(|r| handle_api_request(r, api::binding::link_servant)) .delete(|r| handle_api_request(r, api::binding::unlink_servant)); app.at("/pipeline") .get(|r| handle_api_request(r, api::pipeline::list_artefact)) .post(|r| handle_api_request(r, api::pipeline::publish_artefact)); app.at("/pipeline/:aid") .get(|r| handle_api_request(r, api::pipeline::get_artefact)) .delete(|r| handle_api_request(r, api::pipeline::unpublish_artefact)); app.at("/onramp") .get(|r| handle_api_request(r, api::onramp::list_artefact)) .post(|r| handle_api_request(r, api::onramp::publish_artefact)); app.at("/onramp/:aid") .get(|r| handle_api_request(r, api::onramp::get_artefact)) .delete(|r| handle_api_request(r, api::onramp::unpublish_artefact)); app.at("/offramp") .get(|r| handle_api_request(r, api::offramp::list_artefact)) .post(|r| handle_api_request(r, api::offramp::publish_artefact)); app.at("/offramp/:aid") .get(|r| handle_api_request(r, api::offramp::get_artefact)) .delete(|r| handle_api_request(r, api::offramp::unpublish_artefact)); app } #[cfg(not(tarpaulin_include))] pub(crate) async fn run_dun(matches: &ArgMatches) -> Result<()> { // Logging if let Some(logger_config) = matches.value_of("logger-config") { log4rs::init_file(logger_config, log4rs::config::Deserializers::default())?; } else { env_logger::init(); } version::log(); eprintln!("allocator: {}", crate::alloc::get_allocator_name()); #[cfg(feature = "bert")] { let d = tch::Device::cuda_if_available(); if d.is_cuda() { eprintln!("CUDA is supported"); } else { eprintln!("CUDA is NOT supported, falling back to the CPU"); } } if let Some(pid_file) = matches.value_of("pid") { let mut file = file::create(pid_file) .map_err(|e| Error::from(format!("Failed to create pid file `{}`: {}", pid_file, e)))?; file.write(format!("{}\n", std::process::id()).as_ref()) .map_err(|e| Error::from(format!("Failed to write pid to `{}`: {}", pid_file, e)))?; } let l: u32 = matches .value_of("recursion-limit") .and_then(|l| l.parse().ok()) .ok_or_else(|| Error::from("invalid recursion limit"))?; tremor_script::RECURSION_LIMIT.store(l, Ordering::Relaxed); let storage_directory = matches .value_of("storage-directory") .map(std::string::ToString::to_string); // TODO: Allow configuring this for offramps and pipelines let (world, handle) = World::start(64, storage_directory).await?; if let Some(config_files) = matches.values_of("artefacts") { let mut yaml_files = Vec::with_capacity(16); // We process trickle files first for config_file in config_files { let kind = get_source_kind(config_file); match kind { SourceKind::Trickle => { if let Err(e) = tremor_runtime::load_query_file(&world, config_file).await { return Err(ErrorKind::FileLoadError(config_file.to_string(), e).into()); } } SourceKind::Tremor | SourceKind::Json | SourceKind::Unsupported(_) => { return Err(ErrorKind::UnsupportedFileType( config_file.to_string(), kind, "yaml", ) .into()); } SourceKind::Yaml => yaml_files.push(config_file), }; } // We process config files thereafter for config_file in yaml_files { if let Err(e) = tremor_runtime::load_cfg_file(&world, config_file).await { return Err(ErrorKind::FileLoadError(config_file.to_string(), e).into()); } } } if !matches.is_present("no-api") { let host = matches .value_of("api-host") .ok_or_else(|| Error::from("host argument missing"))?; let app = api_server(&world); eprintln!("Listening at: http://{}", host); info!("Listening at: http://{}", host); if let Err(e) = app.listen(host).await { return Err(format!("API Error: {}", e).into()); } warn!("API stopped"); world.stop().await?; } handle.await?; warn!("World stopped"); Ok(()) } fn server_run(matches: &ArgMatches) { version::print(); if let Err(ref e) = task::block_on(run_dun(matches)) { error!("error: {}", e); for e in e.iter().skip(1) { error!("error: {}", e); } error!("We are SHUTTING DOWN due to errors during initialization!"); // ALLOW: main.rs ::std::process::exit(1); } } #[cfg(not(tarpaulin_include))] pub(crate) fn run_cmd(mut app: App, cmd: &ArgMatches) -> Result<()> { if let Some(matches) = cmd.subcommand_matches("run") { server_run(matches); Ok(()) } else { app.print_long_help() .map_err(|e| Error::from(format!("Failed to print help: {}", e)))?; // ALLOW: main.rs ::std::process::exit(1); } }
use std::fmt; use std::io; use std::result; /// An enum that represents all types of errors that can occur when using PickleDB #[derive(Debug)] pub enum ErrorType { /// I/O error when reading or writing to file, for example: file not found, etc. Io, /// An error when trying to serialize or deserialize data Serialization, } /// A struct that represents all possible errors that can occur when using PickleDB pub struct Error { err_code: ErrorCode, } /// Alias for a `Result` with the error type [Error](struct.Error.html). pub type Result<T> = result::Result<T, Error>; impl Error { pub(crate) fn new(err_code: ErrorCode) -> Error { Error { err_code } } /// Get the error type pub fn get_type(&self) -> ErrorType { match self.err_code { ErrorCode::Io(_) => ErrorType::Io, ErrorCode::Serialization(_) => ErrorType::Serialization, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.err_code { ErrorCode::Io(ref err) => fmt::Display::fmt(err, f), ErrorCode::Serialization(ref err_str) => f.write_str(err_str), } } } impl fmt::Debug for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(&format!( "Error {{ msg: {} }}", match self.err_code { ErrorCode::Io(ref err) => err.to_string(), ErrorCode::Serialization(ref err_str) => err_str.to_string(), } )) } } impl std::error::Error for Error {} pub(crate) enum ErrorCode { Io(io::Error), Serialization(String), }
extern crate meet; use meet::establish_connection; use meet::users::User; use std::io::{stdin}; fn main() { let connection = establish_connection(); println!("What would you like your username to be?"); let mut username = String::new(); stdin().read_line(&mut username).unwrap(); let username = &username[..(username.len() - 1)]; // Drop the newline character println!("What would you like your password to be?"); let mut password = String::new(); stdin().read_line(&mut password).unwrap(); let password = &password[..(password.len() - 1)]; // Drop the newline character let user = User::new().username(&username) .password(&password) .bio("generated") .email(&format!("{}@example.com", username)) .done(); User::from(user).store(&connection); }
use super::*; use std::ops::*; impl BitOr<Square88> for Square88 { type Output = Square88; fn bitor(self, rhs: Square88) -> Self::Output { Square88(self.0 | rhs.0) } } impl BitOrAssign<Square88> for Square88 { fn bitor_assign(&mut self, rhs: Square88) { self.0 |= rhs.0 } } impl BitAnd<Square88> for Square88 { type Output = Square88; fn bitand(self, rhs: Square88) -> Self::Output { Square88(self.0 & rhs.0) } } impl BitAndAssign<Square88> for Square88 { fn bitand_assign(&mut self, rhs: Square88) { self.0 &= rhs.0 } } impl BitXor<Square88> for Square88 { type Output = Square88; fn bitxor(self, rhs: Square88) -> Self::Output { Square88(self.0 & rhs.0) } } impl BitXorAssign<Square88> for Square88 { fn bitxor_assign(&mut self, rhs: Square88) { self.0 &= rhs.0 } } impl Shl<u8> for Square88 { type Output = Square88; fn shl(self, rhs: u8) -> Self::Output { Square88(self.0 << rhs) } } impl ShlAssign<u8> for Square88 { fn shl_assign(&mut self, rhs: u8) { self.0 <<= rhs } } impl Shr<u8> for Square88 { type Output = Square88; fn shr(self, rhs: u8) -> Self::Output { Square88(self.0 >> rhs) } } impl ShrAssign<u8> for Square88 { fn shr_assign(&mut self, rhs: u8) { self.0 >>= rhs } } impl Not for Square88 { type Output = Square88; fn not(self) -> Self::Output { Square88(!self.0) } } impl Add<i8> for Square88 { type Output = Square88; fn add(self, rhs: i8) -> Self::Output { Square88((self.0 as i16 + rhs as i16) as u8) } }
pub const FILE_ASSOCIATION: &'static [(&'static str, &'static str)] = &[ ("T32_bat1.256", "A2b_arch.pl8"), ("T32_bat1.256", "A2b_cros.pl8"), ("T32_bat1.256", "A2b_knig.pl8"), ("T32_bat1.256", "A2b_mace.pl8"), ("T32_bat1.256", "A2b_peas.pl8"), ("T32_bat1.256", "A2b_pike.pl8"), ("T32_bat1.256", "A2b_psnt.pl8"), ("T32_bat1.256", "A2b_swor.pl8"), ("T32_bat1.256", "A2g_arch.pl8"), ("T32_bat1.256", "A2g_cros.pl8"), ("T32_bat1.256", "A2g_knig.pl8"), ("T32_bat1.256", "A2g_mace.pl8"), ("T32_bat1.256", "A2g_pike.pl8"), ("T32_bat1.256", "A2g_psnt.pl8"), ("T32_bat1.256", "A2g_swor.pl8"), ("T32_bat1.256", "A2_horse.pl8"), ("T32_bat1.256", "A2k_arch.pl8"), ("T32_bat1.256", "A2k_cros.pl8"), ("T32_bat1.256", "A2k_knig.pl8"), ("T32_bat1.256", "A2k_mace.pl8"), ("T32_bat1.256", "A2k_pike.pl8"), ("T32_bat1.256", "A2k_psnt.pl8"), ("T32_bat1.256", "A2k_swor.pl8"), ("T32_bat1.256", "A2_miss.pl8"), ("T32_bat1.256", "A2p_arch.pl8"), ("T32_bat1.256", "A2p_cros.pl8"), ("T32_bat1.256", "A2p_knig.pl8"), ("T32_bat1.256", "A2p_mace.pl8"), ("T32_bat1.256", "A2p_pike.pl8"), ("T32_bat1.256", "A2p_psnt.pl8"), ("T32_bat1.256", "A2p_swor.pl8"), ("T32_bat1.256", "A2r_arch.pl8"), ("T32_bat1.256", "A2r_cros.pl8"), ("T32_bat1.256", "A2r_knig.pl8"), ("T32_bat1.256", "A2r_mace.pl8"), ("T32_bat1.256", "A2r_peas.pl8"), ("T32_bat1.256", "A2r_pike.pl8"), ("T32_bat1.256", "A2r_psnt.pl8"), ("T32_bat1.256", "A2r_swor.pl8"), ("T32_bat1.256", "A2w_arch.pl8"), ("T32_bat1.256", "A2w_cros.pl8"), ("T32_bat1.256", "A2w_knig.pl8"), ("T32_bat1.256", "A2w_mace.pl8"), ("T32_bat1.256", "A2w_pike.pl8"), ("T32_bat1.256", "A2w_psnt.pl8"), ("T32_bat1.256", "A2w_swor.pl8"), ("T32_bat1.256", "A2y_arch.pl8"), ("T32_bat1.256", "A2y_cros.pl8"), ("T32_bat1.256", "A2y_knig.pl8"), ("T32_bat1.256", "A2y_mace.pl8"), ("T32_bat1.256", "A2y_pike.pl8"), ("T32_bat1.256", "A2y_psnt.pl8"), ("T32_bat1.256", "A2y_swor.pl8"), ("T32_bat1.256", "A3b_arch.pl8"), ("T32_bat1.256", "A3b_cros.pl8"), ("T32_bat1.256", "A3b_knig.pl8"), ("T32_bat1.256", "A3b_mace.pl8"), ("T32_bat1.256", "A3b_pike.pl8"), ("T32_bat1.256", "A3b_psnt.pl8"), ("T32_bat1.256", "A3b_swor.pl8"), ("T32_bat1.256", "A3_horse.pl8"), ("T32_bat1.256", "A3k_arch.pl8"), ("T32_bat1.256", "A3k_cros.pl8"), ("T32_bat1.256", "A3k_knig.pl8"), ("T32_bat1.256", "A3k_mace.pl8"), ("T32_bat1.256", "A3k_pike.pl8"), ("T32_bat1.256", "A3k_psnt.pl8"), ("T32_bat1.256", "A3k_swor.pl8"), ("T32_bat1.256", "A3p_arch.pl8"), ("T32_bat1.256", "A3p_cros.pl8"), ("T32_bat1.256", "A3p_knig.pl8"), ("T32_bat1.256", "A3p_mace.pl8"), ("T32_bat1.256", "A3p_pike.pl8"), ("T32_bat1.256", "A3p_psnt.pl8"), ("T32_bat1.256", "A3p_swor.pl8"), ("T32_bat1.256", "A3r_arch.pl8"), ("T32_bat1.256", "A3r_cros.pl8"), ("T32_bat1.256", "A3r_knig.pl8"), ("T32_bat1.256", "A3r_mace.pl8"), ("T32_bat1.256", "A3r_pike.pl8"), ("T32_bat1.256", "A3r_psnt.pl8"), ("T32_bat1.256", "A3r_swor.pl8"), ("T32_bat1.256", "A3w_arch.pl8"), ("T32_bat1.256", "A3w_cros.pl8"), ("T32_bat1.256", "A3w_knig.pl8"), ("T32_bat1.256", "A3w_mace.pl8"), ("T32_bat1.256", "A3w_pike.pl8"), ("T32_bat1.256", "A3w_psnt.pl8"), ("T32_bat1.256", "A3w_swor.pl8"), ("T32_bat1.256", "A3y_arch.pl8"), ("T32_bat1.256", "A3y_cros.pl8"), ("T32_bat1.256", "A3y_knig.pl8"), ("T32_bat1.256", "A3y_mace.pl8"), ("T32_bat1.256", "A3y_pike.pl8"), ("T32_bat1.256", "A3y_psnt.pl8"), ("T32_bat1.256", "A3y_swor.pl8"), ("Armitems.256", "Armitems.pl8"), ("Armoury.256", "Arm_bow.pl8"), ("Armoury.256", "Arm_cros.pl8"), ("Armoury.256", "Arm_it_b.pl8"), ("Armoury.256", "Arm_it_k.pl8"), ("Armoury.256", "Arm_it_p.pl8"), ("Armoury.256", "Arm_it_r.pl8"), ("Armoury.256", "Arm_it_y.pl8"), ("Armoury.256", "Arm_mace.pl8"), ("Armoury.256", "Arm_mail.pl8"), ("Armoury.256", "Armoury.pl8"), ("Armoury.256", "Arm_pike.pl8"), ("Armoury.256", "Arm_swor.pl8"), ("Armoury.256", "Armtorch.pl8"), ("Backgrnd.256", "Backgrnd.pl8"), ("Base01.256", "Base1a.pl8"), ("Base01.256", "Base1b.pl8"), ("Base01.256", "Base1c.pl8"), ("Base01.256", "Base1d.pl8"), ("Base01.256", "Base2a.pl8"), ("Base01.256", "Base2b.pl8"), ("Base01.256", "Base2c.pl8"), ("Base01.256", "Base2d.pl8"), ("Sprite01.256", "Batfield.pl8"), ("Sprite01.256", "Batlfix2.pl8"), ("Cas_back.256", "Cas_back.pl8"), ("Cas_back.256", "Cas_bits.pl8"), ("Cas_back.256", "Caspics.pl8"), ("Base01.256", "Castle1a.pl8"), ("Base01.256", "Castle1b.pl8"), ("Base01.256", "Castle1c.pl8"), ("Base01.256", "Castle1d.pl8"), ("Base01.256", "Castle.pl8"), ("T32_bat1.256", "Catarm1.pl8"), ("T32_bat1.256", "Catarm2.pl8"), ("Treasury.256", "Crossbow.pl8"), ("Custom.256", "Custom.pl8"), ("T32_bat1.256", "Engine.pl8"), ("Lords2.256", "Faces.pl8"), ("Base01.256", "Flags1a.pl8"), ("Base01.256", "Flags1b.pl8"), ("Base01.256", "Flags1c.pl8"), ("Base01.256", "Flags1d.pl8"), ("Base01.256", "Flags2a.pl8"), ("Grtnoble.256", "Flags.pl8"), ("Lords2.256", "Fnt_8.pl8"), ("Lords2.256", "Fntl2_14.pl8"), ("Lords2.256", "Fntl2_22.pl8"), ("Lords2.256", "Fntl2_9.pl8"), ("Lords2.256", "Font_10.pl8"), ("Lords2.256", "Font3c2.pl8"), ("Gateway.256", "Gateway.pl8"), ("Base01.256", "Graphs.pl8"), ("Grtnoble.256", "Grtnoble.pl8"), ("Base01.256", "Hearth.pl8"), ("Base01.256", "Icon_tmp.pl8"), ("Merchant.256", "Icontrad.pl8"), ("Base01.256", "Iconvill.pl8"), ("Lords2.256", "Lords2.pl8"), ("Base01.256", "Map01.pl8"), ("Base01.256", "Map02.pl8"), ("Base01.256", "Map03.pl8"), ("Base01.256", "Map04.pl8"), ("Base01.256", "Map05.pl8"), ("Base01.256", "Map06.pl8"), ("Merchant.256", "Merchant.pl8"), ("T32_bat1.256", "Misc_bat.pl8"), ("Base01.256", "Misc_cty.pl8"), ("Custom.256", "Misc_sel.pl8"), ("Base01.256", "Mouse.pl8"), ("Base01.256", "Mtns1a.pl8"), ("Base01.256", "Mtns1b.pl8"), ("Base01.256", "Mtns1c.pl8"), ("Base01.256", "Mtns1d.pl8"), ("Base01.256", "Mtns2a.pl8"), ("Base01.256", "Mtns2b.pl8"), ("Base01.256", "Mtns2c.pl8"), ("Base01.256", "Mtns2d.pl8"), ("Gateway.256", "Panels2.pl8"), ("Base01.256", "Panels.pl8"), ("Armitems.256", "Peasant.pl8"), ("T32_bat1.256", "Pikemen.pl8"), ("Base01.256", "Roads1a.pl8"), ("Base01.256", "Roads1b.pl8"), ("Base01.256", "Roads1c.pl8"), ("Base01.256", "Roads1d.pl8"), ("Base01.256", "Roads2a.pl8"), ("Base01.256", "Roads2b.pl8"), ("Base01.256", "Roads2c.pl8"), ("Base01.256", "Roads2d.pl8"), ("Base01.256", "Sgeplans.pl8"), ("Base01.256", "Smithy.pl8"), ("Sprite01.256", "Sprite02.pl8"), ("Sprite1a.256", "Sprite1a.pl8"), ("Sprite1a.256", "Sprite1b.pl8"), ("Sprite1a.256", "Sprite2a.pl8"), ("Sprite1a.256", "Sprite2b.pl8"), ("Start.256", "Start.pl8"), ("Grtnoble.256", "Stnfield.pl8"), ("Gateway.256", "System2.pl8"), ("Armitems.256", "System.pl8"), ("T32_bat1.256", "T16_bat1.pl8"), ("T32_bat1.256", "T2_bat1.pl8"), ("Sprite01.256", "T2_spri.pl8"), ("T32_stn1.256", "T2_stn1.pl8"), ("T32_stn1.256", "T2_stn2.pl8"), ("T32_stn1.256", "T2_wod1.pl8"), ("T32_stn1.256", "T2_wod2.pl8"), ("T32_bat1.256", "T32_bat1.pl8"), ("T32_stn1.256", "T32_bat.pl8"), ("T32_stn1.256", "T32_stn1.pl8"), ("T32_stn1.256", "T32_stn2.pl8"), ("T32_stn1.256", "T32_stna.pl8"), ("T32_stn1.256", "T32_wod1.pl8"), ("T32_stn1.256", "T32_wod2.pl8"), ("Base01.256", "Title.pl8"), ("Base1a.256", "Torches.pl8"), ("Base1a.256", "Town1a.pl8"), ("Base1a.256", "Town1b.pl8"), ("Base1a.256", "Town1c.pl8"), ("Base1a.256", "Town1d.pl8"), ("Base1a.256", "Town2a.pl8"), ("Base1a.256", "Town2b.pl8"), ("Base1a.256", "Town2c.pl8"), ("Base1a.256", "Town2d.pl8"), ("Treasury.256", "Treasury.pl8"), ("Armitems.256", "Troop1.pl8"), ("Armitems.256", "Trp_ar_b.pl8"), ("Armitems.256", "Trp_ar_k.pl8"), ("Armitems.256", "Trp_ar_p.pl8"), ("Armitems.256", "Trp_ar_r.pl8"), ("Armitems.256", "Trp_ar_y.pl8"), ("Armitems.256", "Trp_kn_b.pl8"), ("Armitems.256", "Trp_kn_k.pl8"), ("Armitems.256", "Trp_kn_p.pl8"), ("Armitems.256", "Trp_kn_r.pl8"), ("Armitems.256", "Trp_kn_y.pl8"), ("Armitems.256", "Trp_ma_b.pl8"), ("Armitems.256", "Trp_ma_k.pl8"), ("Armitems.256", "Trp_ma_p.pl8"), ("Armitems.256", "Trp_ma_r.pl8"), ("Armitems.256", "Trp_ma_y.pl8"), ("Armitems.256", "Trp_pi_b.pl8"), ("Armitems.256", "Trp_pi_k.pl8"), ("Armitems.256", "Trp_pi_p.pl8"), ("Armitems.256", "Trp_pi_r.pl8"), ("Armitems.256", "Trp_pi_y.pl8"), ("Armitems.256", "Trp_sw_b.pl8"), ("Armitems.256", "Trp_sw_k.pl8"), ("Armitems.256", "Trp_sw_p.pl8"), ("Armitems.256", "Trp_sw_r.pl8"), ("Armitems.256", "Trp_sw_y.pl8"), ("Armitems.256", "Trp_xb_b.pl8"), ("Armitems.256", "Trp_xb_k.pl8"), ("Armitems.256", "Trp_xb_p.pl8"), ("Armitems.256", "Trp_xb_r.pl8"), ("Armitems.256", "Trp_xb_y.pl8"), ("Base01.256", "Village3.pl8"), ("Base01.256", "Village4.pl8"), ("Base01.256", "Village.pl8"), ("Base01.256", "Villani1.pl8"), ("Base01.256", "Villani2.pl8"), ("Base01.256", "Villbord.pl8"), ("Base01.256", "Vill.pl8"), ("Base01.256", "Villtops.pl8") ];
//! The graphics platform that is used by the renderer. use std::num::NonZeroU32; use glutin::config::{ColorBufferType, Config, ConfigTemplateBuilder, GetGlConfig}; use glutin::context::{ ContextApi, ContextAttributesBuilder, GlProfile, NotCurrentContext, Version, }; use glutin::display::{Display, DisplayApiPreference, GetGlDisplay}; use glutin::error::Result as GlutinResult; use glutin::prelude::*; use glutin::surface::{Surface, SurfaceAttributesBuilder, WindowSurface}; use log::{debug, LevelFilter}; use raw_window_handle::{RawDisplayHandle, RawWindowHandle}; use winit::dpi::PhysicalSize; #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] use winit::platform::x11; /// Create the GL display. pub fn create_gl_display( raw_display_handle: RawDisplayHandle, _raw_window_handle: Option<RawWindowHandle>, ) -> GlutinResult<Display> { #[cfg(target_os = "macos")] let preference = DisplayApiPreference::Cgl; #[cfg(windows)] let preference = DisplayApiPreference::Wgl(Some(_raw_window_handle.unwrap())); #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] let preference = DisplayApiPreference::GlxThenEgl(Box::new(x11::register_xlib_error_hook)); #[cfg(all(not(feature = "x11"), not(any(target_os = "macos", windows))))] let preference = DisplayApiPreference::Egl; let display = unsafe { Display::new(raw_display_handle, preference)? }; log::info!("Using {}", { display.version_string() }); Ok(display) } pub fn pick_gl_config( gl_display: &Display, raw_window_handle: Option<RawWindowHandle>, ) -> Result<Config, String> { let mut default_config = ConfigTemplateBuilder::new() .with_depth_size(0) .with_stencil_size(0) .with_transparency(true); if let Some(raw_window_handle) = raw_window_handle { default_config = default_config.compatible_with_native_window(raw_window_handle); } let config_10bit = default_config .clone() .with_buffer_type(ColorBufferType::Rgb { r_size: 10, g_size: 10, b_size: 10 }) .with_alpha_size(2); let configs = [ default_config.clone(), config_10bit.clone(), default_config.with_transparency(false), config_10bit.with_transparency(false), ]; for config in configs { let gl_config = unsafe { gl_display.find_configs(config.build()).ok().and_then(|mut configs| configs.next()) }; if let Some(gl_config) = gl_config { debug!( r#"Picked GL Config: buffer_type: {:?} alpha_size: {} num_samples: {} hardware_accelerated: {:?} supports_transparency: {:?} config_api: {:?} srgb_capable: {}"#, gl_config.color_buffer_type(), gl_config.alpha_size(), gl_config.num_samples(), gl_config.hardware_accelerated(), gl_config.supports_transparency(), gl_config.api(), gl_config.srgb_capable(), ); return Ok(gl_config); } } Err(String::from("failed to find suitable GL configuration.")) } pub fn create_gl_context( gl_display: &Display, gl_config: &Config, raw_window_handle: Option<RawWindowHandle>, ) -> GlutinResult<NotCurrentContext> { let debug = log::max_level() >= LevelFilter::Debug; let mut profiles = [ ContextAttributesBuilder::new() .with_debug(debug) .with_context_api(ContextApi::OpenGl(Some(Version::new(3, 3)))) .build(raw_window_handle), // Try gles before OpenGL 2.1 as it tends to be more stable. ContextAttributesBuilder::new() .with_debug(debug) .with_context_api(ContextApi::Gles(Some(Version::new(2, 0)))) .build(raw_window_handle), ContextAttributesBuilder::new() .with_debug(debug) .with_profile(GlProfile::Compatibility) .with_context_api(ContextApi::OpenGl(Some(Version::new(2, 1)))) .build(raw_window_handle), ] .into_iter(); // Try the optimal config first. let mut picked_context = unsafe { gl_display.create_context(gl_config, &profiles.next().unwrap()) }; // Try the fallback ones. while let (Err(_), Some(profile)) = (picked_context.as_ref(), profiles.next()) { picked_context = unsafe { gl_display.create_context(gl_config, &profile) }; } picked_context } pub fn create_gl_surface( gl_context: &NotCurrentContext, size: PhysicalSize<u32>, raw_window_handle: RawWindowHandle, ) -> GlutinResult<Surface<WindowSurface>> { // Get the display and the config used to create that context. let gl_display = gl_context.display(); let gl_config = gl_context.config(); let surface_attributes = SurfaceAttributesBuilder::<WindowSurface>::new().with_srgb(Some(false)).build( raw_window_handle, NonZeroU32::new(size.width).unwrap(), NonZeroU32::new(size.height).unwrap(), ); // Create the GL surface to draw into. unsafe { gl_display.create_window_surface(&gl_config, &surface_attributes) } }
use models::{AppState, Canvas}; #[derive(Clone, Debug)] pub struct LoadingMessage {} impl LoadingMessage { pub fn new() -> Self { LoadingMessage {} } pub fn render_as_canvas(&self, _state: &AppState, width: u16) -> Canvas { use tui::style::*; let mut canvas = Canvas::new(width); canvas.add_string_truncated( &format!("{:^1$}", "Loading more messages", width as usize), Style::default().fg(Color::Red), ); canvas } } #[cfg(test)] mod tests { use super::*; #[test] fn it_renders_as_canvas() { let state = AppState::fixture(); let message = LoadingMessage::new(); let big_canvas = message.render_as_canvas(&state, 50); assert_eq!( &big_canvas.render_to_string(Some("|")), " Loading more messages |" ); let small_canvas = message.render_as_canvas(&state, 20); assert_eq!( &small_canvas.render_to_string(Some("|")), "Loading more message|", ); } }
// Copyright 2019 CoreOS, Inc. // // 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 anyhow::{Context, Result}; use flate2::read::GzDecoder; use std::io::{self, BufRead, Read}; use xz2::read::XzDecoder; enum CompressDecoder<R: BufRead> { Uncompressed(R), Gzip(GzDecoder<R>), Xz(XzDecoder<R>), } pub struct DecompressReader<R: BufRead> { decoder: CompressDecoder<R>, } /// Format-sniffing decompressor impl<R: BufRead> DecompressReader<R> { pub fn new(mut source: R) -> Result<Self> { use CompressDecoder::*; let sniff = source.fill_buf().context("sniffing input")?; let decoder = if sniff.len() > 2 && &sniff[0..2] == b"\x1f\x8b" { Gzip(GzDecoder::new(source)) } else if sniff.len() > 6 && &sniff[0..6] == b"\xfd7zXZ\x00" { Xz(XzDecoder::new(source)) } else { Uncompressed(source) }; Ok(Self { decoder }) } } impl<R: BufRead> Read for DecompressReader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { use CompressDecoder::*; match &mut self.decoder { Uncompressed(d) => d.read(buf), Gzip(d) => d.read(buf), Xz(d) => d.read(buf), } } }
use input_i_scanner::InputIScanner; use std::collections::HashMap; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let n = scan!(usize); let mut freq = HashMap::new(); for _ in 0..n { let s = scan!(String); freq.entry(s) .and_modify(|e| { *e += 1; }) .or_insert(0); } let mut s_freq: Vec<(String, usize)> = freq.into_iter().collect(); s_freq.sort_by_key(|(_, freq)| *freq); s_freq.reverse(); let (ans, _) = &s_freq[0]; println!("{}", ans); }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::ops::Rem; use common_expression::types::number::*; use common_expression::types::ArgType; use common_expression::types::ValueType; use common_expression::EvalContext; use common_expression::Value; use common_expression::ValueRef; use num_traits::AsPrimitive; use strength_reduce::StrengthReducedU16; use strength_reduce::StrengthReducedU32; use strength_reduce::StrengthReducedU64; use strength_reduce::StrengthReducedU8; pub(crate) fn vectorize_modulo<L, R, M, O>() -> impl Fn(ValueRef<NumberType<L>>, ValueRef<NumberType<R>>, &mut EvalContext) -> Value<NumberType<O>> + Copy where L: Number + AsPrimitive<M>, R: Number + AsPrimitive<M> + AsPrimitive<f64>, M: Number + AsPrimitive<O> + Rem<Output = M> + RemScalar<O>, O: Number, { move |arg1, arg2, ctx| { let apply = |lhs: &L, rhs: &R, builder: &mut Vec<O>, ctx: &mut EvalContext| { let r: f64 = rhs.as_(); if r == 0.0 { ctx.set_error(builder.len(), "Division by zero"); builder.push(O::default()); } else { builder.push((lhs.as_() % rhs.as_()).as_()); } }; match (arg1, arg2) { (ValueRef::Column(lhs), ValueRef::Scalar(rhs)) => { if rhs == R::default() { ctx.set_error(0, "Division by zero"); return Value::Column(vec![O::default(); lhs.len()].into()); } let iter = lhs.iter().map(|lhs| lhs.as_()); RemScalar::<O>::rem_scalar(iter, rhs.as_()) } (ValueRef::Scalar(lhs), ValueRef::Scalar(rhs)) => { let mut builder: Vec<O> = Vec::with_capacity(1); apply(&lhs, &rhs, &mut builder, ctx); Value::Scalar(NumberType::<O>::build_scalar(builder)) } (ValueRef::Scalar(arg1), ValueRef::Column(arg2)) => { let mut builder: Vec<O> = Vec::with_capacity(arg2.len()); for val in arg2.iter() { apply(&arg1, val, &mut builder, ctx); } Value::Column(builder.into()) } (ValueRef::Column(arg1), ValueRef::Column(arg2)) => { let mut builder: Vec<O> = Vec::with_capacity(arg2.len()); let iter = arg1.iter().zip(arg2.iter()); for (val1, val2) in iter { apply(val1, val2, &mut builder, ctx); } Value::Column(builder.into()) } } } } pub trait RemScalar<O: Number>: Number { fn rem_scalar(_left: impl Iterator<Item = Self>, _other: Self) -> Value<NumberType<O>> { unimplemented!() } } macro_rules! impl_rem_scalar { ($t: ident, $strength_reduce: ident) => { impl<O> RemScalar<O> for $t where Self: AsPrimitive<O> + AsPrimitive<f64> + Rem<Output = Self>, O: Number, { fn rem_scalar(left: impl Iterator<Item = Self>, other: Self) -> Value<NumberType<O>> { let reduced_rem = $strength_reduce::new(other); let iter = left.map(|v| (v % reduced_rem).as_()); let col = NumberType::<O>::column_from_iter(iter, &[]); Value::Column(col) } } }; } impl_rem_scalar!(u8, StrengthReducedU8); impl_rem_scalar!(u16, StrengthReducedU16); impl_rem_scalar!(u32, StrengthReducedU32); impl_rem_scalar!(u64, StrengthReducedU64); impl<O: Number> RemScalar<O> for i8 {} impl<O: Number> RemScalar<O> for i16 {} impl<O: Number> RemScalar<O> for i32 {} impl<O: Number> RemScalar<O> for i64 {} impl<O: Number> RemScalar<O> for F32 {} impl<O: Number> RemScalar<O> for F64 {}
use colored::*; use crc_any::CRCu16; use goblin::elf::program_header::*; use hidapi::{HidApi, HidDevice}; use maplit::hashmap; use std::{ fs::File, io::Read, path::PathBuf, process::{Command, Stdio}, time::Instant, }; use structopt::StructOpt; fn main() { // Initialize the logging backend. pretty_env_logger::init(); // Get commandline options. // Skip the first arg which is the calling application name. let opt = Opt::from_iter(std::env::args().skip(1)); // Try and get the cargo project information. let project = cargo_project::Project::query(".").expect("Couldn't parse the Cargo.toml"); // Decide what artifact to use. let artifact = if let Some(bin) = &opt.bin { cargo_project::Artifact::Bin(bin) } else if let Some(example) = &opt.example { cargo_project::Artifact::Example(example) } else { cargo_project::Artifact::Bin(project.name()) }; // Decide what profile to use. let profile = if opt.release { cargo_project::Profile::Release } else { cargo_project::Profile::Dev }; // Try and get the artifact path. let path = project .path( artifact, profile, opt.target.as_deref(), "x86_64-unknown-linux-gnu", ) .expect("Couldn't find the build result"); // Remove first two args which is the calling application name and the `hf2` command from cargo. let mut args: Vec<_> = std::env::args().skip(2).collect(); // todo, keep as iter. difficult because we want to filter map remove two items at once. // Remove our args as cargo build does not understand them. let flags = ["--pid", "--vid"].iter(); for flag in flags { if let Some(index) = args.iter().position(|x| x == flag) { args.remove(index); args.remove(index); } } let status = Command::new("cargo") .arg("build") .args(args) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .spawn() .unwrap() .wait() .unwrap(); if !status.success() { exit_with_process_status(status) } let api = HidApi::new().expect("Couldn't find system usb"); let d = if let (Some(v), Some(p)) = (opt.vid, opt.pid) { api.open(v, p) .expect("Are you sure device is plugged in and in bootloader mode?") } else { println!( " {} for a connected device with known vid/pid pair.", "Searching".green().bold(), ); let mut device: Option<HidDevice> = None; let vendor = hashmap! { 0x1D50 => vec![0x6110, 0x6112], 0x239A => vec![0x0035, 0x002D, 0x0015, 0x001B, 0xB000, 0x0024, 0x000F, 0x0013, 0x0021, 0x0022, 0x0031, 0x002B, 0x0037, 0x0035, 0x002F, 0x002B, 0x0033, 0x0034, 0x003D, 0x0018, 0x001C, 0x001E, 0x0027, 0x0022], 0x04D8 => vec![0xEDB3, 0xEDBE, 0xEF66], 0x2341 => vec![0x024E, 0x8053, 0x024D], 0x16D0 => vec![0x0CDA], 0x03EB => vec![0x2402], 0x2886 => vec![0x000D, 0x002F], 0x1B4F => vec![0x0D23, 0x0D22], 0x1209 => vec![0x4D44, 0x2017], }; for device_info in api.device_list() { if let Some(products) = vendor.get(&device_info.vendor_id()) { if products.contains(&device_info.product_id()) { if let Ok(d) = device_info.open_device(&api) { device = Some(d); break; } } } } device.expect("Are you sure device is plugged in and in bootloader mode?") }; println!( " {} {:?} {:?}", "Trying ".green().bold(), d.get_manufacturer_string(), d.get_product_string() ); println!(" {} {:?}", "Flashing".green().bold(), path); // Start timer. let instant = Instant::now(); flash_elf(path, &d); // Stop timer. let elapsed = instant.elapsed(); println!( " {} in {}s", "Finished".green().bold(), elapsed.as_millis() as f32 / 1000.0 ); } #[cfg(unix)] fn exit_with_process_status(status: std::process::ExitStatus) -> ! { use std::os::unix::process::ExitStatusExt; let status = status.code().or_else(|| status.signal()).unwrap_or(1); std::process::exit(status) } #[cfg(not(unix))] fn exit_with_process_status(status: std::process::ExitStatus) -> ! { let status = status.code().unwrap_or(1); std::process::exit(status) } pub trait MemoryRange { fn contains_range(&self, range: &std::ops::Range<u32>) -> bool; fn intersects_range(&self, range: &std::ops::Range<u32>) -> bool; } impl MemoryRange for core::ops::Range<u32> { fn contains_range(&self, range: &std::ops::Range<u32>) -> bool { self.contains(&range.start) && self.contains(&(range.end - 1)) } fn intersects_range(&self, range: &std::ops::Range<u32>) -> bool { self.contains(&range.start) && !self.contains(&(range.end - 1)) || !self.contains(&range.start) && self.contains(&(range.end - 1)) } } /// Starts the download of a elf file. fn flash_elf(path: PathBuf, d: &HidDevice) { let mut file = File::open(path).unwrap(); let mut buffer = vec![]; file.read_to_end(&mut buffer).unwrap(); if let Ok(binary) = goblin::elf::Elf::parse(&buffer.as_slice()) { let bininfo = hf2::bin_info(&d).expect("bin_info failed"); log::debug!("{:?}", bininfo); if bininfo.mode != hf2::BinInfoMode::Bootloader { let _ = hf2::start_flash(&d).expect("start_flash failed"); } //todo this could send multiple binary sections.. let flashed: u8 = binary .program_headers .iter() .filter(|ph| ph.p_type == PT_LOAD && ph.p_filesz > 0) .map(move |ph| { log::debug!( "Flashing {:?} bytes @{:02X?}", ph.p_filesz as usize, ph.p_offset as usize, ); let data = &buffer[(ph.p_offset as usize)..][..ph.p_filesz as usize]; flash(data, ph.p_paddr as u32, &bininfo, &d); 1 }) .sum(); //only reset if we actually sent something if flashed > 0 { let _ = hf2::reset_into_app(&d).expect("reset_into_app failed"); } } } fn flash(binary: &[u8], address: u32, bininfo: &hf2::BinInfoResponse, d: &HidDevice) { let mut binary = binary.to_owned(); //pad zeros to page size let padded_num_pages = (binary.len() as f64 / f64::from(bininfo.flash_page_size)).ceil() as u32; let padded_size = padded_num_pages * bininfo.flash_page_size; log::debug!( "binary is {} bytes, padding to {} bytes", binary.len(), padded_size ); for _i in 0..(padded_size as usize - binary.len()) { binary.push(0x0); } // get checksums of existing pages let top_address = address + padded_size as u32; let max_pages = bininfo.max_message_size / 2 - 2; let steps = max_pages * bininfo.flash_page_size; let mut device_checksums = vec![]; for target_address in (address..top_address).step_by(steps as usize) { let pages_left = (top_address - target_address) / bininfo.flash_page_size; let num_pages = if pages_left < max_pages { pages_left } else { max_pages }; let chk = hf2::checksum_pages(&d, target_address, num_pages).expect("checksum_pages failed"); device_checksums.extend_from_slice(&chk.checksums[..]); } log::debug!("checksums received {:04X?}", device_checksums); // only write changed contents for (page_index, page) in binary.chunks(bininfo.flash_page_size as usize).enumerate() { let mut xmodem = CRCu16::crc16xmodem(); xmodem.digest(&page); if xmodem.get_crc() != device_checksums[page_index] { log::debug!( "ours {:04X?} != {:04X?} theirs, updating page {}", xmodem.get_crc(), device_checksums[page_index], page_index, ); let target_address = address + bininfo.flash_page_size * page_index as u32; let _ = hf2::write_flash_page(&d, target_address, page.to_vec()) .expect("write_flash_page failed"); } else { log::debug!("not updating page {}", page_index,); } } } fn parse_hex_16(input: &str) -> Result<u16, std::num::ParseIntError> { if input.starts_with("0x") { u16::from_str_radix(&input[2..], 16) } else { input.parse::<u16>() } } #[derive(Debug, StructOpt)] struct Opt { // `cargo build` arguments #[structopt(name = "binary", long = "bin")] bin: Option<String>, #[structopt(name = "example", long = "example")] example: Option<String>, #[structopt(name = "package", short = "p", long = "package")] package: Option<String>, #[structopt(name = "release", long = "release")] release: bool, #[structopt(name = "target", long = "target")] target: Option<String>, #[structopt(name = "PATH", long = "manifest-path", parse(from_os_str))] manifest_path: Option<PathBuf>, #[structopt(long)] no_default_features: bool, #[structopt(long)] all_features: bool, #[structopt(long)] features: Vec<String>, #[structopt(name = "pid", long = "pid", parse(try_from_str = parse_hex_16))] pid: Option<u16>, #[structopt(name = "vid", long = "vid", parse(try_from_str = parse_hex_16))] vid: Option<u16>, }
// Copyright 2017 Mathias Svensson. See the COPYRIGHT file at the top-level // directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT> or the Unlicense // <LICENSE-UNLICENSE or https://unlicense.org/UNLICENSE>, at your option. // All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. //! Crate for temporarily moving out of a mutable pointer. //! //! This crate implementation a single wrapper-type `Takeable<T>`. The main purpose of this wrapper //! is that it provides two convenient helper function `borrow` and `borrow_result` that allows for //! temporarily moving out of the wrapper without violating safety. //! //! These work similarly to [`take`][take] from the [`take_mut`][take_mut] crate. The main //! difference is that while the `take_mut` is implemented using careful handling of unwind safety, //! this crate using an `Option<T>` inside to make unwinding work as expected. //! //! [take]: https://docs.rs/take_mut/0.1.3/take_mut/fn.take.html //! [take_mut]: https://crates.io/crates/take_mut #![no_std] #![deny(missing_docs, unsafe_code, missing_debug_implementations, missing_copy_implementations, unstable_features, unused_import_braces, unused_qualifications)] use core::ops::{Deref, DerefMut}; /// A wrapper-type that always holds a single `T` value. /// /// This type is implemented using an `Option<T>`, however outside of the `borrow_result` function, /// this `Option` will always contain a value. /// /// # Panics /// /// If the closure given to `borrow` or `borrow_result` panics, then the `Takeable` is left in an /// unusable state without holding a `T`. Calling any method on the object besides `is_usable` when /// in this state will result in a panic. This includes trying to dereference the object. /// /// It is still safe to drop the value. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] pub struct Takeable<T> { // During normal usage, the invariant is that that this value should *always* be a Some(value), // unless we are inside the `borrow_result` function. However if the closure given the // `borrow_result` panics, then this will no longer be the case. value: Option<T>, } impl<T> Takeable<T> { /// Constructs a new `Takeable<T>` value. #[inline(always)] pub fn new(value: T) -> Takeable<T> { Takeable { value: Some(value) } } /// Gets a reference to the inner value. #[inline(always)] pub fn as_ref(&self) -> &T { self.value.as_ref().expect( "Takeable is not usable after a panic occurred in borrow or borrow_result", ) } /// Gets a mutable reference to the inner value. #[inline(always)] pub fn as_mut(&mut self) -> &mut T { self.value.as_mut().expect( "Takeable is not usable after a panic occurred in borrow or borrow_result", ) } /// Takes ownership of the inner value. #[inline(always)] pub fn into_inner(self) -> T { self.value.expect( "Takeable is not usable after a panic occurred in borrow or borrow_result", ) } /// Updates the inner value using the provided closure. #[inline(always)] pub fn borrow<F>(&mut self, f: F) where F: FnOnce(T) -> T, { self.borrow_result(|v| (f(v), ())) } /// Updates the inner value using the provided closure while also returns a result. #[inline(always)] pub fn borrow_result<F, R>(&mut self, f: F) -> R where F: FnOnce(T) -> (T, R), { let old = self.value.take().expect( "Takeable is not usable after a panic occurred in borrow or borrow_result", ); let (new, result) = f(old); self.value = Some(new); result } /// Check if the object is still usable. /// /// The object will always start out as usable, and can only enter an unusable state if the /// methods `borrow` or `borrow_result` are called with closures that panic. #[inline(always)] pub fn is_usable(&self) -> bool { self.value.is_some() } } impl<T> Deref for Takeable<T> { type Target = T; #[inline(always)] fn deref(&self) -> &T { self.as_ref() } } impl<T> DerefMut for Takeable<T> { #[inline(always)] fn deref_mut(&mut self) -> &mut T { self.as_mut() } } #[cfg(test)] mod tests { use super::Takeable; #[test] fn test_takeable() { let mut takeable = Takeable::new(42u32); *takeable += 1; assert_eq!(*takeable, 43); *takeable.as_mut() += 1; assert_eq!(takeable.as_ref(), &44); takeable.borrow(|n: u32| n + 1); assert_eq!(*takeable, 45); let out = takeable.borrow_result(|n: u32| (n + 1, n)); assert_eq!(out, 45); assert_eq!(takeable.into_inner(), 46); } #[test] #[should_panic] fn test_usable() { struct MyDrop { value: Takeable<()>, should_be_usable: bool, } impl Drop for MyDrop { fn drop(&mut self) { assert_eq!(self.value.is_usable(), self.should_be_usable); } } let _drop1 = MyDrop { value: Takeable::new(()), should_be_usable: true, }; let mut drop2 = MyDrop { value: Takeable::new(()), should_be_usable: false, }; drop2.value.borrow(|_| panic!()); } }
//! RS-Poker is a library for poker. //! It's mostly meant for Holdem games, however the core functionality //! should work for all game types. //! //! # Implemented: //! Currently RS-Poker supports: //! //! * Hand Iteration. //! * Hand Ranking. //! * Hand Range parsing. //! * Hand Range generation. //! //! # Planned: //! * Holdem Game State. //! * Multi-threading //! #![deny(clippy::all)] extern crate rand; /// Allow all the core poker functionality to be used /// externally. Everything in core should be agnostic /// to poker style. pub mod core; /// The holdem specific code. This contains range /// parsing, game state, and starting hand code. pub mod holdem; pub mod simulated_icm;
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkPresentInfoKHR { pub sType: VkStructureType, pub pNext: *const c_void, pub waitSemaphoreCount: u32, pub pWaitSemaphores: *const VkSemaphore, pub swapchainCount: u32, pub pSwapchains: *const VkSwapchainKHR, pub pImageIndices: *const u32, pub pResults: *mut VkResult, } impl VkPresentInfoKHR { pub fn new( wait_semaphores: &[VkSemaphore], swapchains: &[VkSwapchainKHR], image_indices: &[u32], results: &mut [VkResult], ) -> Self { debug_assert!(image_indices.len() == swapchains.len()); VkPresentInfoKHR { sType: VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, pNext: ptr::null(), waitSemaphoreCount: wait_semaphores.len() as u32, pWaitSemaphores: wait_semaphores.as_ptr(), swapchainCount: swapchains.len() as u32, pSwapchains: swapchains.as_ptr(), pImageIndices: image_indices.as_ptr(), pResults: if results.is_empty() { ptr::null_mut() } else { debug_assert!(results.len() == swapchains.len()); results.as_mut_ptr() }, } } }
// array static pada rust // gunakan vec! untuk dinamik elemen fn main() { let mut name = [""; 4]; name[0] = "Agus"; name[1] = "Susilo"; name[2] = "Rust"; name[3] = "Awesome"; for n in name.iter() { println!("{}", n); } let mut lang: [i32; 3] = [0; 3]; lang[0] = 1; lang[1] = 2; lang[2] = 3; for x in lang.iter() { println!("{:?}", x); } }
// Shortest Distance to a Character // https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3631/ pub struct Solution; impl Solution { pub fn shortest_to_char(s: String, c: char) -> Vec<i32> { let max_dist = s.len() as i32; let mut res = Vec::with_capacity(s.len()); let mut cur_dist = max_dist; for (idx, cur_c) in s.chars().enumerate() { if cur_c == c { cur_dist = 0; let mut back_dist = 1; for back_idx in (0..idx).rev() { if res[back_idx] <= back_dist { break; } res[back_idx] = back_dist; back_dist += 1; } } else { cur_dist = (cur_dist + 1).min(max_dist); } res.push(cur_dist); } res } } #[cfg(test)] mod tests { use super::*; fn check(s: &str, c: char, expected: &[i32]) { assert_eq!( Solution::shortest_to_char(String::from(s), c), expected.to_vec() ) } #[test] fn example1() { check("loveleetcode", 'e', &[3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]); } #[test] fn example2() { check("aaab", 'b', &[3, 2, 1, 0]); } #[test] fn test1() { check(&"a".repeat(10000), 'a', &[0; 10000]); } }
//! Ergonomic bindings for the [Max/MSP](https://cycling74.com/) [SDK](https://github.com/Cycling74/max-sdk). //! //! # Example //! //! A very basic external the has `bang`, `int`, `list`, and `any` methods. //! *See the examples folder for more detailed examples.* //! //! ```no_run //! use median::{ //! atom::Atom, builder::MaxWrappedBuilder, max_sys::t_atom_long, object::MaxObj, post, //! symbol::SymbolRef, wrapper::*, //! }; //! //! median::external! { //! pub struct Example; //! //! impl MaxObjWrapped<Example> for Example { //! fn new(builder: &mut dyn MaxWrappedBuilder<Self>) -> Self { //! let _ = builder.add_inlet(median::inlet::MaxInlet::Proxy); //! Self //! } //! } //! //! impl Example { //! #[bang] //! pub fn bang(&self) { //! let i = median::inlet::Proxy::get_inlet(self.max_obj()); //! median::object_post!(self.max_obj(), "bang from inlet {}", i); //! } //! //! #[int] //! pub fn int(&self, v: t_atom_long) { //! let i = median::inlet::Proxy::get_inlet(self.max_obj()); //! post!("int {} from inlet {}", v, i); //! } //! //! #[list] //! pub fn list(&self, atoms: &[Atom]) { //! post!("got list with length {}", atoms.len()); //! } //! //! #[any] //! pub fn baz(&self, sel: &SymbolRef, atoms: &[Atom]) { //! post!("got any with sel {} and length {}", sel, atoms.len()); //! } //! } //! } //! ``` //! pub mod alloc; pub mod atom; pub mod attr; pub mod buffer; pub mod builder; pub mod class; pub mod clock; pub mod error; pub mod file; pub mod inlet; pub mod method; pub mod notify; pub mod num; pub mod object; pub mod outlet; pub mod slice; pub mod symbol; pub mod thread; pub mod wrapper; //re-exports mod max; pub use self::max::*; pub use max_sys; /// Wrap the given code in ext_main pub use median_macros::ext_main; /// Create an external with the wrapped contents. pub use median_macros::external; /// Create an external with the wrapped contents, don't register ext_main. pub use median_macros::external_no_main; /// Post a message to the Max console, using the same format as `std::format!`. #[macro_export] macro_rules! post { ($($arg:tt)*) => {{ $crate::post(::std::format!($($arg)*)) }} } /// Post an error to the Max console, using the same format as `std::format!`. #[macro_export] macro_rules! error { ($($arg:tt)*) => {{ $crate::error(::std::format!($($arg)*)) }} } /// Post a message to the Max console, associated with the given object, using the same format as `std::format!`. /// /// # Examples /// /// Calling inside method for a struct that implements `MaxObjWrapped`. /// ```ignore /// use median::object::MaxObj; /// /// pub fn bang(&self) { /// median::object_post!(self.max_obj(), "from max obj"); /// } /// ``` /// /// Calling inside method for a struct that implements `MSPObjWrapped`. /// ```ignore /// use median::object::MSPObj; /// /// pub fn bang(&self) { /// median::object_post!(self.as_max_obj(), "from msp obj {}", 2084); /// } /// ``` /// /// # Remarks /// * `MaxObjWrapped` objects can use `self.max_obj()` as the first argument, but you must `use /// median::object::MaxObj` /// * `MSPObjWrapped` objects can use `self.as_max_obj()` as the first argument, but you must `use /// median::object::MSPObj` #[macro_export] macro_rules! object_post { ($obj:expr, $($arg:tt)*) => {{ $crate::object::post($obj, ::std::format!($($arg)*)) }} } /// Post an error to the Max console, associated with the given object, using the same format as `std::format!`. /// # Examples /// /// Calling inside method for a struct that implements `MaxObjWrapped`. /// ```ignore /// use median::object::MaxObj; /// /// pub fn bang(&self) { /// median::object_error!(self.max_obj(), "from max obj"); /// } /// ``` /// /// Calling inside method for a struct that implements `MSPObjWrapped`. /// ```ignore /// use median::object::MSPObj; /// /// pub fn bang(&self) { /// median::object_error!(self.as_max_obj(), "from msp obj {}", 2084); /// } /// ``` /// /// # Remarks /// * `MaxObjWrapped` objects can use `self.max_obj()` as the first argument, but you must `use /// median::object::MaxObj` /// * `MSPObjWrapped` objects can use `self.as_max_obj()` as the first argument, but you must `use /// median::object::MSPObj` #[macro_export] macro_rules! object_error { ($obj:expr, $($arg:tt)*) => {{ $crate::object::error($obj, ::std::format!($($arg)*)) }} } #[cfg(test)] pub mod test;
use opc_strip::OpcStrip; use std::io; use color_strip::ColorStrip; use effects::effect::Effect; use effects::ripple::Ripple; use effects::flash::Flash; use effects::blink::Blink; use effects::stream::Stream; use effects::push::Push; use effects::river::River; use effects::fish::Fish; use effects::stream_center::StreamCenter; use color::Color; use std::sync::mpsc; use midi_message::MidiMessage; use std::thread; use std::time::Duration; enum MidiLightMessage { MidiMessage(MidiMessage), Reconfigure(MidiLightPatch), Stop } #[derive(Default, Clone)] pub struct MidiLightConfig { pub led_count: usize, pub reversed: bool, pub patch: MidiLightPatch } pub struct MidiLightStrip { tx_strip: mpsc::Sender<MidiLightMessage>, } impl MidiLightStrip { pub fn start(config: MidiLightConfig) -> io::Result<MidiLightStrip> { let opc_strip = OpcStrip::connect(config.led_count, config.reversed)?; let (tx_strip, rx_strip) = mpsc::channel(); thread::spawn(move || { let mut my_thread = MidiLightStripThread::new(opc_strip, rx_strip, config); my_thread.run(); }); Ok(MidiLightStrip { tx_strip }) } pub fn on_midi_message(&self, midi_message: MidiMessage) { self.tx_strip.send(MidiLightMessage::MidiMessage(midi_message)).ok(); } pub fn reconfigure(&self, midi_light_patch: &MidiLightPatch) { self.tx_strip.send(MidiLightMessage::Reconfigure(midi_light_patch.clone())).ok(); } pub fn on_raw_midi_message(&self, status_and_channel: u8, data1: u8, data2: u8) { self.on_midi_message(MidiMessage::new(status_and_channel, data1, data2)); } pub fn stop(&self) { self.tx_strip.send(MidiLightMessage::Stop).ok(); } } pub struct MidiLightStripThread { opc_strip: OpcStrip, rx_strip: mpsc::Receiver<MidiLightMessage>, effects: Vec<Box<Effect>>, config: MidiLightConfig } impl MidiLightStripThread { fn new(opc_strip: OpcStrip, rx_strip: mpsc::Receiver<MidiLightMessage>, config: MidiLightConfig) -> MidiLightStripThread { let mut result = MidiLightStripThread { rx_strip, config, opc_strip, effects: vec![] }; result.init(); result } fn init(&mut self) { self.effects.clear(); let midi_light_patch = &self.config.patch; if midi_light_patch.push { self.effects.push(Box::new(Push::new(self.config.led_count))); } if midi_light_patch.stream { self.effects.push(Box::new(Stream::new(self.config.led_count))); } if midi_light_patch.stream_center { self.effects.push(Box::new(StreamCenter::new(self.config.led_count))); } if midi_light_patch.flash { self.effects.push(Box::new(Flash::new(self.config.led_count))); } if midi_light_patch.ripples { self.effects.push(Box::new(Ripple::new(self.config.led_count))); } if midi_light_patch.river { self.effects.push(Box::new(River::new(self.config.led_count))); } if midi_light_patch.fish { self.effects.push(Box::new(Fish::new(self.config.led_count))); } if midi_light_patch.blink { if midi_light_patch.flash || midi_light_patch.stream { self.effects.push(Box::new(Blink::new_with_add_color(Color::gray(200)))); } else { self.effects.push(Box::new(Blink::new())); } } } pub fn run(&mut self) { let mut color_strip = ColorStrip::new(self.config.led_count); loop { if let Ok(midi_light_message) = self.rx_strip.try_recv() { match midi_light_message { MidiLightMessage::MidiMessage(midi_message) => { let forward_message = match midi_message { MidiMessage::NoteOn(_, note, _) if note >= self.config.patch.max_note => false, _ => true }; if forward_message { for effect in &mut self.effects { effect.on_midi_message(midi_message); } } } MidiLightMessage::Reconfigure(midi_light_patch) => { self.config.patch = midi_light_patch; self.init(); } MidiLightMessage::Stop => { break; } } } color_strip.clear(Color::black()); for effect in &mut self.effects { effect.paint(&mut color_strip); effect.tick(); } self.opc_strip.send(&color_strip); thread::sleep(Duration::from_millis(10)); } } } #[derive(Default, Clone)] pub struct MidiLightPatch { pub fish: bool, pub river: bool, pub blink: bool, pub flash: bool, pub stream: bool, pub stream_center: bool, pub ripples: bool, pub push: bool, pub max_note: u8 }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "ApplicationModel_Store_LicenseManagement")] pub mod LicenseManagement; #[cfg(feature = "ApplicationModel_Store_Preview")] pub mod Preview; #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct FulfillmentResult(pub i32); impl FulfillmentResult { pub const Succeeded: Self = Self(0i32); pub const NothingToFulfill: Self = Self(1i32); pub const PurchasePending: Self = Self(2i32); pub const PurchaseReverted: Self = Self(3i32); pub const ServerError: Self = Self(4i32); } impl ::core::marker::Copy for FulfillmentResult {} impl ::core::clone::Clone for FulfillmentResult { fn clone(&self) -> Self { *self } } pub type LicenseChangedEventHandler = *mut ::core::ffi::c_void; pub type LicenseInformation = *mut ::core::ffi::c_void; pub type ListingInformation = *mut ::core::ffi::c_void; pub type ProductLicense = *mut ::core::ffi::c_void; pub type ProductListing = *mut ::core::ffi::c_void; pub type ProductPurchaseDisplayProperties = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ProductPurchaseStatus(pub i32); impl ProductPurchaseStatus { pub const Succeeded: Self = Self(0i32); pub const AlreadyPurchased: Self = Self(1i32); pub const NotFulfilled: Self = Self(2i32); pub const NotPurchased: Self = Self(3i32); } impl ::core::marker::Copy for ProductPurchaseStatus {} impl ::core::clone::Clone for ProductPurchaseStatus { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ProductType(pub i32); impl ProductType { pub const Unknown: Self = Self(0i32); pub const Durable: Self = Self(1i32); pub const Consumable: Self = Self(2i32); } impl ::core::marker::Copy for ProductType {} impl ::core::clone::Clone for ProductType { fn clone(&self) -> Self { *self } } pub type PurchaseResults = *mut ::core::ffi::c_void; pub type UnfulfilledConsumable = *mut ::core::ffi::c_void;
///! Kernel erlang is like Core Erlang with a few significant ///! differences: ///! ///! 1. It is flat! There are no nested calls or sub-blocks. ///! ///! 2. All variables are unique in a function. There is no scoping, or ///! rather the scope is the whole function. ///! ///! 3. Pattern matching (in cases and receives) has been compiled. ///! ///! 4. All remote-calls are to statically named m:f/a. Meta-calls are ///! passed via erlang:apply/3. ///! ///! The translation is done in two passes: ///! ///! 1. Basic translation, translate variable/function names, flatten ///! completely, pattern matching compilation. ///! ///! 2. Fun-lifting (lambda-lifting), variable usage annotation and ///! last-call handling. ///! ///! All new Kexprs are created in the first pass, they are just ///! annotated in the second. ///! ///! Functions and BIFs ///! ///! Functions are "call"ed or "enter"ed if it is a last call, their ///! return values may be ignored. BIFs are things which are known to ///! be internal by the compiler and can only be called, their return ///! values cannot be ignored. ///! ///! Letrec's are handled rather naively. All the functions in one ///! letrec are handled as one block to find the free variables. While ///! this is not optimal it reflects how letrec's often are used. We ///! don't have to worry about variable shadowing and nested letrec's as ///! this is handled in the variable/function name translation. There ///! is a little bit of trickery to ensure letrec transformations fit ///! into the scheme of things. ///! ///! To ensure unique variable names we use a variable substitution ///! table and keep the set of all defined variables. The nested ///! scoping of Core means that we must also nest the substitution ///! tables, but the defined set must be passed through to match the ///! flat structure of Kernel and to make sure variables with the same ///! name from different scopes get different substitutions. ///! ///! We also use these substitutions to handle the variable renaming ///! necessary in pattern matching compilation. ///! ///! The pattern matching compilation assumes that the values of ///! different types don't overlap. This means that as there is no ///! character type yet in the machine all characters must be converted ///! to integers! use std::collections::{BTreeMap, BTreeSet}; use std::mem; use std::ops::RangeInclusive; use rpds::{rbt_set, RedBlackTreeSet}; use firefly_binary::{BinaryEntrySpecifier, BitVec, Endianness}; use firefly_diagnostics::*; use firefly_intern::{symbols, Ident, Symbol}; use firefly_number::Integer; use firefly_pass::Pass; use firefly_syntax_base::*; use firefly_syntax_core as core; use crate::{passes::FunctionContext, *}; // Matches collapse max segment CST translation. const EXPAND_MAX_SIZE_SEGMENT: usize = 1024; #[derive(Debug, thiserror::Error)] pub enum ExprError { #[error("bad segment size")] BadSegmentSize(SourceSpan), } /// This pass transforms a Core IR function into its Kernel IR form for further analysis and eventual lowering to SSA IR pub struct CoreToKernel { reporter: Reporter, } impl CoreToKernel { pub fn new(reporter: Reporter) -> Self { Self { reporter } } } impl Pass for CoreToKernel { type Input<'a> = core::Module; type Output<'a> = Module; fn run<'a>(&mut self, mut cst: Self::Input<'a>) -> anyhow::Result<Self::Output<'a>> { let mut module = Module { span: cst.span, annotations: Annotations::default(), name: cst.name, compile: cst.compile, on_load: cst.on_load, nifs: cst.nifs, exports: cst.exports, functions: vec![], }; let mut funs = vec![]; while let Some((name, function)) = cst.functions.pop_first() { let context = FunctionContext::new(function.span(), name, function.var_counter); let mut pipeline = TranslateCore::new(self.reporter.clone(), context, module.name.name); let fun = pipeline.run(function.fun)?; module.functions.push(fun); funs.append(&mut pipeline.context.funs); } module.functions.append(&mut funs); Ok(module) } } struct TranslateCore { reporter: Reporter, context: FunctionContext, module_name: Symbol, } impl TranslateCore { fn new(reporter: Reporter, context: FunctionContext, module_name: Symbol) -> Self { Self { reporter, context, module_name, } } } impl Pass for TranslateCore { type Input<'a> = core::Fun; type Output<'a> = Function; fn run<'a>(&mut self, fun: Self::Input<'a>) -> anyhow::Result<Self::Output<'a>> { match self.expr(core::Expr::Fun(fun), BiMap::default())? { (Expr::Fun(ifun), _) => { let span = ifun.span(); let annotations = ifun.annotations; let vars = ifun.vars; let (body, _) = self.ubody(*ifun.body, Brk::Return)?; match body { body @ Expr::Match(_) => Ok(Function { span, annotations, name: self.context.name, vars, body: Box::new(body), }), other => { let body = Box::new(Expr::Match(Match { span, annotations: Annotations::default(), body: Box::new(other), ret: vec![], })); Ok(Function { span, annotations, name: self.context.name, vars, body, }) } } } _ => unreachable!(), } } } impl TranslateCore { /// body(Cexpr, Sub, State) -> {Kexpr,[PreKepxr],State}. /// Do the main sequence of a body. A body ends in an atomic value or /// values. Must check if vector first so do expr. fn body(&mut self, expr: core::Expr, sub: BiMap) -> Result<(Expr, Vec<Expr>), ExprError> { match expr { core::Expr::Values(core::Values { annotations, values, .. }) => { // Do this here even if only in bodies let (values, pre) = self.atomic_list(values, sub)?; Ok(( Expr::Values(IValues { annotations, values, }), pre, )) } expr => self.expr(expr, sub), } } /// guard(Cexpr, Sub, State) -> {Kexpr,State}. /// We handle guards almost as bodies. The only special thing we /// must do is to make the final Kexpr a #k_test{}. fn guard(&mut self, expr: core::Expr, sub: BiMap) -> Result<Expr, ExprError> { let (guard, pre) = self.expr(expr, sub)?; let guard = self.gexpr_test(guard); Ok(pre_seq(pre, guard)) } /// gexpr_test(Kexpr, State) -> {Kexpr,State}. /// Builds the final boolean test from the last Kexpr in a guard test. /// Must enter try blocks and isets and find the last Kexpr in them. /// This must end in a recognised BEAM test! fn gexpr_test(&mut self, expr: Expr) -> Expr { match expr { // Convert to test Expr::Bif(bif) if bif.is_type_test() || bif.is_comp_op() => { let span = bif.span; let annotations = bif.annotations; let op = bif.op; let args = bif.args; Expr::Test(Test { span, annotations, op, args, }) } Expr::Try(Try { span, annotations, arg, vars, body, evars, handler, ret, }) => { let arg = self.gexpr_test(*arg); Expr::Try(Try { span, annotations, arg: Box::new(arg), vars, body, evars, handler, ret, }) } Expr::Set(ISet { span, annotations, vars, arg, body, }) => { let body = self.gexpr_test(*body.unwrap()); Expr::Set(ISet { span, annotations, vars, arg, body: Some(Box::new(body)), }) } // Add equality test expr => self.gexpr_test_add(expr), } } fn gexpr_test_add(&mut self, expr: Expr) -> Expr { let span = expr.span(); let annotations = expr.annotations().clone(); let op = FunctionName::new(symbols::Erlang, symbols::EqualStrict, 2); let (expr, pre) = self.force_atomic(expr); let t = Expr::Literal(Literal::atom(span, symbols::True)); pre_seq( pre, Expr::Test(Test { span, annotations, op, args: vec![expr, t], }), ) } /// Convert a core expression to a kernel expression, flattening it. fn expr(&mut self, expr: core::Expr, sub: BiMap) -> Result<(Expr, Vec<Expr>), ExprError> { match expr { core::Expr::Var(v) if v.arity.is_some() => { let span = v.span(); let arity = v.arity.unwrap(); let name = Name::from(&v); let name = sub.get(name).unwrap_or(name); let local = FunctionName::new_local(name.symbol(), arity as u8); Ok((Expr::Local(Span::new(span, local)), vec![])) } core::Expr::Var(mut v) => { let name = sub.get_vsub(v.name.name); v.name.name = name; Ok((Expr::Var(v), vec![])) } core::Expr::Literal(lit) => Ok((Expr::Literal(lit), vec![])), core::Expr::Cons(core::Cons { span, annotations, box head, box tail, }) => { // Do cons in two steps, first the expressions left to right, // then any remaining literals right to left. let (kh, mut pre) = self.expr(head, sub.clone())?; let (kt, mut pre2) = self.expr(tail, sub.clone())?; let (kt, mut pre3) = self.force_atomic(kt); let (kh, mut pre4) = self.force_atomic(kh); pre.append(&mut pre2); pre.append(&mut pre3); pre.append(&mut pre4); Ok(( Expr::Cons(Cons { span, annotations, head: Box::new(kh), tail: Box::new(kt), }), pre, )) } core::Expr::Tuple(core::Tuple { span, annotations, elements, }) => { let (elements, pre) = self.atomic_list(elements, sub)?; Ok(( Expr::Tuple(Tuple { span, annotations, elements, }), pre, )) } core::Expr::Map(core::Map { annotations, box arg, pairs, .. }) => self.expr_map(annotations, arg, pairs, sub), core::Expr::Binary(core::Binary { span, annotations, segments, }) => match self.atomic_bin(segments, sub.clone()) { Ok((segment, pre)) => Ok(( Expr::Binary(Binary { span, annotations, segment, }), pre, )), Err(ExprError::BadSegmentSize(span)) => { self.reporter.show_error( "invalid binary size", &[(span, "associated with this segment")], ); let badarg = core::Expr::Literal(Literal::atom(span, symbols::Badarg)); let error = core::Call::new(span, symbols::Erlang, symbols::Error, vec![badarg]); self.expr(core::Expr::Call(error), sub) } }, core::Expr::Fun(core::Fun { span, annotations, mut vars, box body, .. }) => { // Build up the set of current fun arguments let cvars = vars.drain(..).map(core::Expr::Var).collect(); let (mut vars, sub) = self.pattern_list(cvars, sub.clone(), sub)?; let vars = vars.drain(..).map(|v| v.into_var().unwrap()).collect(); // Save any parent fun arguments, replacing with the current args let parent_vars = mem::replace(&mut self.context.args, vars); let (body, pre) = self.body(body, sub)?; let body = pre_seq(pre, body); // Place back the original fun arguments let vars = mem::replace(&mut self.context.args, parent_vars); Ok(( Expr::Fun(IFun { span, annotations, vars, body: Box::new(body), }), vec![], )) } core::Expr::Seq(core::Seq { box arg, box body, .. }) => { let (arg, mut pre) = self.body(arg, sub.clone())?; let (body, mut pre2) = self.body(body, sub)?; pre.push(arg); pre.append(&mut pre2); Ok((body, pre)) } core::Expr::Let(core::Let { span, annotations, mut vars, box arg, box body, }) => { let (arg, mut pre) = self.body(arg, sub.clone())?; let cvars = vars.drain(..).map(core::Expr::Var).collect(); let (mut vars, sub) = self.pattern_list(cvars, sub.clone(), sub)?; // Break down multiple values into separate set expressions match arg { Expr::Values(IValues { mut values, .. }) => { assert_eq!(vars.len(), values.len()); pre.extend(vars.drain(..).zip(values.drain(..)).map(|(var, value)| { let var = var.into_var().unwrap(); let span = var.span(); kset!(span, var, value).into() })); } arg => { pre.push(Expr::Set(ISet { span, annotations, vars: vars.drain(..).map(|v| v.into_var().unwrap()).collect(), arg: Box::new(arg), body: None, })); } }; let (body, mut pre2) = self.body(body, sub)?; pre.append(&mut pre2); Ok((body, pre)) } core::Expr::LetRec(core::LetRec { span, annotations, mut defs, box body, }) => { if annotations.contains(symbols::LetrecGoto) { assert_eq!(defs.len(), 1); let (var, def) = defs.pop().unwrap(); self.letrec_goto(span, var, def, body, sub) } else { self.letrec_local_function(span, annotations, defs, body, sub) } } core::Expr::Case(core::Case { box arg, clauses, .. }) => { let (arg, mut pre) = self.body(arg, sub.clone())?; let (vars, mut pre2) = self.match_vars(arg); let mexpr = self.kmatch(vars, clauses, sub)?; let mut seq = flatten_seq(build_match(mexpr)); let expr = seq.pop().unwrap(); pre.append(&mut pre2); pre.append(&mut seq); Ok((expr, pre)) } core::Expr::If(core::If { span, annotations, box guard, box then_body, box else_body, }) => { let (cond, pre) = self.body(guard, sub.clone())?; let (then_body, tpre) = self.body(then_body, sub.clone())?; let then_body = pre_seq(tpre, then_body); let (else_body, epre) = self.body(else_body, sub.clone())?; let else_body = pre_seq(epre, else_body); Ok(( Expr::If(If { span, annotations, cond: Box::new(cond), then_body: Box::new(then_body), else_body: Box::new(else_body), ret: vec![], }), pre, )) } core::Expr::Apply(core::Apply { span, annotations, box callee, args, }) => self.capply(span, annotations, callee, args, sub), core::Expr::Call(core::Call { span, annotations, box module, box function, mut args, }) => { match call_type(&module, &function, args.as_slice()) { CallType::Error => { // Invalid module/function, must rewrite as a call to apply/3 and let it fail at runtime let argv = make_clist(args); let mut mfa = Vec::with_capacity(3); mfa.push(module); mfa.push(function); mfa.push(argv); let call = core::Expr::Call(core::Call::new( span, symbols::Erlang, symbols::Apply, mfa, )); self.expr(call, sub) } CallType::Bif(op) => { let (args, pre) = self.atomic_list(args, sub)?; Ok(( Expr::Bif(Bif { span, annotations, op, args, ret: vec![], }), pre, )) } CallType::Static(callee) => { let (args, pre) = self.atomic_list(args, sub)?; Ok(( Expr::Call(Call { span, annotations, callee: Box::new(Expr::Remote(Remote::Static(Span::new( span, callee, )))), args, ret: vec![], }), pre, )) } CallType::Dynamic => { let mut mfa = Vec::with_capacity(args.len() + 2); mfa.push(module); mfa.push(function); mfa.append(&mut args); let (mut mfa, pre) = self.atomic_list(mfa, sub)?; let args = mfa.split_off(2); let function = mfa.pop().unwrap(); let module = mfa.pop().unwrap(); let callee = Box::new(Expr::Remote(Remote::Dynamic( Box::new(module), Box::new(function), ))); Ok(( Expr::Call(Call { span, annotations, callee, args, ret: vec![], }), pre, )) } } } core::Expr::PrimOp(core::PrimOp { span, annotations, name: symbols::MatchFail, mut args, }) => self.translate_match_fail(span, annotations, args.pop().unwrap(), sub), core::Expr::PrimOp(core::PrimOp { span, name: symbols::MakeFun, args, .. }) if args.len() == 3 && args.iter().all(|arg| arg.is_literal()) => { // If make_fun/3 is called with all literal values, convert it to its ideal form match args.as_slice() { [core::Expr::Literal(Literal { value: Lit::Atom(m), .. }), core::Expr::Literal(Literal { value: Lit::Atom(f), .. }), core::Expr::Literal(Literal { value: Lit::Integer(Integer::Small(arity)), .. })] => { let arity = *arity; if *m == self.module_name { let local = Expr::Local(Span::new( span, FunctionName::new_local(*f, arity.try_into().unwrap()), )); let op = FunctionName::new(symbols::Erlang, symbols::MakeFun, 3); Ok((Expr::Bif(Bif::new(span, op, vec![local])), vec![])) } else { let remote = Expr::Remote(Remote::Static(Span::new( span, FunctionName::new(*m, *f, arity.try_into().unwrap()), ))); let op = FunctionName::new(symbols::Erlang, symbols::MakeFun, 3); Ok((Expr::Bif(Bif::new(span, op, vec![remote])), vec![])) } } other => panic!("invalid callee, expected literal mfa, got {:#?}", &other), } } core::Expr::PrimOp(core::PrimOp { span, name, args, .. }) => { let arity = args.len() as u8; let (args, pre) = self.atomic_list(args, sub)?; let op = FunctionName::new(symbols::Erlang, name, arity); Ok((Expr::Bif(Bif::new(span, op, args)), pre)) } core::Expr::Try(core::Try { span, annotations, box arg, mut vars, box body, mut evars, box handler, }) => { // The normal try expression. The body and exception handler // variables behave as let variables. let (arg, apre) = self.body(arg, sub.clone())?; let cvars = vars.drain(..).map(core::Expr::Var).collect(); let (mut vars, sub1) = self.pattern_list(cvars, sub.clone(), sub.clone())?; let vars = vars.drain(..).map(|v| v.into_var().unwrap()).collect(); let (body, bpre) = self.body(body, sub1)?; let cevars = evars.drain(..).map(core::Expr::Var).collect(); let (mut evars, sub2) = self.pattern_list(cevars, sub.clone(), sub)?; let evars = evars.drain(..).map(|v| v.into_var().unwrap()).collect(); let (handler, hpre) = self.body(handler, sub2)?; let arg = pre_seq(apre, arg); let body = pre_seq(bpre, body); let handler = pre_seq(hpre, handler); Ok(( Expr::Try(Try { span, annotations, arg: Box::new(arg), body: Box::new(body), handler: Box::new(handler), vars, evars, ret: vec![], }), vec![], )) } core::Expr::Catch(core::Catch { span, annotations, box body, }) => { let (body, pre) = self.body(body, sub)?; let body = pre_seq(pre, body); Ok(( Expr::Catch(Catch { span, annotations, body: Box::new(body), ret: vec![], }), vec![], )) } other => panic!("untranslatable core expression for kernel: {:?}", &other), } } /// Implement letrec in the traditional way as a local function for each definition in the letrec fn letrec_local_function( &mut self, span: SourceSpan, annotations: Annotations, mut defs: Vec<(Var, core::Expr)>, body: core::Expr, sub: BiMap, ) -> Result<(Expr, Vec<Expr>), ExprError> { // Make new function names and store substitution let sub = defs .iter_mut() .fold(sub, |sub, (ref mut var, ref mut def)| { let arity = var.arity.take().unwrap(); let span = var.name.span; let f = var.name.name; let ty = format!("{}/{}", f, arity); let n = self.context.new_fun_name(Some(&ty)); def.annotate(symbols::LetrecName, Literal::atom(span, n)); var.name = Ident::new(n, span); sub.set_fsub(f, arity, Name::Var(n)) }); // Run translation on functions and body. let defs = defs .drain(..) .map(|(var, def)| { let (Expr::Fun(mut def), dpre) = self.expr(def, sub.clone())? else { panic!("expected ifun") }; assert_eq!(dpre.len(), 0); def.annotations_mut().replace(annotations.clone()); Ok((var, def)) }) .try_collect()?; let (body, mut bpre) = self.body(body, sub)?; let mut pre = vec![Expr::LetRec(ILetRec { span, annotations, defs, })]; pre.append(&mut bpre); Ok((body, pre)) } /// Implement letrec with the sole definition as a label and each apply of it as a goto fn letrec_goto( &mut self, span: SourceSpan, var: Var, fail: core::Expr, body: core::Expr, sub: BiMap, ) -> Result<(Expr, Vec<Expr>), ExprError> { let label = var.name.name; assert_ne!(var.arity, None); let core::Expr::Fun(fail) = fail else { panic!("unexpected letrec definition") }; let fun_vars = fail.vars; let fun_body = fail.body; let mut kvars = Vec::with_capacity(fun_vars.len()); let fun_sub = fun_vars.iter().fold(sub.clone(), |sub, fv| { let new_name = self.context.next_var_name(Some(fv.span())); kvars.push(Var { annotations: fv.annotations.clone(), name: new_name, arity: None, }); let sub = sub.set_vsub(fv.name.name, new_name.name); self.context.defined.insert_mut(new_name); sub }); let labels0 = self.context.labels.clone(); self.context.labels.insert_mut(label); let (body, bpre) = self.body(body, sub.clone())?; let (fail, fpre) = self.body(*fun_body, fun_sub)?; match (body, fail) { (Expr::Goto(gt), Expr::Goto(inner_gt)) if gt.label == label => { Ok((Expr::Goto(inner_gt), bpre)) } (body, fail) => { self.context.labels = labels0; let then_body = pre_seq(fpre, fail); let alt = Expr::LetRecGoto(LetRecGoto { span, annotations: Annotations::default(), label, vars: kvars, first: Box::new(body), then: Box::new(then_body), ret: vec![], }); Ok((alt, bpre)) } } } /// Translate match_fail primop, paying extra attention to `function_clause` /// errors that may have been inlined from other functions. fn translate_match_fail( &mut self, span: SourceSpan, annotations: Annotations, arg: core::Expr, sub: BiMap, ) -> Result<(Expr, Vec<Expr>), ExprError> { let (args, annotations) = match arg { core::Expr::Tuple(core::Tuple { annotations, elements, .. }) => match &elements[0] { core::Expr::Literal(Literal { value: Lit::Atom(symbols::FunctionClause), .. }) => self.translate_fc_args(elements, sub.clone(), annotations), _ => (elements, annotations), }, core::Expr::Literal(Literal { value: Lit::Tuple(mut elements), .. }) => match &elements[0].value { Lit::Atom(symbols::FunctionClause) => { let args = elements.drain(..).map(core::Expr::Literal).collect(); self.translate_fc_args(args, sub.clone(), annotations) } _ => { let args = elements.drain(..).map(core::Expr::Literal).collect(); (args, annotations) } }, reason @ core::Expr::Literal(_) => (vec![reason], annotations), other => panic!("unexpected match_fail argument type: {:?}", &other), }; let arity = args.len(); let (args, pre) = self.atomic_list(args, sub)?; Ok(( Expr::Bif(Bif { span, annotations, op: FunctionName::new(symbols::Erlang, symbols::MatchFail, arity as u8), args, ret: vec![], }), pre, )) } fn translate_fc_args( &mut self, args: Vec<core::Expr>, sub: BiMap, mut annotations: Annotations, ) -> (Vec<core::Expr>, Annotations) { if same_args(args.as_slice(), self.context.args.as_slice(), &sub) { // The arguments for the function_clause exception are the arguments // for the current function in the correct order. (args, annotations) } else { // The arguments in the function_clause exception don't match the // arguments for the current function because of inlining match annotations.get(symbols::Function) { None => { let span = SourceSpan::default(); let name = self.context.new_fun_name(Some("inlined")); let name = Literal::atom(span, name); let arity = Literal::integer(span, args.len() - 1); let na = Literal::tuple(span, vec![name, arity]); annotations.insert_mut(symbols::Inlined, na); (args, annotations) } Some(Annotation::Term(Literal { value: Lit::Tuple(elems), .. })) if elems.len() == 2 => { // This is the function that was inlined let span = SourceSpan::default(); let name0 = elems[0].as_atom().unwrap(); let arity0 = elems[1].as_integer().unwrap(); let name = format!("-inlined-{}/{}-", name0, arity0); let name = Literal::atom(span, Symbol::intern(&name)); let arity = Literal::integer(span, arity0.clone()); let na = Literal::tuple(span, vec![name, arity]); annotations.insert_mut(symbols::Inlined, na); (args, annotations) } other => panic!("unexpected value for 'function' annotation: {:?}", &other), } } } fn expr_map( &mut self, annotations: Annotations, arg: core::Expr, pairs: Vec<core::MapPair>, sub: BiMap, ) -> Result<(Expr, Vec<Expr>), ExprError> { let (var, mut pre) = self.expr(arg, sub.clone())?; let (m, mut pre2) = self.map_split_pairs(annotations, var, pairs, sub)?; pre2.append(&mut pre); Ok((m, pre2)) } fn map_split_pairs( &mut self, annotations: Annotations, var: Expr, mut pairs: Vec<core::MapPair>, sub: BiMap, ) -> Result<(Expr, Vec<Expr>), ExprError> { // 1. Force variables. // 2. Group adjacent pairs with literal keys. // 3. Within each such group, remove multiple assignments to the same key. // 4. Partition each group according to operator ('=>' and ':=') let mut pre = vec![]; let mut kpairs = Vec::with_capacity(pairs.len()); for core::MapPair { op, box key, box value, } in pairs.drain(..) { let (key, mut pre1) = self.atomic(key, sub.clone())?; let (value, mut pre2) = self.atomic(value, sub.clone())?; kpairs.push(( op, MapPair { key: Box::new(key), value: Box::new(value), }, )); pre.append(&mut pre1); pre.append(&mut pre2); } let mut iter = kpairs.drain(..); let mut groups: Vec<(MapOp, Vec<MapPair>)> = vec![]; // Group adjacent pairs with literal keys, variables are always in their own groups let mut seen: BTreeMap<Literal, (MapOp, MapPair)> = BTreeMap::new(); while let Some((op, pair)) = iter.next() { match pair.key.as_ref() { Expr::Var(_) => { // Do not group variable keys with other keys if !seen.is_empty() { // Partition the group by operator let (mut a, mut b) = seen .into_values() .partition::<Vec<_>, _>(|(op, _pair)| op == &MapOp::Exact); if !a.is_empty() { groups.push((MapOp::Exact, a.drain(..).map(|(_, p)| p).collect())); } if !b.is_empty() { groups.push((MapOp::Assoc, b.drain(..).map(|(_, p)| p).collect())); } groups.push((op, vec![pair])); seen = BTreeMap::new(); } else { groups.push((op, vec![pair])); } } Expr::Literal(lit) => match seen.get(lit).map(|(o, _)| o) { None => { seen.insert(lit.clone(), (op, pair)); } Some(orig_op) => { seen.insert(lit.clone(), (*orig_op, pair)); } }, other => panic!("expected valid map key pattern, got {:?}", &other), } } if !seen.is_empty() { // Partition the final group by operator let (mut a, mut b) = seen .into_values() .partition::<Vec<_>, _>(|(op, _pair)| op == &MapOp::Exact); if !a.is_empty() { groups.push((MapOp::Exact, a.drain(..).map(|(_, p)| p).collect())); } if !b.is_empty() { groups.push((MapOp::Assoc, b.drain(..).map(|(_, p)| p).collect())); } } Ok(groups .drain(..) .fold((var, pre), |(map, mut pre), (op, pairs)| { let span = map.span(); let (map, mut mpre) = self.force_atomic(map); pre.append(&mut mpre); ( Expr::Map(Map { span, annotations: annotations.clone(), op, var: Box::new(map), pairs, }), pre, ) })) } /// Force return from body into a list of variables fn match_vars(&mut self, expr: Expr) -> (Vec<Var>, Vec<Expr>) { match expr { Expr::Values(IValues { mut values, .. }) => { let mut pre = vec![]; let mut vars = vec![]; for expr in values.drain(..) { let (var, mut pre2) = self.force_variable(expr); vars.push(var); pre.append(&mut pre2); } (vars, pre) } expr => { let (v, pre) = self.force_variable(expr); (vec![v], pre) } } } /// Transform application fn capply( &mut self, span: SourceSpan, annotations: Annotations, callee: core::Expr, args: Vec<core::Expr>, sub: BiMap, ) -> Result<(Expr, Vec<Expr>), ExprError> { match callee { core::Expr::Var(v) if v.arity.is_some() => { let f0 = v.name.name; let (args, pre) = self.atomic_list(args, sub.clone())?; if self.context.labels.contains(&f0) { // This is a goto to a label in a letrec_goto construct let gt = Expr::Goto(Goto { span, annotations: Annotations::default(), label: f0, args, }); Ok((gt, pre)) } else { let arity = v.arity.unwrap(); let f1 = sub.get_fsub(f0, arity); let callee = FunctionName::new_local(f1, arity as u8); let call = Expr::Call(Call { span, annotations, callee: Box::new(Expr::Local(Span::new(span, callee))), args, ret: vec![], }); Ok((call, pre)) } } callee => { let (callee, mut pre) = self.variable(callee, sub.clone())?; let (args, mut ap) = self.atomic_list(args, sub)?; pre.append(&mut ap); Ok(( Expr::Call(Call { span, annotations, callee: Box::new(callee), args, ret: vec![], }), pre, )) } } } /// Convert a core expression making sure the result is an atomic fn atomic(&mut self, expr: core::Expr, sub: BiMap) -> Result<(Expr, Vec<Expr>), ExprError> { let (expr, mut pre) = self.expr(expr, sub)?; let (expr, mut pre2) = self.force_atomic(expr); pre.append(&mut pre2); Ok((expr, pre)) } fn force_atomic(&mut self, expr: Expr) -> (Expr, Vec<Expr>) { if expr.is_atomic() { (expr, vec![]) } else { let span = expr.span(); let v = self.context.next_var(Some(span)); let set = Expr::Set(ISet::new(span, vec![v.clone()], expr, None)); (Expr::Var(v), vec![set]) } } fn atomic_bin( &mut self, mut segments: Vec<core::Bitstring>, sub: BiMap, ) -> Result<(Box<Expr>, Vec<Expr>), ExprError> { if segments.is_empty() { return Ok((Box::new(Expr::BinaryEnd(SourceSpan::default())), vec![])); } let segment = segments.remove(0); let (value, mut pre) = self.atomic(*segment.value, sub.clone())?; let (size, mut pre2) = match segment.size { None => (None, vec![]), Some(sz) => { let (sz, szpre) = self.atomic(*sz, sub.clone())?; (Some(sz), szpre) } }; validate_bin_element_size(size.as_ref(), &segment.annotations)?; let (next, mut pre3) = self.atomic_bin(segments, sub)?; pre.append(&mut pre2); pre.append(&mut pre3); Ok(( Box::new(Expr::BinarySegment(BinarySegment { span: segment.span, annotations: segment.annotations, spec: segment.spec, size: size.map(Box::new), value: Box::new(value), next, })), pre, )) } fn atomic_list( &mut self, mut exprs: Vec<core::Expr>, sub: BiMap, ) -> Result<(Vec<Expr>, Vec<Expr>), ExprError> { let mut pre = vec![]; let mut kexprs = Vec::with_capacity(exprs.len()); for expr in exprs.drain(..) { let (expr, mut pre2) = self.atomic(expr, sub.clone())?; kexprs.push(expr); pre.append(&mut pre2); } Ok((kexprs, pre)) } /// Convert a core expression, ensuring the result is a variable fn variable(&mut self, expr: core::Expr, sub: BiMap) -> Result<(Expr, Vec<Expr>), ExprError> { let (expr, mut pre) = self.expr(expr, sub)?; let (v, mut vpre) = self.force_variable(expr); pre.append(&mut vpre); Ok((Expr::Var(v), pre)) } fn force_variable(&mut self, expr: Expr) -> (Var, Vec<Expr>) { match expr { Expr::Var(v) => (v, vec![]), e => { let span = e.span(); let v = self.context.next_var(Some(span)); let set = Expr::Set(ISet::new(span, vec![v.clone()], e, None)); (v, vec![set]) } } } fn pattern_list( &mut self, mut patterns: Vec<core::Expr>, isub: BiMap, osub: BiMap, ) -> Result<(Vec<Expr>, BiMap), ExprError> { let out = Vec::with_capacity(patterns.len()); patterns .drain(..) .try_fold((out, osub), |(mut out, osub0), pat| { let (pattern, osub1) = self.pattern(pat, isub.clone(), osub0)?; out.push(pattern); Ok((out, osub1)) }) } /// pattern(Cpat, Isub, Osub, State) -> {Kpat,Sub,State}. /// Convert patterns. Variables shadow so rename variables that are /// already defined. /// /// Patterns are complicated by sizes in binaries. These are pure /// input variables which create no bindings. We, therefore, need to /// carry around the original substitutions to get the correct /// handling. fn pattern( &mut self, pattern: core::Expr, isub: BiMap, osub: BiMap, ) -> Result<(Expr, BiMap), ExprError> { match pattern { core::Expr::Var(v) => { if self.context.defined.contains(&v.name) { let new = self.context.next_var(Some(v.name.span)); let osub = osub.set(Name::from(&v), Name::from(&new)); self.context.defined.insert_mut(new.name); Ok((Expr::Var(new), osub)) } else { self.context.defined.insert_mut(v.name); Ok((Expr::Var(v), osub)) } } core::Expr::Literal(lit) => Ok((Expr::Literal(lit), osub)), core::Expr::Cons(core::Cons { span, annotations, box head, box tail, }) => { let (head, osub) = self.pattern(head, isub.clone(), osub)?; let (tail, osub) = self.pattern(tail, isub, osub)?; Ok(( Expr::Cons(Cons { span, annotations, head: Box::new(head), tail: Box::new(tail), }), osub, )) } core::Expr::Tuple(core::Tuple { span, annotations, elements, }) => { let (elements, osub) = self.pattern_list(elements, isub, osub)?; Ok(( Expr::Tuple(Tuple { span, annotations, elements, }), osub, )) } core::Expr::Map(core::Map { span, annotations, arg, pairs, .. }) => { // REVIEW: Is it correct here to handle `arg` as a pattern? let (var, osub) = self.pattern(*arg, isub.clone(), osub)?; let (pairs, osub) = self.pattern_map_pairs(pairs, isub, osub)?; Ok(( Expr::Map(Map { span, annotations, var: Box::new(var), op: MapOp::Exact, pairs, }), osub, )) } core::Expr::Binary(core::Binary { span, annotations, segments, }) => { let (segment, osub) = self.pattern_bin(segments, isub, osub)?; Ok(( Expr::Binary(Binary { span, annotations, segment, }), osub, )) } core::Expr::Alias(core::Alias { span, annotations, var, box pattern, }) => { let (mut vars, pattern) = flatten_alias(pattern); let mut vs = vec![core::Expr::Var(var)]; vs.extend(vars.drain(..).map(core::Expr::Var)); let (mut vars, osub) = self.pattern_list(vs, isub.clone(), osub)?; let vars = vars.drain(..).map(|v| v.into_var().unwrap()).collect(); let (pattern, osub) = self.pattern(pattern, isub, osub)?; Ok(( Expr::Alias(IAlias { span, annotations, vars, pattern: Box::new(pattern), }), osub, )) } invalid => panic!("invalid core expression in pattern: {:?}", &invalid), } } fn pattern_map_pairs( &mut self, mut pairs: Vec<core::MapPair>, isub: BiMap, osub: BiMap, ) -> Result<(Vec<MapPair>, BiMap), ExprError> { // Pattern the pair keys and values as normal let mut kpairs = Vec::with_capacity(pairs.len()); let mut osub1 = osub.clone(); for core::MapPair { op, box key, box value, } in pairs.drain(..) { assert_eq!(op, MapOp::Exact); let (key, _) = self.expr(key, isub.clone())?; let (value, osub2) = self.pattern(value, isub.clone(), osub1)?; osub1 = osub2; kpairs.push(MapPair { key: Box::new(key), value: Box::new(value), }); } // It is later assumed that these keys are term sorted, so we need to sort them here kpairs.sort_by(|a, b| a.cmp(b)); Ok((kpairs, osub1)) } fn pattern_bin( &mut self, mut segments: Vec<core::Bitstring>, isub: BiMap, osub: BiMap, ) -> Result<(Box<Expr>, BiMap), ExprError> { if segments.is_empty() { return Ok((Box::new(Expr::BinaryEnd(SourceSpan::default())), osub)); } let segment = segments.remove(0); let size = match segment.size { None => None, Some(sz) => { let (sz, _) = self.expr(*sz, isub.clone())?; match sz { sz @ Expr::Var(_) => Some(sz), Expr::Literal(Literal { value: Lit::Atom(symbols::All), .. }) => None, sz @ Expr::Literal(_) if sz.is_integer() => Some(sz), // Bad size (coming from an optimization or source code), replace it // with a known atom to avoid accidentally treating it like a real size sz => Some(Expr::Literal(Literal::atom(sz.span(), symbols::BadSize))), } } }; let (value, osub) = self.pattern(*segment.value, isub.clone(), osub)?; let (next, osub) = self.pattern_bin(segments, isub, osub)?; let result = self.build_bin_seg( segment.span, segment.annotations, segment.spec, size.map(Box::new), value, next, ); Ok((result, osub)) } /// build_bin_seg(Anno, Size, Unit, Type, Flags, Seg, Next) -> #k_bin_seg{}. /// This function normalizes literal integers with size > 8 and literal /// utf8 segments into integers with size = 8 (and potentially an integer /// with size less than 8 at the end). This is so further optimizations /// have a normalized view of literal integers, allowing us to generate /// more literals and group more clauses. Those integers may be "squeezed" /// later into the largest integer possible. /// fn build_bin_seg( &mut self, span: SourceSpan, annotations: Annotations, spec: BinaryEntrySpecifier, size: Option<Box<Expr>>, value: Expr, next: Box<Expr>, ) -> Box<Expr> { match spec { BinaryEntrySpecifier::Integer { signed: false, endianness: Endianness::Big, unit, } => match size.as_deref() { Some(Expr::Literal(Literal { value: Lit::Integer(Integer::Small(sz)), .. })) => { let size = (*sz as usize) * unit as usize; match &value { Expr::Literal(Literal { value: Lit::Integer(ref i), .. }) => { if integer_fits_and_is_expandable(i, size) { return build_bin_seg_integer_recur( span, annotations, size, i.clone(), next, ); } } _ => (), } } _ => (), }, BinaryEntrySpecifier::Utf8 => match &value { Expr::Literal(Literal { value: Lit::Integer(ref i), .. }) => { if let Some(c) = i.to_char() { let bits = c.len_utf8() * 8; return build_bin_seg_integer_recur( span, annotations, bits, Integer::from(c as u32), next, ); } } _ => (), }, _ => (), } Box::new(Expr::BinarySegment(BinarySegment { span, annotations, spec, size, value: Box::new(value), next, })) } } #[derive(PartialEq, Eq)] enum MatchGroupKey { Lit(Lit), Arity(usize), Bin(Option<Box<MatchGroupKey>>, BinaryEntrySpecifier), Map(Vec<MapKey>), Var(Symbol), } impl MatchGroupKey { fn from(arg: &Expr, clause: &IClause) -> Self { match arg { Expr::Literal(Literal { value, .. }) => Self::Lit(value.clone()), Expr::Tuple(Tuple { elements, .. }) => Self::Arity(elements.len()), Expr::BinarySegment(BinarySegment { size, spec, .. }) | Expr::BinaryInt(BinarySegment { size, spec, .. }) => match size.as_deref() { None => Self::Bin(None, *spec), Some(Expr::Var(v)) => { let v1 = clause.isub.get_vsub(v.name()); Self::Bin(Some(Box::new(Self::Var(v1))), *spec) } Some(Expr::Literal(Literal { value, .. })) => { Self::Bin(Some(Box::new(Self::Lit(value.clone()))), *spec) } _ => unimplemented!(), }, Expr::Map(Map { pairs, .. }) => { let mut keys = pairs.iter().map(MapKey::from).collect::<Vec<_>>(); keys.sort(); Self::Map(keys) } _ => unimplemented!(), } } } impl PartialOrd for MatchGroupKey { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for MatchGroupKey { fn cmp(&self, other: &Self) -> std::cmp::Ordering { use std::cmp::Ordering; match (self, other) { (Self::Lit(x), Self::Lit(y)) => x.cmp(y), (Self::Lit(x), Self::Arity(y)) => { let lit = Lit::Integer(Integer::Small(*y as i64)); x.cmp(&lit) } (Self::Lit(_), _) => Ordering::Less, (Self::Arity(x), Self::Arity(y)) => x.cmp(y), (Self::Arity(x), Self::Lit(y)) => { let x = Lit::Integer(Integer::Small(*x as i64)); x.cmp(y) } (_, Self::Lit(_)) => Ordering::Greater, (_, Self::Arity(_)) => Ordering::Greater, (Self::Var(x), Self::Var(y)) => x.cmp(y), (Self::Var(_), _) => Ordering::Less, (_, Self::Var(_)) => Ordering::Greater, (Self::Bin(xs, xspec), Self::Bin(ys, yspec)) => { xs.cmp(ys).then_with(|| xspec.cmp(yspec)) } (Self::Bin(_, _), _) => Ordering::Less, (_, Self::Bin(_, _)) => Ordering::Greater, (Self::Map(xs), Self::Map(ys)) => xs.cmp(ys), (_, Self::Map(_)) => Ordering::Less, } } } fn group_value( ty: MatchType, vars: Vec<Var>, clauses: Vec<IClause>, ) -> Vec<(Vec<Var>, Vec<IClause>)> { match ty { MatchType::Cons => vec![(vars, clauses)], MatchType::Nil => vec![(vars, clauses)], MatchType::Binary => vec![(vars, clauses)], MatchType::BinaryEnd => vec![(vars, clauses)], MatchType::BinarySegment => group_keeping_order(vars, clauses), MatchType::BinaryInt => vec![(vars, clauses)], MatchType::Map => group_keeping_order(vars, clauses), _ => { let mut map = group_values(clauses); // We must sort the grouped values to ensure consistent order across compilations let mut result = vec![]; while let Some((_, clauses)) = map.pop_first() { result.push((vars.clone(), clauses)); } result } } } fn group_values(mut clauses: Vec<IClause>) -> BTreeMap<MatchGroupKey, Vec<IClause>> { use std::collections::btree_map::Entry; let mut acc = BTreeMap::new(); for clause in clauses.drain(..) { let key = MatchGroupKey::from(clause.arg(), &clause); match acc.entry(key) { Entry::Vacant(entry) => { entry.insert(vec![clause]); } Entry::Occupied(mut entry) => { entry.get_mut().push(clause); } } } acc } fn group_keeping_order(vars: Vec<Var>, mut clauses: Vec<IClause>) -> Vec<(Vec<Var>, Vec<IClause>)> { if clauses.is_empty() { return vec![]; } let clause = clauses.remove(0); let v1 = MatchGroupKey::from(clause.arg(), &clause); let (mut more, rest) = splitwith(clauses, |c| MatchGroupKey::from(c.arg(), c) == v1); more.insert(0, clause); let group = (vars.clone(), more); let mut tail = group_keeping_order(vars, rest); tail.insert(0, group); tail } fn build_bin_seg_integer_recur( span: SourceSpan, annotations: Annotations, bits: usize, n: Integer, next: Box<Expr>, ) -> Box<Expr> { if bits > 8 { let next_bits = bits - 8; let next_value = n.clone() & (((1u64 << next_bits) - 1) as i64); let last = build_bin_seg_integer_recur(span, annotations.clone(), next_bits, next_value, next); build_bin_seg_integer(span, annotations, 8, n >> (next_bits as u32), last) } else { build_bin_seg_integer(span, annotations, bits, n, next) } } fn build_bin_seg_integer( span: SourceSpan, annotations: Annotations, bits: usize, n: Integer, next: Box<Expr>, ) -> Box<Expr> { let size = Some(Box::new(Expr::Literal(Literal::integer(span, bits)))); let value = Box::new(Expr::Literal(Literal::integer(span, n))); Box::new(Expr::BinarySegment(BinarySegment { span, annotations, spec: BinaryEntrySpecifier::default(), size, value, next, })) } fn integer_fits_and_is_expandable(i: &Integer, size: usize) -> bool { if size > EXPAND_MAX_SIZE_SEGMENT { return false; } size as u64 >= i.bits() } #[derive(Copy, Clone, PartialEq, Eq)] enum CallType { Error, Bif(FunctionName), Static(FunctionName), Dynamic, } fn call_type(module: &core::Expr, function: &core::Expr, args: &[core::Expr]) -> CallType { let arity = args.len() as u8; match (module.as_atom(), function.as_atom()) { (Some(m), Some(f)) => { let callee = FunctionName::new(m, f, arity); if callee.is_bif() { CallType::Bif(callee) } else { CallType::Static(callee) } } (None, Some(_)) if module.is_var() => CallType::Dynamic, (Some(_), None) if function.is_var() => CallType::Dynamic, (None, None) if module.is_var() && function.is_var() => CallType::Dynamic, _ => CallType::Error, } } fn same_args(args: &[core::Expr], fargs: &[Var], sub: &BiMap) -> bool { if args.len() != fargs.len() { return false; } for (arg, farg) in args.iter().zip(fargs.iter()) { match arg { core::Expr::Var(ref v) => { let vname = Name::from(v); let fname = Name::from(farg); let vsub = sub.get(vname).unwrap_or(vname); if vsub != fname { return false; } } _ => return false, } } true } fn make_clist(mut items: Vec<core::Expr>) -> core::Expr { items.drain(..).rfold( core::Expr::Literal(Literal::nil(SourceSpan::default())), |tail, head| { let span = head.span(); core::Expr::Cons(core::Cons::new(span, head, tail)) }, ) } fn flatten_seq(expr: Expr) -> Vec<Expr> { match expr { Expr::Set(mut iset) => match iset.body.take() { None => vec![Expr::Set(iset)], Some(box body) => { let mut seq = vec![Expr::Set(iset)]; let mut rest = flatten_seq(body); seq.append(&mut rest); seq } }, expr => vec![expr], } } fn pre_seq(mut pre: Vec<Expr>, body: Expr) -> Expr { if pre.is_empty() { return body; } let expr = pre.remove(0); match expr { Expr::Set(mut iset) => { assert_eq!(iset.body, None); iset.body = Some(Box::new(pre_seq(pre, body))); return Expr::Set(iset); } arg => { let span = arg.span(); Expr::Set(ISet { span, annotations: Annotations::default(), vars: vec![], arg: Box::new(arg), body: Some(Box::new(pre_seq(pre, body))), }) } } } fn validate_bin_element_size( size: Option<&Expr>, _annotations: &Annotations, ) -> Result<(), ExprError> { match size { None | Some(Expr::Var(_)) => Ok(()), Some(Expr::Literal(Literal { value: Lit::Integer(i), .. })) if i >= &0 => Ok(()), Some(Expr::Literal(Literal { value: Lit::Atom(symbols::All), .. })) => Ok(()), Some(expr) => Err(ExprError::BadSegmentSize(expr.span())), } } fn flatten_alias(expr: core::Expr) -> (Vec<Var>, core::Expr) { let mut vars = vec![]; let mut pattern = expr; while let core::Expr::Alias(core::Alias { var, pattern: box p, .. }) = pattern { vars.push(var); pattern = p; } (vars, pattern) } // This code implements the algorithm for an optimizing compiler for // pattern matching given "The Implementation of Functional // Programming Languages" by Simon Peyton Jones. The code is much // longer as the meaning of constructors is different from the book. // // In Erlang many constructors can have different values, e.g. 'atom' // or 'integer', whereas in the original algorithm thse would be // different constructors. Our view makes it easier in later passes to // handle indexing over each type. // // Patterns are complicated by having alias variables. The form of a // pattern is Pat | {alias,Pat,[AliasVar]}. This is hidden by access // functions to pattern arguments but the code must be aware of it. // // The compilation proceeds in two steps: // // 1. The patterns in the clauses to converted to lists of kernel // patterns. The Core clause is now hybrid, this is easier to work // with. Remove clauses with trivially false guards, this simplifies // later passes. Add locally defined vars and variable subs to each // clause for later use. // // 2. The pattern matching is optimised. Variable substitutions are // added to the VarSub structure and new variables are made visible. // The guard and body are then converted to Kernel form. impl TranslateCore { /// kmatch([Var], [Clause], Sub, State) -> {Kexpr,State}. fn kmatch( &mut self, vars: Vec<Var>, clauses: Vec<core::Clause>, sub: BiMap, ) -> Result<Expr, ExprError> { // Convert clauses let clauses = self.match_pre(clauses, sub)?; self.do_match(vars, clauses, None) } /// match_pre([Cclause], Sub, State) -> {[Clause],State}. /// Must be careful not to generate new substitutions here now! /// Remove clauses with trivially false guards which will never /// succeed. fn match_pre( &mut self, mut clauses: Vec<core::Clause>, sub: BiMap, ) -> Result<Vec<IClause>, ExprError> { clauses .drain(..) .map(|clause| { let (patterns, osub) = self.pattern_list(clause.patterns, sub.clone(), sub.clone())?; Ok(IClause { span: clause.span, annotations: clause.annotations, patterns, guard: clause.guard, body: clause.body, isub: sub.clone(), osub, }) }) .try_collect() } /// match([Var], [Clause], Default, State) -> {MatchExpr,State}. fn do_match( &mut self, vars: Vec<Var>, clauses: Vec<IClause>, default: Option<Expr>, ) -> Result<Expr, ExprError> { if vars.is_empty() { return self.match_guard(clauses, default); } let mut partitions = partition_clauses(clauses); let joined = partitions .drain(..) .try_rfold(default, |default, partition| { self.match_varcon(vars.clone(), partition, default) .map(Some) })?; Ok(joined.unwrap()) } /// match_guard([Clause], Default, State) -> {IfExpr,State}. /// Build a guard to handle guards. A guard *ALWAYS* fails if no /// clause matches, there will be a surrounding 'alt' to catch the /// failure. Drop redundant cases, i.e. those after a true guard. fn match_guard( &mut self, clauses: Vec<IClause>, default: Option<Expr>, ) -> Result<Expr, ExprError> { let (clauses, default) = self.match_guard_1(clauses, default)?; Ok(build_alt(build_guard(clauses), default).unwrap()) } fn match_guard_1( &mut self, mut clauses: Vec<IClause>, default: Option<Expr>, ) -> Result<(Vec<GuardClause>, Option<Expr>), ExprError> { if clauses.is_empty() { return Ok((vec![], default)); } let clause = clauses.remove(0); let span = clause.span; if clause.guard.is_none() || clause .guard .as_ref() .map(|g| g.is_atom_value(symbols::True)) .unwrap_or_default() { // The true clause body becomes the default let (body, pre) = self.body(*clause.body, clause.osub.clone())?; for clause in clauses.iter() { if !clause.is_compiler_generated() { self.reporter.show_warning( "pattern cannot match", &[ (clause.span, "this clause will never match"), (span, "it is shadowed by this clause"), ], ); } } if let Some(default) = default.as_ref() { self.reporter.show_warning( "pattern cannot match", &[ (default.span(), "this clause will never match"), (span, "it is shadowed by this clause"), ], ); } Ok((vec![], Some(pre_seq(pre, body)))) } else { let guard = *clause.guard.unwrap(); let span = guard.span(); let guard = self.guard(guard, clause.osub.clone())?; let (body, pre) = self.body(*clause.body, clause.osub)?; let (mut gcs, default) = self.match_guard_1(clauses, default)?; let gc = GuardClause { span, annotations: Annotations::default(), guard: Box::new(guard), body: Box::new(pre_seq(pre, body)), }; gcs.insert(0, gc); Ok((gcs, default)) } } /// match_varcon([Var], [Clause], Def, [Var], Sub, State) -> /// {MatchExpr,State}. fn match_varcon( &mut self, vars: Vec<Var>, clauses: Vec<IClause>, default: Option<Expr>, ) -> Result<Expr, ExprError> { if clauses[0].is_var_clause() { self.match_var(vars, clauses, default) } else { self.match_con(vars, clauses, default) } } /// match_var([Var], [Clause], Def, State) -> {MatchExpr,State}. /// Build a call to "select" from a list of clauses all containing a /// variable as the first argument. We must rename the variable in /// each clause to be the match variable as these clause will share /// this variable and may have different names for it. Rename aliases /// as well. fn match_var( &mut self, mut vars: Vec<Var>, mut clauses: Vec<IClause>, default: Option<Expr>, ) -> Result<Expr, ExprError> { let var = vars.remove(0); for clause in clauses.iter_mut() { let arg = clause.patterns.remove(0); // Get the variables to rename let aliases = arg.alias(); let mut vs = Vec::with_capacity(1 + aliases.len()); vs.push(arg.as_var().unwrap().clone()); vs.extend(aliases.iter().cloned()); // Rename and update substitutions let osub = vs.iter().fold(clause.osub.clone(), |sub, v| { sub.subst_vsub(Name::from(v), Name::from(&var)) }); let isub = vs.iter().fold(clause.isub.clone(), |sub, v| { sub.subst_vsub(Name::from(v), Name::from(&var)) }); clause.isub = isub; clause.osub = osub; } self.do_match(vars, clauses, default) } /// match_con(Variables, [Clause], Default, State) -> {SelectExpr,State}. /// Build call to "select" from a list of clauses all containing a /// constructor/constant as first argument. Group the constructors /// according to type, the order is really irrelevant but tries to be /// smart. fn match_con( &mut self, mut vars: Vec<Var>, clauses: Vec<IClause>, default: Option<Expr>, ) -> Result<Expr, ExprError> { // Extract clauses for different constructors (types). let l = vars.clone(); let u = vars.remove(0); let selected = select_types(clauses); let mut type_clauses = opt_single_valued(selected); let select_clauses = type_clauses .drain(..) .map(|(ty, clauses)| { let values = self.match_value(l.as_slice(), ty, clauses, None)?; let span = values[0].span(); let annotations = values[0].annotations().clone(); Ok(TypeClause { span, annotations, ty, values, }) }) .try_collect()?; let select = build_select(u, select_clauses); let alt = build_alt_1st_no_fail(select, default); Ok(alt) } /// match_value([Var], Con, [Clause], Default, State) -> {SelectExpr,State}. /// At this point all the clauses have the same constructor, we must /// now separate them according to value. fn match_value( &mut self, vars: &[Var], ty: MatchType, clauses: Vec<IClause>, default: Option<Expr>, ) -> Result<Vec<ValueClause>, ExprError> { let (vars, clauses) = partition_intersection(ty, vars.to_vec(), clauses); let mut grouped = group_value(ty, vars, clauses); let clauses = grouped .drain(..) .map(|(vars, clauses)| self.match_clause(vars, clauses, default.clone())) .try_collect()?; Ok(clauses) } /// match_clause([Var], [Clause], Default, State) -> {Clause,State}. /// At this point all the clauses have the same "value". Build one /// select clause for this value and continue matching. Rename /// aliases as well. fn match_clause( &mut self, mut vars: Vec<Var>, clauses: Vec<IClause>, default: Option<Expr>, ) -> Result<ValueClause, ExprError> { let var = vars.remove(0); let (span, annotations) = clauses .first() .map(|c| (c.span, c.annotations().clone())) .unwrap(); let (value, mut vs) = self.get_match(get_con(clauses.as_slice())); let value = sub_size_var(value, clauses.as_slice()); let clauses = self.new_clauses(clauses, var); let clauses = squeeze_clauses_by_bin_integer_count(clauses); vs.append(&mut vars); let body = self.do_match(vs, clauses, default)?; Ok(ValueClause { span, annotations, value: Box::new(value), body: Box::new(body), }) } fn get_match(&mut self, expr: &Expr) -> (Expr, Vec<Var>) { match expr { Expr::Cons(Cons { span, .. }) => { let span = *span; let [head, tail] = self.context.new_vars(Some(span)); let h = Expr::Var(head.clone()); let t = Expr::Var(tail.clone()); (Expr::Cons(Cons::new(span, h, t)), vec![head, tail]) } Expr::Binary(Binary { span, .. }) => { let span = *span; let v = self.context.next_var(Some(span)); ( Expr::Binary(Binary::new(span, Expr::Var(v.clone()))), vec![v], ) } Expr::BinarySegment(ref segment) if segment.is_all() => { let span = segment.span(); let [value, next] = self.context.new_vars(Some(span)); let segment = BinarySegment { span, annotations: segment.annotations.clone(), spec: segment.spec.clone(), size: segment.size.clone(), value: Box::new(Expr::Var(value)), next: Box::new(Expr::Var(next.clone())), }; (Expr::BinarySegment(segment), vec![next]) } Expr::BinarySegment(ref segment) => { let span = segment.span(); let [value, next] = self.context.new_vars(Some(span)); let segment = BinarySegment { span, annotations: segment.annotations.clone(), spec: segment.spec.clone(), size: segment.size.clone(), value: Box::new(Expr::Var(value.clone())), next: Box::new(Expr::Var(next.clone())), }; (Expr::BinarySegment(segment), vec![value, next]) } Expr::BinaryInt(ref segment) => { let span = segment.span(); let next = self.context.next_var(Some(span)); let segment = BinarySegment { span, annotations: segment.annotations.clone(), spec: segment.spec.clone(), size: segment.size.clone(), value: segment.value.clone(), next: Box::new(Expr::Var(next.clone())), }; (Expr::BinaryInt(segment), vec![next]) } Expr::Tuple(Tuple { span, elements, .. }) => { let span = *span; let vars = self.context.n_vars(elements.len(), Some(span)); let elements = vars.iter().cloned().map(Expr::Var).collect(); (Expr::Tuple(Tuple::new(span, elements)), vars) } Expr::Map(Map { span, pairs, .. }) => { let span = *span; let vars = self.context.n_vars(pairs.len(), Some(span)); let pairs = pairs .iter() .zip(vars.iter().cloned()) .map(|(pair, v)| MapPair { key: pair.key.clone(), value: Box::new(Expr::Var(v)), }) .collect(); let empty = Box::new(Expr::Literal(Literal::map(span, Default::default()))); ( Expr::Map(Map { span, annotations: Annotations::default(), op: MapOp::Exact, var: empty, pairs, }), vars, ) } expr => (expr.clone(), vec![]), } } fn new_clauses(&mut self, mut clauses: Vec<IClause>, var: Var) -> Vec<IClause> { clauses .drain(..) .map(|mut clause| { let arg = clause.patterns.remove(0); let (osub, isub) = { let vs = arg.alias(); let osub = vs.iter().fold(clause.osub.clone(), |osub, v| { osub.subst_vsub(Name::from(v), Name::from(&var)) }); let isub = vs.iter().fold(clause.isub.clone(), |isub, v| { isub.subst_vsub(Name::from(v), Name::from(&var)) }); (osub, isub) }; let head = match arg.into_arg() { Expr::Cons(Cons { box head, box tail, .. }) => { let mut hs = Vec::with_capacity(2 + clause.patterns.len()); hs.push(head); hs.push(tail); hs.append(&mut clause.patterns); hs } Expr::Tuple(Tuple { mut elements, .. }) => { let mut hs = Vec::with_capacity(elements.len() + clause.patterns.len()); hs.append(&mut elements); hs.append(&mut clause.patterns); hs } Expr::Binary(Binary { segment: box segment, .. }) => { let mut hs = Vec::with_capacity(1 + clause.patterns.len()); hs.push(segment); hs.append(&mut clause.patterns); hs } Expr::BinarySegment(segment) if segment.is_all() => { let mut hs = Vec::with_capacity(1 + clause.patterns.len()); hs.push(*segment.value); hs.append(&mut clause.patterns); hs } Expr::BinarySegment(segment) => { let mut hs = Vec::with_capacity(2 + clause.patterns.len()); hs.push(*segment.value); hs.push(*segment.next); hs.append(&mut clause.patterns); hs } Expr::BinaryInt(segment) => { let mut hs = Vec::with_capacity(1 + clause.patterns.len()); hs.push(*segment.next); hs.append(&mut clause.patterns); hs } Expr::Map(Map { mut pairs, .. }) => { let mut hs = Vec::with_capacity(pairs.len() + clause.patterns.len()); hs.extend(pairs.drain(..).map(|p| *p.value)); hs.append(&mut clause.patterns); hs } _ => clause.patterns, }; IClause { span: clause.span, annotations: clause.annotations, isub, osub, patterns: head, guard: clause.guard, body: clause.body, } }) .collect() } } fn sub_size_var(mut expr: Expr, clauses: &[IClause]) -> Expr { if let Expr::BinarySegment(ref mut segment) = &mut expr { let size_var = segment .size .as_deref() .and_then(|sz| sz.as_var()) .map(|v| (v.span(), v.annotations.clone(), Name::from(v))); if let Some((span, annotations, sz)) = size_var { if let Some(clause) = clauses.first() { let name = clause.isub.get(sz).unwrap_or(sz); let size = match name { Name::Var(s) => Expr::Var(Var { annotations, name: Ident::new(s, span), arity: None, }), Name::Fun(s, arity) => Expr::Var(Var { annotations, name: Ident::new(s, span), arity: Some(arity), }), }; segment.size.replace(Box::new(size)); } } } expr } fn select_types(mut clauses: Vec<IClause>) -> Vec<(MatchType, Vec<IClause>)> { use std::collections::btree_map::Entry; let acc: BTreeMap<MatchType, Vec<IClause>> = BTreeMap::new(); let mut acc = clauses.drain(..).fold(acc, |mut acc, mut clause| { expand_pat_lit_clause(&mut clause); let ty = clause.match_type(); match acc.entry(ty) { Entry::Vacant(entry) => { entry.insert(vec![clause]); } Entry::Occupied(mut entry) => { entry.get_mut().push(clause); } } acc }); let mut result = Vec::with_capacity(acc.len()); while let Some((t, cs)) = acc.pop_first() { let cs = match t { MatchType::BinarySegment => { let mut grouped = handle_bin_con(cs); result.append(&mut grouped); continue; } _ => cs, }; result.push((t, cs)); } result } /// handle_bin_con([Clause]) -> [{Type,[Clause]}]. /// Handle clauses for the k_bin_seg constructor. As k_bin_seg /// matching can overlap, the k_bin_seg constructors cannot be /// reordered, only grouped. fn handle_bin_con(clauses: Vec<IClause>) -> Vec<(MatchType, Vec<IClause>)> { if is_select_bin_int_possible(clauses.as_slice()) { // The usual way to match literals is to first extract the // value to a register, and then compare the register to the // literal value. Extracting the value is good if we need // compare it more than once. // // But we would like to combine the extracting and the // comparing into a single instruction if we know that // a binary segment must contain specific integer value // or the matching will fail, like in this example: // // <<42:8,...>> -> // <<42:8,...>> -> // . // . // . // <<42:8,...>> -> // <<>> -> // // The first segment must either contain the integer 42 // or the binary must end for the match to succeed. // // The way we do is to replace the generic #k_bin_seg{} // record with a #k_bin_int{} record if all clauses will // select the same literal integer (except for one or more // clauses that will end the binary). let (mut bin_segs, bin_end) = splitwith(clauses, |clause| { clause.match_type() == MatchType::BinarySegment }); // Swap all BinarySegment exprs with BinaryInt exprs let mut dummy = Expr::Literal(Literal::nil(SourceSpan::default())); for clause in bin_segs.iter_mut() { let pattern = clause.patterns.get_mut(0).unwrap(); let Expr::BinarySegment(mut bs) = mem::replace(pattern, dummy) else { panic!("expected binary segment pattern") }; // To make lowering easier, force the size to always be set, i..e. if the // size value is None, set it to the default of 8 if bs.size.is_none() { let span = bs.span; bs.size .replace(Box::new(Expr::Literal(Literal::integer(span, 8)))); } dummy = mem::replace(pattern, Expr::BinaryInt(bs)); } let mut bin_segs = vec![(MatchType::BinaryInt, bin_segs)]; if !bin_end.is_empty() { bin_segs.push((MatchType::BinaryEnd, bin_end)); } bin_segs } else { handle_bin_con_not_possible(clauses) } } fn handle_bin_con_not_possible(clauses: Vec<IClause>) -> Vec<(MatchType, Vec<IClause>)> { if clauses.is_empty() { return vec![]; } let con = clauses[0].match_type(); let (more, rest) = splitwith(clauses, |clause| clause.match_type() == con); let mut result = vec![(con, more)]; let mut rest = handle_bin_con_not_possible(rest); result.append(&mut rest); result } fn is_select_bin_int_possible(clauses: &[IClause]) -> bool { if clauses.is_empty() { return false; } // Use the first clause to determine how to check the rest let match_bits; let match_size; let match_value; let match_signed; let match_endianness; { match clauses[0].patterns.first().unwrap() { Expr::BinarySegment(BinarySegment { spec: BinaryEntrySpecifier::Integer { unit, signed, endianness, }, size, value: box Expr::Literal(Literal { value: Lit::Integer(ref i), .. }), .. }) => { match_size = match size.as_deref() { None => 8, Some(Expr::Literal(Literal { value: Lit::Integer(ref i), .. })) => match i.to_usize() { None => return false, Some(sz) => sz, }, _ => return false, }; match_bits = (*unit as usize) * match_size; match_signed = *signed; match_endianness = *endianness; match_value = i.clone(); // Expands the code size too much if match_bits > EXPAND_MAX_SIZE_SEGMENT { return false; } // Can't know the native endianness at this point if match_endianness == Endianness::Native { return false; } if !select_match_possible(match_size, &match_value, match_signed, match_endianness) { return false; } } _ => return false, } } for clause in clauses.iter().skip(1) { match clause.patterns.first().unwrap() { Expr::BinarySegment(BinarySegment { spec: BinaryEntrySpecifier::Integer { unit, signed, endianness, }, size, value: box Expr::Literal(Literal { value: Lit::Integer(ref i), .. }), .. }) => { if *signed != match_signed || *endianness != match_endianness || i != &match_value { return false; } let size = match size.as_deref() { None => 8, Some(Expr::Literal(Literal { value: Lit::Integer(ref i), .. })) => match i.to_usize() { None => return false, Some(sz) => sz, }, _ => return false, }; let bits = (*unit as usize) * size; if bits != match_bits { return false; } } _ => return false, } } true } /// Returns true if roundtripping `value` through the given encoding would succeed fn select_match_possible( size: usize, value: &Integer, signed: bool, endianness: Endianness, ) -> bool { // Make sure there is enough available bits to hold the value let needs_bits = value.bits(); let available_bits = size as u64; if needs_bits > available_bits { return false; } // Encode `value` into a binary let mut bv = BitVec::new(); match value { Integer::Small(i) if signed => { bv.push_ap_number(*i, size, endianness); } Integer::Small(i) => { bv.push_ap_number(*i as u64, size, endianness); } Integer::Big(ref i) => { bv.push_ap_bigint(i, size, signed, endianness); } } // Match an integer using the specified encoding, and make sure it equals the input value let mut matcher = bv.matcher(); match value { Integer::Small(i) if signed => { let parsed: Option<i64> = matcher.read_ap_number(size, endianness); match parsed { None => false, Some(p) => p.eq(i), } } Integer::Small(i) => { let parsed: Option<u64> = matcher.read_ap_number(size, endianness); match parsed { None => false, Some(p) => p == (*i as u64), } } Integer::Big(ref i) => { let parsed = matcher.read_bigint(size, signed, endianness); match parsed { None => false, Some(p) => p.eq(i), } } } } /// partition([Clause]) -> [[Clause]]. /// Partition a list of clauses into groups which either contain /// clauses with a variable first argument, or with a "constructor". fn partition_clauses(clauses: Vec<IClause>) -> Vec<Vec<IClause>> { if clauses.is_empty() { return vec![]; } let v1 = clauses[0].is_var_clause() == true; let (more, rest) = splitwith(clauses, |c| c.is_var_clause() == v1); let mut cs = partition_clauses(rest); cs.insert(0, more); cs } fn expand_pat_lit_clause(clause: &mut IClause) { match clause.patterns.get_mut(0).unwrap() { Expr::Alias(ref mut alias) if alias.pattern.is_literal() => { expand_pat_lit(alias.pattern.as_mut()); } lit @ Expr::Literal(_) => { expand_pat_lit(lit); } _ => (), } } fn expand_pat_lit(pattern: &mut Expr) { let pat = match pattern { Expr::Literal(Literal { span, annotations, value, }) => match value { Lit::Cons(head, tail) => Expr::Cons(Cons { span: *span, annotations: annotations.clone(), head: Box::new(Expr::Literal(head.as_ref().clone())), tail: Box::new(Expr::Literal(tail.as_ref().clone())), }), Lit::Tuple(t) => Expr::Tuple(Tuple { span: *span, annotations: annotations.clone(), elements: t.iter().cloned().map(Expr::Literal).collect(), }), _ => return, }, _ => return, }; *pattern = pat; } /// opt_single_valued([{Type,Clauses}]) -> [{Type,Clauses}]. /// If a type only has one clause and if the pattern is a complex /// literal, the matching can be done more efficiently by directly /// comparing with the literal (that is especially true for binaries). /// /// It is important not to do this transformation for atomic literals /// (such as `[]`), since that would cause the test for an empty list /// to be executed before the test for a nonempty list. fn opt_single_valued( mut tclauses: Vec<(MatchType, Vec<IClause>)>, ) -> Vec<(MatchType, Vec<IClause>)> { let mut lcs = vec![]; let mut tcs = vec![]; for (t, mut clauses) in tclauses.drain(..) { if clauses.len() != 1 { tcs.push((t, clauses)); continue; } let mut clause = clauses.pop().unwrap(); if clause.patterns.is_empty() { clauses.push(clause); tcs.push((t, clauses)); continue; } if clause.patterns[0].is_literal() { // This is an atomic literal clauses.push(clause); tcs.push((t, clauses)); continue; } let pattern = clause.patterns[0].clone(); match combine_lit_pat(pattern) { Ok(pattern) => { let _ = mem::replace(&mut clause.patterns[0], pattern); lcs.push(clause); } Err(_) => { // Not possible clauses.push(clause); tcs.push((t, clauses)); } } } if lcs.is_empty() { tcs } else { let literals = (MatchType::Literal, lcs); // Test the literals as early as possible. match tcs.first().map(|(t, _)| *t).unwrap() { MatchType::Binary => { // The delayed creation of sub binaries requires // bs_start_match2 to be the first instruction in the // function tcs.insert(1, literals); tcs } _ => { tcs.insert(0, literals); tcs } } } } fn combine_lit_pat(pattern: Expr) -> Result<Expr, ()> { match pattern { Expr::Alias(IAlias { span, annotations, vars, box pattern, }) => { let pattern = combine_lit_pat(pattern)?; Ok(Expr::Alias(IAlias { span, annotations, vars, pattern: Box::new(pattern), })) } Expr::Literal(_) => { // This is an atomic literal. Rewriting would be a pessimization, especially for nil Err(()) } pattern => { let lit = do_combine_lit_pat(pattern)?; Ok(Expr::Literal(lit)) } } } fn do_combine_lit_pat(pattern: Expr) -> Result<Literal, ()> { match pattern { Expr::Literal(lit) => Ok(lit), Expr::Binary(Binary { span, annotations, segment, }) => { let mut bv = BitVec::new(); combine_bin_segs(*segment, &mut bv)?; Ok(Literal { span, annotations, value: Lit::Binary(bv), }) } Expr::Cons(Cons { span, annotations, box head, box tail, }) => { let head = do_combine_lit_pat(head)?; let tail = do_combine_lit_pat(tail)?; Ok(Literal { span, annotations, value: Lit::Cons(Box::new(head), Box::new(tail)), }) } Expr::Tuple(Tuple { span, annotations, mut elements, }) => { let elements = elements.drain(..).map(do_combine_lit_pat).try_collect()?; Ok(Literal { span, annotations, value: Lit::Tuple(elements), }) } _ => Err(()), } } fn combine_bin_segs(segment: Expr, bin: &mut BitVec) -> Result<(), ()> { match segment { Expr::BinaryEnd(_) => Err(()), Expr::BinarySegment(BinarySegment { spec: BinaryEntrySpecifier::Integer { unit: 1, signed: false, endianness: Endianness::Big, }, size, value, next, .. }) => match size.as_deref() { None => match *value { Expr::Literal(Literal { value: Lit::Integer(i), .. }) if i >= 0 && i <= 255 => { let byte = i.try_into().map_err(|_| ())?; bin.push_byte(byte); combine_bin_segs(*next, bin) } _ => Err(()), }, Some(Expr::Literal(Literal { value: Lit::Integer(i), .. })) if i == &8 => match *value { Expr::Literal(Literal { value: Lit::Integer(i), .. }) if i >= 0 && i <= 255 => { let byte = i.try_into().map_err(|_| ())?; bin.push_byte(byte); combine_bin_segs(*next, bin) } _ => Err(()), }, _ => Err(()), }, _other => Err(()), } } /// partition_intersection(Type, Us, [Clause], State) -> {Us,Cs,State}. /// Partitions a map into two maps with the most common keys to the /// first map. /// /// case <M> of /// <#{a,b}> /// <#{a,c}> /// <#{a}> /// end /// /// becomes /// /// case <M,M> of /// <#{a}, #{b}> /// <#{a}, #{c}> /// <#{a}, #{ }> /// end /// /// The intention is to group as many keys together as possible and /// thus reduce the number of lookups to that key. fn partition_intersection( ty: MatchType, mut vars: Vec<Var>, mut clauses: Vec<IClause>, ) -> (Vec<Var>, Vec<IClause>) { match ty { MatchType::Map => { let patterns = clauses .iter() .map(|clause| match clause.arg().arg() { Expr::Map(Map { pairs, .. }) => pairs.iter().map(MapKey::from).collect(), arg => panic!("expected clause arg to be a map expression, got: {:?}", arg), }) .collect(); match find_key_intersection(patterns) { None => { vars.remove(0); (vars, clauses) } Some(keys) => { for clause in clauses.iter_mut() { let arg = clause.patterns.remove(0); let (arg1, arg2) = partition_keys(arg, &keys); let mut patterns = Vec::with_capacity(2 + clause.patterns.len()); patterns.push(arg1); patterns.push(arg2); patterns.append(&mut clause.patterns); clause.patterns = patterns; } (vars, clauses) } } } _ => (vars, clauses), } } fn find_key_intersection(patterns: Vec<BTreeSet<MapKey>>) -> Option<BTreeSet<MapKey>> { if patterns.is_empty() { return None; } // Get the intersection of all the sets let base = patterns.first().unwrap().clone(); let intersection: BTreeSet<MapKey> = patterns .iter() .skip(1) .fold(base, |acc, set| acc.intersection(set).cloned().collect()); if intersection.is_empty() { None } else { // If all the clauses test the same keys, partitioning can only // make the generated code worse if patterns.iter().all(|set| set.eq(&intersection)) { None } else { Some(intersection) } } } fn partition_keys(arg: Expr, keys: &BTreeSet<MapKey>) -> (Expr, Expr) { match arg { Expr::Map(Map { span, annotations, op, var, mut pairs, }) => { let (ps1, ps2) = pairs.drain(..).partition(|pair| { let key = MapKey::from(pair.key.as_ref()); keys.contains(&key) }); let arg1 = Expr::Map(Map { span, annotations: annotations.clone(), op, var: var.clone(), pairs: ps1, }); let arg2 = Expr::Map(Map { span, annotations, op, var, pairs: ps2, }); (arg1, arg2) } Expr::Alias(IAlias { span, annotations, vars, pattern, }) => { // Only alias one of them let (map1, map2) = partition_keys(*pattern, keys); let alias = Expr::Alias(IAlias { span, annotations, vars, pattern: Box::new(map2), }); (map1, alias) } other => panic!( "unexpected argument to partition_keys, expected map or alias expr, got: {:?}", &other ), } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] enum MapKey { Literal(Lit), Var(Symbol), } impl From<&MapPair> for MapKey { fn from(pair: &MapPair) -> Self { pair.key.as_ref().into() } } impl From<&Expr> for MapKey { fn from(expr: &Expr) -> Self { match expr { Expr::Var(v) => Self::Var(v.name()), Expr::Literal(Literal { value, .. }) => Self::Literal(value.clone()), _ => unimplemented!(), } } } fn get_con(clauses: &[IClause]) -> &Expr { clauses.first().unwrap().arg().arg() } fn build_guard(clauses: Vec<GuardClause>) -> Option<Expr> { if clauses.is_empty() { return None; } Some(Expr::Guard(Guard { span: SourceSpan::default(), annotations: Annotations::default(), clauses, })) } /// Build an alt, attempt some simple optimization fn build_alt(first: Option<Expr>, other: Option<Expr>) -> Option<Expr> { if first.is_none() { return other; } Some(build_alt_1st_no_fail(first.unwrap(), other)) } fn build_alt_1st_no_fail(first: Expr, other: Option<Expr>) -> Expr { if other.is_none() { return first; } Expr::Alt(Alt { span: first.span(), annotations: first.annotations().clone(), first: Box::new(first), then: Box::new(other.unwrap()), }) } fn build_select(var: Var, types: Vec<TypeClause>) -> Expr { let first = types.first().unwrap(); let annotations = first.annotations().clone(); let span = first.span(); Expr::Select(Select { span, annotations, var, types, }) } /// Build a match expresssion if there is a match fn build_match(expr: Expr) -> Expr { match expr { expr @ (Expr::Alt(_) | Expr::Select(_) | Expr::Guard(_)) => { let span = expr.span(); let annotations = expr.annotations().clone(); Expr::Match(Match { span, annotations, body: Box::new(expr), ret: vec![], }) } expr => expr, } } fn squeeze_clauses_by_bin_integer_count(clauses: Vec<IClause>) -> Vec<IClause> { // TODO clauses } /// Partitions the given vector into two vectors based on the predicate. /// /// This is essentially equivalent to `Vec::split_off/1`, but where the /// partition point is determined by the predicate rather than given explicitly. fn splitwith<T, F>(mut items: Vec<T>, predicate: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool, { let index = items.partition_point(predicate); let rest = items.split_off(index); (items, rest) } #[derive(Debug, Clone, PartialEq, Eq)] enum Brk { Return, Break(Vec<Expr>), } impl Brk { pub fn is_break(&self) -> bool { match self { Self::Break(_) => true, _ => false, } } #[inline] pub fn is_return(&self) -> bool { !self.is_break() } pub fn ret(&self) -> &[Expr] { match self { Self::Break(rs) => rs.as_slice(), Self::Return => &[], } } pub fn into_ret(self) -> Vec<Expr> { match self { Self::Break(rs) => rs, Self::Return => vec![], } } } impl TranslateCore { /// ubody(Expr, Break, State) -> {Expr,[UsedVar],State}. /// Tag the body sequence with its used variables. These bodies /// either end with a #k_break{}, or with #k_return{} or an expression /// which itself can return, #k_enter{}, #k_match{} ... . fn ubody(&mut self, body: Expr, brk: Brk) -> Result<(Expr, RedBlackTreeSet<Ident>), ExprError> { match body { // A letrec should never be last Expr::Set(ISet { vars, arg: box Expr::LetRec(letr), body: Some(box body), .. }) if vars.is_empty() => { self.iletrec_funs(letr)?; self.ubody(body, brk) } Expr::Set(ISet { vars, arg: box Expr::Literal(_), body: Some(box body), .. }) if vars.is_empty() => self.ubody(body, brk), Expr::Set(ISet { span, annotations, vars, box arg, body: Some(box body), }) => { let ns = vars.iter().map(|v| v.name).collect(); let vs = vars.iter().cloned().map(Expr::Var).collect(); let (arg, au) = self.uexpr(arg, Brk::Break(vs))?; let (body, bu) = self.ubody(body, brk)?; let used = sets::union(au, sets::subtract(bu, ns)); // used external vars Ok(( Expr::Seq(Seq { span, annotations, arg: Box::new(arg), body: Box::new(body), }), used, )) } Expr::Values(IValues { annotations, values, .. }) => match brk { Brk::Return => { let span = values[0].span(); let au = lit_list_vars(values.as_slice()); Ok(( Expr::Return(Return { span, annotations, args: values, }), au, )) } Brk::Break(_) => { let span = values.first().map(|a| a.span()).unwrap_or_default(); let au = lit_list_vars(values.as_slice()); Ok(( Expr::Break(Break { span, annotations, args: values, }), au, )) } }, goto @ Expr::Goto(_) => Ok((goto, rbt_set![])), // Enterable expressions need no trailing return expr => match brk { Brk::Return if expr.is_enter_expr() => self.uexpr(expr, Brk::Return), Brk::Return => { let (ea, pa) = self.force_atomic(expr); self.ubody(pre_seq(pa, Expr::Values(kvalues!(ea))), Brk::Return) } Brk::Break(args) if args.len() == 1 => { let (ea, pa) = self.force_atomic(expr); self.ubody(pre_seq(pa, Expr::Values(kvalues!(ea))), Brk::Break(args)) } Brk::Break(args) => { let span = args.first().map(|a| a.span()); let vars = self.context.n_vars(args.len(), span); let values = vars.iter().cloned().map(Expr::Var).collect(); let set = Expr::Set(ISet { span: span.unwrap_or_default(), annotations: Annotations::default(), vars, arg: Box::new(expr), body: None, }); let seq = pre_seq(vec![set], Expr::Values(IValues::new(values))); self.ubody(seq, Brk::Break(args)) } }, } } fn iletrec_funs(&mut self, mut lr: ILetRec) -> Result<(), ExprError> { // Use union of all free variables. // First just work out free variables for all functions. let free = lr.defs.iter().try_fold(rbt_set![], |free, (_, ref fun)| { let ns = fun.vars.iter().map(|v| v.name).collect(); let fbu = self.ubody_used_vars(Expr::Fun(fun.clone()))?; Ok(sets::union(sets::subtract(fbu, ns), free)) })?; let free_vars = free .iter() .copied() .map(|id| Var::new(id)) .collect::<Vec<_>>(); for (name, fun) in lr.defs.iter() { self.store_free( name.name(), fun.vars.len(), free_vars.iter().cloned().map(Expr::Var).collect(), ); } // Now regenerate local functions to use free variable information. if self.context.ignore_funs { // Optimization: The ultimate caller is only interested in the used // variables, not the updated state. Makes a difference if there are // nested letrecs. Ok(()) } else { // We perform a transformation here for funs that will help later during // code generation, and forms the calling convention for closures (note // that this does not apply to "empty" closures, i.e. those with no free // variables). The transformation works like this: // // 1. Rewrite the function signature to expect a closure as an extra trailing argument // 2. Inject the unpack_env primop in the function entry for each free variable to extract // it from the closure argument for ( name, IFun { span, mut annotations, mut vars, box body, }, ) in lr.defs.drain(..) { // Perform the usual rewrite, then wrap the body to contain the unpack_env instructions let (body, _) = self.ubody(body, Brk::Return)?; let (name, body) = if free_vars.is_empty() { let name = FunctionName::new_local(name.name(), vars.len() as u8); (name, body) } else { let name = FunctionName::new_local(name.name(), (vars.len() + 1) as u8); let closure_var = self.context.next_var(Some(span)); vars.push(closure_var.clone()); annotations.set(symbols::Closure); ( name, self.unpack_closure_body(span, body, closure_var, free_vars.clone()), ) }; let function = make_function(span, annotations, name, vars, body); self.context.funs.push(function); } Ok(()) } } fn unpack_closure_body( &mut self, span: SourceSpan, body: Expr, closure: Var, mut free: Vec<Var>, ) -> Expr { assert_ne!(free.len(), 0); // We create a chained series of calls to unpack_env/2, in reverse, with appropriate rets for each free variable // This will result in the correct sequence of instructions when lowered let env_arity = free.len(); let mut body = body; for i in (0..env_arity).rev() { let closure = Expr::Var(closure.clone()); let index = Expr::Literal(Literal::integer(span, i)); let unpack_env2 = FunctionName::new(symbols::Erlang, symbols::UnpackEnv, 2); let mut bif = Bif::new(span, unpack_env2, vec![closure, index]); bif.ret.push(Expr::Var(free.pop().unwrap())); let seq = Expr::Seq(Seq { span, annotations: Annotations::default_compiler_generated(), arg: Box::new(Expr::Bif(bif)), body: Box::new(body), }); body = seq; } body } /// uexpr(Expr, Break, State) -> {Expr,[UsedVar],State}. /// Calculate the used variables for an expression. /// Break = return | {break,[RetVar]}. fn uexpr(&mut self, expr: Expr, brk: Brk) -> Result<(Expr, RedBlackTreeSet<Ident>), ExprError> { match expr { Expr::Test(test) if brk.is_break() => { // Sanity check assert_eq!(brk.ret(), &[]); let used = lit_list_vars(test.args.as_slice()); Ok((Expr::Test(test), used)) } Expr::Set(ISet { span, annotations, vars, box arg, body: Some(box body), }) if brk.is_break() => { let ns = vars.iter().map(|v| v.name).collect(); let vars = vars.iter().cloned().map(Expr::Var).collect(); let (e1, eu) = self.uexpr(arg, Brk::Break(vars))?; let (b1, bu) = self.uexpr(body, brk)?; let used = sets::union(eu, sets::subtract(bu, ns)); Ok(( Expr::Seq(Seq { span, annotations, arg: Box::new(e1), body: Box::new(b1), }), used, )) } Expr::If(If { span, annotations, cond, box then_body, box else_body, .. }) => { let ret = brk.ret().to_vec(); let cond_used = lit_vars(cond.as_ref()); let (then_body, tbu) = self.ubody(then_body, brk.clone())?; let (else_body, ebu) = self.ubody(else_body, brk)?; let used = sets::union(cond_used, sets::union(tbu, ebu)); Ok(( Expr::If(If { span, annotations, cond, then_body: Box::new(then_body), else_body: Box::new(else_body), ret, }), used, )) } Expr::Call(mut call) if call.callee.is_local() => { // This is a call to a local function // // If there are free variables, we need to construct a fun and use that // as the callee; if there are no free variables, we can ignore the extra // transformation let mut callee = call.callee.as_local().unwrap(); let callee_span = call.callee.span(); let mut free = self.get_free(callee.function, callee.arity as usize); if !free.is_empty() { // Build bif invocation that creates the fun with the closure environment callee.arity += 1; let op = FunctionName::new(symbols::Erlang, symbols::MakeFun, 2); let mut mf_args = Vec::with_capacity(free.len() + 1); mf_args.push(Expr::Local(Span::new(callee_span, callee))); mf_args.append(&mut free); let fun = Expr::Bif(Bif { span: callee_span, annotations: Annotations::default_compiler_generated(), op, args: mf_args, ret: vec![], }); let used = lit_list_vars(call.args.as_slice()); match brk { Brk::Break(rs) => { let _ = mem::replace(call.callee.as_mut(), fun); call.ret = rs; Ok((Expr::Call(call), used)) } Brk::Return => { let _ = mem::replace(call.callee.as_mut(), fun); let enter = Expr::Enter(Enter { span: call.span, annotations: call.annotations, callee: call.callee, args: call.args, }); Ok((enter, used)) } } } else { let used = lit_list_vars(call.args.as_slice()); match brk { Brk::Break(rs) => { call.ret = rs; Ok((Expr::Call(call), used)) } Brk::Return => { let enter = Expr::Enter(Enter { span: call.span, annotations: call.annotations, callee: call.callee, args: call.args, }); Ok((enter, used)) } } } } Expr::Call(mut call) if brk.is_break() => { let used = sets::union( op_vars(call.callee.as_ref()), lit_list_vars(call.args.as_slice()), ); call.ret = brk.into_ret(); Ok((Expr::Call(call), used)) } Expr::Call(Call { span, annotations, callee, args, .. }) => { let used = sets::union(op_vars(callee.as_ref()), lit_list_vars(args.as_slice())); let enter = Expr::Enter(Enter { span, annotations, callee, args, }); Ok((enter, used)) } Expr::Bif(mut bif) if brk.is_break() => { let used = lit_list_vars(bif.args.as_slice()); let brs = self.bif_returns(bif.span, bif.op, brk.into_ret()); bif.ret = brs; Ok((Expr::Bif(bif), used)) } Expr::Match(Match { span, annotations, box body, .. }) => { let ret = brk.ret().to_vec(); let (body, bu) = self.umatch(body, brk)?; Ok(( Expr::Match(Match { span, annotations, body: Box::new(body), ret, }), bu, )) } Expr::Try(Try { span, annotations, box arg, vars, box body, evars, box handler, .. }) if brk.is_break() => { let is_simple = match (vars.as_slice(), &body, &handler, brk.ret().is_empty()) { ([v1], Expr::Var(v2), Expr::Literal(_), true) => v1 == v2, _ => false, }; if is_simple { // This is a simple try/catch whose return value is // ignored: // // try E of V -> V when _:_:_ -> ignored_literal end, ... // // This is most probably a try/catch in a guard. To // correctly handle the #k_test{} that ends the body of // the guard, we MUST pass an empty list of break // variables when processing the body. let (a1, bu) = self.ubody(arg, Brk::Break(vec![]))?; Ok(( Expr::Try(Try { span, annotations, arg: Box::new(a1), vars: vec![], body: Box::new(Expr::Break(kbreak!(span))), evars: vec![], handler: Box::new(Expr::Break(kbreak!(span))), ret: brk.into_ret(), }), bu, )) } else { // The general try/catch (in a guard or in body). let mut avs = self.context.n_vars(vars.len(), Some(span)); let (arg, au) = self.ubody(arg, Brk::Break(avs.drain(..).map(Expr::Var).collect()))?; let (body, bu) = self.ubody(body, brk.clone())?; let (handler, hu) = self.ubody(handler, brk.clone())?; let var_set = vars.iter().map(|v| v.name).collect(); let evar_set = evars.iter().map(|v| v.name).collect(); let used = sets::union( au, sets::union(sets::subtract(bu, var_set), sets::subtract(hu, evar_set)), ); Ok(( Expr::Try(Try { span, annotations, arg: Box::new(arg), vars, body: Box::new(body), evars, handler: Box::new(handler), ret: brk.into_ret(), }), used, )) } } Expr::Try(Try { span, annotations, box arg, vars, box body, evars, box handler, .. }) if brk.is_return() => { let mut avs = self.context.n_vars(vars.len(), Some(span)); // Need dummy names here let (arg, au) = self.ubody(arg, Brk::Break(avs.drain(..).map(Expr::Var).collect()))?; // Must break to clean up here let (body, bu) = self.ubody(body, Brk::Return)?; let (handler, hu) = self.ubody(handler, Brk::Return)?; let var_set = vars.iter().map(|v| v.name).collect(); let evar_set = evars.iter().map(|v| v.name).collect(); let used = sets::union( au, sets::union(sets::subtract(bu, var_set), sets::subtract(hu, evar_set)), ); Ok(( Expr::TryEnter(TryEnter { span, annotations, arg: Box::new(arg), vars, body: Box::new(body), evars, handler: Box::new(handler), }), used, )) } Expr::Catch(Catch { span, annotations, box body, .. }) if brk.is_break() => { let rb = self.context.next_var(Some(span)); let (b1, bu) = self.ubody(body, Brk::Break(vec![Expr::Var(rb)]))?; // Guarantee _1_ return variable let mut ns = self.context.n_vars(1 - brk.ret().len(), Some(span)); let mut ret = brk.into_ret(); ret.extend(ns.drain(..).map(Expr::Var)); Ok(( Expr::Catch(Catch { span, annotations, body: Box::new(b1), ret, }), bu, )) } Expr::Fun(IFun { span, annotations, mut vars, box body, }) if brk.is_break() => { // We do a transformation here which corresponds to the one in iletrec_funs. // We must also ensure that calls to closures append the closure value as an // extra argument, but that is done elsewhere. let (b1, bu) = self.ubody(body, Brk::Return)?; // Return out of new function let ns = vars.iter().map(|v| v.name).collect(); let free = sets::subtract(bu, ns); // Free variables in fun let free_vars = free.iter().copied().map(Var::new).collect::<Vec<_>>(); let mut fvs = free_vars.iter().cloned().map(Expr::Var).collect::<Vec<_>>(); let closure_var = if free.is_empty() { None } else { let closure_var = self.context.next_var(Some(span)); vars.push(closure_var.clone()); Some(closure_var) }; let arity = vars.len(); let fname = match annotations.get(symbols::Id) { Some(Annotation::Term(Literal { value: Lit::Tuple(es), .. })) => { // {_, _, name} es[2].as_atom().unwrap() } _ => { // No ide annotation, generate a name self.context.new_fun_name(None) } }; // Create function definition let fname = FunctionName::new_local(fname, arity as u8); let body = if free.is_empty() { b1 } else { self.unpack_closure_body(span, b1, closure_var.unwrap(), free_vars) }; let function_annotations = if free.is_empty() { annotations.clone() } else { annotations.insert(symbols::Closure, Annotation::Unit) }; let function = make_function(span, function_annotations, fname, vars, body); self.add_local_function(function); // Build bif invocation that creates the fun with the closure environment let op = FunctionName::new(symbols::Erlang, symbols::MakeFun, 2); let mut args = Vec::with_capacity(fvs.len() + 1); args.push(Expr::Local(Span::new(span, fname))); args.append(&mut fvs); // We know the value produced by this BIF is a function let mut ret = brk.into_ret(); if !ret.is_empty() { ret[0].set_type(Type::Term(TermType::Fun(None))); if !free.is_empty() { ret[0].annotations_mut().set(symbols::Closure); } } Ok(( Expr::Bif(Bif { span, annotations, op, args, ret, }), free, )) } Expr::Local(name) if brk.is_break() => { let span = name.span(); let mut arity = name.arity as usize; let free = self.get_free(name.function, arity); let free = lit_list_vars(free.as_slice()); let fvs = free .iter() .copied() .map(|id| Expr::Var(Var::new(id))) .collect::<Vec<_>>(); let num_free = fvs.len(); if num_free > 0 { arity += 1; } let op = FunctionName::new(symbols::Erlang, symbols::MakeFun, 2); let mut args = Vec::with_capacity(num_free + 1); args.push(Expr::Local(Span::new( span, FunctionName::new_local(name.function, arity as u8), ))); args.extend(fvs.iter().cloned()); // We know the value produced by this BIF is a function let mut ret = brk.into_ret(); if !ret.is_empty() { ret[0].set_type(Type::Term(TermType::Fun(None))); } Ok(( Expr::Bif(Bif { span, annotations: Annotations::default(), op, args, ret, }), free, )) } Expr::LetRecGoto(LetRecGoto { span, annotations, label, vars, box first, box then, .. }) => { let ret = brk.ret().to_vec(); let ns = vars.iter().map(|v| v.name).collect(); let (f1, fu) = self.ubody(first, brk.clone())?; let (t1, tu) = self.ubody(then, brk)?; let used = sets::subtract(sets::union(fu, tu), ns); Ok(( Expr::LetRecGoto(LetRecGoto { span, annotations, label, vars, first: Box::new(f1), then: Box::new(t1), ret, }), used, )) } lit if brk.is_break() => { let span = lit.span(); let annotations = lit.annotations().clone(); // Transform literals to puts here. let used = lit_vars(&lit); let ret = self.ensure_return_vars(brk.into_ret()); Ok(( Expr::Put(Put { span, annotations, arg: Box::new(lit), ret, }), used, )) } other => unimplemented!( "unexpected expression type in uexpr: {:#?} for {:#?}", &other, &brk ), } } /// Return all used variables for the body sequence. /// More efficient than `ubody` if it contains nested letrecs fn ubody_used_vars(&mut self, body: Expr) -> Result<RedBlackTreeSet<Ident>, ExprError> { // We need to save the current state which should be restored when returning // to the caller, since the caller just wants the used variables, not the side // effects on the current context let context = self.context.clone(); self.context.ignore_funs = true; let result = self.ubody(body, Brk::Return); self.context = context; result.map(|(_, used)| used) } /// umatch(Match, Break, State) -> {Match,[UsedVar],State}. /// Calculate the used variables for a match expression. fn umatch( &mut self, expr: Expr, brk: Brk, ) -> Result<(Expr, RedBlackTreeSet<Ident>), ExprError> { match expr { Expr::Alt(Alt { span, annotations, box first, box then, }) => { let (first, fu) = self.umatch(first, brk.clone())?; let (then, tu) = self.umatch(then, brk)?; let used = sets::union(fu, tu); Ok(( Expr::Alt(Alt { span, annotations, first: Box::new(first), then: Box::new(then), }), used, )) } Expr::Select(Select { span, annotations, var, types, }) => { let (types, tu) = self.umatch_type_clauses(types, brk)?; let used = tu.insert(var.name); Ok(( Expr::Select(Select { span, annotations, var, types, }), used, )) } Expr::Guard(Guard { span, annotations, clauses, }) => { let (clauses, used) = self.umatch_guard_clauses(clauses, brk)?; Ok(( Expr::Guard(Guard { span, annotations, clauses, }), used, )) } pattern => self.ubody(pattern, brk), } } fn umatch_type_clause( &mut self, mut clause: TypeClause, brk: Brk, ) -> Result<(TypeClause, RedBlackTreeSet<Ident>), ExprError> { let clauses = clause.values.split_off(0); let (mut values, vu) = self.umatch_value_clauses(clauses, brk)?; clause.values.append(&mut values); Ok((clause, vu)) } fn umatch_value_clause( &mut self, clause: ValueClause, brk: Brk, ) -> Result<(ValueClause, RedBlackTreeSet<Ident>), ExprError> { let (used, ps) = pat_vars(clause.value.as_ref()); let (body, bu) = self.umatch(*clause.body, brk)?; let mut value = *clause.value; pat_anno_unused(&mut value, bu.clone(), ps.clone()); let used = sets::union(used, sets::subtract(bu, ps)); Ok(( ValueClause { span: clause.span, annotations: clause.annotations, value: Box::new(value), body: Box::new(body), }, used, )) } fn umatch_guard_clause( &mut self, clause: GuardClause, brk: Brk, ) -> Result<(GuardClause, RedBlackTreeSet<Ident>), ExprError> { let (guard, gu) = self.uexpr(*clause.guard, Brk::Break(vec![]))?; let (body, bu) = self.umatch(*clause.body, brk)?; let used = sets::union(gu, bu); Ok(( GuardClause { span: clause.span, annotations: clause.annotations, guard: Box::new(guard), body: Box::new(body), }, used, )) } fn umatch_type_clauses( &mut self, mut clauses: Vec<TypeClause>, brk: Brk, ) -> Result<(Vec<TypeClause>, RedBlackTreeSet<Ident>), ExprError> { let result = clauses .drain(..) .try_fold((vec![], rbt_set![]), |(mut ms, used), m| { let (m, mu) = self.umatch_type_clause(m, brk.clone())?; ms.push(m); let used = sets::union(mu, used); Ok((ms, used)) })?; Ok(result) } fn umatch_value_clauses( &mut self, mut clauses: Vec<ValueClause>, brk: Brk, ) -> Result<(Vec<ValueClause>, RedBlackTreeSet<Ident>), ExprError> { let result = clauses .drain(..) .try_fold((vec![], rbt_set![]), |(mut ms, used), m| { let (m, mu) = self.umatch_value_clause(m, brk.clone())?; ms.push(m); let used = sets::union(mu, used); Ok((ms, used)) })?; Ok(result) } fn umatch_guard_clauses( &mut self, mut clauses: Vec<GuardClause>, brk: Brk, ) -> Result<(Vec<GuardClause>, RedBlackTreeSet<Ident>), ExprError> { let result = clauses .drain(..) .try_fold((vec![], rbt_set![]), |(mut ms, used), m| { let (m, mu) = self.umatch_guard_clause(m, brk.clone())?; ms.push(m); let used = sets::union(mu, used); Ok((ms, used)) })?; Ok(result) } fn add_local_function(&mut self, function: Function) { if self.context.ignore_funs { return; } if self.context.funs.iter().any(|f| f.name == function.name) { return; } self.context.funs.push(function); } /// get_free(Name, Arity, State) -> [Free]. fn get_free(&mut self, name: Symbol, arity: usize) -> Vec<Expr> { let key = Name::Fun(name, arity); match self.context.free.get(&key) { None => vec![], Some(val) => val.clone(), } } /// store_free(Name, Arity, [Free], State) -> State. fn store_free(&mut self, name: Symbol, arity: usize, free: Vec<Expr>) { let key = Name::Fun(name, arity); self.context.free.insert_mut(key, free); } /// ensure_return_vars([Ret], State) -> {[Ret],State}. fn ensure_return_vars(&mut self, rets: Vec<Expr>) -> Vec<Expr> { if rets.is_empty() { vec![Expr::Var(self.context.next_var(None))] } else { rets } } fn bif_returns( &mut self, span: SourceSpan, callee: FunctionName, mut ret: Vec<Expr>, ) -> Vec<Expr> { assert!( callee.is_bif(), "expected bif callee to be a known bif, got {}", &callee ); if callee.function == symbols::MatchFail { // This is used for effect only, and may have any number of returns return ret; } let num_values = callee.bif_values(); let mut ns = self.context.n_vars(num_values - ret.len(), Some(span)); ret.extend(ns.drain(..).map(Expr::Var)); ret } } /// Make a Function, making sure that the body is always a Match. fn make_function( span: SourceSpan, annotations: Annotations, name: FunctionName, vars: Vec<Var>, body: Expr, ) -> Function { match body { body @ Expr::Match(_) => Function { span, annotations, name, vars, body: Box::new(body), }, body => { let anno = body.annotations().clone(); let body = Box::new(Expr::Match(Match { span, annotations: anno, body: Box::new(body), ret: vec![], })); Function { span, annotations, name, vars, body, } } } } fn pat_anno_unused(pattern: &mut Expr, used: RedBlackTreeSet<Ident>, ps: RedBlackTreeSet<Ident>) { match pattern { Expr::Tuple(Tuple { ref mut elements, .. }) => { // Not extracting unused tuple elements is an optimization for // compile time and memory use during compilation. It is probably // worthwhile because it is common to extract only a few elements // from a huge record. let used = sets::intersection(used, ps); for element in elements.iter_mut() { match element { Expr::Var(ref mut var) if !used.contains(&var.name) => { var.annotations_mut().set(symbols::Unused); } _ => continue, } } } _ => (), } } /// op_vars(Op) -> [VarName]. fn op_vars(expr: &Expr) -> RedBlackTreeSet<Ident> { match expr { Expr::Remote(Remote::Dynamic(box Expr::Var(m), box Expr::Var(f))) => { rbt_set![m.name, f.name] } Expr::Remote(Remote::Dynamic(box Expr::Var(m), _)) => { rbt_set![m.name] } Expr::Remote(Remote::Dynamic(_, box Expr::Var(f))) => { rbt_set![f.name] } Expr::Remote(_) => rbt_set![], other => lit_vars(other), } } fn lit_list_vars(patterns: &[Expr]) -> RedBlackTreeSet<Ident> { patterns .iter() .fold(rbt_set![], |vars, p| sets::union(lit_vars(p), vars)) } /// lit_vars(Literal) -> [VarName]. /// Return the variables in a literal. fn lit_vars(expr: &Expr) -> RedBlackTreeSet<Ident> { match expr { Expr::Var(v) => rbt_set![v.name], Expr::Cons(Cons { head, tail, .. }) => { sets::union(lit_vars(head.as_ref()), lit_vars(tail.as_ref())) } Expr::Tuple(Tuple { elements, .. }) => lit_list_vars(elements.as_slice()), Expr::Map(Map { var, pairs, .. }) => { let set = lit_vars(var.as_ref()); pairs.iter().fold(set, |vars, pair| { let ku = lit_vars(pair.key.as_ref()); let vu = lit_vars(pair.value.as_ref()); sets::union(sets::union(ku, vu), vars) }) } Expr::Binary(Binary { segment, .. }) => lit_vars(segment.as_ref()), Expr::BinaryEnd(_) => rbt_set![], Expr::BinarySegment(BinarySegment { size: Some(sz), value, next, .. }) => sets::union( lit_vars(sz.as_ref()), sets::union(lit_vars(value.as_ref()), lit_vars(next.as_ref())), ), Expr::BinarySegment(BinarySegment { value, next, .. }) => { sets::union(lit_vars(value.as_ref()), lit_vars(next.as_ref())) } Expr::Literal(_) | Expr::Local(_) | Expr::Remote(Remote::Static(_)) => rbt_set![], Expr::Remote(Remote::Dynamic(m, f)) => { sets::union(lit_vars(m.as_ref()), lit_vars(f.as_ref())) } other => panic!("expected literal pattern, got {:?}", &other), } } /// pat_vars(Pattern) -> {[UsedVarName],[NewVarName]}. /// Return variables in a pattern. All variables are new variables /// except those in the size field of binary segments and the key /// field in map_pairs. fn pat_vars(pattern: &Expr) -> (RedBlackTreeSet<Ident>, RedBlackTreeSet<Ident>) { match pattern { Expr::Var(v) => (rbt_set![], rbt_set![v.name]), Expr::Literal(_) => (rbt_set![], rbt_set![]), Expr::Cons(Cons { head, tail, .. }) => { let (used0, new0) = pat_vars(head.as_ref()); let (used1, new1) = pat_vars(tail.as_ref()); (sets::union(used0, used1), sets::union(new0, new1)) } Expr::Tuple(Tuple { elements, .. }) => pat_list_vars(elements.as_slice()), Expr::Binary(Binary { segment, .. }) => pat_vars(segment.as_ref()), Expr::BinarySegment(BinarySegment { size: Some(sz), value, next, .. }) => { let (used0, new0) = pat_vars(value.as_ref()); let (used1, new1) = pat_vars(next.as_ref()); let (used, new) = (sets::union(used0, used1), sets::union(new0, new1)); let (_, used2) = pat_vars(sz.as_ref()); (sets::union(used, used2), new) } Expr::BinarySegment(BinarySegment { value, next, .. }) => { let (used0, new0) = pat_vars(value.as_ref()); let (used1, new1) = pat_vars(next.as_ref()); (sets::union(used0, used1), sets::union(new0, new1)) } Expr::BinaryInt(BinarySegment { size: Some(sz), next, .. }) => { let (_, new) = pat_vars(next.as_ref()); let (_, used) = pat_vars(sz.as_ref()); (used, new) } Expr::BinaryInt(BinarySegment { next, .. }) => { let (_, new) = pat_vars(next.as_ref()); (rbt_set![], new) } Expr::BinaryEnd(_) => (rbt_set![], rbt_set![]), Expr::Map(Map { pairs, .. }) => { pairs .iter() .fold((rbt_set![], rbt_set![]), |(used, new), pair| { let (used1, new1) = pat_vars(pair.value.as_ref()); let (_, used2) = pat_vars(pair.key.as_ref()); ( sets::union(sets::union(used1, used2), used), sets::union(new1, new), ) }) } other => panic!("expected valid pattern expression, got {:?}", &other), } } fn pat_list_vars(patterns: &[Expr]) -> (RedBlackTreeSet<Ident>, RedBlackTreeSet<Ident>) { patterns .iter() .fold((rbt_set![], rbt_set![]), |(used, new), pattern| { let (used1, new1) = pat_vars(pattern); (sets::union(used, used1), sets::union(new, new1)) }) } #[allow(dead_code)] fn integers(n: usize, m: usize) -> RangeInclusive<usize> { if n > m { // This produces an empty iterator return 1..=0; } n..=m }
use maat_graphics::math; use maat_graphics::DrawCall; use maat_graphics::ModelData; use maat_graphics::camera::PerspectiveCamera; use crate::modules::scenes::Scene; use crate::modules::scenes::SceneData; use crate::cgmath::{Vector2, Vector3 as cgVector3, Vector4}; //use crate::modules::objects::{Character, StaticObject, GenericObject, MovingPlatform}; //use crate::modules::collisions; use rand::prelude::ThreadRng; use rand::thread_rng; use twinstick_logic::{TwinstickGame, Character, Enemy, Input, DataType, GenericObject, Vector3, collisions, SendDynamicObject, SendDynamicObjectUpdate, SendPlayerObjectUpdate}; use twinstick_client::{TwinstickClient}; const CAMERA_DEFAULT_X: f32 = 83.93359; const CAMERA_DEFAULT_Y: f32 = -128.62776; const CAMERA_DEFAULT_Z: f32 = 55.85842; const CAMERA_DEFAULT_PITCH: f32 = -62.27426; const CAMERA_DEFAULT_YAW: f32 = 210.10083; const CAMERA_DEFAULT_SPEED: f32 = 50.0; const CAMERA_ZOOM_SPEED: f32 = 0.05; // percentage per second pub struct PlayScreen { data: SceneData, _rng: ThreadRng, camera: PerspectiveCamera, last_mouse_pos: Vector2<f32>, players: Vec<Box<dyn GenericObject>>, enemies: Vec<Box<dyn GenericObject>>, static_objects: Vec<Box<dyn GenericObject>>, player_bullets: Vec<Box<dyn GenericObject>>, enemy_bullets: Vec<Box<dyn GenericObject>>, dynamic_objects: Vec<Box<dyn GenericObject>>, //decorative_objects: Vec<Box<dyn GenericObject>>, character_idx: Option<usize>, zoom: f32, client: TwinstickClient, } impl PlayScreen { pub fn new(window_size: Vector2<f32>, model_data: Vec<ModelData>) -> PlayScreen { let rng = thread_rng(); let mut camera = PerspectiveCamera::default_vk(); camera.set_position(cgVector3::new(CAMERA_DEFAULT_X, CAMERA_DEFAULT_Y, CAMERA_DEFAULT_Z)); camera.set_pitch(CAMERA_DEFAULT_PITCH); camera.set_yaw(CAMERA_DEFAULT_YAW); camera.set_move_speed(CAMERA_DEFAULT_SPEED); camera.set_target(cgVector3::new(0.0, 0.0, 0.0)); let mut client = TwinstickClient::new("127.0.0.1:8008");//"45.77.234.65:8008");//"127.0.0.1:8008"); client.connect(); client.send(); PlayScreen { data: SceneData::new(window_size, model_data), _rng: rng, camera, last_mouse_pos: Vector2::new(-1.0, -1.0), players: Vec::new(), enemies: Vec::new(), static_objects: Vec::new(), player_bullets: Vec::new(), enemy_bullets: Vec::new(), dynamic_objects: Vec::new(), // decorative_objects, character_idx: None, zoom: 22.0, client, } } pub fn update_player(&mut self, p: SendPlayerObjectUpdate, i: usize) { if i > self.players.len() || self.players.len() == 0 { return; } let rot = p.rotation(); let pos = p.position().clone(); let firing = p.is_firing(); self.players[i].set_position(pos); self.players[i].set_rotation(rot); self.players[i].set_firing(firing); } pub fn update_enemy(&mut self, e: SendDynamicObjectUpdate, i: usize) { if i > self.enemies.len()-1 || self.enemies.len() == 0 { return; } let rot = e.rotation(); let pos = e.position().clone(); self.enemies[i].set_position(pos); self.enemies[i].set_rotation(rot); } pub fn add_enemy(&mut self, enemy: SendDynamicObject) { println!("adding enemy {}", self.enemies.len()); let rot = enemy.rotation(); let pos = enemy.position().clone(); let size = enemy.size(); let hitbox = enemy.hitbox(); let model = enemy.model(); let mut c = Enemy::new(pos, size, model).set_hitbox_size(hitbox); c.set_rotation(rot); self.enemies.push(Box::new(c)); } pub fn add_player(&mut self, character: SendDynamicObject) { let rot = character.rotation(); let pos = character.position().clone(); let mut c = Character::new(pos, Vector3::new_same(1.0)); c.set_rotation(rot); self.players.push(Box::new(c)); } pub fn update_player_rotation(&mut self, char_idx: i32, width: f32, height: f32, mouse: Vector2<f32>) { if char_idx == -1 { return; } let look_vector = math::normalise_vector2(Vector2::new(width*0.5, height*0.5) - mouse); let rot = look_vector.y.atan2(-look_vector.x) as f64; let rotation = math::to_degrees(rot)-90.0; self.players[char_idx as usize].set_rotation(rotation); } pub fn process_player_input(&mut self, char_idx: i32) { if self.data().keys.w_pressed() { self.client.send_datatype(DataType::Input(Input::W)); } else if self.data().keys.s_pressed() { self.client.send_datatype(DataType::Input(Input::S)); } if self.data().keys.d_pressed() { self.client.send_datatype(DataType::Input(Input::D)); } else if self.data().keys.a_pressed() { self.client.send_datatype(DataType::Input(Input::A)); } if self.data().keys.space_pressed() { self.client.send_datatype(DataType::Input(Input::Space)); } if self.data().left_mouse { self.client.send_datatype(DataType::Input(Input::LeftClick)); } if char_idx != -1 { if self.data().keys.w_pressed() { self.players[char_idx as usize].add_input(Input::W); } else if self.data().keys.s_pressed() { self.players[char_idx as usize].add_input(Input::S); } if self.data().keys.d_pressed() { self.players[char_idx as usize].add_input(Input::D); } else if self.data().keys.a_pressed() { self.players[char_idx as usize].add_input(Input::A); } if self.data().keys.space_pressed() { self.players[char_idx as usize].add_input(Input::Space); } if self.data().left_mouse { self.players[char_idx as usize].add_input(Input::LeftClick); } } } } impl Scene for PlayScreen { fn data(&self) -> &SceneData { &self.data } fn mut_data(&mut self) -> &mut SceneData { &mut self.data } fn future_scene(&mut self, _window_size: Vector2<f32>) -> Box<dyn Scene> { let dim = self.data().window_dim; Box::new(PlayScreen::new(dim, self.data.model_data.clone())) } fn update(&mut self, delta_time: f32) { let dim = self.data().window_dim; let (width, height) = (dim.x as f32, dim.y as f32); let mouse = self.data().mouse_pos; if self.client.disconnected() { self.client.connect(); } let mut char_idx: i32 = -1; if self.character_idx.is_some() { char_idx = self.character_idx.unwrap() as i32; if char_idx as usize >= self.players.len() { char_idx = -1; } } if char_idx != -1 { let rot = self.players[char_idx as usize].rotation().y; self.client.send_datatype(DataType::PlayerRotation(rot, char_idx as usize)); } match self.client.recieve() { Some(d_type) => { match d_type { DataType::PlayerNum(i) => { self.character_idx = Some(i); }, DataType::StaticObject(object) => { let object = object.to_static_object(); self.static_objects.push(Box::new(object)); }, DataType::Player(p, idx) => { self.update_player(p, idx); }, DataType::AddPlayer(p) => { self.add_player(p); println!("New player connected!"); }, DataType::RemovePlayer(idx) => { if char_idx != -1 { if char_idx as usize == idx { self.character_idx = None; } else if idx < char_idx as usize { char_idx -= 1; self.character_idx = Some(char_idx as usize); } } self.players.remove(idx); }, DataType::AddEnemy(e) => { self.add_enemy(e); }, DataType::Enemy(e, idx) => { self.update_enemy(e, idx); }, _ => {}, } }, None => { } } self.process_player_input(char_idx); self.update_player_rotation(char_idx, width, height, mouse); TwinstickGame::update(&mut self.players, &mut self.enemies, &mut self.player_bullets, &mut self.enemy_bullets, &mut self.static_objects, &mut self.dynamic_objects, self.character_idx, delta_time as f64); /* if self.data().scroll_delta < 0.0 { self.zoom += CAMERA_ZOOM_SPEED*self.zoom*self.zoom *delta_time + 0.01; if self.zoom > 120.0 { self.zoom = 120.0; } } if self.data().scroll_delta > 0.0 { self.zoom += -CAMERA_ZOOM_SPEED*self.zoom*self.zoom *delta_time - 0.01; if self.zoom < 1.0 { self.zoom = 1.0; } }*/ if let Some(character_idx) = self.character_idx { if character_idx < self.players.len() { let character_pos = self.players[character_idx].position().clone().to_cgmath(); let character_front_vector = self.players[character_idx].front_vector(); self.camera.set_target(character_pos); let mut old_unit_vector = self.camera.get_front(); let mut goal_unit_vector = character_front_vector; old_unit_vector.y = 0.0; goal_unit_vector.y = 0.0; let old_unit_vector = math::normalise_vector3(old_unit_vector); let goal_unit_vector = math::normalise_vector3(goal_unit_vector.to_cgmath()); let lerped_unit_vector = math::vec3_lerp(old_unit_vector, goal_unit_vector, 0.005); let camera_lerp_pos = character_pos - lerped_unit_vector*self.zoom + cgVector3::new(0.0, self.zoom, 0.0);//*self.zoom + Vector3::new(0.0, self.zoom, 0.0);// self.camera.set_position(camera_lerp_pos); self.camera.set_up(cgVector3::new(0.0, -1.0, 0.0)); self.camera.set_front(math::normalise_vector3(character_pos-self.camera.get_position())); } } self.last_mouse_pos = mouse; // println!("Zoom: {}", self.zoom); } fn draw(&self, draw_calls: &mut Vec<DrawCall>) { let dim = self.data().window_dim; let (width, height) = (dim.x as f32, dim.y as f32); draw_calls.push(DrawCall::set_camera(self.camera.clone())); for i in 0..self.players.len() { if let Some(idx) = self.character_idx { if idx == i { self.players[i].draw(true, draw_calls); } else { self.players[i].draw(false, draw_calls); } } else { self.players[i].draw(false, draw_calls); } } for enemy in &self.enemies { enemy.draw(true, draw_calls); } for object in &self.static_objects { object.draw(true, draw_calls); } for object in &self.dynamic_objects { object.draw(true, draw_calls); } for bullets in &self.player_bullets { bullets.draw(true, draw_calls); } for bullets in &self.enemy_bullets { bullets.draw(true, draw_calls); } if self.client.disconnected() { draw_calls.push( DrawCall::draw_text_basic_centered(Vector2::new(width*0.5, height*0.5), Vector2::new(128.0, 128.0), Vector4::new(1.0, 1.0, 1.0, 1.0), String::from("Attempting to connect to server..."), String::from("Arial")) ); } /* for object in &self.dynamic_objects { object.draw(draw_calls, self.debug); } for object in &self.decorative_objects { object.draw(draw_calls, self.debug); }*/ } }
// // // //! Language entrypoint #[lang="termination"] pub trait Termination { fn report(self) -> i32; } #[lang="start"] fn lang_start<T: Termination+'static>(main: fn()->T, argc: isize, argv: *const *const u8) -> isize { #[cfg(arch="native")] { ::syscalls::raw::native_init(32245); } kernel_log!("lang_start(main={:p}, argc={}, argv={:p})", main, argc, argv); main().report() as isize } impl Termination for () { fn report(self) -> i32 { 0 } } impl<T,E> Termination for Result<T,E> where T: Termination//, //E: ::error::Error { fn report(self) -> i32 { match self { Ok(v) => v.report(), Err(_e) => 1, } } } // register_arguments is defined in std::env
use crate::{encode, resample, Image}; use std::{io, fs::File}; #[test] fn load() -> io::Result<()> { if let Err(err) = Image::load(File::open("tests/test.png")?) { panic!("FAILED AT PNG {:?}", err); } if let Err(err) = Image::load(File::open("tests/test.jpg")?) { panic!("FAILED AT JPG {:?}", err); } if let Err(err) = Image::load(File::open("tests/test.gif")?) { panic!("FAILED AT GIF {:?}", err); } if let Err(err) = Image::load(File::open("tests/test.bmp")?) { panic!("FAILED AT BMP {:?}", err); } if let Err(err) = Image::load(File::open("tests/test.webp")?) { panic!("FAILED AT WEBP {:?}", err); } if let Err(err) = Image::load(File::open("tests/test.svg")?) { panic!("FAILED AT SVG {:?}", err); } Ok(()) } #[test] fn rasterize() -> io::Result<()> { let mut file_near = File::create("tests/rasterize/near.png").expect("Couldn't create file"); let mut file_linear = File::create("tests/rasterize/linear.png").expect("Couldn't create file"); let mut file_cubic = File::create("tests/rasterize/cubic.png").expect("Couldn't create file"); let mut file_svg = File::create("tests/rasterize/svg.png").expect("Couldn't create file"); let source_png = Image::open("tests/test.png").expect("File not found"); let source_svg = Image::open("tests/test.svg").expect("File not found"); encode::png( &source_png.rasterize(resample::nearest, (32, 32)).expect("Failed"), &mut file_near )?; encode::png( &source_png.rasterize(resample::linear, (32, 32)).expect("Failed"), &mut file_linear )?; encode::png( &source_png.rasterize(resample::cubic, (32, 32)).expect("Failed"), &mut file_cubic )?; encode::png( &source_svg.rasterize(resample::nearest, (32, 32)).expect("Failed"), &mut file_svg ) }
pub struct Solution; use self::Token::*; use std::iter::Peekable; use std::str::Bytes; #[derive(Debug, Eq, PartialEq)] enum Token { Open, Close, Plus, Minus, Number(i32), } struct Tokens<'a> { bytes: Peekable<Bytes<'a>>, } impl<'a> Tokens<'a> { fn new(s: &'a str) -> Self { Tokens { bytes: s.bytes().peekable(), } } } impl<'a> Iterator for Tokens<'a> { type Item = Token; fn next(&mut self) -> Option<Self::Item> { while self.bytes.peek() == Some(&b' ') { self.bytes.next(); } match self.bytes.next() { None => None, Some(b'(') => Some(Open), Some(b')') => Some(Close), Some(b'+') => Some(Plus), Some(b'-') => Some(Minus), Some(b) if b.is_ascii_digit() => { let mut res = (b - b'0') as i32; while self.bytes.peek().map_or(false, |b| b.is_ascii_digit()) { res = res * 10 + (self.bytes.next().unwrap() - b'0') as i32; } Some(Number(res)) } _ => unreachable!(), } } } fn eval_term<'a>(tokens: &mut Peekable<Tokens<'a>>) -> i32 { match tokens.next() { Some(Open) => { let res = eval_expression(tokens); assert_eq!(tokens.next(), Some(Close)); res } Some(Plus) => eval_term(tokens), Some(Minus) => -eval_term(tokens), Some(Number(n)) => n, _ => unreachable!(), } } fn eval_expression<'a>(tokens: &mut Peekable<Tokens<'a>>) -> i32 { let mut res = eval_term(tokens); while tokens.peek().map_or(false, |t| t != &Close) { match tokens.next() { Some(Plus) => { res += eval_term(tokens); } Some(Minus) => { res -= eval_term(tokens); } _ => unreachable!(), } } res } impl Solution { pub fn calculate(s: String) -> i32 { let mut tokens = Tokens::new(&s).peekable(); let res = eval_expression(&mut tokens); assert_eq!(tokens.next(), None); res } } #[test] fn test0224() { fn case(s: &str, want: i32) { let got = Solution::calculate(s.to_string()); assert_eq!(got, want); } case("1 + 2", 3); case("1 + 1", 2); case(" 2-1 + 2 ", 3); case("(1+(4+5+2)-3)+(6+8)", 23); }
#![allow(unused_attributes)] #![feature(no_coverage)] use std::marker::PhantomData; use fuzzcheck::mutators::testing_utilities::test_mutator; use fuzzcheck::mutators::unit::UnitMutator; use fuzzcheck::{make_mutator, DefaultMutator}; #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct SampleStruct<T> { // #[field_mutator( <bool as DefaultMutator>::Mutator = { bool::default_mutator() } )] x: bool, // #[field_mutator( <bool as DefaultMutator>::Mutator = { bool::default_mutator() } )] y: bool, // #[field_mutator( UnitMutator<PhantomData<T>> = { UnitMutator::new(PhantomData, 0.0) } )] _phantom: PhantomData<T>, } make_mutator! { name: SampleStructMutator, recursive: true, default: true, type: struct SampleStruct<T> { #[field_mutator( <bool as DefaultMutator>::Mutator = { bool::default_mutator() } )] x: bool, #[field_mutator( <bool as DefaultMutator>::Mutator = { bool::default_mutator() } )] y: bool, #[field_mutator( UnitMutator<PhantomData<T>> = { UnitMutator::new(PhantomData, 0.0) } )] _phantom: PhantomData<T>, } } #[test] fn test_derived_struct() { let mutator = SampleStruct::<bool>::default_mutator(); test_mutator(mutator, 1000., 1000., false, true, 100, 100); let mutator = <Vec<SampleStruct<bool>>>::default_mutator(); test_mutator(mutator, 1000., 1000., false, true, 100, 100); }
type Link<T> = Option<Box<Node<T>>>; pub struct Stack<T>{ top: Link<T>, } struct Node<T> { data: T, next: Link<T>, } impl<T> Stack<T> { pub fn new() -> Self { Stack {top: None} } pub fn push(&mut self, data: T) { let node = Box::new(Node { data: data, next: self.top.take(), }); self.top = Some(node); } pub fn pop(&mut self) -> Option<T> { self.top.take().map(|node| { self.top = node.next; node.data }) } } impl<T> Drop for Stack<T> { fn drop(&mut self) { let mut actual = self.top.take(); while let Some(mut link) = actual { actual = link.next.take(); } } } #[cfg(test)] mod test { use super::Stack; #[test] fn empty_test(){ let mut stack:Stack<i32> = Stack::new(); assert_eq!(stack.pop(), None); } #[test] fn push_pop_test(){ let mut stack = Stack::new(); stack.push(22); stack.push(23); assert_eq!(stack.pop(), Some(23)); assert_eq!(stack.pop(), Some(22)); stack.push(2); stack.push(3); assert_eq!(stack.pop(), Some(3)); assert_eq!(stack.pop(), Some(2)); assert_eq!(stack.pop(), None); } }
//! `read` and `write`, optionally positioned, optionally vectored use crate::{backend, io}; use backend::fd::AsFd; // Declare `IoSlice` and `IoSliceMut`. #[cfg(not(windows))] pub use crate::maybe_polyfill::io::{IoSlice, IoSliceMut}; #[cfg(linux_kernel)] pub use backend::io::types::ReadWriteFlags; /// `read(fd, buf)`—Reads from a stream. /// /// # References /// - [POSIX] /// - [Linux] /// - [Apple] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// - [glibc] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html /// [Linux]: https://man7.org/linux/man-pages/man2/read.2.html /// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/read.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=read&sektion=2 /// [NetBSD]: https://man.netbsd.org/read.2 /// [OpenBSD]: https://man.openbsd.org/read.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=read&section=2 /// [illumos]: https://illumos.org/man/2/read /// [glibc]: https://www.gnu.org/software/libc/manual/html_node/I_002fO-Primitives.html#index-reading-from-a-file-descriptor #[inline] pub fn read<Fd: AsFd>(fd: Fd, buf: &mut [u8]) -> io::Result<usize> { backend::io::syscalls::read(fd.as_fd(), buf) } /// `write(fd, buf)`—Writes to a stream. /// /// # References /// - [POSIX] /// - [Linux] /// - [Apple] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// - [glibc] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html /// [Linux]: https://man7.org/linux/man-pages/man2/write.2.html /// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/write.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=write&sektion=2 /// [NetBSD]: https://man.netbsd.org/write.2 /// [OpenBSD]: https://man.openbsd.org/write.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=write&section=2 /// [illumos]: https://illumos.org/man/2/write /// [glibc]: https://www.gnu.org/software/libc/manual/html_node/I_002fO-Primitives.html#index-writing-to-a-file-descriptor #[inline] pub fn write<Fd: AsFd>(fd: Fd, buf: &[u8]) -> io::Result<usize> { backend::io::syscalls::write(fd.as_fd(), buf) } /// `pread(fd, buf, offset)`—Reads from a file at a given position. /// /// # References /// - [POSIX] /// - [Linux] /// - [Apple] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pread.html /// [Linux]: https://man7.org/linux/man-pages/man2/pread.2.html /// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/pread.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=pread&sektion=2 /// [NetBSD]: https://man.netbsd.org/pread.2 /// [OpenBSD]: https://man.openbsd.org/pread.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=pread&section=2 /// [illumos]: https://illumos.org/man/2/pread #[inline] pub fn pread<Fd: AsFd>(fd: Fd, buf: &mut [u8], offset: u64) -> io::Result<usize> { backend::io::syscalls::pread(fd.as_fd(), buf, offset) } /// `pwrite(fd, bufs)`—Writes to a file at a given position. /// /// Contrary to POSIX, on many popular platforms including Linux and FreeBSD, /// if the file is opened in append mode, this ignores the offset appends the /// data to the end of the file. /// /// # References /// - [POSIX] /// - [Linux] /// - [Apple] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pwrite.html /// [Linux]: https://man7.org/linux/man-pages/man2/pwrite.2.html /// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/pwrite.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=pwrite&sektion=2 /// [NetBSD]: https://man.netbsd.org/pwrite.2 /// [OpenBSD]: https://man.openbsd.org/pwrite.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=pwrite&section=2 /// [illumos]: https://illumos.org/man/2/pwrite #[inline] pub fn pwrite<Fd: AsFd>(fd: Fd, buf: &[u8], offset: u64) -> io::Result<usize> { backend::io::syscalls::pwrite(fd.as_fd(), buf, offset) } /// `readv(fd, bufs)`—Reads from a stream into multiple buffers. /// /// # References /// - [POSIX] /// - [Linux] /// - [Apple] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/readv.html /// [Linux]: https://man7.org/linux/man-pages/man2/readv.2.html /// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/readv.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=readv&sektion=2 /// [NetBSD]: https://man.netbsd.org/readv.2 /// [OpenBSD]: https://man.openbsd.org/readv.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=readv&section=2 /// [illumos]: https://illumos.org/man/2/readv #[cfg(not(target_os = "espidf"))] #[inline] pub fn readv<Fd: AsFd>(fd: Fd, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { backend::io::syscalls::readv(fd.as_fd(), bufs) } /// `writev(fd, bufs)`—Writes to a stream from multiple buffers. /// /// # References /// - [POSIX] /// - [Linux] /// - [Apple] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.html /// [Linux]: https://man7.org/linux/man-pages/man2/writev.2.html /// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/writev.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=writev&sektion=2 /// [NetBSD]: https://man.netbsd.org/writev.2 /// [OpenBSD]: https://man.openbsd.org/writev.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=writev&section=2 /// [illumos]: https://illumos.org/man/2/writev #[cfg(not(target_os = "espidf"))] #[inline] pub fn writev<Fd: AsFd>(fd: Fd, bufs: &[IoSlice<'_>]) -> io::Result<usize> { backend::io::syscalls::writev(fd.as_fd(), bufs) } /// `preadv(fd, bufs, offset)`—Reads from a file at a given position into /// multiple buffers. /// /// # References /// - [Linux] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// /// [Linux]: https://man7.org/linux/man-pages/man2/preadv.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=preadv&sektion=2 /// [NetBSD]: https://man.netbsd.org/preadv.2 /// [OpenBSD]: https://man.openbsd.org/preadv.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=preadv&section=2 /// [illumos]: https://illumos.org/man/2/preadv #[cfg(not(any( target_os = "espidf", target_os = "haiku", target_os = "nto", target_os = "redox", target_os = "solaris" )))] #[inline] pub fn preadv<Fd: AsFd>(fd: Fd, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> { backend::io::syscalls::preadv(fd.as_fd(), bufs, offset) } /// `pwritev(fd, bufs, offset)`—Writes to a file at a given position from /// multiple buffers. /// /// Contrary to POSIX, on many popular platforms including Linux and FreeBSD, /// if the file is opened in append mode, this ignores the offset appends the /// data to the end of the file. /// /// # References /// - [Linux] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// /// [Linux]: https://man7.org/linux/man-pages/man2/pwritev.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=pwritev&sektion=2 /// [NetBSD]: https://man.netbsd.org/pwritev.2 /// [OpenBSD]: https://man.openbsd.org/pwritev.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=pwritev&section=2 /// [illumos]: https://illumos.org/man/2/pwritev #[cfg(not(any( target_os = "espidf", target_os = "haiku", target_os = "nto", target_os = "redox", target_os = "solaris" )))] #[inline] pub fn pwritev<Fd: AsFd>(fd: Fd, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> { backend::io::syscalls::pwritev(fd.as_fd(), bufs, offset) } /// `preadv2(fd, bufs, offset, flags)`—Reads data, with several options. /// /// An `offset` of `u64::MAX` means to use and update the current file offset. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/preadv2.2.html #[cfg(linux_kernel)] #[inline] pub fn preadv2<Fd: AsFd>( fd: Fd, bufs: &mut [IoSliceMut<'_>], offset: u64, flags: ReadWriteFlags, ) -> io::Result<usize> { backend::io::syscalls::preadv2(fd.as_fd(), bufs, offset, flags) } /// `pwritev2(fd, bufs, offset, flags)`—Writes data, with several options. /// /// An `offset` of `u64::MAX` means to use and update the current file offset. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/pwritev2.2.html #[cfg(linux_kernel)] #[inline] pub fn pwritev2<Fd: AsFd>( fd: Fd, bufs: &[IoSlice<'_>], offset: u64, flags: ReadWriteFlags, ) -> io::Result<usize> { backend::io::syscalls::pwritev2(fd.as_fd(), bufs, offset, flags) }
//! Parser mod lexer; use std::iter::Peekable; use syntax::ast::{Expr, Expr_}; use syntax::codemap::{Source, Span, Spanned}; use syntax::parse::lexer::{Delim, Lexer, Token_}; use syntax::{Error, Error_}; use util::interner::Interner; struct Parser<'a> { // NB `Option` needed for option dance interner: Option<&'a mut Interner>, lexer: Peekable<Lexer<'a>>, source: &'a Source, span: Span, } impl<'a> Parser<'a> { /// Parses the source code fn new(source: &'a Source, interner: &'a mut Interner) -> Parser<'a> { Parser { interner: Some(interner), lexer: Lexer::new(source).peekable(), source: source, span: Span::dummy(), } } /// Parses an expression fn expr(&mut self) -> Result<Expr, Error> { match self.next() { None => unreachable!(), Some(Ok(Token_::Integer)) => self.integer(), Some(Ok(Token_::Keyword)) => self.keyword(), Some(Ok(Token_::Operator(_))) => Err(self.spanned(Error_::OperatorNotAllowedHere)), Some(Ok(Token_::String)) => self.string(), Some(Ok(Token_::Symbol)) => self.symbol(), Some(Ok(Token_::Whitespace)) => self.expr(), Some(Err(error)) => Err(self.spanned(error)), Some(Ok(Token_::Open(Delim::Paren))) => self.list(), Some(Ok(Token_::Open(Delim::Bracket))) => self.vector(), _ => unimplemented!(), } } /// Parses an integer fn integer(&mut self) -> Result<Expr, Error> { let span = self.span; match self.source[span].parse() { Err(_) => Err(self.spanned(Error_::IntegerTooLarge)), Ok(integer) => Ok(self.spanned(Expr_::Integer(integer))), } } /// Parses a keyword fn keyword(&mut self) -> Result<Expr, Error> { // NB option dance let interner = self.interner.take().unwrap(); let expr = Ok(self.spanned(Expr_::Keyword(interner.intern(&self.source[self.span])))); self.interner = Some(interner); expr } /// Parses a list fn list(&mut self) -> Result<Expr, Error> { Ok(try!(self.seq(Delim::Paren, true)).map(Expr_::List)) } /// Advances the parser by one token fn next(&mut self) -> Option<Result<Token_, Error_>> { self.lexer.next().map(|result| { match result { Err(Spanned { span, node }) => { self.span = span; Err(node) } Ok(Spanned { span, node }) => { self.span = span; Ok(node) }, } }) } /// Parses a "sequence" until the `close` delimiter is reached. Current position must be the /// open delimiter /// /// if `accept_operator` is true, then the first element of the sequence can be a special /// operator fn seq(&mut self, close: Delim, accept_operator: bool) -> Result<Spanned<Vec<Expr>>, Error> { let lo = self.span.lo; let mut exprs = vec![]; loop { match self.lexer.peek() { None => { let span = Span::new(self.span.hi, self.span.hi); return Err(Spanned::new(span, Error_::UnclosedDelimiter)) }, Some(&Err(error)) => { self.next(); return Err(error) }, Some(&Ok(token)) => { match token.node { Token_::Close(delim) => { self.next(); if delim == close { break } else { return Err(self.spanned(Error_::IncorrectCloseDelimiter)) } }, Token_::Operator(operator) if accept_operator && exprs.len() == 0 => { self.next(); exprs.push(self.spanned(Expr_::Operator(operator))); }, Token_::Whitespace => { self.next(); }, _ => { exprs.push(try!(self.expr())) } } } } } let span = Span::new(lo, self.span.hi); Ok(Spanned::new(span, exprs)) } fn spanned<T>(&self, node: T) -> Spanned<T> { Spanned { node: node, span: self.span, } } /// Parses a string fn string(&self) -> Result<Expr, Error> { Ok(self.spanned(Expr_::String)) } /// Parses a symbol fn symbol(&mut self) -> Result<Expr, Error> { // NB option dance let interner = self.interner.take().unwrap(); let string = &self.source[self.span]; let expr = match string { "false" => Ok(self.spanned(Expr_::Bool(false))), "nil" => Ok(self.spanned(Expr_::Nil)), "true" => Ok(self.spanned(Expr_::Bool(true))), _ => Ok(self.spanned(Expr_::Symbol(interner.intern(string)))), }; // NB option dance self.interner = Some(interner); expr } /// Parses a vector fn vector(&mut self) -> Result<Expr, Error> { Ok(try!(self.seq(Delim::Bracket, false)).map(Expr_::Vector)) } } /// Parses a single expression pub fn expr<'a>(source: &'a Source, interner: &'a mut Interner) -> Result<Expr, Error> { let mut parser = Parser::new(source, interner); let expr = try!(parser.expr()); loop { match parser.lexer.peek() { None => break, Some(&Ok(Spanned { node: Token_::Whitespace, .. })) => { parser.next(); }, Some(_) => { parser.next(); return Err((parser.spanned(Error_::ExpectedEndOfLine))) } } } Ok(expr) }
#[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminAcquireContext ( phcatadmin : *mut isize , pgsubsystem : *const :: windows_sys::core::GUID , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminAcquireContext2 ( phcatadmin : *mut isize , pgsubsystem : *const :: windows_sys::core::GUID , pwszhashalgorithm : :: windows_sys::core::PCWSTR , pstronghashpolicy : *const super:: CERT_STRONG_SIGN_PARA , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] fn CryptCATAdminAddCatalog ( hcatadmin : isize , pwszcatalogfile : :: windows_sys::core::PCWSTR , pwszselectbasename : :: windows_sys::core::PCWSTR , dwflags : u32 ) -> isize ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminCalcHashFromFileHandle ( hfile : super::super::super::Foundation:: HANDLE , pcbhash : *mut u32 , pbhash : *mut u8 , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminCalcHashFromFileHandle2 ( hcatadmin : isize , hfile : super::super::super::Foundation:: HANDLE , pcbhash : *mut u32 , pbhash : *mut u8 , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] fn CryptCATAdminEnumCatalogFromHash ( hcatadmin : isize , pbhash : *const u8 , cbhash : u32 , dwflags : u32 , phprevcatinfo : *mut isize ) -> isize ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminPauseServiceForBackup ( dwflags : u32 , fresume : super::super::super::Foundation:: BOOL ) -> super::super::super::Foundation:: BOOL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminReleaseCatalogContext ( hcatadmin : isize , hcatinfo : isize , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminReleaseContext ( hcatadmin : isize , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminRemoveCatalog ( hcatadmin : isize , pwszcatalogfile : :: windows_sys::core::PCWSTR , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATAdminResolveCatalogPath ( hcatadmin : isize , pwszcatalogfile : :: windows_sys::core::PCWSTR , pscatinfo : *mut CATALOG_INFO , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATAllocSortedMemberInfo ( hcatalog : super::super::super::Foundation:: HANDLE , pwszreferencetag : :: windows_sys::core::PCWSTR ) -> *mut CRYPTCATMEMBER ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATCDFClose ( pcdf : *mut CRYPTCATCDF ) -> super::super::super::Foundation:: BOOL ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATCDFEnumAttributes ( pcdf : *mut CRYPTCATCDF , pmember : *mut CRYPTCATMEMBER , pprevattr : *mut CRYPTCATATTRIBUTE , pfnparseerror : PFN_CDF_PARSE_ERROR_CALLBACK ) -> *mut CRYPTCATATTRIBUTE ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATCDFEnumCatAttributes ( pcdf : *mut CRYPTCATCDF , pprevattr : *mut CRYPTCATATTRIBUTE , pfnparseerror : PFN_CDF_PARSE_ERROR_CALLBACK ) -> *mut CRYPTCATATTRIBUTE ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATCDFEnumMembers ( pcdf : *mut CRYPTCATCDF , pprevmember : *mut CRYPTCATMEMBER , pfnparseerror : PFN_CDF_PARSE_ERROR_CALLBACK ) -> *mut CRYPTCATMEMBER ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATCDFOpen ( pwszfilepath : :: windows_sys::core::PCWSTR , pfnparseerror : PFN_CDF_PARSE_ERROR_CALLBACK ) -> *mut CRYPTCATCDF ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATCatalogInfoFromContext ( hcatinfo : isize , pscatinfo : *mut CATALOG_INFO , dwflags : u32 ) -> super::super::super::Foundation:: BOOL ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATClose ( hcatalog : super::super::super::Foundation:: HANDLE ) -> super::super::super::Foundation:: BOOL ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATEnumerateAttr ( hcatalog : super::super::super::Foundation:: HANDLE , pcatmember : *mut CRYPTCATMEMBER , pprevattr : *mut CRYPTCATATTRIBUTE ) -> *mut CRYPTCATATTRIBUTE ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATEnumerateCatAttr ( hcatalog : super::super::super::Foundation:: HANDLE , pprevattr : *mut CRYPTCATATTRIBUTE ) -> *mut CRYPTCATATTRIBUTE ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATEnumerateMember ( hcatalog : super::super::super::Foundation:: HANDLE , pprevmember : *mut CRYPTCATMEMBER ) -> *mut CRYPTCATMEMBER ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATFreeSortedMemberInfo ( hcatalog : super::super::super::Foundation:: HANDLE , pcatmember : *mut CRYPTCATMEMBER ) -> ( ) ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATGetAttrInfo ( hcatalog : super::super::super::Foundation:: HANDLE , pcatmember : *mut CRYPTCATMEMBER , pwszreferencetag : :: windows_sys::core::PCWSTR ) -> *mut CRYPTCATATTRIBUTE ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATGetCatAttrInfo ( hcatalog : super::super::super::Foundation:: HANDLE , pwszreferencetag : :: windows_sys::core::PCWSTR ) -> *mut CRYPTCATATTRIBUTE ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATGetMemberInfo ( hcatalog : super::super::super::Foundation:: HANDLE , pwszreferencetag : :: windows_sys::core::PCWSTR ) -> *mut CRYPTCATMEMBER ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATHandleFromStore ( pcatstore : *mut CRYPTCATSTORE ) -> super::super::super::Foundation:: HANDLE ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATOpen ( pwszfilename : :: windows_sys::core::PCWSTR , fdwopenflags : CRYPTCAT_OPEN_FLAGS , hprov : usize , dwpublicversion : CRYPTCAT_VERSION , dwencodingtype : u32 ) -> super::super::super::Foundation:: HANDLE ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATPersistStore ( hcatalog : super::super::super::Foundation:: HANDLE ) -> super::super::super::Foundation:: BOOL ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATPutAttrInfo ( hcatalog : super::super::super::Foundation:: HANDLE , pcatmember : *mut CRYPTCATMEMBER , pwszreferencetag : :: windows_sys::core::PCWSTR , dwattrtypeandaction : u32 , cbdata : u32 , pbdata : *mut u8 ) -> *mut CRYPTCATATTRIBUTE ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATPutCatAttrInfo ( hcatalog : super::super::super::Foundation:: HANDLE , pwszreferencetag : :: windows_sys::core::PCWSTR , dwattrtypeandaction : u32 , cbdata : u32 , pbdata : *mut u8 ) -> *mut CRYPTCATATTRIBUTE ); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] fn CryptCATPutMemberInfo ( hcatalog : super::super::super::Foundation:: HANDLE , pwszfilename : :: windows_sys::core::PCWSTR , pwszreferencetag : :: windows_sys::core::PCWSTR , pgsubjecttype : *mut :: windows_sys::core::GUID , dwcertversion : u32 , cbsipindirectdata : u32 , pbsipindirectdata : *mut u8 ) -> *mut CRYPTCATMEMBER ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn CryptCATStoreFromHandle ( hcatalog : super::super::super::Foundation:: HANDLE ) -> *mut CRYPTCATSTORE ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wintrust.dll""system" #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] fn IsCatalogFile ( hfile : super::super::super::Foundation:: HANDLE , pwszfilename : :: windows_sys::core::PCWSTR ) -> super::super::super::Foundation:: BOOL ); #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ADDCATALOG_HARDLINK: u32 = 1u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ADDCATALOG_NONE: u32 = 0u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ATTR_AUTHENTICATED: u32 = 268435456u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ATTR_DATAASCII: u32 = 65536u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ATTR_DATABASE64: u32 = 131072u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ATTR_DATAREPLACE: u32 = 262144u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ATTR_NAMEASCII: u32 = 1u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ATTR_NAMEOBJID: u32 = 2u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ATTR_NO_AUTO_COMPAT_ENTRY: u32 = 16777216u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_ATTR_UNAUTHENTICATED: u32 = 536870912u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_AREA_ATTRIBUTE: u32 = 131072u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_AREA_HEADER: u32 = 0u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_AREA_MEMBER: u32 = 65536u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES: u32 = 131074u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_ATTR_TYPECOMBO: u32 = 131076u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_BAD_GUID_CONV: u32 = 131073u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_DUPLICATE: u32 = 2u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_MEMBER_FILENOTFOUND: u32 = 65540u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_MEMBER_FILE_PATH: u32 = 65537u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_MEMBER_INDIRECTDATA: u32 = 65538u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_TAGNOTFOUND: u32 = 4u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_E_CDF_UNSUPPORTED: u32 = 1u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_FILEEXT: ::windows_sys::core::PCWSTR = ::windows_sys::w!("CAT"); #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_MAX_MEMBERTAG: u32 = 64u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_MEMBER_SORTED: u32 = 1073741824u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const szOID_CATALOG_LIST: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.3.6.1.4.1.311.12.1.1"); #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const szOID_CATALOG_LIST_MEMBER: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.3.6.1.4.1.311.12.1.2"); #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const szOID_CATALOG_LIST_MEMBER2: ::windows_sys::core::PCSTR = ::windows_sys::s!("1.3.6.1.4.1.311.12.1.3"); #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub type CRYPTCAT_OPEN_FLAGS = u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_ALWAYS: CRYPTCAT_OPEN_FLAGS = 2u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_CREATENEW: CRYPTCAT_OPEN_FLAGS = 1u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_EXISTING: CRYPTCAT_OPEN_FLAGS = 4u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_EXCLUDE_PAGE_HASHES: CRYPTCAT_OPEN_FLAGS = 65536u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_INCLUDE_PAGE_HASHES: CRYPTCAT_OPEN_FLAGS = 131072u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_VERIFYSIGHASH: CRYPTCAT_OPEN_FLAGS = 268435456u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_NO_CONTENT_HCRYPTMSG: CRYPTCAT_OPEN_FLAGS = 536870912u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_SORTED: CRYPTCAT_OPEN_FLAGS = 1073741824u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_OPEN_FLAGS_MASK: CRYPTCAT_OPEN_FLAGS = 4294901760u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub type CRYPTCAT_VERSION = u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_VERSION_1: CRYPTCAT_VERSION = 256u32; #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub const CRYPTCAT_VERSION_2: CRYPTCAT_VERSION = 512u32; #[repr(C)] #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub struct CATALOG_INFO { pub cbStruct: u32, pub wszCatalogFile: [u16; 260], } impl ::core::marker::Copy for CATALOG_INFO {} impl ::core::clone::Clone for CATALOG_INFO { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub struct CRYPTCATATTRIBUTE { pub cbStruct: u32, pub pwszReferenceTag: ::windows_sys::core::PWSTR, pub dwAttrTypeAndAction: u32, pub cbValue: u32, pub pbValue: *mut u8, pub dwReserved: u32, } impl ::core::marker::Copy for CRYPTCATATTRIBUTE {} impl ::core::clone::Clone for CRYPTCATATTRIBUTE { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct CRYPTCATCDF { pub cbStruct: u32, pub hFile: super::super::super::Foundation::HANDLE, pub dwCurFilePos: u32, pub dwLastMemberOffset: u32, pub fEOF: super::super::super::Foundation::BOOL, pub pwszResultDir: ::windows_sys::core::PWSTR, pub hCATStore: super::super::super::Foundation::HANDLE, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for CRYPTCATCDF {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for CRYPTCATCDF { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] pub struct CRYPTCATMEMBER { pub cbStruct: u32, pub pwszReferenceTag: ::windows_sys::core::PWSTR, pub pwszFileName: ::windows_sys::core::PWSTR, pub gSubjectType: ::windows_sys::core::GUID, pub fdwMemberFlags: u32, pub pIndirectData: *mut super::Sip::SIP_INDIRECT_DATA, pub dwCertVersion: u32, pub dwReserved: u32, pub hReserved: super::super::super::Foundation::HANDLE, pub sEncodedIndirectData: super::CRYPT_INTEGER_BLOB, pub sEncodedMemberInfo: super::CRYPT_INTEGER_BLOB, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] impl ::core::marker::Copy for CRYPTCATMEMBER {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] impl ::core::clone::Clone for CRYPTCATMEMBER { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub struct CRYPTCATSTORE { pub cbStruct: u32, pub dwPublicVersion: u32, pub pwszP7File: ::windows_sys::core::PWSTR, pub hProv: usize, pub dwEncodingType: u32, pub fdwStoreFlags: CRYPTCAT_OPEN_FLAGS, pub hReserved: super::super::super::Foundation::HANDLE, pub hAttrs: super::super::super::Foundation::HANDLE, pub hCryptMsg: *mut ::core::ffi::c_void, pub hSorted: super::super::super::Foundation::HANDLE, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for CRYPTCATSTORE {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for CRYPTCATSTORE { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`, `\"Win32_Foundation\"`, `\"Win32_Security_Cryptography_Sip\"`*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] pub struct MS_ADDINFO_CATALOGMEMBER { pub cbStruct: u32, pub pStore: *mut CRYPTCATSTORE, pub pMember: *mut CRYPTCATMEMBER, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] impl ::core::marker::Copy for MS_ADDINFO_CATALOGMEMBER {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Sip"))] impl ::core::clone::Clone for MS_ADDINFO_CATALOGMEMBER { fn clone(&self) -> Self { *self } } #[doc = "*Required features: `\"Win32_Security_Cryptography_Catalog\"`*"] pub type PFN_CDF_PARSE_ERROR_CALLBACK = ::core::option::Option<unsafe extern "system" fn(dwerrorarea: u32, dwlocalerror: u32, pwszline: ::windows_sys::core::PCWSTR) -> ()>;
use crate::{ error::{ProximateShellError, ShellError}, parser::{ hir::NamedArguments, span::Span, token::{SpannedToken, Token}, }, signature::{NamedType, Signature}, }; use alloc::{string::String, vec::Vec}; pub mod classified; type OptionalHeadTail = (Option<Vec<SpannedToken>>, Option<NamedArguments>); pub fn parse_command_tail( config: &Signature, tail: &mut impl Iterator<Item = SpannedToken>, command_span: Span, source: &str, ) -> Result<Option<OptionalHeadTail>, ShellError> { let mut named = NamedArguments::new(); let mut positional: Vec<SpannedToken> = vec![]; let mut rest_signature = config.clone(); while let Some(spanned) = tail.next() { match spanned.item { Token::String(_) | Token::Bare | Token::ExternalWord | Token::GlobPattern => { if !rest_signature.positional.is_empty() { positional.push(spanned); rest_signature.shift_positional(); } else if config.rest_positional.is_some() { positional.push(spanned); } } Token::Flag(flag) => { if let Some((kind, _)) = config.named.get(flag.slice(source)) { let kind: &NamedType = kind; // just type annotation match kind { NamedType::Switch => { rest_signature.remove_named(flag.slice(source)); named.insert_switch(flag.slice(source), Some(flag)); } NamedType::Mandatory(_) => { if let Some(next_token) = tail.next() { rest_signature.remove_named(flag.slice(source)); named.insert_mandatory(flag.slice(source), next_token); } else { break; } } NamedType::Optional(_) => { let next_token = tail.next(); rest_signature.remove_named(flag.slice(source)); named.insert_optional(flag.slice(source), next_token); } } } } Token::Whitespace | Token::Separator => {} } } let mut err: Option<(Span, Option<String>)> = None; if let Some((positional_type, _)) = rest_signature .positional .iter() .find(|p| p.0.is_mandatory()) { err = Some(( command_span, Some(format!( "{} needs positional parameter: {}", config.name, positional_type.name() )), )); } if err.is_none() { if let Some((name, _)) = rest_signature .named .iter() .find(|(_, kind)| kind.0.is_mandatory()) { err = Some(( command_span, Some(format!("{} needs named parameter: {}", config.name, name)), )); } } if let Some((span, reason)) = err { Err(ProximateShellError::ParseError(span, reason).start()) } else { let positional = (!positional.is_empty()).then(|| positional); let named = (!named.named.is_empty()).then(|| named); if positional.is_none() && named.is_none() { Ok(None) } else { Ok(Some((positional, named))) } } }
use failure::{bail, ensure, Error, Fail, ResultExt}; use libc::*; use std::ffi::{CStr, CString}; use std::result; use std::str::FromStr; use crate::engine::Engine; type Result<T> = result::Result<T, Error>; include!(concat!(env!("OUT_DIR"), "/cvar_array.rs")); pub const EMPTY_CVAR_T: cvar_t = cvar_t { name: 0 as *const _, string: 0 as *mut _, flags: 0, value: 0f32, next: 0 as *mut _ }; /// The engine `CVar` type. #[repr(C)] pub struct cvar_t { name: *const c_char, string: *mut c_char, flags: c_int, value: c_float, next: *mut cvar_t, } /// Safe wrapper for the engine `CVar` type. pub struct CVar { /// This field has to be public because there's no const fn. /// It shouldn't be accessed manually. pub engine_cvar: *mut cvar_t, // This pointer is always valid and points to a 'static. /// This field has to be public because there's no const fn. /// It shouldn't be accessed manually. pub default_value: &'static str, /// This field has to be public because there's no const fn. /// It shouldn't be accessed manually. pub name: &'static str, } unsafe impl Send for CVar {} unsafe impl Sync for CVar {} impl cvar_t { #[inline] pub fn string_is_non_null(&self) -> bool { !self.string.is_null() } } impl CVar { /// Retrieves a mutable reference to the engine CVar. /// /// # Safety /// Unsafe because this function should only be called from the main game thread. /// You should also ensure that you don't call any engine functions while holding /// this reference, because the game also has a mutable reference to this CVar. #[inline] pub unsafe fn get_engine_cvar(&self) -> &'static mut cvar_t { &mut *self.engine_cvar } /// Registers this console variable. pub fn register(&self, engine: &mut Engine) -> Result<()> { let ptr = { let mut engine_cvar = engine.get_engine_cvar(self); if engine_cvar.name.is_null() { let name_cstring = CString::new(self.name).context("could not convert the CVar name to CString")?; // HACK: leak this CString. It's staying around till the end anyway. engine_cvar.name = name_cstring.into_raw(); } // This CString needs to be valid only for the duration of Cvar_RegisterVariable(). let default_value_cstring = CString::new(self.default_value) .context("could not convert default CVar value to CString")?; let ptr = default_value_cstring.into_raw(); engine_cvar.string = ptr; ptr }; engine.register_variable(self) .context("could not register the variable")?; // Free that CString from above. unsafe { CString::from_raw(ptr) }; Ok(()) } /// Returns the string this variable is set to. pub fn to_string(&self, engine: &mut Engine) -> Result<String> { let engine_cvar = engine.get_engine_cvar(self); ensure!(engine_cvar.string_is_non_null(), "the CVar string pointer was null"); let string = unsafe { CStr::from_ptr(engine_cvar.string) } .to_str() .context("could not convert the CVar string to a Rust string")?; Ok(string.to_owned()) } /// Tries parsing this variable's value to the desired type. pub fn parse<T>(&self, engine: &mut Engine) -> Result<T> where T: FromStr, <T as FromStr>::Err: Fail { let string = self.to_string(engine) .context("could not get this CVar's string value")?; Ok(string.parse::<T>() .context("could not convert the CVar string to the desired type")?) } }
// fn prim_serise(min: i32, max: i32) -> Vec<i32> { // let mut series: Vec<i32> = Vec::new(); //empty vector initialization // let mut count = 0; // for num in min..max { // count = 0; // for i in 2..num { // if num % i == 0 { // count += 1; // break; // } // } // if count == 0 && num != 1 { // series.push(num); // } // } // series // } // fn main() { // // let primes = prim_serise(2, 100); // // println!("{:?}",primes); // let primes = prim_serise(2, 100); // for i in primes.iter() { // println!("{} {:b}", i, i); // } // } // fn is_prime (num:i32)->bool{ // let mut flag = 1; // if num <= 1 { // false // } // else { // for i in 2..num/2+1 { // if num%i == 0 { // flag = 0; // break; // } // } // if flag==0 { // false // } // else { // true // } // } // } // fn main() { // // let primes = prim_serise(2, 100); // // println!("{:?}",primes); // let prime = is_prime(4); // println!("{}",prime); // } #[derive(Clone)] #[derive(Debug)] struct Students { name: String, age: String, education: String, timing: String } impl Students { fn get_name(student: Students)-> String { student.name.to_string() } fn get_timing(student: Students)-> String { student.timing.to_string() } fn get_education(student: Students)-> String { student.education.to_string() } } //constructer function impl Students { fn new(name: String, age: String)-> Students{ Students { name, age, education: "Intermediate".to_string(), timing: "Morning".to_string() } } } fn main(){ let student_01 = Students::new("osama qamar".to_string(), "27".to_string()); let student_02 = Students::new("abdullah Alam".to_string(), "16".to_string()); //println!("{:?}",student_01); let student_name_01 = Students::get_name(student_01.clone()); let student_name_02 =Students::get_name(student_02.clone()); println!("{}",student_name_01); println!("{}",Students::get_education(student_01)); println!("{}",student_name_02); println!("{}",Students::get_education(student_02)); }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type BarcodeScannerDisableScannerRequest = *mut ::core::ffi::c_void; pub type BarcodeScannerDisableScannerRequestEventArgs = *mut ::core::ffi::c_void; pub type BarcodeScannerEnableScannerRequest = *mut ::core::ffi::c_void; pub type BarcodeScannerEnableScannerRequestEventArgs = *mut ::core::ffi::c_void; pub type BarcodeScannerFrameReader = *mut ::core::ffi::c_void; pub type BarcodeScannerFrameReaderFrameArrivedEventArgs = *mut ::core::ffi::c_void; pub type BarcodeScannerGetSymbologyAttributesRequest = *mut ::core::ffi::c_void; pub type BarcodeScannerGetSymbologyAttributesRequestEventArgs = *mut ::core::ffi::c_void; pub type BarcodeScannerHideVideoPreviewRequest = *mut ::core::ffi::c_void; pub type BarcodeScannerHideVideoPreviewRequestEventArgs = *mut ::core::ffi::c_void; pub type BarcodeScannerProviderConnection = *mut ::core::ffi::c_void; pub type BarcodeScannerProviderTriggerDetails = *mut ::core::ffi::c_void; pub type BarcodeScannerSetActiveSymbologiesRequest = *mut ::core::ffi::c_void; pub type BarcodeScannerSetActiveSymbologiesRequestEventArgs = *mut ::core::ffi::c_void; pub type BarcodeScannerSetSymbologyAttributesRequest = *mut ::core::ffi::c_void; pub type BarcodeScannerSetSymbologyAttributesRequestEventArgs = *mut ::core::ffi::c_void; pub type BarcodeScannerStartSoftwareTriggerRequest = *mut ::core::ffi::c_void; pub type BarcodeScannerStartSoftwareTriggerRequestEventArgs = *mut ::core::ffi::c_void; pub type BarcodeScannerStopSoftwareTriggerRequest = *mut ::core::ffi::c_void; pub type BarcodeScannerStopSoftwareTriggerRequestEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BarcodeScannerTriggerState(pub i32); impl BarcodeScannerTriggerState { pub const Released: Self = Self(0i32); pub const Pressed: Self = Self(1i32); } impl ::core::marker::Copy for BarcodeScannerTriggerState {} impl ::core::clone::Clone for BarcodeScannerTriggerState { fn clone(&self) -> Self { *self } } pub type BarcodeScannerVideoFrame = *mut ::core::ffi::c_void; pub type BarcodeSymbologyAttributesBuilder = *mut ::core::ffi::c_void;
const NLOOPS: usize = 100000000; fn main(){ for i in 0..NLOOPS { let s = add(3,5); } } fn add(a: i32, b: i32) -> i32 { let s = a+b; s }
#[macro_use] extern crate clap; extern crate rodio; extern crate rustbox; extern crate yaml_rust; use rustbox::RustBox; use std::default::Default; use std::sync::{Arc, Mutex}; mod arguments; mod notes; mod play; mod output; fn main() { let matches = arguments::get_arguments(); // A workaround to stop cracking noise after note ends (issue #4) let blank_point = rodio::get_default_endpoint().unwrap(); let blank_sink = rodio::Sink::new(&blank_point); let blank_source = rodio::source::SineWave::new(0); blank_sink.append(blank_source); let rb = match RustBox::init(Default::default()) { Result::Ok(v) => Arc::new(Mutex::new(v)), Result::Err(e) => panic!("{}", e), }; output::display_keyboard(&rb); let volume = value_t!(matches.value_of("volume"), f32).unwrap_or(1.0); let mark_duration = value_t!(matches.value_of("markduration"), u32).unwrap_or(500); if let Some(playfile) = matches.value_of("play") { let replaycolor = matches.value_of("replaycolor").unwrap_or("blue"); let tempo = value_t!(matches.value_of("tempo"), f32).unwrap_or(1.0); play::play_from_file(playfile, replaycolor, mark_duration, volume, tempo, &rb); } let raw_sequence = value_t!(matches.value_of("sequence"), i16).unwrap_or(2); let note_duration = value_t!(matches.value_of("noteduration"), u32).unwrap_or(0); let record_file = matches.value_of("record"); let color = matches.value_of("color").unwrap_or("red"); play::play_from_keyboard(&rb, color, mark_duration, note_duration, raw_sequence, volume, record_file); } #[cfg(test)] mod tests { use std::path::Path; #[test] fn check_missing_notes() { // Find missing notes in assets/*.ogg, if any let mut missing_notes = Vec::new(); let expected_notes = ["a", "as", "b", "c", "cs", "d", "ds", "e", "f", "fs", "g", "gs"]; for expected_note in expected_notes.iter() { if expected_note == &"a" || expected_note == &"as" { let note = format!("{}-1.ogg", expected_note); let note_path = format!("assets/{}", note); if !Path::new(&note_path).exists() { missing_notes.push(note); } } for sequence in 0..8_u16 { let note = format!("{}{}.ogg", expected_note, sequence); let note_path = format!("assets/{}", note); if !Path::new(&note_path).exists() { missing_notes.push(note); } } } assert!(missing_notes.len() == 0, "Some note sounds are missing: {}", missing_notes.join(", ")); } }
// Copyright 2016 `multipart` Crate Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! Boundary parsing for `multipart` requests. use ::safemem; use super::buf_redux::BufReader; use super::buf_redux::policy::MinBuffered; use super::twoway; use std::cmp; use std::borrow::Borrow; use std::io; use std::io::prelude::*; use self::State::*; pub const MIN_BUF_SIZE: usize = 1024; #[derive(Debug, PartialEq, Eq)] enum State { Searching, BoundaryRead, AtEnd } /// A struct implementing `Read` and `BufRead` that will yield bytes until it sees a given sequence. #[derive(Debug)] pub struct BoundaryReader<R> { source: BufReader<R, MinBuffered>, boundary: Vec<u8>, search_idx: usize, state: State, } impl<R> BoundaryReader<R> where R: Read { /// Internal API pub fn from_reader<B: Into<Vec<u8>>>(reader: R, boundary: B) -> BoundaryReader<R> { let mut boundary = boundary.into(); safemem::prepend(b"--", &mut boundary); let source = BufReader::new(reader).set_policy(MinBuffered(MIN_BUF_SIZE)); BoundaryReader { source, boundary, search_idx: 0, state: Searching, } } fn read_to_boundary(&mut self) -> io::Result<&[u8]> { let buf = self.source.fill_buf()?; trace!("Buf: {:?}", String::from_utf8_lossy(buf)); debug!("Before search Buf len: {} Search idx: {} State: {:?}", buf.len(), self.search_idx, self.state); if self.state == BoundaryRead || self.state == AtEnd { return Ok(&buf[..self.search_idx]) } if self.state == Searching && self.search_idx < buf.len() { let lookahead = &buf[self.search_idx..]; // Look for the boundary, or if it isn't found, stop near the end. match find_boundary(lookahead, &self.boundary) { Ok(found_idx) => { self.search_idx += found_idx; self.state = BoundaryRead; }, Err(yield_len) => { self.search_idx += yield_len; } } } debug!("After search Buf len: {} Search idx: {} State: {:?}", buf.len(), self.search_idx, self.state); // back up the cursor to before the boundary's preceding CRLF if we haven't already if self.search_idx >= 2 && !buf[self.search_idx..].starts_with(b"\r\n") { let two_bytes_before = &buf[self.search_idx - 2 .. self.search_idx]; trace!("Two bytes before: {:?} ({:?}) (\"\\r\\n\": {:?})", String::from_utf8_lossy(two_bytes_before), two_bytes_before, b"\r\n"); if two_bytes_before == *b"\r\n" { debug!("Subtract two!"); self.search_idx -= 2; } } let ret_buf = &buf[..self.search_idx]; trace!("Returning buf: {:?}", String::from_utf8_lossy(ret_buf)); Ok(ret_buf) } pub fn set_min_buf_size(&mut self, min_buf_size: usize) { // ensure the minimum buf size is at least enough to find a boundary with some extra let min_buf_size = cmp::max(self.boundary.len() * 2, min_buf_size); self.source.policy_mut().0 = min_buf_size; } pub fn consume_boundary(&mut self) -> io::Result<bool> { if self.state == AtEnd { return Ok(false); } while self.state == Searching { debug!("Boundary not found yet"); let buf_len = self.read_to_boundary()?.len(); if buf_len == 0 && self.state == Searching { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "unexpected end of request body")); } debug!("Discarding {} bytes", buf_len); self.consume(buf_len); } let consume_amt = { let buf = self.source.fill_buf()?; // if the boundary is found we should have at least this much in-buffer let mut consume_amt = self.search_idx + self.boundary.len(); // we don't care about data before the cursor let bnd_segment = &buf[self.search_idx..]; if bnd_segment.starts_with(b"\r\n") { // preceding CRLF needs to be consumed as well consume_amt += 2; // assert that we've found the boundary after the CRLF debug_assert_eq!(*self.boundary, bnd_segment[2 .. self.boundary.len() + 2]); } else { // assert that we've found the boundary debug_assert_eq!(*self.boundary, bnd_segment[..self.boundary.len()]); } // include the trailing CRLF or -- consume_amt += 2; if buf.len() < consume_amt { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "not enough bytes to verify boundary")); } // we have enough bytes to verify self.state = Searching; let last_two = &buf[consume_amt - 2 .. consume_amt]; match last_two { b"\r\n" => self.state = Searching, b"--" => self.state = AtEnd, _ => return Err(io::Error::new( io::ErrorKind::InvalidData, format!("unexpected bytes following multipart boundary: {:X} {:X}", last_two[0], last_two[1]) )), } consume_amt }; trace!("Consuming {} bytes, remaining buf: {:?}", consume_amt, String::from_utf8_lossy(self.source.buffer())); self.source.consume(consume_amt); if cfg!(debug_assertions) { } self.search_idx = 0; trace!("Consumed boundary (state: {:?}), remaining buf: {:?}", self.state, String::from_utf8_lossy(self.source.buffer())); Ok(self.state != AtEnd) } } /// Find the boundary occurrence or the highest length to safely yield fn find_boundary(buf: &[u8], boundary: &[u8]) -> Result<usize, usize> { if let Some(idx) = twoway::find_bytes(buf, boundary) { return Ok(idx); } let search_start = buf.len().saturating_sub(boundary.len()); // search for just the boundary fragment for i in search_start .. buf.len() { if boundary.starts_with(&buf[i..]) { return Err(i); } } Err(buf.len()) } #[cfg(feature = "bench")] impl<'a> BoundaryReader<io::Cursor<&'a [u8]>> { fn new_with_bytes(bytes: &'a [u8], boundary: &str) -> Self { Self::from_reader(io::Cursor::new(bytes), boundary) } fn reset(&mut self) { // Dump buffer and reset cursor self.source.seek(io::SeekFrom::Start(0)); self.state = Searching; self.search_idx = 0; } } impl<R> Borrow<R> for BoundaryReader<R> { fn borrow(&self) -> &R { self.source.get_ref() } } impl<R> Read for BoundaryReader<R> where R: Read { fn read(&mut self, out: &mut [u8]) -> io::Result<usize> { let read = { let mut buf = self.read_to_boundary()?; // This shouldn't ever be an error so unwrapping is fine. buf.read(out).unwrap() }; self.consume(read); Ok(read) } } impl<R> BufRead for BoundaryReader<R> where R: Read { fn fill_buf(&mut self) -> io::Result<&[u8]> { self.read_to_boundary() } fn consume(&mut self, amt: usize) { let true_amt = cmp::min(amt, self.search_idx); debug!("Consume! amt: {} true amt: {}", amt, true_amt); self.source.consume(true_amt); self.search_idx -= true_amt; } } #[cfg(test)] mod test { use super::BoundaryReader; use std::io; use std::io::prelude::*; const BOUNDARY: &'static str = "boundary"; const TEST_VAL: &'static str = "--boundary\r\n\ dashed-value-1\r\n\ --boundary\r\n\ dashed-value-2\r\n\ --boundary--"; #[test] fn test_boundary() { ::init_log(); debug!("Testing boundary (no split)"); let src = &mut TEST_VAL.as_bytes(); let mut reader = BoundaryReader::from_reader(src, BOUNDARY); let mut buf = String::new(); test_boundary_reader(&mut reader, &mut buf); } struct SplitReader<'a> { left: &'a [u8], right: &'a [u8], } impl<'a> SplitReader<'a> { fn split(data: &'a [u8], at: usize) -> SplitReader<'a> { let (left, right) = data.split_at(at); SplitReader { left: left, right: right, } } } impl<'a> Read for SplitReader<'a> { fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> { fn copy_bytes_partial(src: &mut &[u8], dst: &mut [u8]) -> usize { src.read(dst).unwrap() } let mut copy_amt = copy_bytes_partial(&mut self.left, dst); if copy_amt == 0 { copy_amt = copy_bytes_partial(&mut self.right, dst) }; Ok(copy_amt) } } #[test] fn test_split_boundary() { ::init_log(); debug!("Testing boundary (split)"); let mut buf = String::new(); // Substitute for `.step_by()` being unstable. for split_at in 0 .. TEST_VAL.len(){ debug!("Testing split at: {}", split_at); let src = SplitReader::split(TEST_VAL.as_bytes(), split_at); let mut reader = BoundaryReader::from_reader(src, BOUNDARY); test_boundary_reader(&mut reader, &mut buf); } } fn test_boundary_reader<R: Read>(reader: &mut BoundaryReader<R>, buf: &mut String) { buf.clear(); debug!("Read 1"); let _ = reader.read_to_string(buf).unwrap(); assert!(buf.is_empty(), "Buffer not empty: {:?}", buf); buf.clear(); debug!("Consume 1"); reader.consume_boundary().unwrap(); debug!("Read 2"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "dashed-value-1"); buf.clear(); debug!("Consume 2"); reader.consume_boundary().unwrap(); debug!("Read 3"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "dashed-value-2"); buf.clear(); debug!("Consume 3"); reader.consume_boundary().unwrap(); debug!("Read 4"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, ""); } #[test] fn test_empty_body() { ::init_log(); // empty body contains closing boundary only let mut body: &[u8] = b"--boundary--"; let ref mut buf = String::new(); let mut reader = BoundaryReader::from_reader(&mut body, BOUNDARY); debug!("Consume 1"); assert_eq!(reader.consume_boundary().unwrap(), false); debug!("Read 1"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, ""); buf.clear(); debug!("Consume 2"); assert_eq!(reader.consume_boundary().unwrap(), false); } #[test] fn test_leading_crlf() { ::init_log(); let mut body: &[u8] = b"\r\n\r\n--boundary\r\n\ asdf1234\ \r\n\r\n--boundary--"; let ref mut buf = String::new(); let mut reader = BoundaryReader::from_reader(&mut body, BOUNDARY); debug!("Consume 1"); assert_eq!(reader.consume_boundary().unwrap(), true); debug!("Read 1"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "asdf1234\r\n"); buf.clear(); debug!("Consume 2"); assert_eq!(reader.consume_boundary().unwrap(), false); debug!("Read 2 (empty)"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, ""); } #[test] fn test_trailing_crlf() { ::init_log(); let mut body: &[u8] = b"--boundary\r\n\ asdf1234\ \r\n\r\n--boundary\r\n\ hjkl5678\r\n--boundary--"; let ref mut buf = String::new(); let mut reader = BoundaryReader::from_reader(&mut body, BOUNDARY); debug!("Consume 1"); assert_eq!(reader.consume_boundary().unwrap(), true); debug!("Read 1"); // Repro for https://github.com/abonander/multipart/issues/93 // These two reads should produce the same buffer let buf1 = reader.read_to_boundary().unwrap().to_owned(); let buf2 = reader.read_to_boundary().unwrap().to_owned(); assert_eq!(buf1, buf2); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "asdf1234\r\n"); buf.clear(); debug!("Consume 2"); assert_eq!(reader.consume_boundary().unwrap(), true); debug!("Read 2"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "hjkl5678"); buf.clear(); debug!("Consume 3"); assert_eq!(reader.consume_boundary().unwrap(), false); debug!("Read 3 (empty)"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, ""); } // https://github.com/abonander/multipart/issues/93#issuecomment-343610587 #[test] fn test_trailing_lflf() { ::init_log(); let mut body: &[u8] = b"--boundary\r\n\ asdf1234\ \n\n\r\n--boundary\r\n\ hjkl5678\r\n--boundary--"; let ref mut buf = String::new(); let mut reader = BoundaryReader::from_reader(&mut body, BOUNDARY); debug!("Consume 1"); assert_eq!(reader.consume_boundary().unwrap(), true); debug!("Read 1"); // same as above let buf1 = reader.read_to_boundary().unwrap().to_owned(); let buf2 = reader.read_to_boundary().unwrap().to_owned(); assert_eq!(buf1, buf2); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "asdf1234\n\n"); buf.clear(); debug!("Consume 2"); assert_eq!(reader.consume_boundary().unwrap(), true); debug!("Read 2"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "hjkl5678"); buf.clear(); debug!("Consume 3"); assert_eq!(reader.consume_boundary().unwrap(), false); debug!("Read 3 (empty)"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, ""); } // https://github.com/abonander/multipart/issues/104 #[test] fn test_unterminated_body() { ::init_log(); let mut body: &[u8] = b"--boundary\r\n\ asdf1234\ \n\n\r\n--boundary\r\n\ hjkl5678 "; let ref mut buf = String::new(); let mut reader = BoundaryReader::from_reader(&mut body, BOUNDARY); debug!("Consume 1"); assert_eq!(reader.consume_boundary().unwrap(), true); debug!("Read 1"); // same as above let buf1 = reader.read_to_boundary().unwrap().to_owned(); let buf2 = reader.read_to_boundary().unwrap().to_owned(); assert_eq!(buf1, buf2); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "asdf1234\n\n"); buf.clear(); debug!("Consume 2"); assert_eq!(reader.consume_boundary().unwrap(), true); debug!("Read 2"); let _ = reader.read_to_string(buf).unwrap(); assert_eq!(buf, "hjkl5678 "); buf.clear(); debug!("Consume 3 - expecting error"); reader.consume_boundary().unwrap_err(); } #[test] fn test_lone_boundary() { let mut body: &[u8] = b"--boundary"; let mut reader = BoundaryReader::from_reader(&mut body, "boundary"); reader.consume_boundary().unwrap_err(); } #[test] fn test_invalid_boundary() { let mut body: &[u8] = b"--boundary\x00\x00"; let mut reader = BoundaryReader::from_reader(&mut body, "boundary"); reader.consume_boundary().unwrap_err(); } #[test] fn test_skip_field() { let mut body: &[u8] = b"--boundary\r\nfield1\r\n--boundary\r\nfield2\r\n--boundary--"; let mut reader = BoundaryReader::from_reader(&mut body, "boundary"); assert_eq!(reader.consume_boundary().unwrap(), true); // skip `field1` assert_eq!(reader.consume_boundary().unwrap(), true); let mut buf = String::new(); reader.read_to_string(&mut buf).unwrap(); assert_eq!(buf, "field2"); assert_eq!(reader.consume_boundary().unwrap(), false); } #[cfg(feature = "bench")] mod bench { extern crate test; use self::test::Bencher; use super::*; #[bench] fn bench_boundary_reader(b: &mut Bencher) { let mut reader = BoundaryReader::new_with_bytes(TEST_VAL.as_bytes(), BOUNDARY); let mut buf = String::with_capacity(256); b.iter(|| { reader.reset(); test_boundary_reader(&mut reader, &mut buf); }); } } }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_structure_send_command_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::SendCommandInput, ) { if let Some(var_1) = &input.session_token { object.key("SessionToken").string(var_1); } if let Some(var_2) = &input.start_session { let mut object_3 = object.key("StartSession").start_object(); crate::json_ser::serialize_structure_start_session_request(&mut object_3, var_2); object_3.finish(); } if let Some(var_4) = &input.start_transaction { let mut object_5 = object.key("StartTransaction").start_object(); crate::json_ser::serialize_structure_start_transaction_request(&mut object_5, var_4); object_5.finish(); } if let Some(var_6) = &input.end_session { let mut object_7 = object.key("EndSession").start_object(); crate::json_ser::serialize_structure_end_session_request(&mut object_7, var_6); object_7.finish(); } if let Some(var_8) = &input.commit_transaction { let mut object_9 = object.key("CommitTransaction").start_object(); crate::json_ser::serialize_structure_commit_transaction_request(&mut object_9, var_8); object_9.finish(); } if let Some(var_10) = &input.abort_transaction { let mut object_11 = object.key("AbortTransaction").start_object(); crate::json_ser::serialize_structure_abort_transaction_request(&mut object_11, var_10); object_11.finish(); } if let Some(var_12) = &input.execute_statement { let mut object_13 = object.key("ExecuteStatement").start_object(); crate::json_ser::serialize_structure_execute_statement_request(&mut object_13, var_12); object_13.finish(); } if let Some(var_14) = &input.fetch_page { let mut object_15 = object.key("FetchPage").start_object(); crate::json_ser::serialize_structure_fetch_page_request(&mut object_15, var_14); object_15.finish(); } } pub fn serialize_structure_start_session_request( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::StartSessionRequest, ) { if let Some(var_16) = &input.ledger_name { object.key("LedgerName").string(var_16); } } pub fn serialize_structure_start_transaction_request( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::StartTransactionRequest, ) { let (_, _) = (object, input); } pub fn serialize_structure_end_session_request( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::EndSessionRequest, ) { let (_, _) = (object, input); } pub fn serialize_structure_commit_transaction_request( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::CommitTransactionRequest, ) { if let Some(var_17) = &input.transaction_id { object.key("TransactionId").string(var_17); } if let Some(var_18) = &input.commit_digest { object .key("CommitDigest") .string_unchecked(&smithy_types::base64::encode(var_18)); } } pub fn serialize_structure_abort_transaction_request( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::AbortTransactionRequest, ) { let (_, _) = (object, input); } pub fn serialize_structure_execute_statement_request( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::ExecuteStatementRequest, ) { if let Some(var_19) = &input.transaction_id { object.key("TransactionId").string(var_19); } if let Some(var_20) = &input.statement { object.key("Statement").string(var_20); } if let Some(var_21) = &input.parameters { let mut array_22 = object.key("Parameters").start_array(); for item_23 in var_21 { { let mut object_24 = array_22.value().start_object(); crate::json_ser::serialize_structure_value_holder(&mut object_24, item_23); object_24.finish(); } } array_22.finish(); } } pub fn serialize_structure_fetch_page_request( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::FetchPageRequest, ) { if let Some(var_25) = &input.transaction_id { object.key("TransactionId").string(var_25); } if let Some(var_26) = &input.next_page_token { object.key("NextPageToken").string(var_26); } } pub fn serialize_structure_value_holder( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::ValueHolder, ) { if let Some(var_27) = &input.ion_binary { object .key("IonBinary") .string_unchecked(&smithy_types::base64::encode(var_27)); } if let Some(var_28) = &input.ion_text { object.key("IonText").string(var_28); } }
/* Copyright (c) 2017 The swc Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use crate::{ amp_attributes::amp_attributes, complete_output, complete_output_with_ranges, get_compiler, hook_optimizer::hook_optimizer, next_dynamic::next_dynamic, next_ssg::next_ssg, styled_jsx::styled_jsx, util::{CtxtExt, MapErr}, }; use anyhow::{Context as _, Error}; use napi::{CallContext, Env, JsBoolean, JsObject, JsString, Task}; use serde::Deserialize; use std::{path::PathBuf, sync::Arc}; use swc::{try_with_handler, Compiler, TransformOutput}; use swc_common::{chain, pass::Optional, FileName, SourceFile}; use swc_ecmascript::ast::Program; use swc_ecmascript::transforms::pass::noop; use anyhow::bail; /// Input to transform #[derive(Debug)] pub enum Input { /// Raw source code. Source(Arc<SourceFile>), } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransformOptions { #[serde(flatten)] pub swc: swc::config::Options, #[serde(default)] pub disable_next_ssg: bool, #[serde(default)] pub pages_dir: Option<PathBuf>, } pub struct TransformTask { pub c: Arc<Compiler>, pub input: Input, pub options: TransformOptions, } use crate::ranges::{get_ranges}; impl Task for TransformTask { type Output = TransformOutputWithRanges; type JsValue = JsObject; fn compute(&mut self) -> napi::Result<Self::Output> { let res = try_with_handler(self.c.cm.clone(), |handler| { self.c.run(|| match self.input { Input::Source(ref s) => { let before_pass = noop(); self.c.process_js_with_custom_pass( s.clone(), &handler, &self.options.swc, before_pass, noop(), ) } }) }) .convert_err(); let val = res.unwrap(); let ranges = vec![vec![]]; Ok(TransformOutputWithRanges { code: val.code, map: val.map, ranges, }) } fn resolve(self, env: Env, result: Self::Output) -> napi::Result<Self::JsValue> { complete_output_with_ranges(&env, result) } } /// returns `compiler, (src / path), options, plugin, callback` pub fn schedule_transform<F>(cx: CallContext, op: F) -> napi::Result<JsObject> where F: FnOnce(&Arc<Compiler>, String, bool, TransformOptions) -> TransformTask, { let c = get_compiler(&cx); let s = cx.get::<JsString>(0)?.into_utf8()?.as_str()?.to_owned(); let is_module = cx.get::<JsBoolean>(1)?; let options: TransformOptions = cx.get_deserialized(2)?; let task = op(&c, s, is_module.get_value()?, options); cx.env.spawn(task).map(|t| t.promise_object()) } use crate::ranges::Ranges; use serde::*; use swc::common::errors::Handler; use swc::config::BuiltConfig; #[derive(Debug, Serialize)] pub struct TransformOutputWithRanges { pub code: String, #[serde(skip_serializing_if = "Option::is_none")] pub map: Option<String>, pub ranges: Ranges, } pub fn exec_transform<F>(cx: CallContext, op: F) -> napi::Result<JsObject> where F: FnOnce(&Compiler, String, &TransformOptions) -> Result<Arc<SourceFile>, Error>, { let c = get_compiler(&cx); let s = cx.get::<JsString>(0)?.into_utf8()?; let is_module = cx.get::<JsBoolean>(1)?; let options: TransformOptions = cx.get_deserialized(2)?; let str = s.as_str()?; let output = my_transform(c, str, is_module.get_value()?, options, op).convert_err()?; complete_output_with_ranges(cx.env, output) } pub fn my_transform<F>( c: Arc<Compiler>, s: &str, is_module: bool, options: TransformOptions, op: F, ) -> Result<TransformOutputWithRanges, Error> where F: FnOnce(&Compiler, String, &TransformOptions) -> Result<Arc<SourceFile>, Error>, { let output = try_with_handler(c.cm.clone(), |handler| { c.run(|| { if is_module { let program: Program = serde_json::from_str(s).context("failed to deserialize Program")?; let ranges: Ranges = get_ranges(&program, c.cm.clone()); let res = c.process_js(&handler, program, &options.swc).unwrap(); // let ranges: Ranges = vec![vec![0, 0, 0, 0]]; Ok(TransformOutputWithRanges { code: res.code, map: res.map, ranges, }) } else { let fm = op(&c, s.to_string(), &options).context("failed to load file")?; let program = get_program(&c, fm, handler, &options)?; let ranges: Ranges = get_ranges(&program, c.cm.clone()); let res = c.process_js(&handler, program, &options.swc).unwrap(); // let res = c.process_js_file(fm, &handler, &options.swc).unwrap(); Ok(TransformOutputWithRanges { code: res.code, map: res.map, ranges, }) } }) }); output } pub fn get_program( c: &Arc<Compiler>, fm: Arc<SourceFile>, handler: &Handler, options: &TransformOptions, ) -> Result<Program, Error> { // From `process_js_file`... let opts = &options.swc; let config = c.config_for_file(handler, opts, &fm.name)?; let config = match config { Some(v) => v, None => { bail!("cannot process file because it's ignored by .swcrc") } }; let custom_before_pass = noop(); let custom_after_pass = noop(); let config = BuiltConfig { pass: chain!(custom_before_pass, config.pass, custom_after_pass), syntax: config.syntax, target: config.target, minify: config.minify, external_helpers: config.external_helpers, source_maps: config.source_maps, input_source_map: config.input_source_map, is_module: config.is_module, output_path: config.output_path, source_file_name: config.source_file_name, preserve_comments: config.preserve_comments, inline_sources_content: config.inline_sources_content, }; let program = c.parse_js( fm.clone(), handler, config.target, config.syntax, config.is_module, true, )?; Ok(program) } #[js_function(4)] pub fn transform(cx: CallContext) -> napi::Result<JsObject> { schedule_transform(cx, |c, src, _, options| { let input = Input::Source(c.cm.new_source_file( if options.swc.filename.is_empty() { FileName::Anon } else { FileName::Real(options.swc.filename.clone().into()) }, src, )); TransformTask { c: c.clone(), input, options, } }) } #[js_function(4)] pub fn transform_sync(cx: CallContext) -> napi::Result<JsObject> { exec_transform(cx, |c, src, options| { Ok(c.cm.new_source_file( if options.swc.filename.is_empty() { FileName::Anon } else { FileName::Real(options.swc.filename.clone().into()) }, src, )) }) } #[test] fn test_deser() { const JSON_STR: &str = r#"{"jsc":{"parser":{"syntax":"ecmascript","dynamicImport":true,"jsx":true},"transform":{"react":{"runtime":"automatic","pragma":"React.createElement","pragmaFrag":"React.Fragment","throwIfNamespace":true,"development":false,"useBuiltins":true}},"target":"es5"},"filename":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js","sourceMaps":false,"sourceFileName":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js"}"#; let tr: TransformOptions = serde_json::from_str(&JSON_STR).unwrap(); println!("{:#?}", tr); }
use crate::weapon::Weapon; use fyrox::core::pool::Handle; pub enum Message { ShootWeapon { weapon: Handle<Weapon> }, }
use std::sync::mpsc::channel; use helixdb::iterator::Iterator; use helixdb::option::ScanOption; use helixdb::{HelixDB, NoOrderComparator}; use tokio::runtime::Builder; use crate::panel::Panel; pub fn scan(helixdb: HelixDB, num_thread: usize, repeat_time: usize, prefetch_buf_size: usize) { let (tx, rx) = channel(); let mut panel = Panel::with_amount(repeat_time as u64); let rt = Builder::new_multi_thread() .worker_threads(num_thread) .build() .unwrap(); for _ in 0..repeat_time as u64 { let helixdb = helixdb.clone(); let tx = tx.clone(); rt.spawn(async move { let mut iter = helixdb .scan::<NoOrderComparator>( (0, 4).into(), ( 0usize.to_le_bytes().to_vec(), 1024usize.to_le_bytes().to_vec(), ), ScanOption { prefetch_buf_size }, ) .await .unwrap(); let mut scan_cnt = 0; while iter.next().await.unwrap().is_some() { scan_cnt += 1 } println!("scanned {} item", scan_cnt); tx.send(()).unwrap(); }); } for _ in rx.iter().take(repeat_time) { panel.increase(1); } }
use crate::codec::{Decode, Encode}; use crate::remote_type; use crate::spacecenter::Vessel; mod servo; mod servogroup; pub use self::servo::*; pub use self::servogroup::*; remote_type!( /// This service provides functionality to interact with Infernal Robotics. service InfernalRobotics { properties: { { Available { /// Returns whether Infernal Robotics is installed. /// /// **Game Scenes**: Flight get: is_available -> bool } } { Ready { /// Returns whether the Infernal Robotics API is ready. /// /// **Game Scenes**: Flight get: is_ready -> bool } } } methods: { { /// A list of all the servo groups in the given vessel. /// /// **Game Scenes**: Flight /// /// # Arguments /// * `vessel` - Vessel to check. fn servo_groups(vessel: &Vessel) -> Vec<ServoGroup> { ServoGroups(vessel) } } { /// Returns the servo group in the given vessel with the given name, /// or `None` if none exists. If multiple servo groups have the same name, /// only one of them is returned. /// /// **Game Scenes**: Flight /// /// # Arguments /// * `vessel` - Vessel to check. /// * `name` - Name of servo group to find. fn servo_group_with_name(vessel: &Vessel, name: &str) -> Option<ServoGroup> { ServoGroupWithName(vessel, name) } } { /// Returns the servo in the given vessel with the given name, /// or `None` if none exists. If multiple servos have the same name, /// only one of them is returned. /// /// **Game Scenes**: Flight /// /// # Arguments /// * `vessel` - Vessel to check. /// * `name` - Name of servo to find. fn servo_with_name(vessel: &Vessel, name: &str) -> Option<Servo> { ServoWithName(vessel, name) } } } });
#[macro_use] extern crate log; use actix_web::middleware::Logger; use actix_web::{web, App, HttpServer}; use std::env; mod db; mod graphql; mod handler; struct ActixConfig { host: String, port: u32, workers: u8, } fn get_server_env() -> ActixConfig { let host = env::var("SERVER_HOST").unwrap_or(String::from("127.0.0.1")); let port: u32 = env::var("SERVER_PORT") .unwrap_or(String::from("8080")) .parse() .unwrap(); let workers: u8 = env::var("SERVER_WORKERS") .unwrap_or(String::from("1")) .parse() .unwrap(); ActixConfig { host, port, workers, } } #[actix_web::main] async fn main() -> std::io::Result<()> { // get env vars let cfg = get_server_env(); // define host let host = format!("{}:{}", cfg.host, cfg.port); // println!("Starting http server at {:?}", host); // enable logger // std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "info"); env_logger::init(); // show this info!("Starting http server at {:?}", host); // create db connection pool let pool = db::create_pool().await; //start http server HttpServer::new(move || { App::new() .wrap(Logger::default()) .data(pool.clone()) .configure(handler::register) .default_service(web::to(handler::page404)) }) .bind(host)? .workers(cfg.workers.into()) .run() .await }
#![feature(proc_macro)] // allow defining non-derive proc macros extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro] pub fn utf16(input: TokenStream) -> TokenStream { let mut it = input.into_iter(); let mut rv = Vec::new(); loop { match it.next() { Some(::proc_macro::TokenTree { kind: ::proc_macro::TokenNode::Literal(l), .. }) => { let s = match literal_to_string(l) { Ok(s) => s, Err(l) => panic!("Unexpected token '{}'", l), }; //println!("s = {:?}", s); for c in s.chars() { if c as u32 <= 0xFFFF { rv.push(::proc_macro::TokenNode::Literal(::proc_macro::Literal::u16(c as u32 as u16))); rv.push(::proc_macro::TokenNode::Op(',', ::proc_macro::Spacing::Alone)); } else { let v = c as u32 - 0x1_0000; let hi = v >> 10; assert!(hi <= 0x3FF); let lo = v & 0x3FF; rv.push(::proc_macro::TokenNode::Literal(::proc_macro::Literal::u16(0xD800 + hi as u16))); rv.push(::proc_macro::TokenNode::Op(',', ::proc_macro::Spacing::Alone)); rv.push(::proc_macro::TokenNode::Literal(::proc_macro::Literal::u16(0xDC00 + lo as u16))); rv.push(::proc_macro::TokenNode::Literal(::proc_macro::Literal::u16(c as u32 as u16))); rv.push(::proc_macro::TokenNode::Op(',', ::proc_macro::Spacing::Alone)); } } }, Some(t) => panic!("Unexpected token '{}'", t), None => panic!("utf16! requires a string literal argument"), } match it.next() { Some(::proc_macro::TokenTree { kind: ::proc_macro::TokenNode::Op(',', _), .. }) => {}, Some(t) => panic!("Unexpected token '{}'", t), None => break, } } //println!("{:?}", rv); vec![ ::proc_macro::TokenNode::Op('&', ::proc_macro::Spacing::Alone), ::proc_macro::TokenNode::Group(::proc_macro::Delimiter::Bracket, rv.into_iter().collect()), ].into_iter().collect() } fn literal_to_string(lit: ::proc_macro::Literal) -> Result<String,::proc_macro::Literal> { let formatted = lit.to_string(); let mut it = formatted.chars(); if it.next() != Some('"') { return Err(lit); } let mut rv = String::new(); loop { match it.next() { Some('"') => match it.next() { Some(v) => panic!("malformed string, stray \" in the middle (followed by '{:?}')", v), None => break, }, Some('\\') => match it.next() { Some('0') => rv.push('\0'), Some('\\') => rv.push('\\'), Some(c) => panic!("TODO: Escape sequence \\{:?}", c), None => panic!("malformed string, unexpected EOS (after \\)"), }, Some(c) => rv.push(c), None => panic!("malformed string, unexpected EOS"), } } Ok(rv) }
use rocket::Request; use rocket_contrib::Json; use serde_derive::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct JsonErrorResponse { pub error: String, } #[catch(404)] pub fn json_404(_req: &Request) -> Json<JsonErrorResponse> { Json(JsonErrorResponse { error: "Could not find the requested resource".to_string(), }) } #[catch(500)] pub fn json_500(_req: &Request) -> Json<JsonErrorResponse> { Json(JsonErrorResponse { error: "Server encountered an internal error".to_string(), }) } #[catch(401)] pub fn json_401(_req: &Request) -> Json<JsonErrorResponse> { Json(JsonErrorResponse { error: "User authentication is required".to_string(), }) } #[catch(403)] pub fn json_403(_req: &Request) -> Json<JsonErrorResponse> { Json(JsonErrorResponse { error: "Request refused".to_string(), }) }
use rand::Rng; use secret_integers::*; /// classify vector of u8s into U8s fn classify_u8s(v: &[u8]) -> Vec<U8> { v.iter().map(|x| U8::classify(*x)).collect() } /// declassify vector of U8s into u8s fn declassify_u8s(v: &[U8]) -> Vec<u8> { v.iter().map(|x| U8::declassify(*x)).collect() } pub fn get_secret_key() -> Vec<U8> { let random_bytes = rand::thread_rng().gen::<[u8; 8]>(); return classify_u8s(&random_bytes); } pub fn encrypt(msg: &[u8], sk: &[U8]) -> Vec<u8> { let mut new_block = [U8::zero(); 8]; let classified_msg = classify_u8s(msg); for i in 0..8 { new_block[i] = classified_msg[i] ^ sk[i]; } return declassify_u8s(&new_block); } pub fn decrypt(cipher: &[u8], sk: &[U8]) -> Vec<u8> { let mut new_block = [U8::zero(); 8]; let classified_cipher = classify_u8s(cipher); for i in 0..8 { new_block[i] = classified_cipher[i] ^ sk[i]; } return declassify_u8s(&new_block); }
use std::env; use std::fmt::Display; use std::fs::File; use std::path::{Path, PathBuf}; use std::str::FromStr; use color_eyre::eyre::Result; use structopt::StructOpt; use crate::day::Day; #[derive(StructOpt)] pub struct Run { /// Problem day to run day: Day, /// Path to input file #[structopt(long)] input: Option<PathBuf>, /// Any extra arguments in question #[structopt(long)] extra: Vec<String>, /// Part to run #[structopt(long, short, default_value)] part: Part, } #[derive(StructOpt)] enum Part { Part1, Part2, Both, } impl FromStr for Part { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "part1" | "1" => Ok(Self::Part1), "part2" | "2" => Ok(Self::Part2), "both" | "b" => Ok(Self::Both), _ => Err("Unknown"), } } } impl Default for Part { fn default() -> Self { Self::Both } } impl Display for Part { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Part::Part1 => write!(f, "part1"), Part::Part2 => write!(f, "part2"), Part::Both => write!(f, "both"), } } } impl Run { pub fn run(&self) -> Result<String> { let mut file; if let Some(ref path) = self.input { file = File::open(path)?; } else { let path = env::var("AOC_INPUT")?; let path = Path::new(&path).join(format!("Day{}", self.day.get())); file = File::open(path)?; } let code = self.day.get_code(); let extra_args = &self.extra; let output = match self.part { Part::Part1 => code.part1(&mut file, extra_args), Part::Part2 => code.part2(&mut file, extra_args), Part::Both => code.both(&mut file, extra_args), }; Ok(output) } }
// 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 std::collections::BTreeMap; use std::convert::TryFrom; use common_exception::ErrorCode; use common_exception::Result; pub const PARTITION_KEYS: &str = "partition_keys"; pub const LOCATION: &str = "location"; // represents hive table schema info // // partition_keys, hive partition keys, such as: "p_date", "p_hour" // location, hive table location, such as: hdfs://namenode:8020/user/hive/warehouse/a.db/b.table/ #[derive(Clone, Debug, PartialEq, Eq)] pub struct HiveTableOptions { pub partition_keys: Option<Vec<String>>, pub location: Option<String>, } impl From<HiveTableOptions> for BTreeMap<String, String> { fn from(options: HiveTableOptions) -> BTreeMap<String, String> { let mut map = BTreeMap::new(); if let Some(partition_keys) = options.partition_keys { if !partition_keys.is_empty() { map.insert(PARTITION_KEYS.to_string(), partition_keys.join(" ")); } } options .location .map(|v| map.insert(LOCATION.to_string(), v)); map } } impl TryFrom<&BTreeMap<String, String>> for HiveTableOptions { type Error = ErrorCode; fn try_from(options: &BTreeMap<String, String>) -> Result<HiveTableOptions> { let partition_keys = options.get(PARTITION_KEYS); let partition_keys = if let Some(partition_keys) = partition_keys { let a: Vec<String> = partition_keys.split(' ').map(str::to_string).collect(); if !a.is_empty() { Some(a) } else { None } } else { None }; let location = options .get(LOCATION) .ok_or_else(|| ErrorCode::Internal("Hive engine table missing location key"))? .clone(); let options = HiveTableOptions { partition_keys, location: Some(location), }; Ok(options) } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use super::HiveTableOptions; fn do_test_hive_table_options(hive_table_options: HiveTableOptions) { let m: BTreeMap<String, String> = hive_table_options.clone().into(); let options2 = HiveTableOptions::try_from(&m).unwrap(); assert_eq!(hive_table_options, options2); } #[test] fn test_hive_table_options() { let hive_table_options = HiveTableOptions { partition_keys: Some(vec!["a".to_string(), "b".to_string()]), location: Some("test".to_string()), }; do_test_hive_table_options(hive_table_options); let empty = HiveTableOptions { partition_keys: None, location: Some("test".to_string()), }; do_test_hive_table_options(empty); } }
use std::cmp::Ordering; fn main() { let secret_number = 0; let guess = 0; // -1, 1 match guess.cmp(&secret_number) { Ordering::Less => println!("小さすぎます。残念……"), Ordering::Greater => println!("大きすぎます。残念……"), Ordering::Equal => println!("ぴったり! やったね!"), } }
mod buffer; mod pool; mod status; mod string; pub use buffer::*; pub use pool::*; pub use status::*; pub use string::*; #[macro_export] macro_rules! ngx_string { ($x:expr) => { { // const asserts are not yet supported (see rust-lang/rust#51999) &[()][1 - (($x[$x.len() - 1] == b'\0') as usize)]; // must have nul-byte ngx_str_t { len: $x.len() - 1, data: $x.as_ptr() as *mut u8 } } }; } #[macro_export] macro_rules! ngx_null_string { () => { ngx_str_t { len: 0, data: ::std::ptr::null_mut() } }; } #[macro_export] macro_rules! ngx_null_command { () => { ngx_command_t { name: $crate::ngx_null_string!(), type_: 0, set: None, conf: 0, offset: 0, post: ::std::ptr::null_mut(), } }; }
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::eager_or_lazy::switch_to_lazy_eval; use clippy_utils::source::{snippet, snippet_with_applicability, snippet_with_macro_callsite}; use clippy_utils::ty::{implements_trait, match_type}; use clippy_utils::{contains_return, is_trait_item, last_path_segment, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::source_map::Span; use rustc_span::symbol::{kw, sym}; use std::borrow::Cow; use super::OR_FUN_CALL; /// Checks for the `OR_FUN_CALL` lint. #[allow(clippy::too_many_lines)] pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, method_span: Span, name: &str, args: &'tcx [hir::Expr<'_>], ) { /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`. fn check_unwrap_or_default( cx: &LateContext<'_>, name: &str, fun: &hir::Expr<'_>, self_expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, or_has_args: bool, span: Span, ) -> bool { let is_default_default = || is_trait_item(cx, fun, sym::Default); let implements_default = |arg, default_trait_id| { let arg_ty = cx.typeck_results().expr_ty(arg); implements_trait(cx, arg_ty, default_trait_id, &[]) }; if_chain! { if !or_has_args; if name == "unwrap_or"; if let hir::ExprKind::Path(ref qpath) = fun.kind; if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default); let path = last_path_segment(qpath).ident.name; // needs to target Default::default in particular or be *::new and have a Default impl // available if (matches!(path, kw::Default) && is_default_default()) || (matches!(path, sym::new) && implements_default(arg, default_trait_id)); then { let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, OR_FUN_CALL, span, &format!("use of `{}` followed by a call to `{}`", name, path), "try this", format!( "{}.unwrap_or_default()", snippet_with_applicability(cx, self_expr.span, "..", &mut applicability) ), applicability, ); true } else { false } } } /// Checks for `*or(foo())`. #[allow(clippy::too_many_arguments)] fn check_general_case<'tcx>( cx: &LateContext<'tcx>, name: &str, method_span: Span, self_expr: &hir::Expr<'_>, arg: &'tcx hir::Expr<'_>, span: Span, // None if lambda is required fun_span: Option<Span>, ) { // (path, fn_has_argument, methods, suffix) static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [ (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"), (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"), (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"), (&paths::RESULT, true, &["or", "unwrap_or"], "else"), ]; if_chain! { if KNOW_TYPES.iter().any(|k| k.2.contains(&name)); if switch_to_lazy_eval(cx, arg); if !contains_return(arg); let self_ty = cx.typeck_results().expr_ty(self_expr); if let Some(&(_, fn_has_arguments, poss, suffix)) = KNOW_TYPES.iter().find(|&&i| match_type(cx, self_ty, i.0)); if poss.contains(&name); then { let macro_expanded_snipped; let sugg: Cow<'_, str> = { let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) { (false, Some(fun_span)) => (fun_span, false), _ => (arg.span, true), }; let snippet = { let not_macro_argument_snippet = snippet_with_macro_callsite(cx, snippet_span, ".."); if not_macro_argument_snippet == "vec![]" { macro_expanded_snipped = snippet(cx, snippet_span, ".."); match macro_expanded_snipped.strip_prefix("$crate::vec::") { Some(stripped) => Cow::from(stripped), None => macro_expanded_snipped } } else { not_macro_argument_snippet } }; if use_lambda { let l_arg = if fn_has_arguments { "_" } else { "" }; format!("|{}| {}", l_arg, snippet).into() } else { snippet } }; let span_replace_word = method_span.with_hi(span.hi()); span_lint_and_sugg( cx, OR_FUN_CALL, span_replace_word, &format!("use of `{}` followed by a function call", name), "try this", format!("{}_{}({})", name, suffix, sugg), Applicability::HasPlaceholders, ); } } } if let [self_arg, arg] = args { let inner_arg = if let hir::ExprKind::Block( hir::Block { stmts: [], expr: Some(expr), .. }, _, ) = arg.kind { expr } else { arg }; match inner_arg.kind { hir::ExprKind::Call(fun, or_args) => { let or_has_args = !or_args.is_empty(); if !check_unwrap_or_default(cx, name, fun, self_arg, arg, or_has_args, expr.span) { let fun_span = if or_has_args { None } else { Some(fun.span) }; check_general_case(cx, name, method_span, self_arg, arg, expr.span, fun_span); } }, hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => { check_general_case(cx, name, method_span, self_arg, arg, expr.span, None); }, _ => (), } } }
use std::fs::File; use std::io; use std::io::prelude::*; use std::sync::mpsc::{Receiver, Sender}; mod gui; mod i2c; mod protocol; mod shared; use shared::{Event, SerialEvent}; pub fn launch(tx: Sender<Event>, rx: Receiver<SerialEvent>) { let mut file = File::create("/tmp/altctrl.serial").unwrap(); file.write_all(b"Hello, world!").unwrap(); let stdin = io::stdin(); for line in stdin.lock().lines() { // println!("Input received: {}", line.unwrap()); match line { Ok(command) => match command.as_ref() { "print" => { println!("Hullo!!!! :)"); } "yeet" => { println!("who is ligma?"); } _ => { println!("NANI THE FUCK???"); } }, _ => { println!("*** OH FUCK!!! ***"); } } } } fn main() { shared::start(launch); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Devices_I2c_Provider")] pub mod Provider; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct I2cBusSpeed(pub i32); impl I2cBusSpeed { pub const StandardMode: I2cBusSpeed = I2cBusSpeed(0i32); pub const FastMode: I2cBusSpeed = I2cBusSpeed(1i32); } impl ::core::convert::From<i32> for I2cBusSpeed { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for I2cBusSpeed { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for I2cBusSpeed { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.I2c.I2cBusSpeed;i4)"); } impl ::windows::core::DefaultType for I2cBusSpeed { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct I2cConnectionSettings(pub ::windows::core::IInspectable); impl I2cConnectionSettings { pub fn SlaveAddress(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetSlaveAddress(&self, value: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn BusSpeed(&self) -> ::windows::core::Result<I2cBusSpeed> { let this = self; unsafe { let mut result__: I2cBusSpeed = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<I2cBusSpeed>(result__) } } pub fn SetBusSpeed(&self, value: I2cBusSpeed) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } pub fn SharingMode(&self) -> ::windows::core::Result<I2cSharingMode> { let this = self; unsafe { let mut result__: I2cSharingMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<I2cSharingMode>(result__) } } pub fn SetSharingMode(&self, value: I2cSharingMode) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn Create(slaveaddress: i32) -> ::windows::core::Result<I2cConnectionSettings> { Self::II2cConnectionSettingsFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), slaveaddress, &mut result__).from_abi::<I2cConnectionSettings>(result__) }) } pub fn II2cConnectionSettingsFactory<R, F: FnOnce(&II2cConnectionSettingsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<I2cConnectionSettings, II2cConnectionSettingsFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for I2cConnectionSettings { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.I2c.I2cConnectionSettings;{f2db1307-ab6f-4639-a767-54536dc3460f})"); } unsafe impl ::windows::core::Interface for I2cConnectionSettings { type Vtable = II2cConnectionSettings_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf2db1307_ab6f_4639_a767_54536dc3460f); } impl ::windows::core::RuntimeName for I2cConnectionSettings { const NAME: &'static str = "Windows.Devices.I2c.I2cConnectionSettings"; } impl ::core::convert::From<I2cConnectionSettings> for ::windows::core::IUnknown { fn from(value: I2cConnectionSettings) -> Self { value.0 .0 } } impl ::core::convert::From<&I2cConnectionSettings> for ::windows::core::IUnknown { fn from(value: &I2cConnectionSettings) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for I2cConnectionSettings { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a I2cConnectionSettings { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<I2cConnectionSettings> for ::windows::core::IInspectable { fn from(value: I2cConnectionSettings) -> Self { value.0 } } impl ::core::convert::From<&I2cConnectionSettings> for ::windows::core::IInspectable { fn from(value: &I2cConnectionSettings) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for I2cConnectionSettings { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a I2cConnectionSettings { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for I2cConnectionSettings {} unsafe impl ::core::marker::Sync for I2cConnectionSettings {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct I2cController(pub ::windows::core::IInspectable); impl I2cController { pub fn GetDevice<'a, Param0: ::windows::core::IntoParam<'a, I2cConnectionSettings>>(&self, settings: Param0) -> ::windows::core::Result<I2cDevice> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), settings.into_param().abi(), &mut result__).from_abi::<I2cDevice>(result__) } } #[cfg(all(feature = "Devices_I2c_Provider", feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetControllersAsync<'a, Param0: ::windows::core::IntoParam<'a, Provider::II2cProvider>>(provider: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<I2cController>>> { Self::II2cControllerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), provider.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<I2cController>>>(result__) }) } #[cfg(feature = "Foundation")] pub fn GetDefaultAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<I2cController>> { Self::II2cControllerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<I2cController>>(result__) }) } pub fn II2cControllerStatics<R, F: FnOnce(&II2cControllerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<I2cController, II2cControllerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for I2cController { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.I2c.I2cController;{c48ab1b2-87a0-4166-8e3e-b4b8f97cd729})"); } unsafe impl ::windows::core::Interface for I2cController { type Vtable = II2cController_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc48ab1b2_87a0_4166_8e3e_b4b8f97cd729); } impl ::windows::core::RuntimeName for I2cController { const NAME: &'static str = "Windows.Devices.I2c.I2cController"; } impl ::core::convert::From<I2cController> for ::windows::core::IUnknown { fn from(value: I2cController) -> Self { value.0 .0 } } impl ::core::convert::From<&I2cController> for ::windows::core::IUnknown { fn from(value: &I2cController) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for I2cController { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a I2cController { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<I2cController> for ::windows::core::IInspectable { fn from(value: I2cController) -> Self { value.0 } } impl ::core::convert::From<&I2cController> for ::windows::core::IInspectable { fn from(value: &I2cController) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for I2cController { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a I2cController { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for I2cController {} unsafe impl ::core::marker::Sync for I2cController {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct I2cDevice(pub ::windows::core::IInspectable); impl I2cDevice { pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn ConnectionSettings(&self) -> ::windows::core::Result<I2cConnectionSettings> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<I2cConnectionSettings>(result__) } } pub fn Write(&self, buffer: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), buffer.len() as u32, ::core::mem::transmute(buffer.as_ptr())).ok() } } pub fn WritePartial(&self, buffer: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<I2cTransferResult> { let this = self; unsafe { let mut result__: I2cTransferResult = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), buffer.len() as u32, ::core::mem::transmute(buffer.as_ptr()), &mut result__).from_abi::<I2cTransferResult>(result__) } } pub fn Read(&self, buffer: &mut [<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), buffer.len() as u32, ::core::mem::transmute_copy(&buffer)).ok() } } pub fn ReadPartial(&self, buffer: &mut [<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<I2cTransferResult> { let this = self; unsafe { let mut result__: I2cTransferResult = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), buffer.len() as u32, ::core::mem::transmute_copy(&buffer), &mut result__).from_abi::<I2cTransferResult>(result__) } } pub fn WriteRead(&self, writebuffer: &[<u8 as ::windows::core::DefaultType>::DefaultType], readbuffer: &mut [<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), writebuffer.len() as u32, ::core::mem::transmute(writebuffer.as_ptr()), readbuffer.len() as u32, ::core::mem::transmute_copy(&readbuffer)).ok() } } pub fn WriteReadPartial(&self, writebuffer: &[<u8 as ::windows::core::DefaultType>::DefaultType], readbuffer: &mut [<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<I2cTransferResult> { let this = self; unsafe { let mut result__: I2cTransferResult = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), writebuffer.len() as u32, ::core::mem::transmute(writebuffer.as_ptr()), readbuffer.len() as u32, ::core::mem::transmute_copy(&readbuffer), &mut result__).from_abi::<I2cTransferResult>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } pub fn GetDeviceSelector() -> ::windows::core::Result<::windows::core::HSTRING> { Self::II2cDeviceStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn GetDeviceSelectorFromFriendlyName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(friendlyname: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::II2cDeviceStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), friendlyname.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } #[cfg(feature = "Foundation")] pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, I2cConnectionSettings>>(deviceid: Param0, settings: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<I2cDevice>> { Self::II2cDeviceStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), settings.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<I2cDevice>>(result__) }) } pub fn II2cDeviceStatics<R, F: FnOnce(&II2cDeviceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<I2cDevice, II2cDeviceStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for I2cDevice { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.I2c.I2cDevice;{8636c136-b9c5-4f70-9449-cc46dc6f57eb})"); } unsafe impl ::windows::core::Interface for I2cDevice { type Vtable = II2cDevice_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8636c136_b9c5_4f70_9449_cc46dc6f57eb); } impl ::windows::core::RuntimeName for I2cDevice { const NAME: &'static str = "Windows.Devices.I2c.I2cDevice"; } impl ::core::convert::From<I2cDevice> for ::windows::core::IUnknown { fn from(value: I2cDevice) -> Self { value.0 .0 } } impl ::core::convert::From<&I2cDevice> for ::windows::core::IUnknown { fn from(value: &I2cDevice) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for I2cDevice { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a I2cDevice { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<I2cDevice> for ::windows::core::IInspectable { fn from(value: I2cDevice) -> Self { value.0 } } impl ::core::convert::From<&I2cDevice> for ::windows::core::IInspectable { fn from(value: &I2cDevice) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for I2cDevice { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a I2cDevice { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<I2cDevice> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: I2cDevice) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&I2cDevice> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &I2cDevice) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for I2cDevice { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &I2cDevice { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for I2cDevice {} unsafe impl ::core::marker::Sync for I2cDevice {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct I2cSharingMode(pub i32); impl I2cSharingMode { pub const Exclusive: I2cSharingMode = I2cSharingMode(0i32); pub const Shared: I2cSharingMode = I2cSharingMode(1i32); } impl ::core::convert::From<i32> for I2cSharingMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for I2cSharingMode { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for I2cSharingMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.I2c.I2cSharingMode;i4)"); } impl ::windows::core::DefaultType for I2cSharingMode { type DefaultType = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct I2cTransferResult { pub Status: I2cTransferStatus, pub BytesTransferred: u32, } impl I2cTransferResult {} impl ::core::default::Default for I2cTransferResult { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for I2cTransferResult { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("I2cTransferResult").field("Status", &self.Status).field("BytesTransferred", &self.BytesTransferred).finish() } } impl ::core::cmp::PartialEq for I2cTransferResult { fn eq(&self, other: &Self) -> bool { self.Status == other.Status && self.BytesTransferred == other.BytesTransferred } } impl ::core::cmp::Eq for I2cTransferResult {} unsafe impl ::windows::core::Abi for I2cTransferResult { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for I2cTransferResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Devices.I2c.I2cTransferResult;enum(Windows.Devices.I2c.I2cTransferStatus;i4);u4)"); } impl ::windows::core::DefaultType for I2cTransferResult { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct I2cTransferStatus(pub i32); impl I2cTransferStatus { pub const FullTransfer: I2cTransferStatus = I2cTransferStatus(0i32); pub const PartialTransfer: I2cTransferStatus = I2cTransferStatus(1i32); pub const SlaveAddressNotAcknowledged: I2cTransferStatus = I2cTransferStatus(2i32); pub const ClockStretchTimeout: I2cTransferStatus = I2cTransferStatus(3i32); pub const UnknownError: I2cTransferStatus = I2cTransferStatus(4i32); } impl ::core::convert::From<i32> for I2cTransferStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for I2cTransferStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for I2cTransferStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.I2c.I2cTransferStatus;i4)"); } impl ::windows::core::DefaultType for I2cTransferStatus { type DefaultType = Self; } #[repr(transparent)] #[doc(hidden)] pub struct II2cConnectionSettings(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for II2cConnectionSettings { type Vtable = II2cConnectionSettings_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf2db1307_ab6f_4639_a767_54536dc3460f); } #[repr(C)] #[doc(hidden)] pub struct II2cConnectionSettings_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut I2cBusSpeed) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: I2cBusSpeed) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut I2cSharingMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: I2cSharingMode) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct II2cConnectionSettingsFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for II2cConnectionSettingsFactory { type Vtable = II2cConnectionSettingsFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x81b586b3_9693_41b1_a243_ded4f6e66926); } #[repr(C)] #[doc(hidden)] pub struct II2cConnectionSettingsFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, slaveaddress: i32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct II2cController(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for II2cController { type Vtable = II2cController_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc48ab1b2_87a0_4166_8e3e_b4b8f97cd729); } #[repr(C)] #[doc(hidden)] pub struct II2cController_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, settings: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct II2cControllerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for II2cControllerStatics { type Vtable = II2cControllerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x40fc0365_5f05_4e7e_84bd_100db8e0aec5); } #[repr(C)] #[doc(hidden)] pub struct II2cControllerStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Devices_I2c_Provider", feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, provider: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_I2c_Provider", feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct II2cDevice(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for II2cDevice { type Vtable = II2cDevice_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8636c136_b9c5_4f70_9449_cc46dc6f57eb); } #[repr(C)] #[doc(hidden)] pub struct II2cDevice_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer_array_size: u32, buffer: *const u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer_array_size: u32, buffer: *const u8, result__: *mut I2cTransferResult) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer_array_size: u32, buffer: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer_array_size: u32, buffer: *mut u8, result__: *mut I2cTransferResult) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, writeBuffer_array_size: u32, writebuffer: *const u8, readBuffer_array_size: u32, readbuffer: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, writeBuffer_array_size: u32, writebuffer: *const u8, readBuffer_array_size: u32, readbuffer: *mut u8, result__: *mut I2cTransferResult) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct II2cDeviceStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for II2cDeviceStatics { type Vtable = II2cDeviceStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x91a33be3_7334_4512_96bc_fbae9459f5f6); } impl II2cDeviceStatics { pub fn GetDeviceSelector(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn GetDeviceSelectorFromFriendlyName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, friendlyname: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), friendlyname.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, I2cConnectionSettings>>(&self, deviceid: Param0, settings: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<I2cDevice>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), settings.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<I2cDevice>>(result__) } } } unsafe impl ::windows::core::RuntimeType for II2cDeviceStatics { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{91a33be3-7334-4512-96bc-fbae9459f5f6}"); } impl ::core::convert::From<II2cDeviceStatics> for ::windows::core::IUnknown { fn from(value: II2cDeviceStatics) -> Self { value.0 .0 } } impl ::core::convert::From<&II2cDeviceStatics> for ::windows::core::IUnknown { fn from(value: &II2cDeviceStatics) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for II2cDeviceStatics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a II2cDeviceStatics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<II2cDeviceStatics> for ::windows::core::IInspectable { fn from(value: II2cDeviceStatics) -> Self { value.0 } } impl ::core::convert::From<&II2cDeviceStatics> for ::windows::core::IInspectable { fn from(value: &II2cDeviceStatics) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for II2cDeviceStatics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a II2cDeviceStatics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct II2cDeviceStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, friendlyname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, settings: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, );
extern crate jlib; use jlib::api::set_relation::data::{RelationType, RelationTxResponse, RelationSideKick}; use jlib::api::set_relation::api::Relation; use jlib::api::message::amount::Amount; use jlib::api::config::Config; pub static TEST_SERVER: &'static str = "ws://101.200.176.249:5040"; //dev12 国密服务器 fn main() { let config = Config::new(TEST_SERVER, true); let from: String = "j9syYwWgtmjchcbqhVB18pmFqXUYahZvvg".to_string(); let secret:String= "shstwqJpVJbsqFA5uYJJw1YniXcDF".to_string(); let relation_type = RelationType::AUTHORIZE; let to : String = "jP7G6Ue5AcQ5GZ71LkMxXvf5Reg44EKrjy".to_string(); let amount: Amount = Amount::new(Some( "CCA".to_string() ), "0.01".to_string(), Some( "j9syYwWgtmjchcbqhVB18pmFqXUYahZvvg".to_string()) ); Relation::with_params(config, from, secret) .set_relation(relation_type, to, amount, |x| match x { Ok(response) => { let res: RelationTxResponse = response; println!("relations: {:?}", &res); }, Err(e) => { let err: RelationSideKick = e; println!("err: {:?}", err); } }); }
//! Tests auto-converted from "sass-spec/spec/parser/interpolate/04_space_list_quoted" #[allow(unused)] use super::rsass; #[allow(unused)] use rsass::precision; /// From "sass-spec/spec/parser/interpolate/04_space_list_quoted/01_inline" #[test] fn t01_inline() { assert_eq!( rsass( ".result {\n output: \"alpha\" \'beta\';\n output: #{\"alpha\" \'beta\'};\n output: \"[#{\"alpha\" \'beta\'}]\";\n output: \"#{\"alpha\" \'beta\'}\";\n output: \'#{\"alpha\" \'beta\'}\';\n output: \"[\'#{\"alpha\" \'beta\'}\']\";\n}\n" ) .unwrap(), ".result {\n output: \"alpha\" \'beta\';\n output: alpha beta;\n output: \"[alpha beta]\";\n output: \"alpha beta\";\n output: \"alpha beta\";\n output: \"[\'alpha beta\']\";\n}\n" ); } /// From "sass-spec/spec/parser/interpolate/04_space_list_quoted/02_variable" #[test] fn t02_variable() { assert_eq!( rsass( "$input: \"alpha\" \'beta\';\n.result {\n output: $input;\n output: #{$input};\n output: \"[#{$input}]\";\n output: \"#{$input}\";\n output: \'#{$input}\';\n output: \"[\'#{$input}\']\";\n}\n" ) .unwrap(), ".result {\n output: \"alpha\" \"beta\";\n output: alpha beta;\n output: \"[alpha beta]\";\n output: \"alpha beta\";\n output: \"alpha beta\";\n output: \"[\'alpha beta\']\";\n}\n" ); } /// From "sass-spec/spec/parser/interpolate/04_space_list_quoted/03_inline_double" #[test] fn t03_inline_double() { assert_eq!( rsass( ".result {\n output: #{#{\"alpha\" \'beta\'}};\n output: #{\"[#{\"alpha\" \'beta\'}]\"};\n output: #{\"#{\"alpha\" \'beta\'}\"};\n output: #{\'#{\"alpha\" \'beta\'}\'};\n output: #{\"[\'#{\"alpha\" \'beta\'}\']\"};\n}\n" ) .unwrap(), ".result {\n output: alpha beta;\n output: [alpha beta];\n output: alpha beta;\n output: alpha beta;\n output: [\'alpha beta\'];\n}\n" ); } /// From "sass-spec/spec/parser/interpolate/04_space_list_quoted/04_variable_double" #[test] fn t04_variable_double() { assert_eq!( rsass( "$input: \"alpha\" \'beta\';\n.result {\n output: #{#{$input}};\n output: #{\"[#{$input}]\"};\n output: #{\"#{$input}\"};\n output: #{\'#{$input}\'};\n output: #{\"[\'#{$input}\']\"};\n}\n" ) .unwrap(), ".result {\n output: alpha beta;\n output: [alpha beta];\n output: alpha beta;\n output: alpha beta;\n output: [\'alpha beta\'];\n}\n" ); } /// From "sass-spec/spec/parser/interpolate/04_space_list_quoted/05_variable_quoted_double" #[test] fn t05_variable_quoted_double() { assert_eq!( rsass( "$input: \"alpha\" \'beta\';\n.result {\n dquoted: \"#{#{$input}}\";\n dquoted: \"#{\"[#{$input}]\"}\";\n dquoted: \"#{\"#{$input}\"}\";\n dquoted: \"#{\'#{$input}\'}\";\n dquoted: \"#{\"[\'#{$input}\']\"}\";\n squoted: \'#{#{$input}}\';\n squoted: \'#{\"[#{$input}]\"}\';\n squoted: \'#{\"#{$input}\"}\';\n squoted: \'#{\'#{$input}\'}\';\n squoted: \'#{\"[\'#{$input}\']\"}\';\n}\n" ) .unwrap(), ".result {\n dquoted: \"alpha beta\";\n dquoted: \"[alpha beta]\";\n dquoted: \"alpha beta\";\n dquoted: \"alpha beta\";\n dquoted: \"[\'alpha beta\']\";\n squoted: \"alpha beta\";\n squoted: \"[alpha beta]\";\n squoted: \"alpha beta\";\n squoted: \"alpha beta\";\n squoted: \"[\'alpha beta\']\";\n}\n" ); } /// From "sass-spec/spec/parser/interpolate/04_space_list_quoted/06_escape_interpolation" #[test] fn t06_escape_interpolation() { assert_eq!( rsass( "$input: \"alpha\" \'beta\';\n.result {\n output: \"[\\#{\"alpha\" \'beta\'}]\";\n output: \"\\#{\"alpha\" \'beta\'}\";\n output: \'\\#{\"alpha\" \'beta\'}\';\n output: \"[\'\\#{\"alpha\" \'beta\'}\']\";\n}\n" ) .unwrap(), ".result {\n output: \"[#{\" alpha \" \'beta\'}]\";\n output: \"#{\" alpha \" \'beta\'}\";\n output: \'#{\"alpha\" \' beta \"}\";\n output: \"[\'#{\" alpha \" \'beta\'}\']\";\n}\n" ); }
extern crate limonite; extern crate clap; use clap::App; use limonite::site::Site; use limonite::VERSION; use std::path::Path; fn main() { let matches = App::new("limonite") .author("Douglas Campos <qmx@qmx.me>") .version(VERSION) .about("blazing fast static site and blog generator") .args_from_usage( "[verbose] -v --verbose 'increase verboseness' <SOURCE_PATH> 'path to folder containing the site structure' <TARGET_PATH> 'path to where limonite should write the generated files'") .get_matches(); let src_path = Path::new(matches.value_of("SOURCE_PATH").unwrap()); let dst_path = Path::new(matches.value_of("TARGET_PATH").unwrap()); let site = Site::new(&src_path); site.generate(&dst_path); }
#[allow(non_upper_case_globals)] #[allow(non_camel_case_types)] #[allow(non_snake_case)] #[allow(unused)] #[allow(clippy::all)] #[cfg(feature = "callback")] pub mod callback { include!(concat!(env!("OUT_DIR"), "/callback.rs")); } #[allow(non_upper_case_globals)] #[allow(non_camel_case_types)] #[allow(non_snake_case)] #[allow(unused)] #[allow(clippy::all)] #[cfg(feature = "sync")] pub mod sync { include!(concat!(env!("OUT_DIR"), "/sync.rs")); } #[allow(non_upper_case_globals)] #[allow(non_camel_case_types)] #[allow(non_snake_case)] #[allow(unused)] #[allow(clippy::all)] pub mod dns { include!(concat!(env!("OUT_DIR"), "/dns.rs")); } #[cfg(test)] #[cfg(feature = "sync")] mod sync_test { #[test] fn smoke() { unsafe { let ctx = super::sync::pubnub_alloc(); super::sync::pubnub_free(ctx); } } } #[cfg(test)] #[cfg(feature = "callback")] mod callback_test { #[test] fn smoke() { unsafe { let ctx = super::callback::pubnub_alloc(); super::callback::pubnub_free(ctx); } } }
#![allow(non_camel_case_types)] #![allow(dead_code)] use std::cmp::Ordering; mod ffi { use std::cmp::Ordering; use std::hash::{Hash, Hasher}; #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] #[repr(C)] pub enum Maybe<T> { Just(T), Nothing, } use self::Maybe::*; impl<T: Clone> Clone for Maybe<T> { #[inline] fn clone(&self) -> Self { match self { Just(x) => Just(x.clone()), Nothing => Nothing, } } #[inline] fn clone_from(&mut self, source: &Self) { match (self, source) { (Just(to), Just(from)) => to.clone_from(from), (to, from) => *to = from.clone(), } } } #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] #[repr(C)] pub struct Pair<U, V>(pub U, pub V); #[derive(Debug)] #[repr(C)] pub struct SliceMut<'a, T> { pub data: *mut T, pub len: usize, pub alloc: usize, // *const bumpalo::Bump pub marker: std::marker::PhantomData<&'a ()>, } impl<'a, T> SliceMut<'a, T> { pub fn new(alloc: &'a bumpalo::Bump, t: &'a mut [T]) -> Self { SliceMut { data: t.as_mut_ptr(), len: t.len(), alloc: alloc as *const bumpalo::Bump as usize, marker: std::marker::PhantomData, } } } impl<'a, T> AsRef<[T]> for SliceMut<'a, T> { fn as_ref<'r>(&'r self) -> &'r [T] { unsafe { std::slice::from_raw_parts(self.data, self.len) } } } impl<'a, T> AsMut<[T]> for SliceMut<'a, T> { fn as_mut<'r>(&'r mut self) -> &'r mut [T] { unsafe { std::slice::from_raw_parts_mut(self.data, self.len) } } } impl<'a, T: 'a + Clone> Clone for SliceMut<'a, T> { fn clone(&self) -> Self { let alloc: &'a bumpalo::Bump = unsafe { (self.alloc as *const bumpalo::Bump).as_ref().unwrap() }; SliceMut::new(alloc, alloc.alloc_slice_clone(self.as_ref())) } } #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Slice<'arena, T> { pub data: *const T, pub len: usize, pub marker: std::marker::PhantomData<&'arena ()>, } impl<'a, T: 'a> Slice<'a, T> { fn new(t: &'a [T]) -> Slice<'a, T> { Slice { data: t.as_ptr(), len: t.len(), marker: std::marker::PhantomData, } } } impl<'a, T> AsRef<[T]> for Slice<'a, T> { fn as_ref(&self) -> &[T] { unsafe { std::slice::from_raw_parts(self.data, self.len) } } } impl<'arena, T: PartialEq> PartialEq for Slice<'arena, T> { fn eq(&self, other: &Self) -> bool { unsafe { let left = std::slice::from_raw_parts(self.data, self.len); let right = std::slice::from_raw_parts(other.data, other.len); left.eq(right) } } } impl<'arena, T: Eq> Eq for Slice<'arena, T> {} impl<'arena, T: Hash> Hash for Slice<'arena, T> { fn hash<H: Hasher>(&self, state: &mut H) { unsafe { let me = std::slice::from_raw_parts(self.data, self.len); me.hash(state); } } } impl<'arena, T: Ord> Ord for Slice<'arena, T> { fn cmp(&self, other: &Self) -> Ordering { unsafe { let left = std::slice::from_raw_parts(self.data, self.len); let right = std::slice::from_raw_parts(other.data, other.len); left.cmp(right) } } } impl<'arena, T: PartialOrd> PartialOrd for Slice<'arena, T> { fn partial_cmp(&self, other: &Self) -> std::option::Option<Ordering> { unsafe { let left = std::slice::from_raw_parts(self.data, self.len); let right = std::slice::from_raw_parts(other.data, other.len); left.partial_cmp(right) } } } pub type Str<'arena> = Slice<'arena, u8>; // C++: // std::string slice_to_string(Str s) { // std::string {s.data, s.data + s.len} // } } use ffi::{Maybe, Pair, Slice, SliceMut, Str}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum CheckStarted { IgnoreStarted, CheckStarted, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum FreeIterator { IgnoreIter, FreeIter, } pub type RepoAuthType<'arena> = Str<'arena>; #[derive(Clone, Debug)] #[repr(C)] pub enum ParamId<'arena> { ParamUnnamed(isize), ParamNamed(Str<'arena>), } pub type ParamNum = isize; pub type StackIndex = isize; pub type RecordNum = isize; pub type TypedefNum = isize; pub type ClassNum = isize; pub type ConstNum = isize; mod hhbc_by_ref_id { pub mod class { use super::super::Str; //hhbc_id::class::Type<'arena> #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Type<'arena>(pub Str<'arena>); } pub mod function { use super::super::Str; //hhbc_id::function::Type<'arena> #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Type<'arena>(pub Str<'arena>); } pub mod method { use super::super::Str; //hhbc_id::method::Type<'arena> #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Type<'arena>(pub Str<'arena>); } pub mod prop { use super::super::Str; //hhbc_id::prop::Type<'arena> #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Type<'arena>(pub Str<'arena>); } pub mod r#const { use super::super::Str; //hhbc_id::r#const::Type<'arena> #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Type<'arena>(pub Str<'arena>); } pub mod record { use super::super::Str; //hhbc_id::record::Type<'arena> #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Type<'arena>(pub Str<'arena>); } } pub type ClassId<'arena> = hhbc_by_ref_id::class::Type<'arena>; pub type FunctionId<'arena> = hhbc_by_ref_id::function::Type<'arena>; pub type MethodId<'arena> = hhbc_by_ref_id::method::Type<'arena>; pub type ConstId<'arena> = hhbc_by_ref_id::method::Type<'arena>; pub type PropId<'arena> = hhbc_by_ref_id::prop::Type<'arena>; pub type NumParams = usize; pub type ByRefs<'arena> = Slice<'arena, bool>; bitflags::bitflags! { #[repr(C)] pub struct FcallFlags: u8 { const HAS_UNPACK = 0b0001; const HAS_GENERICS = 0b0010; const LOCK_WHILE_UNWINDING = 0b0100; } } mod hhbc_by_ref_label { pub type Id = usize; #[derive(Debug, Clone, Copy, PartialEq, Eq, std::cmp::Ord, std::cmp::PartialOrd)] #[repr(C)] pub enum Label { Regular(Id), DefaultArg(Id), } } #[derive(Clone, Debug)] #[repr(C)] pub struct FcallArgs<'arena>( pub FcallFlags, pub NumParams, pub NumParams, pub ByRefs<'arena>, pub Maybe<hhbc_by_ref_label::Label>, pub Maybe<Str<'arena>>, ); mod iterator { #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Id(pub usize); } mod local { pub type Id = usize; use super::Str; #[derive(Copy, Clone, Debug)] #[repr(C)] pub enum Type<'arena> { Unnamed(Id), Named(Str<'arena>), } } #[derive(Clone, Debug)] #[repr(C)] pub struct IterArgs<'arena> { pub iter_id: iterator::Id, pub key_id: Maybe<local::Type<'arena>>, pub val_id: local::Type<'arena>, } pub type ClassrefId = isize; /// Conventionally this is "A_" followed by an integer pub type AdataId<'arena> = Str<'arena>; //&'arena str; pub type ParamLocations<'arena> = Slice<'arena, isize>; //&'arena [isize]; #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum SpecialClsRef { Static, Self_, Parent, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum MemberOpMode { ModeNone, Warn, Define, Unset, InOut, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum QueryOp { CGet, CGetQuiet, Isset, InOut, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum CollectionType { Vector, Map, Set, Pair, ImmVector, ImmMap, ImmSet, Dict, Array, Keyset, Vec, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum FatalOp { Parse, Runtime, RuntimeOmitFrame, } #[derive(Clone, Copy, Debug)] #[repr(C)] pub enum MemberKey<'arena> { EC(StackIndex, ReadOnlyOp), EL(local::Type<'arena>, ReadOnlyOp), ET(Str<'arena>, ReadOnlyOp), EI(i64, ReadOnlyOp), PC(StackIndex, ReadOnlyOp), PL(local::Type<'arena>, ReadOnlyOp), PT(PropId<'arena>, ReadOnlyOp), QT(PropId<'arena>, ReadOnlyOp), W, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum InstructBasic { Nop, EntryNop, PopC, PopU, Dup, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum TypestructResolveOp { Resolve, DontResolve, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum ReadOnlyOp { ReadOnly, Mutable, Any, CheckROCOW, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum HasGenericsOp { NoGenerics, MaybeGenerics, HasGenerics, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum IsLogAsDynamicCallOp { LogAsDynamicCall, DontLogAsDynamicCall, } mod hhbc_by_ref_runtime { mod float { #[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] #[repr(C)] pub struct F64([u8; 8]); } use super::Pair; use super::Slice; use super::Str; #[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] #[repr(C)] pub enum TypedValue<'arena> { /// Used for fields that are initialized in the 86pinit method Uninit, /// Hack/PHP integers are 64-bit Int(i64), Bool(bool), /// Both Hack/PHP and Caml floats are IEEE754 64-bit Float(float::F64), String(Str<'arena>), LazyClass(Str<'arena>), Null, // Classic PHP arrays with explicit (key,value) entries HhasAdata(Str<'arena>), // Hack arrays: vectors, keysets, and dictionaries Vec(Slice<'arena, TypedValue<'arena>>), Keyset(Slice<'arena, TypedValue<'arena>>), Dict(Slice<'arena, Pair<TypedValue<'arena>, TypedValue<'arena>>>), } } #[derive(Debug)] #[repr(C)] pub enum InstrSeq<'a> { List(SliceMut<'a, Instruct<'a>>), Concat(SliceMut<'a, InstrSeq<'a>>), } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructLitConst<'arena> { Null, True, False, NullUninit, Int(i64), Double(Str<'arena>), String(Str<'arena>), LazyClass(ClassId<'arena>), /// Pseudo instruction that will get translated into appropraite /// literal bytecode, with possible reference to .adata *) TypedValue(hhbc_by_ref_runtime::TypedValue<'arena>), Vec(AdataId<'arena>), Dict(AdataId<'arena>), Keyset(AdataId<'arena>), /// capacity hint NewDictArray(isize), NewStructDict(Slice<'arena, Str<'arena>>), NewVec(isize), NewKeysetArray(isize), NewPair, NewRecord(ClassId<'arena>, Slice<'arena, Str<'arena>>), AddElemC, AddNewElemC, NewCol(CollectionType), ColFromArray(CollectionType), CnsE(ConstId<'arena>), ClsCns(ConstId<'arena>), ClsCnsD(ConstId<'arena>, ClassId<'arena>), ClsCnsL(local::Type<'arena>), File, Dir, Method, FuncCred, } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructOperator<'arena> { Concat, ConcatN(isize), Add, Sub, Mul, AddO, SubO, MulO, Div, Mod, Pow, Not, Same, NSame, Eq, Neq, Lt, Lte, Gt, Gte, Cmp, BitAnd, BitOr, BitXor, BitNot, Shl, Shr, CastBool, CastInt, CastDouble, CastString, CastVec, CastDict, CastKeyset, InstanceOf, InstanceOfD(ClassId<'arena>), IsLateBoundCls, IsTypeStructC(TypestructResolveOp), ThrowAsTypeStructException, CombineAndResolveTypeStruct(isize), Print, Clone, Exit, Fatal(FatalOp), ResolveFunc(FunctionId<'arena>), ResolveRFunc(FunctionId<'arena>), ResolveMethCaller(FunctionId<'arena>), ResolveObjMethod, ResolveClsMethod(MethodId<'arena>), ResolveClsMethodD(ClassId<'arena>, MethodId<'arena>), ResolveClsMethodS(SpecialClsRef, MethodId<'arena>), ResolveRClsMethod(MethodId<'arena>), ResolveRClsMethodD(ClassId<'arena>, MethodId<'arena>), ResolveRClsMethodS(SpecialClsRef, MethodId<'arena>), ResolveClass(ClassId<'arena>), } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum Switchkind { Bounded, Unbounded, } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructControlFlow<'arena> { Jmp(hhbc_by_ref_label::Label), JmpNS(hhbc_by_ref_label::Label), JmpZ(hhbc_by_ref_label::Label), JmpNZ(hhbc_by_ref_label::Label), /// bounded, base, offset vector Switch( Switchkind, isize, SliceMut<'arena, hhbc_by_ref_label::Label>, //bumpalo::collections::Vec<'arena, hhbc_by_ref_label::Label>, ), /// litstr id / offset vector SSwitch(SliceMut<'arena, Pair<Str<'arena>, hhbc_by_ref_label::Label>>), //bumpalo::collections::Vec<'arena, (&'arena str, hhbc_by_ref_label::Label)>), RetC, RetCSuspended, RetM(NumParams), Throw, } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructSpecialFlow<'arena> { Continue(isize), Break(isize), Goto(Str<'arena>), } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructGet<'arena> { CGetL(local::Type<'arena>), CGetQuietL(local::Type<'arena>), CGetL2(local::Type<'arena>), CUGetL(local::Type<'arena>), PushL(local::Type<'arena>), CGetG, CGetS(ReadOnlyOp), ClassGetC, ClassGetTS, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum IstypeOp { OpNull, OpBool, OpInt, OpDbl, OpStr, OpObj, OpRes, OpScalar, /// Int or Dbl or Str or Bool OpKeyset, OpDict, OpVec, OpArrLike, /// Arr or Vec or Dict or Keyset *) OpClsMeth, OpFunc, OpLegacyArrLike, OpClass, } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructIsset<'arena> { IssetC, IssetL(local::Type<'arena>), IssetG, IssetS, IsUnsetL(local::Type<'arena>), IsTypeC(IstypeOp), IsTypeL(local::Type<'arena>, IstypeOp), } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum SetrangeOp { Forward, Reverse, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum EqOp { PlusEqual, MinusEqual, MulEqual, ConcatEqual, DivEqual, PowEqual, ModEqual, AndEqual, OrEqual, XorEqual, SlEqual, SrEqual, PlusEqualO, MinusEqualO, MulEqualO, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum IncdecOp { PreInc, PostInc, PreDec, PostDec, PreIncO, PostIncO, PreDecO, PostDecO, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum InitpropOp { Static, NonStatic, } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructMutator<'arena> { SetL(local::Type<'arena>), /// PopL is put in mutators since it behaves as SetL + PopC PopL(local::Type<'arena>), SetG, SetS(ReadOnlyOp), SetOpL(local::Type<'arena>, EqOp), SetOpG(EqOp), SetOpS(EqOp), IncDecL(local::Type<'arena>, IncdecOp), IncDecG(IncdecOp), IncDecS(IncdecOp), UnsetL(local::Type<'arena>), UnsetG, CheckProp(PropId<'arena>), InitProp(PropId<'arena>, InitpropOp), } #[derive(Clone, Debug, Eq, PartialEq)] #[repr(C)] pub enum ObjNullFlavor { NullThrows, NullSafe, } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructCall<'arena> { NewObj, NewObjR, NewObjD(ClassId<'arena>), NewObjRD(ClassId<'arena>), NewObjS(SpecialClsRef), FCall(FcallArgs<'arena>), FCallClsMethod(FcallArgs<'arena>, IsLogAsDynamicCallOp), FCallClsMethodD(FcallArgs<'arena>, ClassId<'arena>, MethodId<'arena>), FCallClsMethodS(FcallArgs<'arena>, SpecialClsRef), FCallClsMethodSD(FcallArgs<'arena>, SpecialClsRef, MethodId<'arena>), FCallCtor(FcallArgs<'arena>), FCallFunc(FcallArgs<'arena>), FCallFuncD(FcallArgs<'arena>, FunctionId<'arena>), FCallObjMethod(FcallArgs<'arena>, ObjNullFlavor), FCallObjMethodD(FcallArgs<'arena>, ObjNullFlavor, MethodId<'arena>), } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructBase<'arena> { BaseGC(StackIndex, MemberOpMode), BaseGL(local::Type<'arena>, MemberOpMode), BaseSC(StackIndex, StackIndex, MemberOpMode, ReadOnlyOp), BaseL(local::Type<'arena>, MemberOpMode), BaseC(StackIndex, MemberOpMode), BaseH, Dim(MemberOpMode, MemberKey<'arena>), } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructFinal<'arena> { QueryM(NumParams, QueryOp, MemberKey<'arena>), SetM(NumParams, MemberKey<'arena>), IncDecM(NumParams, IncdecOp, MemberKey<'arena>), SetOpM(NumParams, EqOp, MemberKey<'arena>), UnsetM(NumParams, MemberKey<'arena>), SetRangeM(NumParams, isize, SetrangeOp), } mod hhbc_by_ref_iterator { #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] pub struct Id(pub usize); } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructIterator<'arena> { IterInit(IterArgs<'arena>, hhbc_by_ref_label::Label), IterNext(IterArgs<'arena>, hhbc_by_ref_label::Label), IterFree(hhbc_by_ref_iterator::Id), } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructIncludeEvalDefine { Incl, InclOnce, Req, ReqOnce, ReqDoc, Eval, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum BareThisOp { Notice, NoNotice, NeverNull, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum ClassKind { Class, Interface, Trait, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum OpSilence { Start, End, } #[derive(Clone, Debug)] #[repr(C)] pub enum InstructMisc<'arena> { This, BareThis(BareThisOp), CheckThis, FuncNumArgs, ChainFaults, OODeclExists(ClassKind), VerifyParamType(ParamId<'arena>), VerifyParamTypeTS(ParamId<'arena>), VerifyOutType(ParamId<'arena>), VerifyRetTypeC, VerifyRetTypeTS, Self_, Parent, LateBoundCls, ClassName, LazyClassFromClass, RecordReifiedGeneric, CheckReifiedGenericMismatch, NativeImpl, AKExists, CreateCl(NumParams, ClassNum), Idx, ArrayIdx, ArrayMarkLegacy, ArrayUnmarkLegacy, AssertRATL(local::Type<'arena>, RepoAuthType<'arena>), AssertRATStk(StackIndex, RepoAuthType<'arena>), BreakTraceHint, Silence(local::Type<'arena>, OpSilence), GetMemoKeyL(local::Type<'arena>), CGetCUNop, UGetCUNop, MemoGet( hhbc_by_ref_label::Label, Maybe<Pair<local::Type<'arena>, isize>>, ), MemoGetEager( hhbc_by_ref_label::Label, hhbc_by_ref_label::Label, Maybe<Pair<local::Type<'arena>, isize>>, ), MemoSet(Maybe<Pair<local::Type<'arena>, isize>>), MemoSetEager(Maybe<Pair<local::Type<'arena>, isize>>), LockObj, ThrowNonExhaustiveSwitch, RaiseClassStringConversionWarning, } #[derive(Clone, Debug)] #[repr(C)] pub enum GenCreationExecution { CreateCont, ContEnter, ContRaise, Yield, YieldK, ContCheck(CheckStarted), ContValid, ContKey, ContGetReturn, ContCurrent, } #[derive(Clone, Debug)] #[repr(C)] pub enum AsyncFunctions<'arena> { WHResult, Await, AwaitAll(Maybe<Pair<local::Type<'arena>, isize>>), } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum InstructTry { TryCatchBegin, TryCatchMiddle, TryCatchEnd, } #[derive(Clone, Debug)] #[repr(C)] pub struct Srcloc { pub line_begin: isize, pub col_begin: isize, pub line_end: isize, pub col_end: isize, } #[derive(Clone, Debug)] #[repr(C)] pub enum Instruct<'arena> { IBasic(InstructBasic), IIterator(InstructIterator<'arena>), ILitConst(InstructLitConst<'arena>), IOp(InstructOperator<'arena>), IContFlow(InstructControlFlow<'arena>), ISpecialFlow(InstructSpecialFlow<'arena>), ICall(InstructCall<'arena>), IMisc(InstructMisc<'arena>), IGet(InstructGet<'arena>), IMutator(InstructMutator<'arena>), IIsset(InstructIsset<'arena>), IBase(InstructBase<'arena>), IFinal(InstructFinal<'arena>), ILabel(hhbc_by_ref_label::Label), ITry(InstructTry), IComment(Str<'arena>), ISrcLoc(Srcloc), IAsync(AsyncFunctions<'arena>), IGenerator(GenCreationExecution), IIncludeEvalDefine(InstructIncludeEvalDefine), } // -- #[no_mangle] pub unsafe extern "C" fn foo_07<'a, 'arena>( _: FcallFlags, _: CheckStarted, _: FreeIterator, _: Str<'arena>, _: RepoAuthType<'arena>, _: ParamId<'arena>, _: ParamNum, _: StackIndex, _: RecordNum, _: TypedefNum, _: ClassNum, _: ClassId<'arena>, _: FunctionId<'arena>, _: MethodId<'arena>, _: ConstId<'arena>, _: PropId<'arena>, _: NumParams, _: ByRefs<'arena>, _: hhbc_by_ref_label::Label, _: FcallArgs<'arena>, _: iterator::Id, _: local::Type<'arena>, _: IterArgs<'arena>, _: ClassrefId, _: AdataId<'arena>, _: ParamLocations<'arena>, _: FatalOp, _: CollectionType, _: QueryOp, _: MemberOpMode, _: SpecialClsRef, _: MemberKey<'arena>, _: InstructBasic, _: TypestructResolveOp, _: ReadOnlyOp, _: HasGenericsOp, _: IsLogAsDynamicCallOp, _: hhbc_by_ref_runtime::TypedValue<'arena>, _: InstructLitConst<'arena>, _: InstructOperator<'arena>, _: Switchkind, _: InstructControlFlow<'arena>, _: InstructSpecialFlow<'arena>, _: InstructGet<'arena>, _: IstypeOp, _: InstructIsset<'arena>, _: SetrangeOp, _: EqOp, _: InitpropOp, _: InstructMutator<'arena>, _: ObjNullFlavor, _: InstructCall<'arena>, _: InstructBase<'arena>, _: InstructFinal<'arena>, _: hhbc_by_ref_iterator::Id, _: InstructIterator<'arena>, _: BareThisOp, _: ClassKind, _: OpSilence, _: InstructMisc<'arena>, _: GenCreationExecution, _: AsyncFunctions<'arena>, _: InstructTry, _: Srcloc, _: Instruct<'arena>, _: InstrSeq<'arena>, ) { unimplemented!() } // -- #[derive(Debug)] pub struct DocComment(pub String); // pub struct DocComment(pub Rc<Pstring>); #[derive(Debug)] pub struct HhasAdata<'arena> { pub id: String, pub value: hhbc_by_ref_runtime::TypedValue<'arena>, } mod hhas_pos { /// Span, emitted as prefix to classes and functions #[derive(Clone, Copy, Debug, Default)] pub struct Span(pub usize, pub usize); } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Ctx { Defaults, // Shared WriteThisProps, WriteProps, // Rx hierarchy RxLocal, RxShallow, Rx, // Policied hierarchy PoliciedOfLocal, PoliciedOfShallow, PoliciedOf, PoliciedLocal, PoliciedShallow, Policied, Controlled, ReadGlobals, Globals, // Pure Pure, } #[derive(Debug)] pub struct HhasCtxConstant { pub name: String, pub coeffects: Vec<Ctx>, pub is_abstract: bool, } #[derive(Clone, Debug, Default)] pub struct HhasCoeffects { static_coeffects: Vec<Ctx>, unenforced_static_coeffects: Vec<String>, fun_param: Vec<usize>, cc_param: Vec<(usize, String)>, cc_this: Vec<Vec<String>>, cc_reified: Vec<(bool, usize, Vec<String>)>, closure_parent_scope: bool, generator_this: bool, caller: bool, } #[derive(Default, Debug)] pub struct HhasBodyEnv { pub is_namespaced: bool, //pub class_info: Option<(ast_defs::ClassKind, String)>, pub parent_name: Option<String>, } mod hhas_type { #[derive(Clone, Debug)] pub struct Info { pub user_type: Option<String>, pub type_constraint: constraint::Type, } pub mod constraint { use bitflags::bitflags; #[derive(Clone, Default, Debug)] pub struct Type { pub name: Option<String>, pub flags: Flags, } bitflags! { #[derive(Default)] pub struct Flags: u8 { const NULLABLE = 0b0000_0001; const EXTENDED_HINT = 0b0000_0100; const TYPE_VAR = 0b0000_1000; const SOFT = 0b0001_0000; const TYPE_CONSTANT = 0b0010_0000; const DISPLAY_NULLABLE = 0b0100_0000; const UPPERBOUND = 0b1000_0000; } } } } #[derive(Debug)] //Cannot be Default... pub struct HhasBody<'arena> { pub body_instrs: InstrSeq<'arena>, //... because InstrSeq not Default. pub decl_vars: Vec<String>, pub num_iters: usize, pub num_closures: u32, pub is_memoize_wrapper: bool, pub is_memoize_wrapper_lsb: bool, pub upper_bounds: Vec<(String, Vec<hhas_type::Info>)>, pub shadowed_tparams: Vec<String>, pub params: Vec<HhasParam<'arena>>, pub return_type_info: Option<hhas_type::Info>, pub doc_comment: Option<DocComment>, pub env: Option<HhasBodyEnv>, } mod hhas_function { bitflags::bitflags! { pub struct Flags: u8 { const ASYNC = 1 << 1; const GENERATOR = 1 << 2; const PAIR_GENERATOR = 1 << 3; const NO_INJECTION = 1 << 4; const INTERCEPTABLE = 1 << 5; const MEMOIZE_IMPL = 1 << 6; const RX_DISABLED = 1 << 7; } } } #[derive(Debug)] pub struct HhasFunction<'arena> { pub attributes: Vec<HhasAttribute<'arena>>, pub name: hhbc_by_ref_id::function::Type<'arena>, pub body: HhasBody<'arena>, pub span: hhas_pos::Span, pub coeffects: HhasCoeffects, pub flags: hhas_function::Flags, } #[derive(Debug)] pub enum TraitReqKind { MustExtend, MustImplement, } mod hhas_property { bitflags::bitflags! { pub struct HhasPropertyFlags: u16 { const IS_ABSTRACT = 1 << 0; const IS_STATIC = 1 << 1; const IS_DEEP_INIT = 1 << 2; const IS_CONST = 1 << 3; const IS_LSB = 1 << 4; const IS_NO_BAD_REDECLARE = 1 << 5; const HAS_SYSTEM_INITIAL = 1 << 6; const NO_IMPLICIT_NULL = 1 << 7; const INITIAL_SATISFIES_TC = 1 << 8; const IS_LATE_INIT = 1 << 9; const IS_READONLY = 1 << 10; } } } #[derive(Debug)] pub struct HhasProperty<'arena> { pub name: hhbc_by_ref_id::prop::Type<'arena>, pub flags: hhas_property::HhasPropertyFlags, pub attributes: Vec<HhasAttribute<'arena>>, //pub visibility: Visibility, pub initial_value: Option<hhbc_by_ref_runtime::TypedValue<'arena>>, pub initializer_instrs: Option<InstrSeq<'arena>>, pub type_info: hhas_type::Info, pub doc_comment: Option<DocComment>, } #[derive(Debug)] pub struct HhasMethod<'arena> { pub attributes: Vec<HhasAttribute<'arena>>, //pub visibility: Visibility, pub name: hhbc_by_ref_id::method::Type<'arena>, pub body: HhasBody<'arena>, pub span: hhas_pos::Span, pub coeffects: HhasCoeffects, pub flags: hhas_method::HhasMethodFlags, } mod hhas_method { bitflags::bitflags! { pub struct HhasMethodFlags: u16 { const IS_STATIC = 1 << 1; const IS_FINAL = 1 << 2; const IS_ABSTRACT = 1 << 3; const IS_ASYNC = 1 << 4; const IS_GENERATOR = 1 << 5; const IS_PAIR_GENERATOR = 1 << 6; const IS_CLOSURE_BODY = 1 << 7; const IS_INTERCEPTABLE = 1 << 8; const IS_MEMOIZE_IMPL = 1 << 9; const RX_DISABLED = 1 << 10; const NO_INJECTION = 1 << 11; } } } #[derive(Debug)] pub struct HhasTypeConstant<'arena> { pub name: String, pub initializer: Option<hhbc_by_ref_runtime::TypedValue<'arena>>, pub is_abstract: bool, } #[derive(Debug)] pub struct HhasClass<'a, 'arena> { pub attributes: Vec<HhasAttribute<'arena>>, pub base: Option<hhbc_by_ref_id::class::Type<'arena>>, pub implements: Vec<hhbc_by_ref_id::class::Type<'arena>>, pub enum_includes: Vec<hhbc_by_ref_id::class::Type<'arena>>, pub name: hhbc_by_ref_id::class::Type<'arena>, pub span: hhas_pos::Span, pub uses: Vec<&'a str>, // Deprecated - kill please pub use_aliases: Vec<( Option<hhbc_by_ref_id::class::Type<'arena>>, hhbc_by_ref_id::class::Type<'arena>, Option<hhbc_by_ref_id::class::Type<'arena>>, //&'a Vec<tast::UseAsVisibility>, )>, // Deprecated - kill please pub use_precedences: Vec<( hhbc_by_ref_id::class::Type<'arena>, hhbc_by_ref_id::class::Type<'arena>, Vec<hhbc_by_ref_id::class::Type<'arena>>, )>, pub enum_type: Option<hhas_type::Info>, pub methods: Vec<HhasMethod<'arena>>, pub properties: Vec<HhasProperty<'arena>>, pub constants: Vec<HhasConstant<'arena>>, pub type_constants: Vec<HhasTypeConstant<'arena>>, pub ctx_constants: Vec<HhasCtxConstant>, pub requirements: Vec<(hhbc_by_ref_id::class::Type<'arena>, TraitReqKind)>, pub upper_bounds: Vec<(String, Vec<hhas_type::Info>)>, pub doc_comment: Option<DocComment>, pub flags: HhasClassFlags, } bitflags::bitflags! { pub struct HhasClassFlags: u16 { const IS_FINAL = 1 << 1; const IS_SEALED = 1 << 2; const IS_ABSTRACT = 1 << 3; const IS_INTERFACE = 1 << 4; const IS_TRAIT = 1 << 5; const IS_XHP = 1 << 6; const IS_CONST = 1 << 7; const NO_DYNAMIC_PROPS = 1 << 8; const NEEDS_NO_REIFIEDINIT = 1 << 9; } } #[derive(Debug)] pub struct Field<'a, 'arena>( pub &'a str, pub hhas_type::Info, pub Option<hhbc_by_ref_runtime::TypedValue<'arena>>, ); #[derive(Debug)] pub struct HhasRecord<'a, 'arena> { pub name: hhbc_by_ref_id::record::Type<'arena>, pub is_abstract: bool, pub base: Option<hhbc_by_ref_id::record::Type<'arena>>, pub fields: Vec<Field<'a, 'arena>>, pub span: hhas_pos::Span, } #[derive(Clone, Debug)] pub struct HhasParam<'arena> { pub name: String, pub is_variadic: bool, pub is_inout: bool, pub user_attributes: Vec<HhasAttribute<'arena>>, pub type_info: Option<hhas_type::Info>, // I think about the best we can do is send a pretty-print of the // expression here. //pub default_value: Option<(Label, tast::Expr)>, } #[derive(Debug)] pub struct Typedef<'arena> { pub name: hhbc_by_ref_id::class::Type<'arena>, pub attributes: Vec<HhasAttribute<'arena>>, pub type_info: hhas_type::Info, pub type_structure: hhbc_by_ref_runtime::TypedValue<'arena>, pub span: hhas_pos::Span, } #[derive(Clone, Debug)] pub struct HhasAttribute<'arena> { pub name: String, pub arguments: Vec<hhbc_by_ref_runtime::TypedValue<'arena>>, } /// Data structure for keeping track of symbols (and includes) we encounter in ///the course of emitting bytecode for an AST. We split them into these four /// categories for the sake of HHVM, which has lookup function corresponding to each. #[derive(Clone, Debug, Default)] pub struct HhasSymbolRefs { pub includes: IncludePathSet, pub constants: SSet, pub functions: SSet, pub classes: SSet, } /// NOTE(hrust): order matters (hhbc_hhas write includes in sorted order) pub type IncludePathSet = std::collections::BTreeSet<IncludePath>; type SSet = std::collections::BTreeSet<String>; #[derive(Clone, Debug, Eq)] pub enum IncludePath { Absolute(String), // /foo/bar/baz.php SearchPathRelative(String), // foo/bar/baz.php IncludeRootRelative(String, String), // $_SERVER['PHP_ROOT'] . "foo/bar/baz.php" DocRootRelative(String), } impl IncludePath { fn extract_str(&self) -> (&str, &str) { use IncludePath::*; match self { Absolute(s) | SearchPathRelative(s) | DocRootRelative(s) => (s, ""), IncludeRootRelative(s1, s2) => (s1, s2), } } } impl Ord for IncludePath { fn cmp(&self, other: &Self) -> Ordering { self.extract_str().cmp(&other.extract_str()) } } impl PartialOrd for IncludePath { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for IncludePath { fn eq(&self, other: &Self) -> bool { self.extract_str().eq(&other.extract_str()) } } #[derive(Debug)] pub struct HhasConstant<'arena> { pub name: hhbc_by_ref_id::r#const::Type<'arena>, pub value: Option<hhbc_by_ref_runtime::TypedValue<'arena>>, pub initializer_instrs: Option<InstrSeq<'arena>>, pub is_abstract: bool, } #[derive(Debug)] pub enum Pos { Pos, } // oxidized::pos::Pos #[derive(Default, Debug)] //#[repr(C)] pub struct HhasProgram<'a, 'arena> { pub adata: Vec<HhasAdata<'arena>>, pub functions: Vec<HhasFunction<'arena>>, pub classes: Vec<HhasClass<'a, 'arena>>, pub record_defs: Vec<HhasRecord<'a, 'arena>>, pub typedefs: Vec<Typedef<'arena>>, pub file_attributes: Vec<HhasAttribute<'arena>>, pub symbol_refs: HhasSymbolRefs, pub constants: Vec<HhasConstant<'arena>>, pub fatal: Option<(FatalOp, Pos, String)>, } /* #[derive(Debug)] #[repr(C)] pub struct HhasProgram<'arena> { pub adata: Slice<'arena, HhasAdata<'arena>>, pub functions: Slice<'arena, HhasFunction<'arena>>, pub classes: Slice<'arena, HhasClass<'arena>>, pub record_defs: Slice<'arena, HhasRecord<'arena>>, pub typedefs: Slice<'arena, Typedef<'arena>>, pub file_attributes: Slice<'arena, HhasAttribute<'arena>>, pub symbol_refs: HhasSymbolRefs<'arena>, pub constants: Slice<'arena, HhasConstant<'arena>>, pub fatal: Maybe<(FatalOp, Pos, Str<'arena>)>, } */
use std::env; use std::fs::canonicalize; use std::path::PathBuf; mod platform; fn main() { let args: Vec<String> = env::args().collect(); match args.len() { 1 => eprintln!( "No arguments is passed. Please pass the file path that you want to set to the wallpaper." ), 2 => { let path = PathBuf::from(&args[1]); if !path.exists() || !path.is_file() { eprintln!("No such file or could not open the file"); return; } // convert to absolute path let path = canonicalize(&path).unwrap(); platform::apply_change(&path.to_str().unwrap()).unwrap(); } _ => eprintln!( "More than 1 argument. Please pass the only 1 argument that you want to set to the wallpaper." ), } }
unsafe fn hello() { let x = 32; let y = 23; let pointx = &x; let pointy = &y; println!("{}",pointx); println!("{}",pointy); } fn main() { unsafe { hello(); } }
use model::*; use pancurses::*; type color_pair = u32; const DEFAULT_COLORS: color_pair = 0; const GOAL_COLORS: color_pair = 1; const BROKEN_TURRET_COLORS: color_pair = 2; const DAMAGED_TURRET_COLORS: color_pair = 3; const PLACEMENT_COLORS: color_pair = 4; const GAMEOVER_COLORS: color_pair = 5; const EMPTY_CELL: chtype = ' ' as u32; pub struct GameWindows { stats: Window, view: Window, help: Window, log: Window, } impl GameWindows { fn refresh(&self) { self.stats.refresh(); self.view.refresh(); self.help.refresh(); self.log.refresh(); } } pub fn setup_render(window: &Window) -> GameWindows { start_color(); use_default_colors(); init_pair(DEFAULT_COLORS as i16, COLOR_WHITE, -1); init_pair(GOAL_COLORS as i16, COLOR_YELLOW, -1); init_pair(BROKEN_TURRET_COLORS as i16, COLOR_RED, -1); init_pair(DAMAGED_TURRET_COLORS as i16, COLOR_MAGENTA, -1); init_pair(PLACEMENT_COLORS as i16, COLOR_BLUE, -1); init_pair(GAMEOVER_COLORS as i16, COLOR_RED, -1); let stats = window.subwin(5, X as i32, 0, 0).unwrap(); stats.keypad(true); stats.draw_box(0, 0); let view = window.subwin(Y as i32, X as i32, 5, 0).unwrap(); view.keypad(true); let help = window.subwin(5 + Y as i32 + 7, 80 - X as i32, 0, X as i32).unwrap(); help.draw_box(0, 0); help.keypad(true); let log = window.subwin(7, X as i32, 5 + Y as i32, 0).unwrap(); log.draw_box(0, 0); log.keypad(true); return GameWindows { stats: stats, view: view, help: help, log: log, }; } impl WorldData { pub fn render(&self, windows: &GameWindows, game_state: &GameState) { self.render_frame(windows); match *game_state { Startup => self.render_startup(windows), Construct { menu, menu_index } => self.render_construct(windows, menu, menu_index), Fight { .. } => self.render_fight(windows), GameOver { ref msg } => self.render_gameover(windows, msg), _ => unimplemented!(), }; windows.refresh(); } fn render_frame(&self, windows: &GameWindows) { windows.help.erase(); windows.help.draw_box(0, 0); windows.help.mvaddstr(1, 1, "THING PROTECTOR"); let stat_string1 = format!("Health: {:3} | Thing Integrity: {:3} | Wave: {:3}", self.player_info.health, match self.statics[Y / 2][X / 2] { Some(Goal { health: h, .. }) => h, _ => 0, }, self.wave); let stat_string2 = format!("Cash: {:5}", self.cash); let offset = (X - stat_string1.len()) as i32 / 2; windows.stats.mvaddstr(2, offset, stat_string1.as_str()); windows.stats.mvaddstr(3, offset, stat_string2.as_str()); windows.log.clear(); windows.log.draw_box(0, 0); for i in 0..self.log.len() { windows.log.mvaddstr(i as i32 + 1, 1, self.log[i].as_str()); } for row_n in 0..Y { for col_n in 0..X { let ch = self.statics[row_n][col_n].map_or(EMPTY_CELL, |s| s.render(row_n)); windows.view.mvaddch(row_n as i32, col_n as i32, ch); } } } fn render_startup(&self, windows: &GameWindows) { let message = " You are in a room.\n\nThe Thing is also in the room. It is \ holy to you.\nFoul fiends endevour even as we speak to destroy\nthe Thing. \ You must protect it with all your might!\n\nYou can defend the Thing by \ building turrets and\nobstacles, and by thrusting yourself into the \ path\nof your many, many formidable foes.\n\nUse WASD or Arrow keys to \ move, and space or return\nto select items in menus. Your forsworn fight \ begins!"; let max_line_length = message.lines().max_by_key(|line| line.len()).unwrap().len(); let lines_count = message.lines().count(); for line in message.lines().enumerate() { let (row, line) = line; windows.view.mvaddstr((row + (Y - lines_count) / 2) as i32, ((X - max_line_length) / 2) as i32, line); } } fn render_construct(&self, windows: &GameWindows, menu: Menu, menu_index: usize) { match menu { Menu::Root => { windows.help.mvaddstr(3, 3, "Build"); windows.help.mvaddstr(4, 3, "Move"); windows.help.mvaddstr(5, 3, "Continue"); windows.help.mvaddch(menu_index as i32 + 3, 2, '>'); windows.help.mvaddch(menu_index as i32 + 3, 13, '<'); } Menu::Build => { windows.help.mvaddstr(3, 3, "Turret"); windows.help.mvaddstr(4, 3, "Obstacle"); windows.help.mvaddstr(5, 3, "Back"); windows.help.mvaddch(menu_index as i32 + 3, 2, '>'); windows.help.mvaddch(menu_index as i32 + 3, 13, '<'); } Menu::Move(depth) => { // we want to display Y - 2 (border) - 3 (title) rows // and we have 1 + self.turrets.len() items let turrets = self.turrets.iter().enumerate().skip(depth); let nturrets = turrets.len(); let y = Y + 5 + 7 - 5; for item in turrets.take(y) { let (i, s) = item; windows.help.mvaddstr((i - depth) as i32 + 3, 3, format!("Turret {}", i + 1).as_str()); if i - depth == menu_index { let placement = self.statics[s.1][s.0].unwrap(); windows.view.mvaddch(s.1 as i32, s.0 as i32, placement.render(1) | COLOR_PAIR(PLACEMENT_COLORS)); } } if nturrets <= depth { let obstacles = self.obstacles.iter().enumerate().skip(depth - nturrets); for item in obstacles.take(y) { let (i, s) = item; windows.help.mvaddstr((i - nturrets) as i32 + 3, 3, format!("Obstacle {}", i + 1).as_str()); if i - nturrets == menu_index { let placement = self.statics[s.1][s.0].unwrap(); windows.view.mvaddch(s.1 as i32, s.0 as i32, placement.render(1) | COLOR_PAIR(PLACEMENT_COLORS)); } } } else if nturrets > depth + y { } else { let obstacles = self.obstacles.iter().enumerate(); for item in obstacles.take(depth + y - nturrets) { let (i, s) = item; windows.help.mvaddstr(i as i32 + nturrets as i32 + 3, 3, format!("Obstacle {}", i + 1).as_str()); if i + nturrets == menu_index { let placement = self.statics[s.1][s.0].unwrap(); windows.view.mvaddch(s.1 as i32, s.0 as i32, placement.render(1) | COLOR_PAIR(PLACEMENT_COLORS)); } } }; let break_point = self.turrets.len() + self.obstacles.len() - depth; if break_point < y { windows.help.mvaddstr(break_point as i32 + 3, 3, "Back"); } windows.help.mvaddch(menu_index as i32 + 3, 2, '>'); windows.help.mvaddch(menu_index as i32 + 3, 13, '<'); } Menu::Place(placement, location) => { windows.help.mvaddstr(3, 3, "Placing a"); windows.help.mvaddstr(4, 3, match placement { Turret { .. } => "Turret", Obstacle { .. } => "Obstacle", _ => "Error", }); windows.view.mvaddch(location.1 as i32, location.0 as i32, placement.render(1) | COLOR_PAIR(PLACEMENT_COLORS)); } } } fn render_fight(&self, windows: &GameWindows) { for row_n in 0..Y { for col_n in 0..X { match self.mobiles[row_n][col_n] { Some(mob) => { windows.view.mvaddch(row_n as i32, col_n as i32, mob.render()); } None => {} } } } } fn render_gameover(&self, windows: &GameWindows, msg: &String) { let x = (X - msg.len() - 2) as i32 / 2; let y = (Y - 3) as i32 / 2 + 5; let gameover = windows.view.subwin(3, msg.len() as i32 + 2, y, x).unwrap(); gameover.attron(COLOR_PAIR(GAMEOVER_COLORS)); gameover.draw_box(0, 0); gameover.attron(A_BOLD); gameover.mvaddstr(1, 1, msg.as_str()); gameover.attroff(A_BOLD | COLOR_PAIR(GAMEOVER_COLORS)); gameover.refresh(); } } impl Mobile { fn render(&self) -> chtype { match *self { Player => '@'.to_chtype(), Fiend { info } => info.ch, Arrow { info: ArrowInfo { dx, dy, dir, .. } } => { if (dx as f64) < 0.3 * dy as f64 { '|' } else if (dy as f64) < 0.3 * dx as f64 { '-' } else if dir.0 == dir.1 { '\\' } else { '/' } .to_chtype() } } } } impl Static { fn render(&self, row_n: usize) -> chtype { let chty = match *self { Wall => '#', Gate => { if row_n == 0 || row_n == Y - 1 { '-' } else { '|' } } Goal { .. } => 'Y', Turret { .. } => 'O', Obstacle { .. } => '=', } .to_chtype(); // Apply formatting match *self { Goal { .. } => chty | COLOR_PAIR(GOAL_COLORS), Turret { info } => { let colour = if info.health == 0 { BROKEN_TURRET_COLORS } else if info.health <= info.max_health / 2 { DAMAGED_TURRET_COLORS } else { DEFAULT_COLORS }; chty | A_BOLD | COLOR_PAIR(colour) } _ => chty, } } }
use std::{unimplemented, vec}; use utils::Grid; #[derive(Clone, Hash, PartialEq, Eq)] pub enum Seat { FLOOR, FILLED, EMPTY, } impl Default for Seat { fn default() -> Self { Seat::EMPTY } } // #[test] pub fn run() { let input = read_input(include_str!("input/day11.txt")); // println!("{:?}", input); println!("{}", exercise_1(&input)); println!("{}", exercise_2(&input)); } pub fn read_input(input: &str) -> Grid<Seat> { let lines = input .lines() .map(|x| { x.chars() .map(|x| match x { '.' => Seat::FLOOR, 'L' => Seat::EMPTY, '#' => Seat::FILLED, _ => unreachable!(), }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); Grid::from_vec(lines) } fn exercise_1(input: &Grid<Seat>) -> usize { let mut continue_loop = true; let mut prev_round = input.clone(); let mut next_round = prev_round.clone(); let seen_grid = { let mut grid = Grid::new(input.width, input.height); input .iter() .filter(|x| match x.1 { Seat::FLOOR => false, Seat::FILLED => true, Seat::EMPTY => true, }) .for_each(|((x, y), v)| { grid.set(x, y, neighbours(&input, x, y)); }); grid }; while continue_loop { continue_loop = false; for ((x, y), v) in prev_round.iter() { let counter = seen_grid .get(x, y) .unwrap() .iter() .map(|(a, b)| prev_round.get(*a, *b).unwrap()) .filter(|&x| x == &Seat::FILLED); match v { Seat::FLOOR => {} Seat::FILLED => { let n = counter.take(4).count(); if n >= 4 { continue_loop = true; next_round.set(x, y, Seat::EMPTY); } else { next_round.set(x, y, Seat::FILLED); } } Seat::EMPTY => { let n = counter.take(1).count(); if n == 0 { continue_loop = true; next_round.set(x, y, Seat::FILLED); } else { next_round.set(x, y, Seat::EMPTY); } } } } let t = prev_round; prev_round = next_round; next_round = t; } // println!("r: {}", round); prev_round .grid .iter() .filter(|x| **x == Seat::FILLED) .count() } fn exercise_2(input: &Grid<Seat>) -> usize { let mut continue_loop = true; let mut prev_round = input.clone(); let mut next_round = prev_round.clone(); let seen_grid = { let mut grid = Grid::new(input.width, input.height); input .iter() .filter(|x| match x.1 { Seat::FLOOR => false, Seat::FILLED => true, Seat::EMPTY => true, }) .for_each(|((x, y), v)| { grid.set(x, y, seen_neighbours(&input, x, y)); }); grid }; while continue_loop { continue_loop = false; for ((x, y), v) in prev_round.iter() { let counter = seen_grid .get(x, y) .unwrap() .iter() .map(|(a, b)| prev_round.get(*a, *b).unwrap()) .filter(|&x| x == &Seat::FILLED); match v { Seat::FLOOR => {} Seat::FILLED => { let n = counter.take(5).count(); if n >= 5 { continue_loop = true; next_round.set(x, y, Seat::EMPTY); } else { next_round.set(x, y, Seat::FILLED); } } Seat::EMPTY => { let n = counter.take(1).count(); if n == 0 { continue_loop = true; next_round.set(x, y, Seat::FILLED); } else { next_round.set(x, y, Seat::EMPTY); } } } } let t = prev_round; prev_round = next_round; next_round = t; } prev_round .grid .iter() .filter(|x| **x == Seat::FILLED) .count() } fn neighbours(grid: &Grid<Seat>, x: usize, y: usize) -> Vec<(usize, usize)> { vec![ (-1isize, -1isize), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1), ] .into_iter() .filter_map(|(dx, dy)| { let nx = ((x as isize) + dx) as usize; let ny = ((y as isize) + dy) as usize; match grid.get(nx, ny) { Some(Seat::FILLED) => Some((nx, ny)), Some(Seat::EMPTY) => Some((nx, ny)), _ => None, } }) .collect() } fn seen_neighbours(grid: &Grid<Seat>, x: usize, y: usize) -> Vec<(usize, usize)> { let w = grid.width; let h = grid.height; vec![ (-1isize, -1isize), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1), ] .into_iter() .filter_map(|(dx, dy)| { let dw = if dx > 0 { w - x } else if dx < 0 { x } else { std::usize::MAX }; let dh = if dy > 0 { h - y } else if dy < 0 { y } else { std::usize::MAX }; for i in 1..=(dw.min(dh)) { let nx = ((x as isize) + dx * i as isize) as usize; let ny = ((y as isize) + dy * i as isize) as usize; match grid.get(nx, ny) { Some(Seat::FILLED) => { return Some((nx, ny)); } Some(Seat::EMPTY) => { return Some((nx, ny)); } _ => {} } } return None; }) .collect() } #[cfg(test)] mod tests { use super::*; use crate::test::Bencher; #[test] fn d11p1_test() { let input = read_input(include_str!("input/day11.txt")); assert_eq!(2441, exercise_1(&input)); } #[test] fn d11p2_test() { let input = read_input(include_str!("input/day11.txt")); assert_eq!(2190, exercise_2(&input)); } #[bench] fn d11_bench_parse(b: &mut Bencher) { b.iter(|| read_input(include_str!("input/day11.txt"))); } #[bench] fn d11_bench_ex1(b: &mut Bencher) { let input = read_input(include_str!("input/day11.txt")); b.iter(|| exercise_1(&input)); } #[bench] fn d11_bench_ex2(b: &mut Bencher) { let input = read_input(include_str!("input/day11.txt")); b.iter(|| exercise_2(&input)); } }
use std::collections::VecDeque; use hashbrown::HashMap; use pest::iterators::Pair; use pest::Parser; use serde::Serialize; use serde_json::value::{to_value, Map, Value as Json}; use crate::error::RenderError; use crate::grammar::{HandlebarsParser, Rule}; pub type Object = HashMap<String, Json>; /// The context wrap data you render on your templates. /// #[derive(Debug, Clone)] pub struct Context { data: Json, } #[inline] fn parse_json_visitor_inner<'a>( path_stack: &mut VecDeque<&'a str>, path: &'a str, ) -> Result<(), RenderError> { let parsed_path = HandlebarsParser::parse(Rule::path, path) .map(|p| p.flatten()) .map_err(|_| RenderError::new("Invalid JSON path"))?; let mut seg_stack: VecDeque<Pair<Rule>> = VecDeque::new(); for seg in parsed_path { if seg.as_str() == "@root" { seg_stack.clear(); path_stack.clear(); continue; } match seg.as_rule() { Rule::path_up => { path_stack.pop_back(); if let Some(p) = seg_stack.pop_back() { // also pop array index like [1] if p.as_rule() == Rule::path_raw_id { seg_stack.pop_back(); } } } Rule::path_id | Rule::path_raw_id => { seg_stack.push_back(seg); } _ => {} } } for i in seg_stack { let span = i.as_span(); path_stack.push_back(&path[span.start()..span.end()]); } Ok(()) } fn parse_json_visitor<'a>( path_stack: &mut VecDeque<&'a str>, base_path: &'a str, path_context: &'a VecDeque<String>, relative_path: &'a str, ) -> Result<(), RenderError> { let parser = HandlebarsParser::parse(Rule::path, relative_path) .map(|p| p.flatten()) .map_err(|_| RenderError::new(format!("Invalid JSON path: {}", relative_path)))?; let mut path_context_depth: i64 = -1; for sg in parser { if sg.as_rule() == Rule::path_up { path_context_depth += 1; } else { break; } } if path_context_depth >= 0 { if let Some(context_base_path) = path_context.get(path_context_depth as usize) { parse_json_visitor_inner(path_stack, context_base_path)?; } else { parse_json_visitor_inner(path_stack, base_path)?; } } else { parse_json_visitor_inner(path_stack, base_path)?; } parse_json_visitor_inner(path_stack, relative_path)?; Ok(()) } pub fn merge_json(base: &Json, addition: &Object) -> Json { let mut base_map = match *base { Json::Object(ref m) => m.clone(), _ => Map::new(), }; for (k, v) in addition.iter() { base_map.insert(k.clone(), v.clone()); } Json::Object(base_map) } impl Context { /// Create a context with null data pub fn null() -> Context { Context { data: Json::Null } } /// Create a context with given data pub fn wraps<T: Serialize>(e: T) -> Result<Context, RenderError> { to_value(e) .map_err(RenderError::from) .map(|d| Context { data: d }) } /// Navigate the context with base path and relative path /// Typically you will set base path to `RenderContext.get_path()` /// and set relative path to helper argument or so. /// /// If you want to navigate from top level, set the base path to `"."` pub fn navigate( &self, base_path: &str, path_context: &VecDeque<String>, relative_path: &str, ) -> Result<Option<&Json>, RenderError> { let mut path_stack: VecDeque<&str> = VecDeque::new(); parse_json_visitor(&mut path_stack, base_path, path_context, relative_path)?; let paths: Vec<&str> = path_stack.iter().cloned().collect(); let mut data: Option<&Json> = Some(&self.data); for p in &paths { if *p == "this" { continue; } data = match data { Some(&Json::Array(ref l)) => p .parse::<usize>() .map_err(RenderError::with) .map(|idx_u| l.get(idx_u))?, Some(&Json::Object(ref m)) => m.get(*p), Some(_) => None, None => break, } } Ok(data) } pub fn data(&self) -> &Json { &self.data } pub fn data_mut(&mut self) -> &mut Json { &mut self.data } } #[cfg(test)] mod test { use crate::context::{self, Context}; use crate::value::{self, JsonRender}; use hashbrown::HashMap; use serde_json::value::Map; use std::collections::VecDeque; #[derive(Serialize)] struct Address { city: String, country: String, } #[derive(Serialize)] struct Person { name: String, age: i16, addr: Address, titles: Vec<String>, } #[test] fn test_render() { let v = "hello"; let ctx = Context::wraps(&v.to_string()).unwrap(); assert_eq!( ctx.navigate(".", &VecDeque::new(), "this") .unwrap() .unwrap() .render(), v.to_string() ); } #[test] fn test_navigation() { let addr = Address { city: "Beijing".to_string(), country: "China".to_string(), }; let person = Person { name: "Ning Sun".to_string(), age: 27, addr, titles: vec!["programmer".to_string(), "cartographier".to_string()], }; let ctx = Context::wraps(&person).unwrap(); assert_eq!( ctx.navigate(".", &VecDeque::new(), "./name/../addr/country") .unwrap() .unwrap() .render(), "China".to_string() ); assert_eq!( ctx.navigate(".", &VecDeque::new(), "addr.[country]") .unwrap() .unwrap() .render(), "China".to_string() ); let v = true; let ctx2 = Context::wraps(&v).unwrap(); assert_eq!( ctx2.navigate(".", &VecDeque::new(), "this") .unwrap() .unwrap() .render(), "true".to_string() ); assert_eq!( ctx.navigate(".", &VecDeque::new(), "titles.[0]") .unwrap() .unwrap() .render(), "programmer".to_string() ); assert_eq!( ctx.navigate(".", &VecDeque::new(), "titles.[0]/../../age") .unwrap() .unwrap() .render(), "27".to_string() ); assert_eq!( ctx.navigate(".", &VecDeque::new(), "this.titles.[0]/../../age") .unwrap() .unwrap() .render(), "27".to_string() ); } #[test] fn test_this() { let mut map_with_this = Map::new(); map_with_this.insert("this".to_string(), value::to_json("hello")); map_with_this.insert("age".to_string(), value::to_json(5usize)); let ctx1 = Context::wraps(&map_with_this).unwrap(); let mut map_without_this = Map::new(); map_without_this.insert("age".to_string(), value::to_json(4usize)); let ctx2 = Context::wraps(&map_without_this).unwrap(); assert_eq!( ctx1.navigate(".", &VecDeque::new(), "this") .unwrap() .unwrap() .render(), "[object]".to_owned() ); assert_eq!( ctx2.navigate(".", &VecDeque::new(), "age") .unwrap() .unwrap() .render(), "4".to_owned() ); } #[test] fn test_merge_json() { let map = json!({ "age": 4 }); let s = "hello".to_owned(); let mut hash = HashMap::new(); hash.insert("tag".to_owned(), value::to_json("h1")); let ctx_a1 = Context::wraps(&context::merge_json(&map, &hash)).unwrap(); assert_eq!( ctx_a1 .navigate(".", &VecDeque::new(), "age") .unwrap() .unwrap() .render(), "4".to_owned() ); assert_eq!( ctx_a1 .navigate(".", &VecDeque::new(), "tag") .unwrap() .unwrap() .render(), "h1".to_owned() ); let ctx_a2 = Context::wraps(&context::merge_json(&value::to_json(s), &hash)).unwrap(); assert_eq!( ctx_a2 .navigate(".", &VecDeque::new(), "this") .unwrap() .unwrap() .render(), "[object]".to_owned() ); assert_eq!( ctx_a2 .navigate(".", &VecDeque::new(), "tag") .unwrap() .unwrap() .render(), "h1".to_owned() ); } #[test] fn test_key_name_with_this() { let m = btreemap! { "this_name".to_string() => "the_value".to_string() }; let ctx = Context::wraps(&m).unwrap(); assert_eq!( ctx.navigate(".", &VecDeque::new(), "this_name") .unwrap() .unwrap() .render(), "the_value".to_string() ); } use serde::ser::Error as SerdeError; use serde::{Serialize, Serializer}; struct UnserializableType {} impl Serialize for UnserializableType { fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error> where S: Serializer, { Err(SerdeError::custom("test")) } } #[test] fn test_serialize_error() { let d = UnserializableType {}; assert!(Context::wraps(&d).is_err()); } #[test] fn test_root() { let m = json!({ "a" : { "b" : { "c" : { "d" : 1 } } }, "b": 2 }); let ctx = Context::wraps(&m).unwrap(); assert_eq!( ctx.navigate("a/b", &VecDeque::new(), "@root/b") .unwrap() .unwrap() .render(), "2".to_string() ); } }
// Copyright 2018 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std; use sys; use {Direction, Language}; /// A series of Unicode characters. /// /// ## Adding Text /// /// Since in Rust, a value of type `&str` must contain valid UTF-8 /// text, adding text to a `Buffer` is simple: /// /// ``` /// # use harfbuzz::Buffer; /// let mut b = Buffer::new(); /// b.add_str("Hello World"); /// assert_eq!(b.is_empty(), false); /// ``` /// /// or, more simply: /// /// ``` /// # use harfbuzz::Buffer; /// let b = Buffer::with("Hello World"); /// assert_eq!(b.is_empty(), false); /// ``` /// /// ## Segment Properties /// /// In addition to the text itself, there are three important properties /// that influence how a piece of text is shaped: /// /// * Direction: The direction in which the output glyphs flow. This is /// typically left to right or right to left. This is controlled via /// the [`set_direction`] method on `Buffer`. /// * Script: Script is crucial for choosing the proper shaping behaviour /// for scripts that require it (e.g. Arabic) and the which OpenType /// features defined in the font to be applied. This is controlled via /// the [`set_script`] method on `Buffer`. /// * Language: Languages are crucial for selecting which OpenType feature /// to apply to the buffer which can result in applying language-specific /// behaviour. Languages are orthogonal to the scripts, and though they /// are related, they are different concepts and should not be confused /// with each other. This is controlled via the [`set_language`] method /// on `Buffer`. /// /// Additionally, Harfbuzz can attempt to infer the values for these /// properties using the [`guess_segment_properties`] method on `Buffer`: /// /// ``` /// # use harfbuzz::{Buffer, Direction, sys}; /// let mut b = Buffer::with("مساء الخير"); /// b.guess_segment_properties(); /// assert_eq!(b.get_direction(), Direction::RTL); /// assert_eq!(b.get_script(), sys::HB_SCRIPT_ARABIC); /// ``` /// /// [`set_direction`]: #method.set_direction /// [`set_script`]: #method.set_script /// [`set_language`]: #method.set_language /// [`guess_segment_properties`]: #method.guess_segment_properties pub struct Buffer { /// The underlying `hb_buffer_t` from the `harfbuzz-sys` crate. /// /// This isn't commonly needed unless interfacing directly with /// functions from the `harfbuzz-sys` crate that haven't been /// safely exposed. raw: *mut sys::hb_buffer_t, } impl Buffer { /// Create a new, empty buffer. /// /// ``` /// # use harfbuzz::Buffer; /// let b = Buffer::new(); /// assert!(b.is_empty()); /// ``` pub fn new() -> Self { Buffer::default() } /// Construct a `Buffer` from a raw pointer. Takes ownership of the buffer. pub unsafe fn from_raw(raw: *mut sys::hb_buffer_t) -> Self { Buffer { raw } } /// Borrows a raw pointer to the buffer. pub fn as_ptr(&self) -> *mut sys::hb_buffer_t { self.raw } /// Gives up ownership and returns a raw pointer to the buffer. pub fn into_raw(self) -> *mut sys::hb_buffer_t { let raw = self.raw; std::mem::forget(self); raw } /// Create a new buffer with the given text. pub fn with(text: &str) -> Self { let mut b = Buffer::new(); b.add_str(text); b } /// Create a new, empty buffer with the specified capacity. pub fn with_capacity(capacity: usize) -> Self { let mut b = Buffer::default(); b.reserve(capacity); b } /// Add UTF-8 encoded text to the buffer. pub fn add_str(&mut self, text: &str) { unsafe { sys::hb_buffer_add_utf8( self.raw, text.as_ptr() as *const std::os::raw::c_char, text.len() as std::os::raw::c_int, 0, text.len() as std::os::raw::c_int, ) }; } /// Append part of the contents of another buffer to this one. /// /// ``` /// # use harfbuzz::Buffer; /// let mut b1 = Buffer::with("butter"); /// let b2 = Buffer::with("fly"); /// b1.append(&b2, 0, 3); /// assert_eq!(b1.len(), "butterfly".len()); /// ``` pub fn append(&mut self, other: &Buffer, start: usize, end: usize) { unsafe { sys::hb_buffer_append( self.raw, other.raw, start as std::os::raw::c_uint, end as std::os::raw::c_uint, ) }; } /// Throw away text stored in the buffer, but maintain the /// currently configured Unicode functions and flags. /// /// Text, glyph info, and segment properties will be discarded. pub fn clear_contents(&mut self) { unsafe { sys::hb_buffer_clear_contents(self.raw) }; } /// Throw away all data stored in the buffer as well as configuration /// parameters like Unicode functions, flags, and segment properties. pub fn reset(&mut self) { unsafe { sys::hb_buffer_reset(self.raw) }; } /// Preallocate space to fit at least *size* number of items. /// /// FIXME: Does this correctly match the expected semantics? pub fn reserve(&mut self, size: usize) { unsafe { sys::hb_buffer_pre_allocate(self.raw, size as u32) }; } /// Returns the number of elements in the buffer, also referred to as its 'length'. pub fn len(&self) -> usize { unsafe { sys::hb_buffer_get_length(self.raw) as usize } } /// Returns `true` if the buffer contains no data. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Sets unset buffer segment properties based on buffer Unicode /// contents. /// /// If buffer is not empty, it must have content type /// `HB_BUFFER_CONTENT_TYPE_UNICODE`. /// /// If buffer script is not set (ie. is `HB_SCRIPT_INVALID`), it will /// be set to the Unicode script of the first character in the buffer /// that has a script other than `HB_SCRIPT_COMMON`, /// `HB_SCRIPT_INHERITED`, and `HB_SCRIPT_UNKNOWN`. /// /// Next, if buffer direction is not set (ie. is `Direction::Invalid`), /// it will be set to the natural horizontal direction of the buffer /// script as returned by `hb_script_get_horizontal_direction()`. /// /// Finally, if buffer language is not set (ie. is `HB_LANGUAGE_INVALID`), /// it will be set to the process's default language as returned by /// `hb_language_get_default()`. This may change in the future by /// taking buffer script into consideration when choosing a language. /// /// ``` /// # use harfbuzz::{Buffer, Direction, sys}; /// let mut b = Buffer::with("Hello, world!"); /// b.guess_segment_properties(); /// assert_eq!(b.get_direction(), Direction::LTR); /// assert_eq!(b.get_script(), sys::HB_SCRIPT_LATIN); /// ``` /// /// See also: /// /// * [`get_direction`](#method.get_direction) /// * [`set_direction`](#method.set_direction) /// * [`get_script`](#method.get_script) /// * [`set_script`](#method.set_script) /// * [`get_language`](#method.get_language) /// * [`set_language`](#method.set_language) pub fn guess_segment_properties(&mut self) { unsafe { sys::hb_buffer_guess_segment_properties(self.raw) }; } /// Set the text flow direction of the buffer. /// /// No shaping can happen without setting buffer direction, and /// it controls the visual direction for the output glyphs; for /// RTL direction the glyphs will be reversed. Many layout features /// depend on the proper setting of the direction, for example, /// reversing RTL text before shaping, then shaping with LTR direction /// is not the same as keeping the text in logical order and shaping /// with RTL direction. /// /// See also: /// /// * [`get_direction`](#method.get_direction) /// * [`guess_segment_properties`](#method.guess_segment_properties) pub fn set_direction(&mut self, direction: Direction) { unsafe { sys::hb_buffer_set_direction(self.raw, direction.into()) }; } /// Get the text flow direction for the buffer. /// /// See also: /// /// * [`set_direction`](#method.set_direction) pub fn get_direction(&self) -> Direction { (unsafe { sys::hb_buffer_get_direction(self.raw) }).into() } /// Sets the script of buffer to *script*. /// /// Script is crucial for choosing the proper shaping behaviour /// for scripts that require it (e.g. Arabic) and the which /// OpenType features defined in the font to be applied. /// /// See also: /// /// * [`get_script`](#method.get_script) /// * [`guess_segment_properties`](#method.guess_segment_properties) pub fn set_script(&mut self, script: sys::hb_script_t) { unsafe { sys::hb_buffer_set_script(self.raw, script) }; } /// Get the script for the buffer. /// /// See also: /// /// * [`set_script`](#method.set_script) pub fn get_script(&self) -> sys::hb_script_t { unsafe { sys::hb_buffer_get_script(self.raw) } } /// Sets the language of buffer to *language*. /// /// Languages are crucial for selecting which OpenType feature /// to apply to the buffer which can result in applying /// language-specific behaviour. Languages are orthogonal to /// the scripts, and though they are related, they are different /// concepts and should not be confused with each other. /// /// See also: /// /// * [`get_language`](#method.get_language) /// * [`guess_segment_properties`](#method.guess_segment_properties) pub fn set_language(&mut self, language: Language) { unsafe { sys::hb_buffer_set_language(self.raw, language.as_raw()) }; } /// Get the language for the buffer. /// /// See also: /// /// * [`set_language`](#method.set_language) pub fn get_language(&self) -> Language { unsafe { Language::from_raw(sys::hb_buffer_get_language(self.raw)) } } } impl std::fmt::Debug for Buffer { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { fmt.debug_struct("Buffer") .field("direction", &self.get_direction()) .field("script", &self.get_script()) .field("language", &self.get_language()) .finish() } } impl Default for Buffer { /// Create a new, empty buffer. fn default() -> Self { Buffer { raw: unsafe { sys::hb_buffer_create() }, } } } impl Drop for Buffer { fn drop(&mut self) { unsafe { sys::hb_buffer_destroy(self.raw) } } }
use std::fmt; use Command; #[deriving(PartialEq, Eq, PartialOrd, Ord)] pub struct Grid { width: u32, height: u32, chars: Vec<char>, } impl fmt::Show for Grid { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { let s: String = String::from_chars(self.chars.as_slice()); write!(w, "Grid {{ width: {}, height: {}, chars: {} }}", self.width, self.height, s) } } #[deriving(PartialEq, Eq, PartialOrd, Ord)] pub enum ParseErr { PrematureLineEnd(u32, String, u32), BadTerminationChar(u32, String, char), } impl fmt::Show for ParseErr { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { match *self { PrematureLineEnd(h, ref s, width) => write!(w, "line {} content {} ended prematurely; \ expected {} characters", h, s, width), BadTerminationChar(h, ref s, c) => write!(w, "line {} expected end of input or line \ after {}, got {}", h, s, c), } } } impl Grid { pub fn new(width: u32, height: u32, background: char) -> Grid { let len = width * height; let chars = Vec::from_elem(len.to_uint().unwrap(), background); Grid { width: width, height: height, chars: chars } } pub fn to_string(&self) -> String { let len = self.height * (self.width + 1); let mut s = String::with_capacity(len.to_uint().unwrap()); for y in range(0, self.height) { for x in range(0, self.width) { s.push(self.get(x, y)); } s.push('\n'); } s } pub fn from_str(s: &str) -> Result<Grid, ParseErr> { let mut w = 0u32; for c in s.chars() { if c == '\n' { break; } else { w += 1; } } let mut grid = vec![]; let mut chars = s.chars(); let mut h = 0; loop { let mut started_line = false; let row_start = grid.len(); for i in range(0, w) { match (i, chars.next()) { (0, None) => break, (_, None) => { let line = String::from_chars(grid.slice_from(row_start)); return Err(PrematureLineEnd(h, line, w)) } (_, Some(c)) => { if !started_line { h += 1; started_line = true; } grid.push(c) } } } match chars.next() { None => break, Some('\n') => continue, Some(c) => { let line = String::from_chars(grid.slice_from(row_start)); return Err(BadTerminationChar(h, line, c)) } } } Ok(Grid { width: w, height: h, chars: grid }) } pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } pub fn get(&self, x: u32, y: u32) -> char { assert!(x < self.width); assert!(y < self.height); let idx = y * self.width + x; self.chars[idx.to_uint().unwrap()] } pub fn set(&mut self, x: u32, y: u32, c: char) { assert!(x < self.width); assert!(y < self.height); let idx = y * self.width + x; *self.chars.get_mut(idx.to_uint().unwrap()) = c; } pub fn exec(&mut self, command: &Command) { let Command { x, y, w, h, fill } = *command; if w == 1 || h == 1 { return self.draw_line(command); } self.set(x, y, '+'); self.set(x, y+h-1, '+'); self.set(x+w-1, y, '+'); self.set(x+w-1, y+h-1, '+'); for i in range(x + 1, x + w - 1) { self.set(i, y, '-'); self.set(i, y + h - 1, '-'); } for j in range(y + 1, y + h - 1) { self.set(x, j, '|'); self.set(x + w - 1, j, '|'); } for i in range(x+1, x + w - 1) { for j in range(y + 1, y + h - 1) { self.set(i, j, fill); } } } fn draw_line(&mut self, command: &Command) { assert!(command.w == 1 || command.h == 1); let Command { x, y, w, h, fill } = *command; for i in range(x, x+w) { for j in range(y, y+h) { self.set(i, j, fill); } } } } #[test] fn simple_parse() { assert_eq!(Grid::from_str("...").unwrap(), Grid {width: 3, height: 1, chars: "...".chars().collect() }); assert_eq!(Grid::from_str("...\n").unwrap(), Grid {width: 3, height: 1, chars: "...".chars().collect() }); assert_eq!(Grid::from_str("...\n...\n").unwrap(), Grid {width: 3, height: 2, chars: "......".chars().collect() }); assert_eq!(Grid::from_str("...\n...").unwrap(), Grid {width: 3, height: 2, chars: "......".chars().collect() }); assert_eq!(Grid::from_str("abc\ndef\n").unwrap(), Grid {width: 3, height: 2, chars: "abcdef".chars().collect() }); } #[test] fn premature_line_end() { assert_eq!(Grid::from_str("abc\nd"), Err(PrematureLineEnd(2, "d".to_string(), 3))); } #[test] fn unexpected_terminator() { assert_eq!(Grid::from_str("abc\ndefg"), Err(BadTerminationChar(2, "def".to_string(), 'g'))) }
//! RPC interface for the transaction payment module. use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; use pallet_template_runtime_api::SumStorageApi as SumStorageRuntimeApi; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_runtime::{generic::BlockId, traits::Block as BlockT}; use std::sync::Arc; #[rpc] pub trait SumStorageApi<BlockHash> { #[rpc(name = "sumStorage_getSum")] fn get_sum(&self, at: Option<BlockHash>) -> Result<u32>; } /// A struct that implements the `SumStorageApi`. pub struct SumStorage<C, M> { // If you have more generics, no need to SumStorage<C, M, N, P, ...> // just use a tuple like SumStorage<C, (M, N, P, ...)> client: Arc<C>, _marker: std::marker::PhantomData<M>, } impl<C, M> SumStorage<C, M> { /// Create new `SumStorage` instance with the given reference to the client. pub fn new(client: Arc<C>) -> Self { Self { client, _marker: Default::default(), } } } /// Error type of this RPC api. // pub enum Error { // /// The transaction was not decodable. // DecodeError, // /// The call to runtime failed. // RuntimeError, // } // // impl From<Error> for i64 { // fn from(e: Error) -> i64 { // match e { // Error::RuntimeError => 1, // Error::DecodeError => 2, // } // } // } impl<C, Block> SumStorageApi<<Block as BlockT>::Hash> for SumStorage<C, Block> where Block: BlockT, C: Send + Sync + 'static, C: ProvideRuntimeApi<Block>, C: HeaderBackend<Block>, C::Api: SumStorageRuntimeApi<Block>, { fn get_sum(&self, at: Option<<Block as BlockT>::Hash>) -> Result<u32> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash)); let runtime_api_result = api.get_sum(&at); runtime_api_result.map_err(|e| RpcError { code: ErrorCode::ServerError(9876), // No real reason for this value message: "Something wrong".into(), data: Some(format!("{:?}", e).into()), }) } }
#[doc = "Reader of register SSDC1"] pub type R = crate::R<u32, super::SSDC1>; #[doc = "Writer for register SSDC1"] pub type W = crate::W<u32, super::SSDC1>; #[doc = "Register SSDC1 `reset()`'s with value 0"] impl crate::ResetValue for super::SSDC1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `S0DCSEL`"] pub type S0DCSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `S0DCSEL`"] pub struct S0DCSEL_W<'a> { w: &'a mut W, } impl<'a> S0DCSEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `S1DCSEL`"] pub type S1DCSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `S1DCSEL`"] pub struct S1DCSEL_W<'a> { w: &'a mut W, } impl<'a> S1DCSEL_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 << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `S2DCSEL`"] pub type S2DCSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `S2DCSEL`"] pub struct S2DCSEL_W<'a> { w: &'a mut W, } impl<'a> S2DCSEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `S3DCSEL`"] pub type S3DCSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `S3DCSEL`"] pub struct S3DCSEL_W<'a> { w: &'a mut W, } impl<'a> S3DCSEL_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 << 12)) | (((value as u32) & 0x0f) << 12); self.w } } impl R { #[doc = "Bits 0:3 - Sample 0 Digital Comparator Select"] #[inline(always)] pub fn s0dcsel(&self) -> S0DCSEL_R { S0DCSEL_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - Sample 1 Digital Comparator Select"] #[inline(always)] pub fn s1dcsel(&self) -> S1DCSEL_R { S1DCSEL_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - Sample 2 Digital Comparator Select"] #[inline(always)] pub fn s2dcsel(&self) -> S2DCSEL_R { S2DCSEL_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - Sample 3 Digital Comparator Select"] #[inline(always)] pub fn s3dcsel(&self) -> S3DCSEL_R { S3DCSEL_R::new(((self.bits >> 12) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - Sample 0 Digital Comparator Select"] #[inline(always)] pub fn s0dcsel(&mut self) -> S0DCSEL_W { S0DCSEL_W { w: self } } #[doc = "Bits 4:7 - Sample 1 Digital Comparator Select"] #[inline(always)] pub fn s1dcsel(&mut self) -> S1DCSEL_W { S1DCSEL_W { w: self } } #[doc = "Bits 8:11 - Sample 2 Digital Comparator Select"] #[inline(always)] pub fn s2dcsel(&mut self) -> S2DCSEL_W { S2DCSEL_W { w: self } } #[doc = "Bits 12:15 - Sample 3 Digital Comparator Select"] #[inline(always)] pub fn s3dcsel(&mut self) -> S3DCSEL_W { S3DCSEL_W { w: self } } }
// Copyright 2017 Dasein Phaos aka. Luxko // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! resource macro_rules! impl_as_raw { ($Trait: ident, $Type: ident, $Raw: ident) => { impl $Trait for $Type { #[inline] fn as_raw(&self) -> & $Raw { &self.raw } #[inline] fn as_raw_mut(&mut self) ->&mut $Raw { &mut self.raw } } } } pub mod usage; pub use self::usage::*; pub mod description; pub use self::description::*; pub mod heap; pub use self::heap::*; pub mod raw; pub use self::raw::*; pub mod barrier; pub use self::barrier::*; pub mod state; pub use self::state::*; pub mod traits; pub use self::traits::*; pub mod buffer; pub use self::buffer::*; pub mod texture; pub use self::texture::*; use format::*; // TODO: find out a sound way to work with different types of resources #[repr(C)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct ResourceAllocInfo { /// consumed size of the resource on paged heap pub size: u64, pub alignment: ResourceAlignment, } /// describes a resource used for GPU texture copying #[derive(Copy, Clone, Debug)] pub struct TextureCopyLocation { ptr: *mut ::winapi::ID3D12Resource, pub copy_type: TextureCopyType, } impl From<TextureCopyLocation> for ::winapi::D3D12_TEXTURE_COPY_LOCATION { #[inline] fn from(loc: TextureCopyLocation) -> Self { unsafe { let mut ret: Self = ::std::mem::uninitialized(); ret.pResource = loc.ptr; match loc.copy_type { TextureCopyType::SubresourceIndex(idx) => { ret.Type = ::winapi::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; ret.u = ::std::mem::transmute_copy(&idx); }, TextureCopyType::PlacedFootprint(footprint) => { ret.Type = ::winapi::D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; ret.u = ::std::mem::transmute(footprint); }, } ret } } } #[derive(Copy, Clone, Debug)] pub enum TextureCopyType { SubresourceIndex(u32), PlacedFootprint(PlacedSubresourceFootprint), } /// [more info](https://msdn.microsoft.com/library/windows/desktop/dn986749(v=vs.85).aspx) #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct PlacedSubresourceFootprint { /// offset within the parent resource pub offset: u64, pub format: DxgiFormat, pub width: u32, pub height: u32, pub depth: u32, pub row_pitch: u32, } // TODO: reserved resource?
use text_grid::*; fn main() {} pub fn f_ok() -> Cell<impl CellSource> { let s = String::from("ABC"); cell(s) // OK } // fn f_error() -> Cell<impl CellSource> { // let s = String::from("ABC"); // cell(&s) // Error : returns a value referencing data owned by the current function // }