text
stringlengths
8
4.13M
use wasm_bindgen::prelude::*; /// Computes the principal for a loan with fixed-rate interest and fixed payments /// to be paid off in a certain number of payments. /// /// # Arguments /// * interest_rate - The interest rate of the loan per payment period. /// * payment - The payment made each period. /// * num_periods - The number of payment periods. #[wasm_bindgen] pub fn solve_for_principal(interest_rate: f64, payment: f64, num_periods: f64) -> f64 { const EPSILON: f64 = 1e-5; // Initialize upper and lower bound to solution. let mut lo = payment / (1.0 + interest_rate); let mut hi = (payment * num_periods).min(0.8 * payment / interest_rate); let mut n = -1.0; let mut principal = -1.0; while (n - num_periods).abs() > EPSILON { // Update guess to midpoint between upper and lower bound principal = (lo + hi) / 2.0; n = calc_number_of_payments(principal, interest_rate, payment); // Initialize upper or lower bound to solution if n < num_periods { lo = principal } else { hi = principal } } return principal; } /// Computes the number of payments to pay down the principal. /// Returns non-integer values to assist with goal seeking. /// /// # Arguments /// /// * `principal` - The principal of the loan. /// * `interest_rate` - The interest rate of the loan per payment period. /// * `payment` - The payment made each period. #[wasm_bindgen] pub fn calc_number_of_payments(principal: f64, interest_rate: f64, payment: f64) -> f64 { if payment <= principal * interest_rate { panic!("Payment must exceed first interest charge."); } let mut number_of_payments = 0.0; let mut remaining_principal = principal; while remaining_principal > 0.0 { remaining_principal += remaining_principal * interest_rate - payment; number_of_payments += 1.0; } number_of_payments += remaining_principal / payment; return number_of_payments; }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "Devices_Adc_Provider")] pub mod Provider; #[link(name = "windows")] extern "system" {} pub type AdcChannel = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct AdcChannelMode(pub i32); impl AdcChannelMode { pub const SingleEnded: Self = Self(0i32); pub const Differential: Self = Self(1i32); } impl ::core::marker::Copy for AdcChannelMode {} impl ::core::clone::Clone for AdcChannelMode { fn clone(&self) -> Self { *self } } pub type AdcController = *mut ::core::ffi::c_void;
use crate::comms::{CommsMessage, CommsVerifier}; use crate::manager::OnChainIdentity; use crate::primitives::{unix_time, Account, AccountType, Judgement, NetAccount, Result}; use futures::sink::SinkExt; use futures::stream::{SplitSink, SplitStream}; use futures::{StreamExt, TryStreamExt}; use futures_channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}; use serde_json::Value; use std::collections::HashMap; use std::convert::TryFrom; use std::sync::Arc; use tokio::net::TcpStream; use tokio::sync::RwLock; use tokio::time::{self, Duration}; use tokio_tungstenite::{connect_async, WebSocketStream}; use tungstenite::protocol::Message as TungMessage; #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub enum EventType { #[serde(rename = "ack")] Ack, #[serde(rename = "error")] Error, #[serde(rename = "newJudgementRequest")] NewJudgementRequest, #[serde(rename = "judgementResult")] JudgementResult, #[serde(rename = "pendingJudgementsRequest")] PendingJudgementsRequests, #[serde(rename = "pendingJudgementsResponse")] PendingJudgementsResponse, #[serde(rename = "displayNamesRequest")] DisplayNamesRequest, #[serde(rename = "displayNamesResponse")] DisplayNamesResponse, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct Message { pub event: EventType, #[serde(skip_serializing_if = "Value::is_null")] pub data: Value, } impl Message { fn ack(msg: Option<&str>) -> Message { Message { event: EventType::Ack, data: serde_json::to_value(&AckResponse { result: msg.unwrap_or("Message acknowledged").to_string(), }) .unwrap(), } } fn error() -> Message { Message { event: EventType::Error, data: serde_json::to_value(&ErrorResponse { error: "Message is invalid. Rejected".to_string(), }) .unwrap(), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct AckResponse { pub result: String, } #[derive(Debug, Clone, Serialize, Deserialize)] struct ErrorResponse { error: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct JudgementResponse { pub address: NetAccount, pub judgement: Judgement, } #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct JudgementRequest { pub address: NetAccount, pub accounts: HashMap<AccountType, Option<Account>>, } impl TryFrom<JudgementRequest> for OnChainIdentity { type Error = failure::Error; fn try_from(request: JudgementRequest) -> Result<Self> { let mut ident = OnChainIdentity::new(request.address)?; for (account_ty, account) in request.accounts { if let Some(account) = account { ident.push_account(account_ty, account)?; } } Ok(ident) } } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub(crate) struct JudgementGiven { address: NetAccount, result: String, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct DisplayNamesEntry { display_name: Account, address: NetAccount, } #[async_trait] pub trait ConnectorInitTransports<W: ConnectorWriterTransport, R: ConnectorReaderTransport> { type Endpoint; async fn init(endpoint: Self::Endpoint) -> Result<(W, R)>; } #[async_trait] pub trait ConnectorReaderTransport { async fn read(&mut self) -> Result<Option<String>>; } #[async_trait] pub trait ConnectorWriterTransport { async fn write(&mut self, message: &Message) -> Result<()>; } pub struct WebSockets {} #[async_trait] impl ConnectorInitTransports<WebSocketWriter, WebSocketReader> for WebSockets { type Endpoint = String; async fn init(endpoint: Self::Endpoint) -> Result<(WebSocketWriter, WebSocketReader)> { let (sink, stream) = connect_async(endpoint.as_str()).await?.0.split(); Ok((sink.into(), stream.into())) } } pub struct WebSocketReader { reader: SplitStream<WebSocketStream<TcpStream>>, } impl From<SplitStream<WebSocketStream<TcpStream>>> for WebSocketReader { fn from(reader: SplitStream<WebSocketStream<TcpStream>>) -> Self { WebSocketReader { reader: reader } } } #[async_trait] impl ConnectorReaderTransport for WebSocketReader { async fn read(&mut self) -> Result<Option<String>> { if let Some(message) = self.reader.try_next().await? { match message { TungMessage::Text(message) => Ok(Some(message)), _ => Err(failure::err_msg("Not a text message")), } } else { Ok(None) } } } pub struct WebSocketWriter { writer: SplitSink<WebSocketStream<TcpStream>, TungMessage>, } impl From<SplitSink<WebSocketStream<TcpStream>, TungMessage>> for WebSocketWriter { fn from(writer: SplitSink<WebSocketStream<TcpStream>, TungMessage>) -> Self { WebSocketWriter { writer: writer } } } #[async_trait] impl ConnectorWriterTransport for WebSocketWriter { async fn write(&mut self, message: &Message) -> Result<()> { self.writer .send(TungMessage::Text(serde_json::to_string(message)?)) .await .map_err(|err| err.into()) } } pub struct Connector<W, R, P> { writer: W, reader: R, comms: CommsVerifier, endpoint: P, } impl< W: 'static + Send + Sync + ConnectorWriterTransport, R: 'static + Send + Sync + ConnectorReaderTransport, P: 'static + Send + Sync + Clone, > Connector<W, R, P> { pub async fn new<T: ConnectorInitTransports<W, R, Endpoint = P>>( endpoint: P, comms: CommsVerifier, ) -> Result<Self> { let (writer, reader) = T::init(endpoint.clone()).await?; Ok(Connector { writer: writer, reader: reader, comms: comms, endpoint: endpoint, }) } #[cfg(test)] pub fn set_writer_reader(&mut self, writer: W, reader: R) { self.writer = writer; self.reader = reader; } pub async fn start<T: ConnectorInitTransports<W, R, Endpoint = P>>(mut self) { loop { let (mut sender, receiver) = unbounded(); let exit_token = Arc::new(RwLock::new(false)); tokio::spawn(Self::start_comms_receiver( self.comms.clone(), sender.clone(), Arc::clone(&exit_token), )); tokio::spawn(Self::start_websocket_writer( self.writer, self.comms.clone(), receiver, Arc::clone(&exit_token), )); let handle = tokio::spawn(Self::start_websocket_reader( self.reader, self.comms.clone(), sender.clone(), Arc::clone(&exit_token), )); info!("Requesting display names"); sender .send(Message { event: EventType::DisplayNamesRequest, data: serde_json::to_value(Option::<()>::None).unwrap(), }) .await .map_err(|err| { error!("Failed to fetch display names: {}", err); std::process::exit(1); }) .unwrap(); info!("Requesting pending judgments"); sender .send(Message { event: EventType::PendingJudgementsRequests, data: serde_json::to_value(Option::<()>::None).unwrap(), }) .await .map_err(|err| { error!("Failed to fetch pending judgment requests: {}", err); std::process::exit(1); }) .unwrap(); // Wait for the reader to exit, which in return will close the comms // receiver and writer task. This occurs when the connection to the // Watcher is closed. handle.await.unwrap(); let mut interval = time::interval(Duration::from_secs(5)); info!("Trying to reconnect to Watcher..."); loop { interval.tick().await; if let Ok((writer, reader)) = T::init(self.endpoint.clone()).await { info!("Connected successfully to Watcher, spawning tasks"); self.writer = writer; self.reader = reader; break; } else { trace!("Connection to Watcher failed..."); } } } } async fn start_comms_receiver( comms: CommsVerifier, mut sender: UnboundedSender<Message>, exit_token: Arc<RwLock<bool>>, ) { loop { match comms.try_recv() { Some(CommsMessage::JudgeIdentity { net_account, judgement, }) => { sender .send(Message { event: EventType::JudgementResult, data: serde_json::to_value(&JudgementResponse { address: net_account.clone(), judgement: judgement, }) .unwrap(), }) .await .unwrap(); } _ => {} } let t = exit_token.read().await; if *t { debug!("Closing websocket writer task"); break; } } } async fn start_websocket_writer<T: ConnectorWriterTransport>( mut transport: T, _comms: CommsVerifier, mut receiver: UnboundedReceiver<Message>, exit_token: Arc<RwLock<bool>>, ) { let mut last_check = unix_time(); loop { if let Ok(msg) = time::timeout(Duration::from_millis(10), receiver.next()).await { if let Some(msg) = msg { let _ = transport.write(&msg).await.map_err(|err| { error!("{}", err); }); } } // Ping the Watcher every minute. Serves as a keep-alive mechanism. let now = unix_time(); if now >= last_check + 60 { debug!("Keep-alive ping"); let _ = transport .write(&Message { event: EventType::PendingJudgementsRequests, data: serde_json::to_value(Option::<()>::None).unwrap(), }) .await .map_err(|err| { error!("{}", err); }); last_check = now; } let t = exit_token.read().await; if *t { debug!("Closing websocket writer task"); break; } } } async fn start_websocket_reader<T: ConnectorReaderTransport>( mut transport: T, comms: CommsVerifier, mut sender: UnboundedSender<Message>, exit_token: Arc<RwLock<bool>>, ) { use EventType::*; loop { if let Ok(message) = transport.read().await { if let Some(message) = message { trace!("Received message: {:?}", message); let try_msg = serde_json::from_str::<Message>(&message); let msg = if let Ok(msg) = try_msg { msg } else { sender.send(Message::error()).await.unwrap(); return; }; match msg.event { NewJudgementRequest => { info!("Received a new judgement request"); if let Ok(request) = serde_json::from_value::<JudgementRequest>(msg.data) { if let Ok(ident) = OnChainIdentity::try_from(request) { comms.notify_new_identity(ident); sender.send(Message::ack(None)).await.unwrap(); } else { error!("Invalid `newJudgementRequest` message format"); sender.send(Message::error()).await.unwrap(); }; } else { error!("Invalid `newJudgementRequest` message format"); sender.send(Message::error()).await.unwrap(); } } Ack => { if let Ok(msg) = serde_json::from_value::<AckResponse>(msg.data.clone()) { trace!("Received acknowledgement: {}", msg.result); comms.notify_ack(); } else if let Ok(msg) = serde_json::from_value::<JudgementGiven>(msg.data) { if msg.result.to_lowercase() == "judgement given" { info!( "Received judgement acknowledgement for address: {}", msg.address.as_str() ); comms.notify_judgement_given_ack(msg.address) } else { error!("Invalid 'acknowledgement' message format"); } } else { error!("Invalid 'acknowledgement' message format"); } } Error => { if let Ok(msg) = serde_json::from_value::<ErrorResponse>(msg.data) { error!("Received error message: {}", msg.error); } else { error!("Invalid 'error' message format"); } } PendingJudgementsResponse => { trace!("Received pending challenges"); if let Ok(requests) = serde_json::from_value::<Vec<JudgementRequest>>(msg.data) { if requests.is_empty() { trace!("The pending judgement list is empty. Waiting..."); } else { info!("Pending judgement requests: {:?}", requests); } for request in requests { if let Ok(ident) = OnChainIdentity::try_from(request) { sender.send(Message::ack(None)).await.unwrap(); comms.notify_new_identity(ident); sender.send(Message::ack(None)).await.unwrap(); } else { error!("Invalid `newJudgementRequest` message format"); sender.send(Message::error()).await.unwrap(); }; } } else { error!("Invalid `pendingChallengesRequest` message format"); } } DisplayNamesResponse => { trace!("Received display names response"); trace!("Display names {:?}", msg.data); if let Ok(display_names) = serde_json::from_value::<Vec<DisplayNamesEntry>>(msg.data) { comms.notify_existing_display_names( display_names .into_iter() .map(|e| (e.display_name, e.address)) .collect(), ); } else { error!("Invalid `displayNamesResponse` message format"); } } _ => { warn!("Received unrecognized message: '{:?}'", msg); } } } } else { warn!("Connection to Watcher closed"); debug!("Closing websocket reader task"); // Close Comms receiver and client writer tasks. let mut t = exit_token.write().await; *t = true; break; } } } }
#[doc = "Reader of register IER"] pub type R = crate::R<u32, super::IER>; #[doc = "Writer for register IER"] pub type W = crate::W<u32, super::IER>; #[doc = "Register IER `reset()`'s with value 0"] impl crate::ResetValue for super::IER { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Additional number of transactions reload interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TSERFIE_A { #[doc = "0: TSER loaded interrupt masked"] MASKED = 0, #[doc = "1: TSER loaded interrupt not masked"] NOTMASKED = 1, } impl From<TSERFIE_A> for bool { #[inline(always)] fn from(variant: TSERFIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TSERFIE`"] pub type TSERFIE_R = crate::R<bool, TSERFIE_A>; impl TSERFIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TSERFIE_A { match self.bits { false => TSERFIE_A::MASKED, true => TSERFIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == TSERFIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == TSERFIE_A::NOTMASKED } } #[doc = "Write proxy for field `TSERFIE`"] pub struct TSERFIE_W<'a> { w: &'a mut W, } impl<'a> TSERFIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TSERFIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TSER loaded interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(TSERFIE_A::MASKED) } #[doc = "TSER loaded interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(TSERFIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Mode Fault interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MODFIE_A { #[doc = "0: Mode fault interrupt masked"] MASKED = 0, #[doc = "1: Mode fault interrupt not masked"] NOTMASKED = 1, } impl From<MODFIE_A> for bool { #[inline(always)] fn from(variant: MODFIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `MODFIE`"] pub type MODFIE_R = crate::R<bool, MODFIE_A>; impl MODFIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MODFIE_A { match self.bits { false => MODFIE_A::MASKED, true => MODFIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == MODFIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == MODFIE_A::NOTMASKED } } #[doc = "Write proxy for field `MODFIE`"] pub struct MODFIE_W<'a> { w: &'a mut W, } impl<'a> MODFIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MODFIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Mode fault interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(MODFIE_A::MASKED) } #[doc = "Mode fault interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(MODFIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "TIFRE interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIFREIE_A { #[doc = "0: TI frame format error interrupt masked"] MASKED = 0, #[doc = "1: TI frame format error interrupt not masked"] NOTMASKED = 1, } impl From<TIFREIE_A> for bool { #[inline(always)] fn from(variant: TIFREIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIFREIE`"] pub type TIFREIE_R = crate::R<bool, TIFREIE_A>; impl TIFREIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIFREIE_A { match self.bits { false => TIFREIE_A::MASKED, true => TIFREIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == TIFREIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == TIFREIE_A::NOTMASKED } } #[doc = "Write proxy for field `TIFREIE`"] pub struct TIFREIE_W<'a> { w: &'a mut W, } impl<'a> TIFREIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIFREIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TI frame format error interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(TIFREIE_A::MASKED) } #[doc = "TI frame format error interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(TIFREIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "CRC Interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CRCEIE_A { #[doc = "0: CRC error interrupt masked"] MASKED = 0, #[doc = "1: CRC error interrupt not masked"] NOTMASKED = 1, } impl From<CRCEIE_A> for bool { #[inline(always)] fn from(variant: CRCEIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CRCEIE`"] pub type CRCEIE_R = crate::R<bool, CRCEIE_A>; impl CRCEIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CRCEIE_A { match self.bits { false => CRCEIE_A::MASKED, true => CRCEIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == CRCEIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == CRCEIE_A::NOTMASKED } } #[doc = "Write proxy for field `CRCEIE`"] pub struct CRCEIE_W<'a> { w: &'a mut W, } impl<'a> CRCEIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CRCEIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "CRC error interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(CRCEIE_A::MASKED) } #[doc = "CRC error interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(CRCEIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "OVR interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OVRIE_A { #[doc = "0: Overrun interrupt masked"] MASKED = 0, #[doc = "1: Overrun interrupt not masked"] NOTMASKED = 1, } impl From<OVRIE_A> for bool { #[inline(always)] fn from(variant: OVRIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `OVRIE`"] pub type OVRIE_R = crate::R<bool, OVRIE_A>; impl OVRIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OVRIE_A { match self.bits { false => OVRIE_A::MASKED, true => OVRIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == OVRIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == OVRIE_A::NOTMASKED } } #[doc = "Write proxy for field `OVRIE`"] pub struct OVRIE_W<'a> { w: &'a mut W, } impl<'a> OVRIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OVRIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Overrun interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(OVRIE_A::MASKED) } #[doc = "Overrun interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(OVRIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "UDR interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum UDRIE_A { #[doc = "0: Underrun interrupt masked"] MASKED = 0, #[doc = "1: Underrun interrupt not masked"] NOTMASKED = 1, } impl From<UDRIE_A> for bool { #[inline(always)] fn from(variant: UDRIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `UDRIE`"] pub type UDRIE_R = crate::R<bool, UDRIE_A>; impl UDRIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> UDRIE_A { match self.bits { false => UDRIE_A::MASKED, true => UDRIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == UDRIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == UDRIE_A::NOTMASKED } } #[doc = "Write proxy for field `UDRIE`"] pub struct UDRIE_W<'a> { w: &'a mut W, } impl<'a> UDRIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: UDRIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Underrun interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(UDRIE_A::MASKED) } #[doc = "Underrun interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(UDRIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "TXTFIE interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXTFIE_A { #[doc = "0: Transmission transfer filled interrupt masked"] MASKED = 0, #[doc = "1: Transmission transfer filled interrupt not masked"] NOTMASKED = 1, } impl From<TXTFIE_A> for bool { #[inline(always)] fn from(variant: TXTFIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TXTFIE`"] pub type TXTFIE_R = crate::R<bool, TXTFIE_A>; impl TXTFIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TXTFIE_A { match self.bits { false => TXTFIE_A::MASKED, true => TXTFIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == TXTFIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == TXTFIE_A::NOTMASKED } } #[doc = "Write proxy for field `TXTFIE`"] pub struct TXTFIE_W<'a> { w: &'a mut W, } impl<'a> TXTFIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TXTFIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Transmission transfer filled interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(TXTFIE_A::MASKED) } #[doc = "Transmission transfer filled interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(TXTFIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "EOT, SUSP and TXC interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOTIE_A { #[doc = "0: End-of-transfer interrupt masked"] MASKED = 0, #[doc = "1: End-of-transfer interrupt not masked"] NOTMASKED = 1, } impl From<EOTIE_A> for bool { #[inline(always)] fn from(variant: EOTIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EOTIE`"] pub type EOTIE_R = crate::R<bool, EOTIE_A>; impl EOTIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EOTIE_A { match self.bits { false => EOTIE_A::MASKED, true => EOTIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == EOTIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == EOTIE_A::NOTMASKED } } #[doc = "Write proxy for field `EOTIE`"] pub struct EOTIE_W<'a> { w: &'a mut W, } impl<'a> EOTIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EOTIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "End-of-transfer interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(EOTIE_A::MASKED) } #[doc = "End-of-transfer interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(EOTIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "DXP interrupt enabled\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DXPIE_A { #[doc = "0: Duplex transfer complete interrupt masked"] MASKED = 0, #[doc = "1: Duplex transfer complete interrupt not masked"] NOTMASKED = 1, } impl From<DXPIE_A> for bool { #[inline(always)] fn from(variant: DXPIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DXPIE`"] pub type DXPIE_R = crate::R<bool, DXPIE_A>; impl DXPIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DXPIE_A { match self.bits { false => DXPIE_A::MASKED, true => DXPIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == DXPIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == DXPIE_A::NOTMASKED } } #[doc = "Write proxy for field `DXPIE`"] pub struct DXPIE_W<'a> { w: &'a mut W, } impl<'a> DXPIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DXPIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Duplex transfer complete interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(DXPIE_A::MASKED) } #[doc = "Duplex transfer complete interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(DXPIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "TXP interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXPIE_A { #[doc = "0: TX space available interrupt masked"] MASKED = 0, #[doc = "1: TX space available interrupt not masked"] NOTMASKED = 1, } impl From<TXPIE_A> for bool { #[inline(always)] fn from(variant: TXPIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TXPIE`"] pub type TXPIE_R = crate::R<bool, TXPIE_A>; impl TXPIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TXPIE_A { match self.bits { false => TXPIE_A::MASKED, true => TXPIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == TXPIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == TXPIE_A::NOTMASKED } } #[doc = "Write proxy for field `TXPIE`"] pub struct TXPIE_W<'a> { w: &'a mut W, } impl<'a> TXPIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TXPIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TX space available interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(TXPIE_A::MASKED) } #[doc = "TX space available interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(TXPIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "RXP Interrupt Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXPIE_A { #[doc = "0: RX data available interrupt masked"] MASKED = 0, #[doc = "1: RX data available interrupt not masked"] NOTMASKED = 1, } impl From<RXPIE_A> for bool { #[inline(always)] fn from(variant: RXPIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RXPIE`"] pub type RXPIE_R = crate::R<bool, RXPIE_A>; impl RXPIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXPIE_A { match self.bits { false => RXPIE_A::MASKED, true => RXPIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == RXPIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == RXPIE_A::NOTMASKED } } #[doc = "Write proxy for field `RXPIE`"] pub struct RXPIE_W<'a> { w: &'a mut W, } impl<'a> RXPIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RXPIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "RX data available interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(RXPIE_A::MASKED) } #[doc = "RX data available interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(RXPIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 10 - Additional number of transactions reload interrupt enable"] #[inline(always)] pub fn tserfie(&self) -> TSERFIE_R { TSERFIE_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - Mode Fault interrupt enable"] #[inline(always)] pub fn modfie(&self) -> MODFIE_R { MODFIE_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - TIFRE interrupt enable"] #[inline(always)] pub fn tifreie(&self) -> TIFREIE_R { TIFREIE_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - CRC Interrupt enable"] #[inline(always)] pub fn crceie(&self) -> CRCEIE_R { CRCEIE_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - OVR interrupt enable"] #[inline(always)] pub fn ovrie(&self) -> OVRIE_R { OVRIE_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5 - UDR interrupt enable"] #[inline(always)] pub fn udrie(&self) -> UDRIE_R { UDRIE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - TXTFIE interrupt enable"] #[inline(always)] pub fn txtfie(&self) -> TXTFIE_R { TXTFIE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - EOT, SUSP and TXC interrupt enable"] #[inline(always)] pub fn eotie(&self) -> EOTIE_R { EOTIE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - DXP interrupt enabled"] #[inline(always)] pub fn dxpie(&self) -> DXPIE_R { DXPIE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - TXP interrupt enable"] #[inline(always)] pub fn txpie(&self) -> TXPIE_R { TXPIE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - RXP Interrupt Enable"] #[inline(always)] pub fn rxpie(&self) -> RXPIE_R { RXPIE_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 10 - Additional number of transactions reload interrupt enable"] #[inline(always)] pub fn tserfie(&mut self) -> TSERFIE_W { TSERFIE_W { w: self } } #[doc = "Bit 9 - Mode Fault interrupt enable"] #[inline(always)] pub fn modfie(&mut self) -> MODFIE_W { MODFIE_W { w: self } } #[doc = "Bit 8 - TIFRE interrupt enable"] #[inline(always)] pub fn tifreie(&mut self) -> TIFREIE_W { TIFREIE_W { w: self } } #[doc = "Bit 7 - CRC Interrupt enable"] #[inline(always)] pub fn crceie(&mut self) -> CRCEIE_W { CRCEIE_W { w: self } } #[doc = "Bit 6 - OVR interrupt enable"] #[inline(always)] pub fn ovrie(&mut self) -> OVRIE_W { OVRIE_W { w: self } } #[doc = "Bit 5 - UDR interrupt enable"] #[inline(always)] pub fn udrie(&mut self) -> UDRIE_W { UDRIE_W { w: self } } #[doc = "Bit 4 - TXTFIE interrupt enable"] #[inline(always)] pub fn txtfie(&mut self) -> TXTFIE_W { TXTFIE_W { w: self } } #[doc = "Bit 3 - EOT, SUSP and TXC interrupt enable"] #[inline(always)] pub fn eotie(&mut self) -> EOTIE_W { EOTIE_W { w: self } } #[doc = "Bit 2 - DXP interrupt enabled"] #[inline(always)] pub fn dxpie(&mut self) -> DXPIE_W { DXPIE_W { w: self } } #[doc = "Bit 1 - TXP interrupt enable"] #[inline(always)] pub fn txpie(&mut self) -> TXPIE_W { TXPIE_W { w: self } } #[doc = "Bit 0 - RXP Interrupt Enable"] #[inline(always)] pub fn rxpie(&mut self) -> RXPIE_W { RXPIE_W { w: self } } }
use std::fmt::Write; fn main() { let n: usize = read(); let mut vec: Vec<i32> = read_as_vec(); build_max_heap(n, &mut vec); println!(" {}", join(' ', &vec)); } fn build_max_heap(len: usize, slice: &mut [i32]) { for i in (0..(len / 2)).rev() { max_heapify(len, slice, i); } } fn max_heapify(len: usize, slice: &mut [i32], idx: usize) { let left = idx * 2 + 1; let right = idx * 2 + 2; let me = slice[idx]; if right < len { // 子ノードが2つ let max = if slice[left] > slice[right] { left } else { right }; if slice[max] > me { slice[idx] = slice[max]; slice[max] = me; max_heapify(len, slice, max); } } else if left < len { // 子ノードが1つ if slice[left] > me { slice[idx] = slice[left]; slice[left] = me; max_heapify(len, slice, left); } } } fn read<T: std::str::FromStr>() -> T { let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); input.trim().parse::<T>().ok().unwrap() } fn read_as_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>() .split_whitespace() .map(|e| e.parse::<T>().ok().unwrap()) .collect() } fn join<T: std::fmt::Display>(delimiter: char, arr: &[T]) -> String { let mut text = String::new(); for e in arr.iter() { write!(text, "{}", e).unwrap(); text.push(delimiter); } text.pop(); text } #[cfg(test)] mod tests { use super::*; #[test] fn test_build_max_heap_1() { let len: usize = 10; let mut vec: Vec<i32> = vec![4, 1, 3, 2, 16, 9, 10, 14, 8, 7]; build_max_heap(len, &mut vec); assert_eq!(vec![16, 14, 10, 8, 7, 9, 3, 2, 4, 1], vec); } #[test] fn test_build_max_heap_2() { let len: usize = 16; let mut vec: Vec<i32> = vec![-1000000000, 88, 6, 3, 100, 4, 5, 7, 15, 21, 50, 999999999, 53, 23, 8, 18]; build_max_heap(len, &mut vec); assert_eq!(vec![999999999, 100, 53, 18, 88, 6, 23, 7, 15, 21, 50, 4, -1000000000, 5, 8, 3], vec); } }
pub fn run() -> String{ return format!("Dara é doida!"); }
// 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 common_base::base::GlobalInstance; use common_base::runtime::GlobalIORuntime; use common_exception::Result; use crate::accessor::SharingAccessor; use crate::configs::Config; // hold singleton services. pub struct SharingServices {} impl SharingServices { pub async fn init(config: Config) -> Result<()> { // init global instance singleton GlobalInstance::init_production(); GlobalIORuntime::init(config.storage.num_cpus as usize)?; SharingAccessor::init(&config).await } }
use std::os; use std::io; fn main() { let args = os::args(); let _prog = args[0].clone(); let src_file = args[1].clone(); let exec_args = args.slice_from(2); match io::Command::new("rustc").arg("-o").arg("/tmp/rust-exe").arg(src_file).spawn() { Ok(mut p) => { let output = p.stdout.get_mut_ref().read_to_string().unwrap() + p.stderr.get_mut_ref().read_to_string().unwrap(); if output.len() != 0 { println!("COMPILE:\n================================================================================"); print!("{}", output); if output.as_slice().contains("error:") { return; } println!("\nEXECUTE:\n================================================================================"); } }, Err(e) => fail!("failed to execute process: {}", e), }; match io::Command::new("/tmp/rust-exe").args(exec_args.as_slice()).spawn() { Ok(mut p) => { let output = p.stdout.get_mut_ref().read_to_string().unwrap() + p.stderr.get_mut_ref().read_to_string().unwrap(); if output.len() != 0 { print!("{}", output); } }, Err(e) => fail!("failed to execute process: {}", e), }; }
use proconio::input; fn main() { input! { n: i32, m: i32, t: i32, ab: [(i32, i32); m] } let mut ans = true; let mut rest: i32 = n; let mut time = 0; for (a,b) in ab.into_iter(){ rest += time - a; time = a; if rest < 1{ ans = false; break; } rest += b - a; rest = std::cmp::min(n, rest); time = b; } rest += time - t; if rest < 1{ ans = false; } println!("{}",if ans {"Yes"} else {"No"}) }
#![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; #[ink::contract] mod kingsman { #[cfg(not(feature = "ink-as-dependency"))] use ink_storage::Lazy; #[cfg(not(feature = "ink-as-dependency"))] use ink_env::call::FromAccountId; use accountbook::AccountBook; use debtpool::SDP; #[ink(storage)] pub struct Kingsman { account_book: Lazy<AccountBook>, sdp: Lazy<SDP>, owner: AccountId, } #[ink(event)] pub struct Swap { #[ink(topic)] trader: AccountId, #[ink(topic)] old_asset: AccountId, #[ink(topic)] new_asset: AccountId, swap_amount: Balance, in_debtpool: bool, } impl Kingsman { #[ink(constructor)] pub fn new(accountbook_account: AccountId, debtpool_account: AccountId) -> Self { let account_book: AccountBook = FromAccountId::from_account_id(accountbook_account); let sdp:SDP = FromAccountId::from_account_id(debtpool_account); Self { account_book: Lazy::new(account_book), sdp: Lazy::new(sdp), owner: Self::env().caller(), } } #[ink(message)] pub fn swap(&mut self, old_asset: AccountId, new_asset: AccountId, swap_amount: Balance, in_debtpool: bool) { assert_ne!(old_asset, Default::default()); assert_ne!(new_asset, Default::default()); assert!(swap_amount > 0); let caller = self.env().caller(); if in_debtpool { self.sdp.swap_in_sdp(caller, old_asset, new_asset, swap_amount); } else { self.account_book.swap(caller, old_asset, new_asset, swap_amount); self.sdp.swap_not_in_sdp(old_asset, new_asset, swap_amount); } self.env().emit_event(Swap { trader: caller, old_asset, new_asset, swap_amount, in_debtpool, }); } #[ink(message)] pub fn transfer_ownership(&mut self, new_owner: AccountId) { assert_eq!(self.owner, self.env().caller()); assert_ne!(new_owner, Default::default()); self.owner = new_owner; } } }
pub const DEFAULT_ACTION_ENV: &str = "SNAPSHOTS"; /// Test action, see [`Assert`][crate::Assert] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Action { /// Do not run the test Skip, /// Ignore test failures Ignore, /// Fail on mismatch Verify, /// Overwrite on mismatch Overwrite, } impl Action { pub fn with_env_var(var: impl AsRef<std::ffi::OsStr>) -> Option<Self> { let var = var.as_ref(); let value = std::env::var_os(var)?; Self::with_env_value(value) } pub fn with_env_value(value: impl AsRef<std::ffi::OsStr>) -> Option<Self> { let value = value.as_ref(); match value.to_str()? { "skip" => Some(Action::Skip), "ignore" => Some(Action::Ignore), "verify" => Some(Action::Verify), "overwrite" => Some(Action::Overwrite), _ => None, } } } impl Default for Action { fn default() -> Self { Self::Verify } }
use crate::mechanics::damage::{Damage, DamageValue}; use crate::mechanics::damage::deal_damage::DealDamage; use crate::monsters::Monster; use crate::types::MonsterType; pub struct SeaSerpent { strength: DamageValue, } impl SeaSerpent { pub fn new(strength: DamageValue) -> Self { SeaSerpent { strength } } } impl Monster for SeaSerpent { fn primary_type(&self) -> MonsterType { MonsterType::WATER } fn secondary_type(&self) -> Option<MonsterType> { None } } impl DealDamage for SeaSerpent { fn deal_damage(&self) -> Damage { Damage::new(self.strength) } }
use amethyst::{ assets::{Handle, Prefab}, core::Transform, prelude::{Builder, World, WorldExt}, window::ScreenDimensions, }; use crate::components::{animation, Player}; pub fn init_player( world: &mut World, prefab: Handle<Prefab<animation::AnimationPrefabData>>, dimensions: &ScreenDimensions, ) { let mut transform = Transform::default(); transform.set_translation_xyz(dimensions.width() * 0.5, dimensions.height() * 0.5, 0.); world .create_entity() .with(animation::Animation::new( animation::AnimationId::Idle, vec![animation::AnimationId::Idle, animation::AnimationId::MoveLeft, animation::AnimationId::MoveRight, animation::AnimationId::MoveUp, animation::AnimationId::MoveDown], )) .with(prefab) .with(Player::new()) .with(transform) .build(); }
use crate::{addrs::BindAddresses, ServerType, UdpCapture}; use http::{header::HeaderName, HeaderValue}; use observability_deps::tracing::info; use rand::Rng; use std::{collections::HashMap, num::NonZeroUsize, path::Path, sync::Arc}; use tempfile::TempDir; /// Options for creating test servers (`influxdb_iox` processes) #[derive(Debug, Clone)] pub struct TestConfig { /// environment variables to pass to server process. HashMap to avoid duplication env: HashMap<String, String>, /// Headers to add to all client requests client_headers: Vec<(HeaderName, HeaderValue)>, /// Server type server_type: ServerType, /// Catalog DSN value. Required unless you're running all-in-one in ephemeral mode. dsn: Option<String>, /// Catalog schema name catalog_schema_name: String, /// Object store directory, if needed. object_store_dir: Option<Arc<TempDir>>, /// WAL directory, if needed. wal_dir: Option<Arc<TempDir>>, /// Catalog directory, if needed catalog_dir: Option<Arc<TempDir>>, /// Which ports this server should use addrs: Arc<BindAddresses>, } impl TestConfig { /// Create a new TestConfig. Tests should use one of the specific /// configuration setup below, such as [new_router](Self::new_router). fn new( server_type: ServerType, dsn: Option<String>, catalog_schema_name: impl Into<String>, ) -> Self { let catalog_schema_name = catalog_schema_name.into(); let (dsn, catalog_dir) = specialize_dsn_if_needed(dsn, &catalog_schema_name); Self { env: HashMap::new(), client_headers: vec![], server_type, dsn, catalog_schema_name, object_store_dir: None, wal_dir: None, catalog_dir, addrs: Arc::new(BindAddresses::default()), } } /// Creates a new TestConfig of `server_type` with the same catalog as `other` fn new_with_existing_catalog(server_type: ServerType, other: &TestConfig) -> Self { Self::new( server_type, other.dsn.clone(), other.catalog_schema_name.clone(), ) // also copy a reference to the temp dir, if any, so it isn't // deleted too soon .with_catalog_dir(other.catalog_dir.as_ref().map(Arc::clone)) } /// Create a minimal router2 configuration sharing configuration with the ingester2 config pub fn new_router(ingester_config: &TestConfig) -> Self { assert_eq!(ingester_config.server_type(), ServerType::Ingester); Self::new_with_existing_catalog(ServerType::Router, ingester_config) .with_existing_object_store(ingester_config) .with_ingester_addresses(&[ingester_config.ingester_base()]) } /// Create a minimal ingester configuration, using the dsn configuration specified. Set the /// persistence options such that it will persist as quickly as possible. pub fn new_ingester(dsn: impl Into<String>) -> Self { let dsn = Some(dsn.into()); Self::new(ServerType::Ingester, dsn, random_catalog_schema_name()) .with_new_object_store() .with_new_wal() .with_env("INFLUXDB_IOX_WAL_ROTATION_PERIOD_SECONDS", "1") } /// Create a minimal ingester configuration, using the dsn configuration specified. Set the /// persistence options such that it will likely never persist, to be able to test when data /// only exists in the ingester's memory. pub fn new_ingester_never_persist(dsn: impl Into<String>) -> Self { let dsn = Some(dsn.into()); Self::new(ServerType::Ingester, dsn, random_catalog_schema_name()) .with_new_object_store() .with_new_wal() // I didn't run my tests for a day, because that would be too long .with_env("INFLUXDB_IOX_WAL_ROTATION_PERIOD_SECONDS", "86400") } /// Create another ingester with the same dsn, catalog schema name, and object store, but with /// its own WAL directory and own addresses. pub fn another_ingester(ingester_config: &TestConfig) -> Self { Self { env: ingester_config.env.clone(), client_headers: ingester_config.client_headers.clone(), server_type: ServerType::Ingester, dsn: ingester_config.dsn.clone(), catalog_schema_name: ingester_config.catalog_schema_name.clone(), object_store_dir: None, wal_dir: None, catalog_dir: ingester_config.catalog_dir.as_ref().map(Arc::clone), addrs: Arc::new(BindAddresses::default()), } .with_existing_object_store(ingester_config) .with_new_wal() } /// Create a minimal querier configuration from the specified ingester configuration, using /// the same dsn and object store, and pointing at the specified ingester. pub fn new_querier(ingester_config: &TestConfig) -> Self { assert_eq!(ingester_config.server_type(), ServerType::Ingester); Self::new_querier_without_ingester(ingester_config) .with_ingester_addresses(&[ingester_config.ingester_base()]) } /// Create a minimal compactor configuration, using the dsn configuration from other pub fn new_compactor(other: &TestConfig) -> Self { Self::new_with_existing_catalog(ServerType::Compactor, other) .with_existing_object_store(other) } /// Create a minimal querier configuration from the specified ingester configuration, using /// the same dsn and object store, but without specifying the ingester addresses pub fn new_querier_without_ingester(ingester_config: &TestConfig) -> Self { Self::new_with_existing_catalog(ServerType::Querier, ingester_config) .with_existing_object_store(ingester_config) // Hard code query threads so query plans do not vary based on environment .with_env("INFLUXDB_IOX_NUM_QUERY_THREADS", "4") .with_env( "INFLUXDB_IOX_DATAFUSION_CONFIG", "iox.influxql_metadata_cutoff:1990-01-01T00:00:00Z", ) } /// Create a minimal all in one configuration pub fn new_all_in_one(dsn: Option<String>) -> Self { Self::new(ServerType::AllInOne, dsn, random_catalog_schema_name()).with_new_object_store() } /// Create a minimal all in one configuration with the specified /// data directory (`--data_dir = <data_dir>`) /// /// the data_dir has a file based object store and sqlite catalog pub fn new_all_in_one_with_data_dir(data_dir: &Path) -> Self { let dsn = None; // use default sqlite catalog in data_dir let data_dir_str = data_dir.as_os_str().to_str().unwrap(); Self::new(ServerType::AllInOne, dsn, random_catalog_schema_name()) .with_env("INFLUXDB_IOX_DB_DIR", data_dir_str) } /// Set the number of failed ingester queries before the querier considers /// the ingester to be dead. pub fn with_querier_circuit_breaker_threshold(self, count: usize) -> Self { assert!(count > 0); self.with_env( "INFLUXDB_IOX_INGESTER_CIRCUIT_BREAKER_THRESHOLD", count.to_string(), ) } /// Configure tracing capture pub fn with_tracing(self, udp_capture: &UdpCapture) -> Self { self.with_env("TRACES_EXPORTER", "jaeger") .with_env("TRACES_EXPORTER_JAEGER_AGENT_HOST", udp_capture.ip()) .with_env("TRACES_EXPORTER_JAEGER_AGENT_PORT", udp_capture.port()) .with_env( "TRACES_EXPORTER_JAEGER_TRACE_CONTEXT_HEADER_NAME", "custom-trace-header", ) .with_client_header("custom-trace-header", "4:3:2:1") .with_env("INFLUXDB_IOX_COMPACTION_PARTITION_TRACE", "all") } /// Configure a custom debug name for tracing pub fn with_tracing_debug_name(self, custom_debug_name: &str) -> Self { // setup a custom debug name (to ensure it gets plumbed through) self.with_env("TRACES_EXPORTER_JAEGER_DEBUG_NAME", custom_debug_name) .with_client_header(custom_debug_name, "some-debug-id") } pub fn with_ingester_addresses( self, ingester_addresses: &[impl std::borrow::Borrow<str>], ) -> Self { self.with_env( "INFLUXDB_IOX_INGESTER_ADDRESSES", ingester_addresses.join(","), ) } pub fn with_rpc_write_replicas(self, rpc_write_replicas: NonZeroUsize) -> Self { self.with_env( "INFLUXDB_IOX_RPC_WRITE_REPLICAS", rpc_write_replicas.get().to_string(), ) } pub fn with_ingester_never_persist(self) -> Self { self.with_env("INFLUXDB_IOX_WAL_ROTATION_PERIOD_SECONDS", "86400") } /// Configure the single tenancy mode, including the authorization server. pub fn with_single_tenancy(self, addr: impl Into<String>) -> Self { self.with_env("INFLUXDB_IOX_AUTHZ_ADDR", addr) .with_env("INFLUXDB_IOX_SINGLE_TENANCY", "true") } // Get the catalog DSN URL if set. pub fn dsn(&self) -> &Option<String> { &self.dsn } // Get the catalog postgres schema name pub fn catalog_schema_name(&self) -> &str { &self.catalog_schema_name } /// Retrieve the directory used to write WAL files to, if set pub fn wal_dir(&self) -> &Option<Arc<TempDir>> { &self.wal_dir } /// Retrieve the directory used for object store, if set pub fn object_store_dir(&self) -> &Option<Arc<TempDir>> { &self.object_store_dir } // copy a reference to the catalog temp dir, if any fn with_catalog_dir(mut self, catalog_dir: Option<Arc<TempDir>>) -> Self { self.catalog_dir = catalog_dir; self } /// add a name=value environment variable when starting the server /// /// Should not be called directly, but instead all mapping to /// environment variables should be done via this structure fn with_env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self { self.env.insert(name.into(), value.into()); self } /// copy the specified environment variables from other; Panic's if they do not exist. /// /// Should not be called directly, but instead all mapping to /// environment variables should be done via this structure fn copy_env(self, name: impl Into<String>, other: &TestConfig) -> Self { let name = name.into(); let value = match other.env.get(&name) { Some(v) => v.clone(), None => panic!( "Cannot copy {} from existing config. Available values are: {:#?}", name, other.env ), }; self.with_env(name, value) } /// add a name=value http header to all client requests made to the server fn with_client_header(mut self, name: impl AsRef<str>, value: impl AsRef<str>) -> Self { self.client_headers.push(( name.as_ref().parse().expect("valid header name"), value.as_ref().parse().expect("valid header value"), )); self } /// Configures a new WAL fn with_new_wal(mut self) -> Self { let tmpdir = TempDir::new().expect("cannot create tmp dir"); let wal_string = tmpdir.path().display().to_string(); self.wal_dir = Some(Arc::new(tmpdir)); self.with_env("INFLUXDB_IOX_WAL_DIRECTORY", wal_string) } /// Configures a new object store fn with_new_object_store(mut self) -> Self { let tmpdir = TempDir::new().expect("cannot create tmp dir"); let object_store_string = tmpdir.path().display().to_string(); self.object_store_dir = Some(Arc::new(tmpdir)); self.with_env("INFLUXDB_IOX_OBJECT_STORE", "file") .with_env("INFLUXDB_IOX_DB_DIR", object_store_string) } /// Configures this TestConfig to use the same object store as other fn with_existing_object_store(mut self, other: &TestConfig) -> Self { // copy a reference to the temp dir, if any self.object_store_dir = other.object_store_dir.clone(); self.copy_env("INFLUXDB_IOX_OBJECT_STORE", other) .copy_env("INFLUXDB_IOX_DB_DIR", other) } /// Configure maximum per-table query bytes for the querier. pub fn with_querier_mem_pool_bytes(self, bytes: usize) -> Self { self.with_env("INFLUXDB_IOX_EXEC_MEM_POOL_BYTES", bytes.to_string()) } /// Configure sharding splits for the compactor. pub fn with_compactor_shards(self, n_shards: usize, shard_id: usize) -> Self { self.with_env("INFLUXDB_IOX_COMPACTION_SHARD_COUNT", n_shards.to_string()) .with_env("INFLUXDB_IOX_COMPACTION_SHARD_ID", shard_id.to_string()) } /// Get the test config's server type. #[must_use] pub fn server_type(&self) -> ServerType { self.server_type } /// Get a reference to the test config's env. pub fn env(&self) -> impl Iterator<Item = (&str, &str)> { self.env.iter().map(|(k, v)| (k.as_str(), v.as_str())) } /// Get a reference to the test config's client headers. #[must_use] pub fn client_headers(&self) -> &[(HeaderName, HeaderValue)] { self.client_headers.as_ref() } /// Get a reference to the test config's addrs. #[must_use] pub fn addrs(&self) -> &BindAddresses { &self.addrs } /// return the base ingester gRPC address, such as /// `http://localhost:8082/` pub fn ingester_base(&self) -> Arc<str> { self.addrs().ingester_grpc_api().client_base() } } fn random_catalog_schema_name() -> String { let mut rng = rand::thread_rng(); (&mut rng) .sample_iter(rand::distributions::Alphanumeric) .filter(|c| c.is_ascii_alphabetic()) .take(20) .map(char::from) .collect::<String>() } /// Rewrites the special "sqlite" catalog DSN to a new /// temporary sqlite filename in a new temporary directory such as /// /// sqlite:///tmp/XygUWHUwBhSdIUNXblXo.sqlite /// /// /// This is needed to isolate different test runs from each other /// (there is no "schema" within a sqlite database, it is the name of /// the file). /// /// returns (dsn, catalog_dir) fn specialize_dsn_if_needed( dsn: Option<String>, catalog_schema_name: &str, ) -> (Option<String>, Option<Arc<TempDir>>) { if dsn.as_deref() == Some("sqlite") { let tmpdir = TempDir::new().expect("cannot create tmp dir for catalog"); let catalog_dir = Arc::new(tmpdir); let dsn = format!( "sqlite://{}/{catalog_schema_name}.sqlite", catalog_dir.path().display() ); info!(%dsn, "rewrote 'sqlite' to temporary file"); (Some(dsn), Some(catalog_dir)) } else { (dsn, None) } }
// Copyright 2016 Jeffrey Burdges and David Stainton //! Sphinx mixnet packet crypto extern crate crypto; #[macro_use] extern crate arrayref; pub mod node; pub mod crypto_primitives; pub use crypto_primitives::{GroupCurve25519, SphinxDigest}; #[cfg(test)] mod tests { #[test] fn it_works() { } }
//! Contains a structure to map from strings to integer symbols based on //! string interning. use std::convert::TryFrom; use arrow::array::{Array, ArrayDataBuilder, DictionaryArray}; use arrow::buffer::NullBuffer; use arrow::datatypes::{DataType, Int32Type}; use hashbrown::HashMap; use num_traits::{AsPrimitive, FromPrimitive, Zero}; use snafu::Snafu; use crate::string::PackedStringArray; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("duplicate key found {}", key))] DuplicateKeyFound { key: String }, } /// A String dictionary that builds on top of `PackedStringArray` adding O(1) /// index lookups for a given string /// /// Heavily inspired by the string-interner crate #[derive(Debug, Clone)] pub struct StringDictionary<K> { hash: ahash::RandomState, /// Used to provide a lookup from string value to key type /// /// Note: K's hash implementation is not used, instead the raw entry /// API is used to store keys w.r.t the hash of the strings themselves /// dedup: HashMap<K, (), ()>, /// Used to store strings storage: PackedStringArray<K>, } impl<K: AsPrimitive<usize> + FromPrimitive + Zero> Default for StringDictionary<K> { fn default() -> Self { Self { hash: ahash::RandomState::new(), dedup: Default::default(), storage: PackedStringArray::new(), } } } impl<K: AsPrimitive<usize> + FromPrimitive + Zero> StringDictionary<K> { pub fn new() -> Self { Default::default() } pub fn with_capacity(keys: usize, values: usize) -> StringDictionary<K> { Self { hash: Default::default(), dedup: HashMap::with_capacity_and_hasher(keys, ()), storage: PackedStringArray::with_capacity(keys, values), } } /// Returns the id corresponding to value, adding an entry for the /// id if it is not yet present in the dictionary. pub fn lookup_value_or_insert(&mut self, value: &str) -> K { use hashbrown::hash_map::RawEntryMut; let hasher = &self.hash; let storage = &mut self.storage; let hash = hash_str(hasher, value); let entry = self .dedup .raw_entry_mut() .from_hash(hash, |key| value == storage.get(key.as_()).unwrap()); match entry { RawEntryMut::Occupied(entry) => *entry.into_key(), RawEntryMut::Vacant(entry) => { let index = storage.append(value); let key = K::from_usize(index).expect("failed to fit string index into dictionary key"); *entry .insert_with_hasher(hash, key, (), |key| { let string = storage.get(key.as_()).unwrap(); hash_str(hasher, string) }) .0 } } } /// Returns the ID in self.dictionary that corresponds to `value`, if any. pub fn lookup_value(&self, value: &str) -> Option<K> { let hash = hash_str(&self.hash, value); self.dedup .raw_entry() .from_hash(hash, |key| value == self.storage.get(key.as_()).unwrap()) .map(|(&symbol, &())| symbol) } /// Returns the str in self.dictionary that corresponds to `id` pub fn lookup_id(&self, id: K) -> Option<&str> { self.storage.get(id.as_()) } pub fn size(&self) -> usize { self.storage.size() + self.dedup.len() * std::mem::size_of::<K>() } pub fn values(&self) -> &PackedStringArray<K> { &self.storage } pub fn into_inner(self) -> PackedStringArray<K> { self.storage } /// Truncates this dictionary removing all keys larger than `id` pub fn truncate(&mut self, id: K) { let id = id.as_(); self.dedup.retain(|k, _| k.as_() <= id); self.storage.truncate(id + 1) } /// Clears this dictionary removing all elements pub fn clear(&mut self) { self.storage.clear(); self.dedup.clear() } } fn hash_str(hasher: &ahash::RandomState, value: &str) -> u64 { use std::hash::{BuildHasher, Hash, Hasher}; let mut state = hasher.build_hasher(); value.hash(&mut state); state.finish() } impl StringDictionary<i32> { /// Convert to an arrow representation with the provided set of /// keys and an optional null bitmask pub fn to_arrow<I>(&self, keys: I, nulls: Option<NullBuffer>) -> DictionaryArray<Int32Type> where I: IntoIterator<Item = i32>, I::IntoIter: ExactSizeIterator, { // the nulls are recorded in the keys array, the dictionary itself // is entirely non null let dictionary_nulls = None; let keys = keys.into_iter(); let array_data = ArrayDataBuilder::new(DataType::Dictionary( Box::new(DataType::Int32), Box::new(DataType::Utf8), )) .len(keys.len()) .add_buffer(keys.collect()) .add_child_data(self.storage.to_arrow(dictionary_nulls).into_data()) .nulls(nulls) // TODO consider skipping the validation checks by using // `build_unchecked()` .build() .expect("Valid array data"); DictionaryArray::<Int32Type>::from(array_data) } } impl<K> TryFrom<PackedStringArray<K>> for StringDictionary<K> where K: AsPrimitive<usize> + FromPrimitive + Zero, { type Error = Error; fn try_from(storage: PackedStringArray<K>) -> Result<Self, Error> { use hashbrown::hash_map::RawEntryMut; let hasher = ahash::RandomState::new(); let mut dedup: HashMap<K, (), ()> = HashMap::with_capacity_and_hasher(storage.len(), ()); for (idx, value) in storage.iter().enumerate() { let hash = hash_str(&hasher, value); let entry = dedup .raw_entry_mut() .from_hash(hash, |key| value == storage.get(key.as_()).unwrap()); match entry { RawEntryMut::Occupied(_) => { return Err(Error::DuplicateKeyFound { key: value.to_string(), }) } RawEntryMut::Vacant(entry) => { let key = K::from_usize(idx).expect("failed to fit string index into dictionary key"); entry.insert_with_hasher(hash, key, (), |key| { let string = storage.get(key.as_()).unwrap(); hash_str(&hasher, string) }); } } } Ok(Self { hash: hasher, dedup, storage, }) } } #[cfg(test)] mod test { use std::convert::TryInto; use super::*; #[test] fn test_dictionary() { let mut dictionary = StringDictionary::<i32>::new(); let id1 = dictionary.lookup_value_or_insert("cupcake"); let id2 = dictionary.lookup_value_or_insert("cupcake"); let id3 = dictionary.lookup_value_or_insert("womble"); let id4 = dictionary.lookup_value("cupcake").unwrap(); let id5 = dictionary.lookup_value("womble").unwrap(); let cupcake = dictionary.lookup_id(id4).unwrap(); let womble = dictionary.lookup_id(id5).unwrap(); let arrow_expected = arrow::array::StringArray::from(vec!["cupcake", "womble"]); let arrow_actual = dictionary.values().to_arrow(None); assert_eq!(id1, id2); assert_eq!(id1, id4); assert_ne!(id1, id3); assert_eq!(id3, id5); assert_eq!(cupcake, "cupcake"); assert_eq!(womble, "womble"); assert!(dictionary.lookup_value("foo").is_none()); assert!(dictionary.lookup_id(-1).is_none()); assert_eq!(arrow_expected, arrow_actual); } #[test] fn from_string_array() { let mut data = PackedStringArray::<u64>::new(); data.append("cupcakes"); data.append("foo"); data.append("bingo"); let dictionary: StringDictionary<_> = data.try_into().unwrap(); assert_eq!(dictionary.lookup_value("cupcakes"), Some(0)); assert_eq!(dictionary.lookup_value("foo"), Some(1)); assert_eq!(dictionary.lookup_value("bingo"), Some(2)); assert_eq!(dictionary.lookup_id(0), Some("cupcakes")); assert_eq!(dictionary.lookup_id(1), Some("foo")); assert_eq!(dictionary.lookup_id(2), Some("bingo")); } #[test] fn from_string_array_duplicates() { let mut data = PackedStringArray::<u64>::new(); data.append("cupcakes"); data.append("foo"); data.append("bingo"); data.append("cupcakes"); let err = TryInto::<StringDictionary<_>>::try_into(data).expect_err("expected failure"); assert!(matches!(err, Error::DuplicateKeyFound { key } if &key == "cupcakes")) } #[test] fn test_truncate() { let mut dictionary = StringDictionary::<i32>::new(); dictionary.lookup_value_or_insert("cupcake"); dictionary.lookup_value_or_insert("cupcake"); dictionary.lookup_value_or_insert("bingo"); let bingo = dictionary.lookup_value_or_insert("bingo"); let bongo = dictionary.lookup_value_or_insert("bongo"); dictionary.lookup_value_or_insert("bingo"); dictionary.lookup_value_or_insert("cupcake"); dictionary.truncate(bingo); assert_eq!(dictionary.values().len(), 2); assert_eq!(dictionary.dedup.len(), 2); assert_eq!(dictionary.lookup_value("cupcake"), Some(0)); assert_eq!(dictionary.lookup_value("bingo"), Some(1)); assert!(dictionary.lookup_value("bongo").is_none()); assert!(dictionary.lookup_id(bongo).is_none()); dictionary.lookup_value_or_insert("bongo"); assert_eq!(dictionary.lookup_value("bongo"), Some(2)); } }
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] ::windows_targets::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_Memory_NonVolatile\"`*"] fn RtlDrainNonVolatileFlush ( nvtoken : *const ::core::ffi::c_void ) -> u32 ); #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] ::windows_targets::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_Memory_NonVolatile\"`*"] fn RtlFillNonVolatileMemory ( nvtoken : *const ::core::ffi::c_void , nvdestination : *mut ::core::ffi::c_void , size : usize , value : u8 , flags : u32 ) -> u32 ); #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] ::windows_targets::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_Memory_NonVolatile\"`*"] fn RtlFlushNonVolatileMemory ( nvtoken : *const ::core::ffi::c_void , nvbuffer : *const ::core::ffi::c_void , size : usize , flags : u32 ) -> u32 ); #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] ::windows_targets::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_Memory_NonVolatile\"`*"] fn RtlFlushNonVolatileMemoryRanges ( nvtoken : *const ::core::ffi::c_void , nvranges : *const NV_MEMORY_RANGE , numranges : usize , flags : u32 ) -> u32 ); #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] ::windows_targets::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_Memory_NonVolatile\"`*"] fn RtlFreeNonVolatileToken ( nvtoken : *const ::core::ffi::c_void ) -> u32 ); #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] ::windows_targets::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_Memory_NonVolatile\"`*"] fn RtlGetNonVolatileToken ( nvbuffer : *const ::core::ffi::c_void , size : usize , nvtoken : *mut *mut ::core::ffi::c_void ) -> u32 ); #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] ::windows_targets::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_Memory_NonVolatile\"`*"] fn RtlWriteNonVolatileMemory ( nvtoken : *const ::core::ffi::c_void , nvdestination : *mut ::core::ffi::c_void , source : *const ::core::ffi::c_void , size : usize , flags : u32 ) -> u32 ); #[repr(C)] #[doc = "*Required features: `\"Win32_System_Memory_NonVolatile\"`*"] pub struct NV_MEMORY_RANGE { pub BaseAddress: *mut ::core::ffi::c_void, pub Length: usize, } impl ::core::marker::Copy for NV_MEMORY_RANGE {} impl ::core::clone::Clone for NV_MEMORY_RANGE { fn clone(&self) -> Self { *self } }
enum Color { Hijau, Biru, } fn main() { let warna: Color = Color::Biru; match warna { Color::Biru => println!("Biru"), Color::Hijau => println!("Hijau"), } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![allow(dead_code)] use crate::indexing::load_module_facet; use crate::models::{Action, FuchsiaFulfillment, Parameter}; use failure::Error; use fidl_fuchsia_sys_index::{ComponentIndexMarker, ComponentIndexProxy}; use fuchsia_component::client::{launch, launcher, App}; use fuchsia_syslog::macros::*; const COMPONENT_INDEX_URL: &str = "fuchsia-pkg://fuchsia.com/component_index#meta/component_index.cmx"; /// Starts and connects to the component index service. // TODO: combine with version in package_suggestions_provider fn get_index_service() -> Result<(App, ComponentIndexProxy), Error> { let app = launch(&launcher()?, COMPONENT_INDEX_URL.to_string(), None)?; let service = app.connect_to_service::<ComponentIndexMarker>()?; Ok((app, service)) } /// Gets a list of all components on the system // TODO: combine with version in package_suggestions_provider async fn get_components() -> Result<Vec<String>, Error> { let (_app, index_service) = get_index_service().map_err(|e| { fx_log_err!("Failed to connect to index service"); e })?; // Empty string returns all components. let index_response = index_service.fuzzy_search("").await.map_err(|e| { fx_log_err!("Fuzzy search error from component index: {:?}", e); e })?; index_response.or_else(|e| { fx_log_err!("Fuzzy search error from component index: {:?}", e); Ok(vec![]) }) } // Gets a vector of all actions on the system pub async fn get_local_actions() -> Result<Vec<Action>, Error> { let urls = get_components().await?; let mut result = vec![]; for url in urls { let module_facet = load_module_facet(&url).await?; for intent_filter in module_facet.intent_filters.into_iter() { // Convert from Indexing to Models result.push(Action { name: intent_filter.action, parameters: intent_filter .parameters .iter() .map(|(k, v)| Parameter { name: k.to_string(), parameter_type: v.to_string() }) .collect(), action_display: intent_filter.action_display, web_fulfillment: None, fuchsia_fulfillment: Some(FuchsiaFulfillment { component_url: url.to_string() }), }) } } Ok(result) } #[cfg(test)] mod test { use {super::*, fuchsia_async as fasync}; const TEST_COMPONENT_URL: &str = "fuchsia-pkg://fuchsia.com/discovermgr_tests#meta/discovermgr_bin_test.cmx"; // Verify the actions in this component test manifest #[fasync::run_singlethreaded(test)] async fn test_component_index() -> Result<(), Error> { // TODO fix tests -- failing only in CQ let result = get_local_actions().await.unwrap_or_else(|e| { fx_log_err!("Error! {:?}", e); vec![] }); #[allow(unused)] let actions: Vec<&Action> = result .iter() .filter(|a| match &a.fuchsia_fulfillment { Some(v) => v.component_url == TEST_COMPONENT_URL, None => false, }) .collect(); // assert_eq!(actions.len(), 3, "Expecting to find 3 actions in discovermgr test cmx file"); Ok(()) } }
use fuzzcheck_mutators_derive::make_mutator; extern crate self as fuzzcheck; make_mutator! { name: OptionMutator, default: true, type: pub enum Option<T> { Some(T), None, } }
#[derive(Debug)] enum Message { Quit, Move{x: i32, y: i32}, Write(String), ChangeColor(i32, i32, i32) } fn main() { let msg = Message::ChangeColor(0, 256, 256); match msg{ Message::Quit => { println!("quit"); }, Message::Move{x,y} =>{ println!("move, x: {}, y: {}", x ,y) }, Message::Write(text) => { println!("write msg : {}", text); }, Message::ChangeColor(r, g, b) => { println!("ChangeColor r: {} g: {} b: {}", r, g ,b); } }; let num = Some(4); match num { Some(x) if x < 5 => println!("< 5"), Some(x) => println!("x : {}", x), None => (), }; println!("num"); println!("Hello, world!"); let i = 5; let j = false; match i { 4 | 5 | 6 if j => println!("1"), _ => println!("2"), } let msg_bak = Message_bak::Hello{id: 5}; match msg_bak{ Message_bak::Hello{id: id_va @ 3..=7} => { println!("id_va : {}", id_va); }, Message_bak::Hello{id:10..=20} => { println!("large"); }, Message_bak::Hello{id} => { println!("id : {}", id); }, } } #[derive(Debug)] enum Message_bak { Hello{id : i32}, }
#[macro_use] extern crate hprof; fn main() { let p = hprof::Profiler::new("main loop"); loop { p.start_frame(); p.enter_noguard("setup"); std::thread::sleep_ms(1); p.leave(); p.enter_noguard("physics"); std::thread::sleep_ms(2); p.leave(); p.enter_noguard("render"); std::thread::sleep_ms(8); p.leave(); p.end_frame(); // this would usually depend on debug data, or use custom functionality for drawing the // debug information. if true { p.print_timing(); } break; } }
pub struct Rhyme { word: String, freq: i8, score: i16, flags: String, syllables: i8, } impl Rhyme { pub fn new(word: &str, freq: i8, score: i16, flags: &str, syllables: i8) -> Rhyme { return Rhyme { word: word.to_string(), freq: 1, score: 300, flags: flags.to_string(), syllables: 1 }; } }
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::erlang::spawn_apply_1; use crate::runtime::process::spawn::options::Options; #[native_implemented::function(erlang:spawn_monitor/1)] pub fn result(process: &Process, function: Term) -> exception::Result<Term> { spawn_apply_1::result( process, function, Options { monitor: true, ..Default::default() }, ) }
use crate::download::Downloader; use crate::download_body::{DownloadBodyActor, SyncBodyEvent}; use crate::helper::get_header_by_hash; use actix::prelude::*; use anyhow::Result; use crypto::hash::HashValue; use logger::prelude::*; use network::NetworkAsyncService; use std::sync::Arc; use traits::Consensus; use types::peer_info::PeerInfo; #[derive(Default, Debug, Message)] #[rtype(result = "Result<()>")] struct SyncHeaderEvent { pub hashs: Vec<HashValue>, pub peers: Vec<PeerInfo>, } #[derive(Clone)] pub struct DownloadHeaderActor<C> where C: Consensus + Sync + Send + 'static + Clone, { downloader: Arc<Downloader<C>>, peer_info: Arc<PeerInfo>, network: NetworkAsyncService, download_body: Addr<DownloadBodyActor<C>>, } impl<C> DownloadHeaderActor<C> where C: Consensus + Sync + Send + 'static + Clone, { pub fn _launch( downloader: Arc<Downloader<C>>, peer_info: Arc<PeerInfo>, network: NetworkAsyncService, download_body: Addr<DownloadBodyActor<C>>, ) -> Result<Addr<DownloadHeaderActor<C>>> { Ok(Actor::create(move |_ctx| DownloadHeaderActor { downloader, peer_info, network, download_body, })) } } impl<C> Actor for DownloadHeaderActor<C> where C: Consensus + Sync + Send + 'static + Clone, { type Context = Context<Self>; } impl<C> Handler<SyncHeaderEvent> for DownloadHeaderActor<C> where C: Consensus + Sync + Send + 'static + Clone, { type Result = Result<()>; fn handle(&mut self, event: SyncHeaderEvent, _ctx: &mut Self::Context) -> Self::Result { let network = self.network.clone(); let peers = event.peers.clone(); let hashs = event.hashs.clone(); let download_body = self.download_body.clone(); Arbiter::spawn(async move { for peer in peers.clone() { match get_header_by_hash(&network, peer.get_peer_id(), hashs.clone()).await { Ok(headers) => { download_body.do_send(SyncBodyEvent { headers: headers.headers, peers: peers.clone(), }); break; } Err(e) => { error!("error: {:?}", e); } }; } }); Ok(()) } }
use rand::{Rng, thread_rng}; pub trait Vector<I32> { fn new(number: usize, min: i32, max: i32) -> Self where Self: Sized; fn len(&self) -> isize; fn display(&self); fn swap(&mut self, a: isize, b: isize); fn right_partition(&mut self, l: isize, r: isize) -> isize; fn random_partition(&mut self, l: isize, r: isize) -> isize; fn right_quick_sort(&mut self, l: isize, r: isize); fn random_quick_sort(&mut self, l: isize, r: isize); fn insertion_sort(&mut self, l: isize, r: isize); fn hybrid_sort(&mut self, l: isize, r: isize, k: isize); } impl Vector<i32> for Vec<i32> { fn new(number: usize, min: i32, max: i32) -> Self { let mut rng = thread_rng(); let mut ret: Vec<i32> = Vec::with_capacity(number); for _ in 0..ret.capacity() { ret.push(rng.gen_range(min, max)); } ret } fn len(&self) -> isize { self.len() as isize } fn display(&self) { println!("{:?}", self); } fn swap(&mut self, a: isize, b: isize) { let tmp = self[a as usize]; self[a as usize] = self[b as usize]; self[b as usize] = tmp; } fn right_partition(&mut self, l: isize, r: isize) -> isize { let pivot = self[r as usize]; let mut i = l - 1; let mut j = l; while j < r { if self[j as usize] < pivot { i = i + 1; self.swap(i, j); } j = j + 1; } self.swap(i + 1, r); (i + 1) } fn random_partition(&mut self, l: isize, r: isize) -> isize { let mut rng = thread_rng(); let pivot = self[rng.gen_range(l, r) as usize]; let mut i = l; let mut j = r; loop { while self[i as usize] < pivot { i = i + 1; } while self[j as usize] > pivot { j = j - 1; } if i >= j { break; } self.swap(i, j); if self[i as usize] == self[j as usize] { i = i + 1; } } j } fn right_quick_sort(&mut self, l: isize, r: isize) { if l < r { let sep = self.right_partition(l, r); self.right_quick_sort(l, sep - 1); self.right_quick_sort(sep + 1, r); } } fn random_quick_sort(&mut self, l: isize, r: isize) { if l < r { let sep = self.random_partition(l, r); self.random_quick_sort(l, sep - 1); self.random_quick_sort(sep + 1, r); } } fn insertion_sort(&mut self, l: isize, r: isize) { // 1 let mut value; // 1 1 let mut i = l; // 1 // => 4 let mut j; // 1 => n while i <= r { /* 1 3 2 => 5n^2 + 1 for (j = l; j < i; i++) for j in (l..i).rev() { 1 1 2 => 4n^2 if self[j as usize] >= self[(j + 1) as usize] { // 8 => 8n^2 self.swap(j, j + 1); } else { 1 => n^2 break; } } // 17n^2 + 2n + 4 */ // 1 1 => 2n value = self[i as usize]; // 1 => n j = i; // 1 1 2 1 => 7n^2 while j > l && self[j as usize - 1] > value { // 1 1 2 => 4n^2 self[j as usize] = self[j as usize - 1]; //1 1 => 2n^2 j = j - 1; } // 1 1 => 2n self[j as usize] = value; // 1 1 => 2n i = i + 1; } //4 + n + 2n + n + 7n^2 + 4n^2 + 2n^2 + 2n + 2n = 13n^2 + 8n + 4 => O(n^2) } fn hybrid_sort(&mut self, l: isize, r: isize, k: isize) { if l < r { if (r - l) > k { let sep = self.right_partition(l, r); self.hybrid_sort(l, sep - 1, k); self.hybrid_sort(sep + 1, r, k); } else { self.insertion_sort(l, r); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_len() { let vec: Vec<i32> = Vector::new(9, 1, 4); assert!(vec.len() == 9); } #[test] fn test_swap() { let mut vec: Vec<i32> = vec![1, 3, 0, 8, 2]; vec.swap(0, 3); assert!(vec == vec![8, 3, 0, 1, 2]); } #[test] fn test_right_qs() { let mut vec: Vec<i32> = Vector::new(1_000, 0, 1000); vec.right_quick_sort(0, vec.len() as isize - 1); for i in 0..vec.len() - 1 { assert!(vec[i] <= vec[i + 1]); } } #[test] fn test_random_qs() { let mut vec: Vec<i32> = Vector::new(1_000, 0, 1000); vec.random_quick_sort(0, vec.len() as isize - 1); for i in 0..vec.len() - 1 { assert!(vec[i] <= vec[i + 1]); } } #[test] fn test_insertion_sort() { let mut vec: Vec<i32> = Vector::new(1_000, 0, 1000); vec.insertion_sort(0, 999); for i in 0..vec.len() - 1 { assert!(vec[i] <= vec[i + 1]); } } #[test] fn test_hybrid_sort() { let mut vec: Vec<i32> = Vector::new(1_000, 0, 1000); vec.hybrid_sort(0, vec.len() as isize- 1, 10); for i in 0..vec.len() - 1 { assert!(vec[i] <= vec[i + 1]); } } }
use candy_frontend::position::Offset; use std::{borrow::Cow, ops::Range}; #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct TextEdit { pub range: Range<Offset>, pub new_text: String, } impl TextEdit { fn is_insert(&self) -> bool { self.range.is_empty() } } /// All text edits ranges refer to positions in the document they are computed on. They therefore /// move a document from state S1 to S2 without describing any intermediate state. Text edits ranges /// must never overlap, that means no part of the original document must be manipulated by more than /// one edit. However, it is possible that multiple edits have the same start position: multiple /// inserts, or any number of inserts followed by a single remove or replace edit. If multiple /// inserts have the same position, the order in the array defines the order in which the inserted /// strings appear in the resulting text. /// /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textEditArray pub struct TextEdits { source: String, /// The edits are sorted by their start position. edits: Vec<TextEdit>, } impl TextEdits { pub fn new(source: String) -> Self { Self { source, edits: vec![], } } pub fn source(&self) -> &str { &self.source } pub fn has_edits(&self) -> bool { !self.edits.is_empty() } pub fn has_edit_at(&self, offset: Offset) -> bool { self.edits .binary_search_by_key(&offset, |it| it.range.start) .map(|_| true) // An edit starts at this position. .unwrap_or_else(|index| { self.edits .get(index) // An edit contains this position. .map(|it| it.range.contains(&offset)) .unwrap_or_default() }) } pub fn insert(&mut self, offset: Offset, text: impl Into<Cow<str>>) { self.change(offset..offset, text); } pub fn delete(&mut self, range: Range<Offset>) { self.change(range, ""); } pub fn change(&mut self, range: Range<Offset>, new_text: impl Into<Cow<str>>) { let new_text = new_text.into(); if self.source[*range.start..*range.end] == new_text { return; } let index = self .edits .binary_search_by_key(&range.start, |it| it.range.start); match index { Ok(index) => { let existing = &mut self.edits[index]; assert!( existing.is_insert() || range.is_empty(), "At least one of [existing, new] must be an insert.", ); if existing.range.is_empty() { existing.range = range; } existing.new_text = format!("{}{}", existing.new_text, new_text); } Err(index) => { if index > 0 { let previous = &self.edits[index - 1]; assert!(previous.range.end <= range.start); if previous.range.end == range.start { self.edits[index - 1] = TextEdit { range: previous.range.start..range.end, new_text: format!("{}{}", previous.new_text, new_text), }; return; } } if index < self.edits.len() { let next = &self.edits[index]; assert!(range.end <= next.range.start); if range.end == next.range.start { self.edits[index] = TextEdit { range: range.start..next.range.end, new_text: format!("{}{}", new_text, next.new_text), }; return; } } self.edits.insert( index, TextEdit { range, new_text: new_text.into(), }, ); } } } pub fn finish(self) -> Vec<TextEdit> { self.edits } pub fn apply(&self) -> String { let mut result = self.source.to_string(); for edit in self.edits.iter().rev() { result.replace_range(*edit.range.start..*edit.range.end, &edit.new_text); } result } }
//! RustType is a pure Rust alternative to libraries like FreeType. //! //! The current capabilities of RustType: //! //! * Reading TrueType formatted fonts and font collections. This includes //! `*.ttf` as well as a subset of `*.otf` font files. //! * Retrieving glyph shapes and commonly used properties for a font and its //! glyphs. //! * Laying out glyphs horizontally using horizontal and vertical metrics, and //! glyph-pair-specific kerning. //! * Rasterising glyphs with sub-pixel positioning using an accurate analytical //! algorithm (not based on sampling). //! * Managing a font cache on the GPU with the `gpu_cache` module. This keeps //! recently used glyph renderings in a dynamic cache in GPU memory to //! minimise texture uploads per-frame. It also allows you keep the draw call //! count for text very low, as all glyphs are kept in one GPU texture. //! //! Notable things that RustType does not support *yet*: //! //! * OpenType formatted fonts that are not just TrueType fonts (OpenType is a //! superset of TrueType). Notably there is no support yet for cubic Bezier //! curves used in glyphs. //! * Font hinting. //! * Ligatures of any kind. //! * Some less common TrueType sub-formats. //! * Right-to-left and vertical text layout. //! //! # Getting Started //! //! To hit the ground running with RustType, look at the `simple.rs` example //! supplied with the crate. It demonstrates loading a font file, rasterising an //! arbitrary string, and displaying the result as ASCII art. If you prefer to //! just look at the documentation, the entry point for loading fonts is //! `FontCollection`, from which you can access individual fonts, then their //! glyphs. //! //! # Glyphs //! //! The glyph API uses wrapper structs to augment a glyph with information such //! as scaling and positioning, making relevant methods that make use of this //! information available as appropriate. For example, given a `Glyph` `glyph` //! obtained directly from a `Font`: //! //! ```no_run //! # use rusttype::*; //! # let glyph: Glyph<'static> = unimplemented!(); //! // One of the few things you can do with an unsized, positionless glyph is get its id. //! let id = glyph.id(); //! let glyph = glyph.scaled(Scale::uniform(10.0)); //! // Now glyph is a ScaledGlyph, you can do more with it, as well as what you can do with Glyph. //! // For example, you can access the correctly scaled horizontal metrics for the glyph. //! let h_metrics = glyph.h_metrics(); //! let glyph = glyph.positioned(point(5.0, 3.0)); //! // Now glyph is a PositionedGlyph, and you can do even more with it, e.g. drawing. //! glyph.draw(|x, y, v| {}); // In this case the pixel values are not used. //! ``` //! //! # Unicode terminology //! //! This crate uses terminology for computerised typography as specified by the //! Unicode standard. If you are not sure of the differences between a code //! point, a character, and a glyph, you may want to check the [official Unicode //! glossary](http://unicode.org/glossary/), or alternatively, here's my take on //! it from a practical perspective: //! //! * A character is what you would conventionally call a single symbol, //! independent of its appearance or representation in a particular font. //! Examples include `a`, `A`, `ä`, `å`, `1`, `*`, `Ω`, etc. //! * A Unicode code point is the particular number that the Unicode standard //! associates with a particular character. Note however that code points also //! exist for things not conventionally thought of as characters by //! themselves, but can be combined to form characters, such as diacritics //! like accents. These "characters" are known in Unicode as "combining //! characters". E.g., a diaeresis (`¨`) has the code point U+0308. If this //! code point follows the code point U+0055 (the letter `u`), this sequence //! represents the character `ü`. Note that there is also a single codepoint //! for `ü`, U+00FC. This means that what visually looks like the same string //! can have multiple different Unicode representations. Some fonts will have //! glyphs (see below) for one sequence of codepoints, but not another that //! has the same meaning. To deal with this problem it is recommended to use //! Unicode normalisation, as provided by, for example, the //! [unicode-normalization](http://crates.io/crates/unicode-normalization) //! crate, to convert to code point sequences that work with the font in //! question. Typically a font is more likely to support a single code point //! vs. a sequence with the same meaning, so the best normalisation to use is //! "canonical recomposition", known as NFC in the normalisation crate. //! * A glyph is a particular font's shape to draw the character for a //! particular Unicode code point. This will have its own identifying number //! unique to the font, its ID. #![allow(unknown_lints)] #![warn(clippy::all)] #![allow( clippy::cyclomatic_complexity, clippy::doc_markdown, clippy::cast_lossless, clippy::many_single_char_names )] #![cfg_attr(feature = "bench", feature(test))] #[cfg(feature = "bench")] extern crate test; mod geometry; mod rasterizer; #[cfg(feature = "gpu_cache")] pub mod gpu_cache; pub use crate::geometry::{point, vector, Curve, Line, Point, Rect, Vector}; use approx::relative_eq; use stb_truetype as tt; use std::fmt; use std::sync::Arc; /// A collection of fonts read straight from a font file's data. The data in the /// collection is not validated. This structure may or may not own the font /// data. /// /// # Lifetime /// The lifetime reflects the font data lifetime. `FontCollection<'static>` /// covers most cases ie both dynamically loaded owned data and for referenced /// compile time font data. #[derive(Clone, Debug)] pub struct FontCollection<'a>(SharedBytes<'a>); /// A single font. This may or may not own the font data. /// /// # Lifetime /// The lifetime reflects the font data lifetime. `Font<'static>` covers most /// cases ie both dynamically loaded owned data and for referenced compile time /// font data. /// /// # Example /// /// ``` /// # use rusttype::{Font, Error}; /// # fn example() -> Result<(), Error> { /// let font_data: &[u8] = include_bytes!("../fonts/dejavu/DejaVuSansMono.ttf"); /// let font: Font<'static> = Font::from_bytes(font_data)?; /// /// let owned_font_data: Vec<u8> = font_data.to_vec(); /// let from_owned_font: Font<'static> = Font::from_bytes(owned_font_data)?; /// # Ok(()) /// # } /// ``` #[derive(Clone)] pub struct Font<'a> { info: tt::FontInfo<SharedBytes<'a>>, } impl fmt::Debug for Font<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Font") } } /// `SharedBytes` handles the lifetime of font data used in RustType. The data /// is either a shared reference to externally owned data, or managed by /// reference counting. `SharedBytes` can be conveniently used with `From` and /// `Into`, and dereferences to the contained bytes. /// /// # Lifetime /// The lifetime reflects the font data lifetime. `SharedBytes<'static>` covers /// most cases ie both dynamically loaded owned data and for referenced compile /// time font data. #[derive(Clone, Debug)] pub enum SharedBytes<'a> { ByRef(&'a [u8]), ByArc(Arc<[u8]>), } impl<'a> ::std::ops::Deref for SharedBytes<'a> { type Target = [u8]; fn deref(&self) -> &[u8] { match *self { SharedBytes::ByRef(bytes) => bytes, SharedBytes::ByArc(ref bytes) => &**bytes, } } } /// ``` /// # use rusttype::SharedBytes; /// let bytes: &[u8] = &[0u8, 1, 2, 3]; /// let shared: SharedBytes = bytes.into(); /// assert_eq!(&*shared, bytes); /// ``` impl<'a> From<&'a [u8]> for SharedBytes<'a> { fn from(bytes: &'a [u8]) -> SharedBytes<'a> { SharedBytes::ByRef(bytes) } } /// ``` /// # use rusttype::SharedBytes; /// # use std::sync::Arc; /// let bytes: Arc<[u8]> = vec![0u8, 1, 2, 3].into(); /// let shared: SharedBytes = Arc::clone(&bytes).into(); /// assert_eq!(&*shared, &*bytes); /// ``` impl From<Arc<[u8]>> for SharedBytes<'static> { fn from(bytes: Arc<[u8]>) -> SharedBytes<'static> { SharedBytes::ByArc(bytes) } } /// ``` /// # use rusttype::SharedBytes; /// let bytes: Box<[u8]> = vec![0u8, 1, 2, 3].into(); /// let shared: SharedBytes = bytes.into(); /// assert_eq!(&*shared, &[0u8, 1, 2, 3]); /// ``` impl From<Box<[u8]>> for SharedBytes<'static> { fn from(bytes: Box<[u8]>) -> SharedBytes<'static> { SharedBytes::ByArc(bytes.into()) } } /// ``` /// # use rusttype::SharedBytes; /// let bytes = vec![0u8, 1, 2, 3]; /// let shared: SharedBytes = bytes.into(); /// assert_eq!(&*shared, &[0u8, 1, 2, 3]); /// ``` impl From<Vec<u8>> for SharedBytes<'static> { fn from(bytes: Vec<u8>) -> SharedBytes<'static> { SharedBytes::ByArc(bytes.into()) } } /// ``` /// # use rusttype::SharedBytes; /// let bytes = vec![0u8, 1, 2, 3]; /// let shared: SharedBytes = (&bytes).into(); /// assert_eq!(&*shared, &bytes as &[u8]); /// ``` impl<'a, T: AsRef<[u8]>> From<&'a T> for SharedBytes<'a> { fn from(bytes: &'a T) -> SharedBytes<'a> { SharedBytes::ByRef(bytes.as_ref()) } } #[test] fn lazy_static_shared_bytes() { lazy_static::lazy_static! { static ref BYTES: Vec<u8> = vec![0, 1, 2, 3]; } let shared_bytes: SharedBytes<'static> = (&*BYTES).into(); assert_eq!(&*shared_bytes, &[0, 1, 2, 3]); } /// Represents a Unicode code point. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Codepoint(pub u32); /// Represents a glyph identifier for a particular font. This identifier will /// not necessarily correspond to the correct glyph in a font other than the /// one that it was obtained from. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct GlyphId(pub u32); /// A single glyph of a font. this may either be a thin wrapper referring to the /// font and the glyph id, or it may be a standalone glyph that owns the data /// needed by it. /// /// A `Glyph` does not have an inherent scale or position associated with it. To /// augment a glyph with a size, give it a scale using `scaled`. You can then /// position it using `positioned`. #[derive(Clone)] pub struct Glyph<'a> { inner: GlyphInner<'a>, } impl fmt::Debug for Glyph<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Glyph").field("id", &self.id().0).finish() } } #[derive(Clone)] enum GlyphInner<'a> { Proxy(Font<'a>, u32), Shared(Arc<SharedGlyphData>), } #[derive(Debug)] pub struct SharedGlyphData { pub id: u32, pub extents: Option<Rect<i32>>, pub scale_for_1_pixel: f32, pub unit_h_metrics: HMetrics, pub shape: Option<Vec<tt::Vertex>>, } /// The "horizontal metrics" of a glyph. This is useful for calculating the /// horizontal offset of a glyph from the previous one in a string when laying a /// string out horizontally. #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] pub struct HMetrics { /// The horizontal offset that the origin of the next glyph should be from /// the origin of this glyph. pub advance_width: f32, /// The horizontal offset between the origin of this glyph and the leftmost /// edge/point of the glyph. pub left_side_bearing: f32, } #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] /// The "vertical metrics" of a font at a particular scale. This is useful for /// calculating the amount of vertical space to give a line of text, and for /// computing the vertical offset between successive lines. pub struct VMetrics { /// The highest point that any glyph in the font extends to above the /// baseline. Typically positive. pub ascent: f32, /// The lowest point that any glyph in the font extends to below the /// baseline. Typically negative. pub descent: f32, /// The gap to leave between the descent of one line and the ascent of the /// next. This is of course only a guideline given by the font's designers. pub line_gap: f32, } impl From<tt::VMetrics> for VMetrics { fn from(vm: tt::VMetrics) -> Self { Self { ascent: vm.ascent as f32, descent: vm.descent as f32, line_gap: vm.line_gap as f32, } } } impl ::std::ops::Mul<f32> for VMetrics { type Output = VMetrics; fn mul(self, rhs: f32) -> Self { Self { ascent: self.ascent * rhs, descent: self.descent * rhs, line_gap: self.line_gap * rhs, } } } /// A glyph augmented with scaling information. You can query such a glyph for /// information that depends on the scale of the glyph. #[derive(Clone)] pub struct ScaledGlyph<'a> { g: Glyph<'a>, api_scale: Scale, scale: Vector<f32>, } impl fmt::Debug for ScaledGlyph<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ScaledGlyph") .field("id", &self.id().0) .field("scale", &self.api_scale) .finish() } } /// A glyph augmented with positioning and scaling information. You can query /// such a glyph for information that depends on the scale and position of the /// glyph. #[derive(Clone)] pub struct PositionedGlyph<'a> { sg: ScaledGlyph<'a>, position: Point<f32>, bb: Option<Rect<i32>>, } impl fmt::Debug for PositionedGlyph<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PositionedGlyph") .field("id", &self.id().0) .field("scale", &self.scale()) .field("position", &self.position) .finish() } } /// Defines the size of a rendered face of a font, in pixels, horizontally and /// vertically. A vertical scale of `y` pixels means that the distance betwen /// the ascent and descent lines (see `VMetrics`) of the face will be `y` /// pixels. If `x` and `y` are equal the scaling is uniform. Non-uniform scaling /// by a factor *f* in the horizontal direction is achieved by setting `x` equal /// to *f* times `y`. #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] pub struct Scale { /// Horizontal scale, in pixels. pub x: f32, /// Vertical scale, in pixels. pub y: f32, } impl Scale { /// Uniform scaling, equivalent to `Scale { x: s, y: s }`. #[inline] pub fn uniform(s: f32) -> Scale { Scale { x: s, y: s } } } /// A trait for types that can be converted into a `GlyphId`, in the context of /// a specific font. /// /// Many `rusttype` functions that operate on characters accept values of any /// type that implements `IntoGlyphId`. Such types include `char`, `Codepoint`, /// and obviously `GlyphId` itself. pub trait IntoGlyphId { /// Convert `self` into a `GlyphId`, consulting the index map of `font` if /// necessary. fn into_glyph_id(self, _: &Font<'_>) -> GlyphId; } impl IntoGlyphId for char { fn into_glyph_id(self, font: &Font<'_>) -> GlyphId { GlyphId(font.info.find_glyph_index(self as u32)) } } impl IntoGlyphId for Codepoint { fn into_glyph_id(self, font: &Font<'_>) -> GlyphId { GlyphId(font.info.find_glyph_index(self.0)) } } impl IntoGlyphId for GlyphId { #[inline] fn into_glyph_id(self, _font: &Font<'_>) -> GlyphId { self } } impl<'a> FontCollection<'a> { /// Constructs a font collection from an array of bytes, typically loaded /// from a font file, which may be a single font or a TrueType Collection /// holding a number of fonts. This array may be owned (e.g. `Vec<u8>`), or /// borrowed (`&[u8]`). As long as `From<T>` is implemented for `Bytes` for /// some type `T`, `T` can be used as input. /// /// This returns an error if `bytes` does not seem to be font data in a /// format we recognize. pub fn from_bytes<B: Into<SharedBytes<'a>>>(bytes: B) -> Result<FontCollection<'a>, Error> { let bytes = bytes.into(); // We should use tt::is_collection once it lands in stb_truetype-rs: // https://github.com/redox-os/stb_truetype-rs/pull/15 if !tt::is_font(&bytes) && &bytes[0..4] != b"ttcf" { return Err(Error::UnrecognizedFormat); } Ok(FontCollection(bytes)) } /// If this `FontCollection` holds a single font, or a TrueType Collection /// containing only one font, return that as a `Font`. The `FontCollection` /// is consumed. /// /// If this `FontCollection` holds multiple fonts, return a /// `CollectionContainsMultipleFonts` error. /// /// If an error occurs, the `FontCollection` is lost, since this function /// takes ownership of it, and the error values don't give it back. If that /// is a problem, use the `font_at` or `into_fonts` methods instead, which /// borrow the `FontCollection` rather than taking ownership of it. pub fn into_font(self) -> Result<Font<'a>, Error> { let offset = if tt::is_font(&self.0) { 0 } else if tt::get_font_offset_for_index(&self.0, 1).is_some() { return Err(Error::CollectionContainsMultipleFonts); } else { // We now know that either a) `self.0` is a collection with only one // font, or b) `get_font_offset_for_index` found data it couldn't // recognize. Request the first font's offset, distinguishing // those two cases. match tt::get_font_offset_for_index(&self.0, 0) { None => return Err(Error::IllFormed), Some(offset) => offset, } }; let info = tt::FontInfo::new(self.0, offset as usize).ok_or(Error::IllFormed)?; Ok(Font { info }) } /// Gets the font at index `i` in the font collection, if it exists and is /// valid. The produced font borrows the font data that is either borrowed /// or owned by this font collection. pub fn font_at(&self, i: usize) -> Result<Font<'a>, Error> { let offset = tt::get_font_offset_for_index(&self.0, i as i32) .ok_or(Error::CollectionIndexOutOfBounds)?; let info = tt::FontInfo::new(self.0.clone(), offset as usize).ok_or(Error::IllFormed)?; Ok(Font { info }) } /// Converts `self` into an `Iterator` yielding each `Font` that exists /// within the collection. pub fn into_fonts(self) -> IntoFontsIter<'a> { IntoFontsIter { collection: self, next_index: 0, } } } pub struct IntoFontsIter<'a> { next_index: usize, collection: FontCollection<'a>, } impl<'a> Iterator for IntoFontsIter<'a> { type Item = Result<Font<'a>, Error>; fn next(&mut self) -> Option<Self::Item> { let result = self.collection.font_at(self.next_index); if let Err(Error::CollectionIndexOutOfBounds) = result { return None; } self.next_index += 1; Some(result) } } impl<'a> Font<'a> { /// Constructs a font from an array of bytes, this is a shortcut for /// `FontCollection::from_bytes` for collections comprised of a single font. pub fn from_bytes<B: Into<SharedBytes<'a>>>(bytes: B) -> Result<Font<'a>, Error> { FontCollection::from_bytes(bytes).and_then(|c| c.into_font()) } /// The "vertical metrics" for this font at a given scale. These metrics are /// shared by all of the glyphs in the font. See `VMetrics` for more detail. pub fn v_metrics(&self, scale: Scale) -> VMetrics { let vm = self.info.get_v_metrics(); let scale = self.info.scale_for_pixel_height(scale.y); VMetrics::from(vm) * scale } /// Get the unscaled VMetrics for this font, shared by all glyphs. /// See `VMetrics` for more detail. pub fn v_metrics_unscaled(&self) -> VMetrics { VMetrics::from(self.info.get_v_metrics()) } /// Returns the units per EM square of this font pub fn units_per_em(&self) -> u16 { self.info.units_per_em() } /// The number of glyphs present in this font. Glyph identifiers for this /// font will always be in the range `0..self.glyph_count()` pub fn glyph_count(&self) -> usize { self.info.get_num_glyphs() as usize } /// Returns the corresponding glyph for a Unicode code point or a glyph id /// for this font. /// /// If `id` is a `GlyphId`, it must be valid for this font; otherwise, this /// function panics. `GlyphId`s should always be produced by looking up some /// other sort of designator (like a Unicode code point) in a font, and /// should only be used to index the font they were produced for. /// /// Note that code points without corresponding glyphs in this font map to /// the ".notdef" glyph, glyph 0. pub fn glyph<C: IntoGlyphId>(&self, id: C) -> Glyph<'a> { let gid = id.into_glyph_id(self); assert!((gid.0 as usize) < self.glyph_count()); // font clone either a reference clone, or arc clone Glyph::new(GlyphInner::Proxy(self.clone(), gid.0)) } /// A convenience function. /// /// Returns an iterator that produces the glyphs corresponding to the code /// points or glyph ids produced by the given iterator `itr`. /// /// This is equivalent in behaviour to `itr.map(|c| font.glyph(c))`. pub fn glyphs_for<I: Iterator>(&self, itr: I) -> GlyphIter<'_, I> where I::Item: IntoGlyphId, { GlyphIter { font: self, itr } } /// Returns an iterator over the names for this font. pub fn font_name_strings(&self) -> tt::FontNameIter<'_, SharedBytes<'a>> { self.info.get_font_name_strings() } /// A convenience function for laying out glyphs for a string horizontally. /// It does not take control characters like line breaks into account, as /// treatment of these is likely to depend on the application. /// /// Note that this function does not perform Unicode normalisation. /// Composite characters (such as ö constructed from two code points, ¨ and /// o), will not be normalised to single code points. So if a font does not /// contain a glyph for each separate code point, but does contain one for /// the normalised single code point (which is common), the desired glyph /// will not be produced, despite being present in the font. Deal with this /// by performing Unicode normalisation on the input string before passing /// it to `layout`. The crate /// [unicode-normalization](http://crates.io/crates/unicode-normalization) /// is perfect for this purpose. /// /// Calling this function is equivalent to a longer sequence of operations /// involving `glyphs_for`, e.g. /// /// ```no_run /// # use rusttype::*; /// # let (scale, start) = (Scale::uniform(0.0), point(0.0, 0.0)); /// # let font: Font = unimplemented!(); /// font.layout("Hello World!", scale, start) /// # ; /// ``` /// /// produces an iterator with behaviour equivalent to the following: /// /// ```no_run /// # use rusttype::*; /// # let (scale, start) = (Scale::uniform(0.0), point(0.0, 0.0)); /// # let font: Font = unimplemented!(); /// font.glyphs_for("Hello World!".chars()) /// .scan((None, 0.0), |&mut (mut last, mut x), g| { /// let g = g.scaled(scale); /// if let Some(last) = last { /// x += font.pair_kerning(scale, last, g.id()); /// } /// let w = g.h_metrics().advance_width; /// let next = g.positioned(start + vector(x, 0.0)); /// last = Some(next.id()); /// x += w; /// Some(next) /// }) /// # ; /// ``` pub fn layout<'b>(&self, s: &'b str, scale: Scale, start: Point<f32>) -> LayoutIter<'_, 'b> { LayoutIter { font: self, chars: s.chars(), caret: 0.0, scale, start, last_glyph: None, } } /// Returns additional kerning to apply as well as that given by HMetrics /// for a particular pair of glyphs. pub fn pair_kerning<A, B>(&self, scale: Scale, first: A, second: B) -> f32 where A: IntoGlyphId, B: IntoGlyphId, { let first_id = first.into_glyph_id(self); let second_id = second.into_glyph_id(self); let factor = self.info.scale_for_pixel_height(scale.y) * (scale.x / scale.y); let kern = self.info.get_glyph_kern_advance(first_id.0, second_id.0); factor * kern as f32 } } #[derive(Clone)] pub struct GlyphIter<'a, I: Iterator> where I::Item: IntoGlyphId, { font: &'a Font<'a>, itr: I, } impl<'a, I: Iterator> Iterator for GlyphIter<'a, I> where I::Item: IntoGlyphId, { type Item = Glyph<'a>; fn next(&mut self) -> Option<Glyph<'a>> { self.itr.next().map(|c| self.font.glyph(c)) } } #[derive(Clone)] pub struct LayoutIter<'a, 'b> { font: &'a Font<'a>, chars: ::std::str::Chars<'b>, caret: f32, scale: Scale, start: Point<f32>, last_glyph: Option<GlyphId>, } impl<'a, 'b> Iterator for LayoutIter<'a, 'b> { type Item = PositionedGlyph<'a>; fn next(&mut self) -> Option<PositionedGlyph<'a>> { self.chars.next().map(|c| { let g = self.font.glyph(c).scaled(self.scale); if let Some(last) = self.last_glyph { self.caret += self.font.pair_kerning(self.scale, last, g.id()); } let g = g.positioned(point(self.start.x + self.caret, self.start.y)); self.caret += g.sg.h_metrics().advance_width; self.last_glyph = Some(g.id()); g }) } } impl<'a> Glyph<'a> { fn new(inner: GlyphInner<'a>) -> Glyph<'a> { Glyph { inner } } /// The font to which this glyph belongs. If the glyph is a standalone glyph /// that owns its resources, it no longer has a reference to the font which /// it was created from (using `standalone()`). In which case, `None` is /// returned. pub fn font(&self) -> Option<&Font<'a>> { match self.inner { GlyphInner::Proxy(ref f, _) => Some(f), GlyphInner::Shared(_) => None, } } /// The glyph identifier for this glyph. pub fn id(&self) -> GlyphId { match self.inner { GlyphInner::Proxy(_, id) => GlyphId(id), GlyphInner::Shared(ref data) => GlyphId(data.id), } } /// Augments this glyph with scaling information, making methods that depend /// on the scale of the glyph available. pub fn scaled(self, scale: Scale) -> ScaledGlyph<'a> { let (scale_x, scale_y) = match self.inner { GlyphInner::Proxy(ref font, _) => { let scale_y = font.info.scale_for_pixel_height(scale.y); let scale_x = scale_y * scale.x / scale.y; (scale_x, scale_y) } GlyphInner::Shared(ref data) => { let scale_y = data.scale_for_1_pixel * scale.y; let scale_x = scale_y * scale.x / scale.y; (scale_x, scale_y) } }; ScaledGlyph { g: self, api_scale: scale, scale: vector(scale_x, scale_y), } } /// Turns a `Glyph<'a>` into a `Glyph<'static>`. This produces a glyph that /// owns its resources, extracted from the font. This glyph can outlive the /// font that it comes from. /// /// Calling `standalone()` on a standalone glyph shares the resources, and /// is equivalent to `clone()`. pub fn standalone(&self) -> Glyph<'static> { match self.inner { GlyphInner::Proxy(ref font, id) => { Glyph::new(GlyphInner::Shared(Arc::new(SharedGlyphData { id, scale_for_1_pixel: font.info.scale_for_pixel_height(1.0), unit_h_metrics: { let hm = font.info.get_glyph_h_metrics(id); HMetrics { advance_width: hm.advance_width as f32, left_side_bearing: hm.left_side_bearing as f32, } }, extents: font.info.get_glyph_box(id).map(|bb| Rect { min: point(bb.x0 as i32, -(bb.y1 as i32)), max: point(bb.x1 as i32, -(bb.y0 as i32)), }), shape: font.info.get_glyph_shape(id), }))) } GlyphInner::Shared(ref data) => Glyph::new(GlyphInner::Shared(data.clone())), } } /// Get the data from this glyph (such as width, extents, vertices, etc.). /// Only possible if the glyph is a shared glyph. pub fn get_data(&self) -> Option<Arc<SharedGlyphData>> { match self.inner { GlyphInner::Proxy(..) => None, GlyphInner::Shared(ref s) => Some(s.clone()), } } } /// Part of a `Contour`, either a `Line` or a `Curve`. #[derive(Copy, Clone, Debug)] pub enum Segment { Line(Line), Curve(Curve), } /// A closed loop consisting of a sequence of `Segment`s. #[derive(Clone, Debug)] pub struct Contour { pub segments: Vec<Segment>, } impl<'a> ScaledGlyph<'a> { /// The glyph identifier for this glyph. pub fn id(&self) -> GlyphId { self.g.id() } /// The font to which this glyph belongs. If the glyph is a standalone glyph /// that owns its resources, it no longer has a reference to the font which /// it was created from (using `standalone()`). In which case, `None` is /// returned. pub fn font(&self) -> Option<&Font<'a>> { self.g.font() } /// A reference to this glyph without the scaling pub fn into_unscaled(self) -> Glyph<'a> { self.g } /// Removes the scaling from this glyph pub fn unscaled(&self) -> &Glyph<'a> { &self.g } /// Augments this glyph with positioning information, making methods that /// depend on the position of the glyph available. pub fn positioned(self, p: Point<f32>) -> PositionedGlyph<'a> { let bb = self.pixel_bounds_at(p); PositionedGlyph { sg: self, position: p, bb, } } pub fn scale(&self) -> Scale { self.api_scale } /// Retrieves the "horizontal metrics" of this glyph. See `HMetrics` for /// more detail. pub fn h_metrics(&self) -> HMetrics { match self.g.inner { GlyphInner::Proxy(ref font, id) => { let hm = font.info.get_glyph_h_metrics(id); HMetrics { advance_width: hm.advance_width as f32 * self.scale.x, left_side_bearing: hm.left_side_bearing as f32 * self.scale.x, } } GlyphInner::Shared(ref data) => HMetrics { advance_width: data.unit_h_metrics.advance_width * self.scale.x, left_side_bearing: data.unit_h_metrics.left_side_bearing * self.scale.y, }, } } fn shape_with_offset(&self, offset: Point<f32>) -> Option<Vec<Contour>> { use stb_truetype::VertexType; use std::mem::replace; match self.g.inner { GlyphInner::Proxy(ref font, id) => font.info.get_glyph_shape(id), GlyphInner::Shared(ref data) => data.shape.clone(), } .map(|shape| { let mut result = Vec::new(); let mut current = Vec::new(); let mut last = point(0.0, 0.0); for v in shape { let end = point( v.x as f32 * self.scale.x + offset.x, v.y as f32 * self.scale.y + offset.y, ); match v.vertex_type() { VertexType::MoveTo if !current.is_empty() => result.push(Contour { segments: replace(&mut current, Vec::new()), }), VertexType::LineTo => current.push(Segment::Line(Line { p: [last, end] })), VertexType::CurveTo => { let control = point( v.cx as f32 * self.scale.x + offset.x, v.cy as f32 * self.scale.y + offset.y, ); current.push(Segment::Curve(Curve { p: [last, control, end], })) } _ => (), } last = end; } if !current.is_empty() { result.push(Contour { segments: replace(&mut current, Vec::new()), }); } result }) } /// Produces a list of the contours that make up the shape of this glyph. /// Each contour consists of a sequence of segments. Each segment is either /// a straight `Line` or a `Curve`. /// /// The winding of the produced contours is clockwise for closed shapes, /// anticlockwise for holes. pub fn shape(&self) -> Option<Vec<Contour>> { self.shape_with_offset(point(0.0, 0.0)) } /// The bounding box of the shape of this glyph, not to be confused with /// `pixel_bounding_box`, the conservative pixel-boundary bounding box. The /// coordinates are relative to the glyph's origin. pub fn exact_bounding_box(&self) -> Option<Rect<f32>> { match self.g.inner { GlyphInner::Proxy(ref font, id) => font.info.get_glyph_box(id).map(|bb| Rect { min: point(bb.x0 as f32 * self.scale.x, -bb.y1 as f32 * self.scale.y), max: point(bb.x1 as f32 * self.scale.x, -bb.y0 as f32 * self.scale.y), }), GlyphInner::Shared(ref data) => data.extents.map(|bb| Rect { min: point( bb.min.x as f32 * self.scale.x, bb.min.y as f32 * self.scale.y, ), max: point( bb.max.x as f32 * self.scale.x, bb.max.y as f32 * self.scale.y, ), }), } } /// Constructs a glyph that owns its data from this glyph. This is similar /// to `Glyph::standalone`. See that function for more details. pub fn standalone(&self) -> ScaledGlyph<'static> { ScaledGlyph { g: self.g.standalone(), api_scale: self.api_scale, scale: self.scale, } } #[inline] fn pixel_bounds_at(&self, p: Point<f32>) -> Option<Rect<i32>> { // Use subpixel fraction in floor/ceil rounding to elimate rounding error // from identical subpixel positions let (x_trunc, x_fract) = (p.x.trunc() as i32, p.x.fract()); let (y_trunc, y_fract) = (p.y.trunc() as i32, p.y.fract()); match self.g.inner { GlyphInner::Proxy(ref font, id) => font .info .get_glyph_bitmap_box_subpixel(id, self.scale.x, self.scale.y, x_fract, y_fract) .map(|bb| Rect { min: point(x_trunc + bb.x0, y_trunc + bb.y0), max: point(x_trunc + bb.x1, y_trunc + bb.y1), }), GlyphInner::Shared(ref data) => data.extents.map(|bb| Rect { min: point( (bb.min.x as f32 * self.scale.x + x_fract).floor() as i32 + x_trunc, (bb.min.y as f32 * self.scale.y + y_fract).floor() as i32 + y_trunc, ), max: point( (bb.max.x as f32 * self.scale.x + x_fract).ceil() as i32 + x_trunc, (bb.max.y as f32 * self.scale.y + y_fract).ceil() as i32 + y_trunc, ), }), } } } impl<'a> PositionedGlyph<'a> { /// The glyph identifier for this glyph. pub fn id(&self) -> GlyphId { self.sg.id() } /// The font to which this glyph belongs. If the glyph is a standalone glyph /// that owns its resources, it no longer has a reference to the font which /// it was created from (using `standalone()`). In which case, `None` is /// returned. pub fn font(&self) -> Option<&Font<'a>> { self.sg.font() } /// A reference to this glyph without positioning pub fn unpositioned(&self) -> &ScaledGlyph<'a> { &self.sg } /// Removes the positioning from this glyph pub fn into_unpositioned(self) -> ScaledGlyph<'a> { self.sg } /// The conservative pixel-boundary bounding box for this glyph. This is the /// smallest rectangle aligned to pixel boundaries that encloses the shape /// of this glyph at this position. Note that the origin of the glyph, at /// pixel-space coordinates (0, 0), is at the top left of the bounding box. pub fn pixel_bounding_box(&self) -> Option<Rect<i32>> { self.bb } /// Similar to `ScaledGlyph::shape()`, but with the position of the glyph /// taken into account. pub fn shape(&self) -> Option<Vec<Contour>> { self.sg.shape_with_offset(self.position) } pub fn scale(&self) -> Scale { self.sg.api_scale } pub fn position(&self) -> Point<f32> { self.position } /// Rasterises this glyph. For each pixel in the rect given by /// `pixel_bounding_box()`, `o` is called: /// /// ```ignore /// o(x, y, v) /// ``` /// /// where `x` and `y` are the coordinates of the pixel relative to the `min` /// coordinates of the bounding box, and `v` is the analytically calculated /// coverage of the pixel by the shape of the glyph. Calls to `o` proceed in /// horizontal scanline order, similar to this pseudo-code: /// /// ```ignore /// let bb = glyph.pixel_bounding_box(); /// for y in 0..bb.height() { /// for x in 0..bb.width() { /// o(x, y, calc_coverage(&glyph, x, y)); /// } /// } /// ``` pub fn draw<O: FnMut(u32, u32, f32)>(&self, o: O) { use crate::geometry::{Curve, Line}; use stb_truetype::VertexType; let shape = match self.sg.g.inner { GlyphInner::Proxy(ref font, id) => { font.info.get_glyph_shape(id).unwrap_or_else(Vec::new) } GlyphInner::Shared(ref data) => data.shape.clone().unwrap_or_else(Vec::new), }; let bb = if let Some(bb) = self.bb.as_ref() { bb } else { return; }; let offset = vector(bb.min.x as f32, bb.min.y as f32); let mut lines = Vec::new(); let mut curves = Vec::new(); let mut last = point(0.0, 0.0); for v in shape { let end = point( v.x as f32 * self.sg.scale.x + self.position.x, -v.y as f32 * self.sg.scale.y + self.position.y, ) - offset; match v.vertex_type() { VertexType::LineTo => lines.push(Line { p: [last, end] }), VertexType::CurveTo => { let control = point( v.cx as f32 * self.sg.scale.x + self.position.x, -v.cy as f32 * self.sg.scale.y + self.position.y, ) - offset; curves.push(Curve { p: [last, control, end], }) } VertexType::MoveTo => {} } last = end; } rasterizer::rasterize( &lines, &curves, (bb.max.x - bb.min.x) as u32, (bb.max.y - bb.min.y) as u32, o, ); } /// Constructs a glyph that owns its data from this glyph. This is similar /// to `Glyph::standalone`. See that function for more details. pub fn standalone(&self) -> PositionedGlyph<'static> { PositionedGlyph { sg: self.sg.standalone(), bb: self.bb, position: self.position, } } /// Resets positioning information and recalculates the pixel bounding box pub fn set_position(&mut self, p: Point<f32>) { let p_diff = p - self.position; if relative_eq!(p_diff.x.fract(), 0.0) && relative_eq!(p_diff.y.fract(), 0.0) { if let Some(bb) = self.bb.as_mut() { let rounded_diff = vector(p_diff.x.round() as i32, p_diff.y.round() as i32); bb.min = bb.min + rounded_diff; bb.max = bb.max + rounded_diff; } } else { self.bb = self.sg.pixel_bounds_at(p); } self.position = p; } } /// The type for errors returned by rusttype. #[derive(Debug)] pub enum Error { /// Font data presented to rusttype is not in a format that the library /// recognizes. UnrecognizedFormat, /// Font data presented to rusttype was ill-formed (lacking necessary /// tables, for example). IllFormed, /// The caller tried to access the `i`'th font from a `FontCollection`, but /// the collection doesn't contain that many fonts. CollectionIndexOutOfBounds, /// The caller tried to convert a `FontCollection` into a font via /// `into_font`, but the `FontCollection` contains more than one font. CollectionContainsMultipleFonts, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::result::Result<(), fmt::Error> { f.write_str(std::error::Error::description(self)) } } impl std::error::Error for Error { fn description(&self) -> &str { use self::Error::*; match *self { UnrecognizedFormat => "Font data in unrecognized format", IllFormed => "Font data is ill-formed", CollectionIndexOutOfBounds => "Font collection has no font at the given index", CollectionContainsMultipleFonts => { "Attempted to convert collection into a font, \ but collection contais more than one font" } } } } impl std::convert::From<Error> for std::io::Error { fn from(error: Error) -> Self { std::io::Error::new(std::io::ErrorKind::Other, error) } }
use crate::utils::{get_current_directory, to_url}; use regex::Regex; use serde::Deserialize; use std::{path::Path, fs}; #[derive(Clone, Debug, Deserialize)] pub struct Languages { pub en: String, pub es: String, } #[derive(Clone, Debug, Deserialize)] pub struct ProjectDate { pub day: Option<i64>, pub month: usize, pub year: i64, } #[derive(Clone, Debug, Deserialize)] #[serde(tag = "type")] pub enum ProjectLink { #[serde(rename = "single")] Single { name: String, url: String }, #[serde(rename = "multiple")] Multiple { name: Languages, url: String }, } impl ProjectLink { pub fn format(&self, page_lang: &String) -> (String, String) { match self { ProjectLink::Single { name, url } => (name.clone(), url.clone()), ProjectLink::Multiple { name, url } => ( match page_lang.as_str() { "es" => name.es.clone(), _ => name.en.clone(), }, url.clone(), ), } } } #[derive(Clone, Debug, Deserialize)] pub struct Project { pub images: Vec<String>, pub category: usize, pub name: Languages, pub date: ProjectDate, pub description: Languages, pub links: Option<Vec<ProjectLink>>, } impl Project { pub fn get_main_image(&self) -> String { if self.images.len() >= 1 { self.images[0].clone() } else { String::new() } } pub fn get_name(&self, lang: &String) -> String { if lang == "es" { self.name.es.clone() } else { self.name.en.clone() } } pub fn get_url(&self, lang: &String) -> String { to_url(&self.get_name(lang)) } pub fn get_description(&self, lang: &String) -> String { if lang == "es" { self.description.es.clone() } else { self.description.en.clone() } } } #[derive(Clone, Debug, Deserialize)] pub struct Projects { pub categories: Vec<Languages>, pub projects: Vec<Project>, } impl Projects { pub fn get_category(&self, category_index: usize, page_lang: &String) -> String { let page_category = &self.categories[category_index]; if page_lang == "es" { page_category.es.clone() } else { page_category.en.clone() } } pub fn get_project(&self, name: &String, lang: &String) -> Option<Project> { for project in self.projects.iter() { if &project.get_url(lang) == name { return Some(project.clone()); } } None } } impl Projects { pub fn new() -> Self { Self { categories: Vec::new(), projects: Vec::new(), } } pub fn get(&mut self) -> Result<(), String> { let file_rute: String = format!("{}assets/projects.json", get_current_directory()); match fs::read_to_string(&file_rute) { Ok(projects_json) => match serde_json::from_str::<Projects>(&projects_json) { Ok(projects) => { self.categories = projects.categories; self.projects = projects.projects; Ok(()) }, Err(e) => Err(format!("Cannot parse file: {} - {}", file_rute, e)), }, Err(_) => Err(format!("Cannot read file: {}", file_rute)), } } } #[derive(Clone, Debug)] pub struct BlogPostDate { pub day: i64, pub month: usize, pub year: i64, } impl BlogPostDate { pub fn new() -> Self { Self { day: 0, month: 1, year: 2020, } } pub fn from(text: String) -> Self { let mut date = Self::new(); let parts: Vec<String> = text.split("-").map(|e| e.to_string()).collect(); if parts.len() == 3 { date.year = parts[0].parse().expect("Cannot parse year."); date.month = parts[1].parse().expect("Cannot parse month."); date.day = parts[2].parse().expect("Cannot parse day."); } date } pub fn to_string(&self) -> String { let month: String = format!("0{}", self.month); let day: String = format!("0{}", self.day); format!("{}-{}-{}", self.year, &month[month.len() - 2..], &day[day.len() - 2..]) } } #[derive(Clone, Debug)] pub struct BlogPostTitle { pub size: usize, pub title: String, } impl BlogPostTitle { pub fn new(size: usize, title: String) -> Self { Self { size, title, } } pub fn get_url(&self) -> String { to_url(&self.title) } } #[derive(Clone, Debug)] pub struct BlogPost { pub url: String, pub lang: String, pub title: String, pub description: String, pub image: String, pub posted_date: BlogPostDate, pub titles: Vec<BlogPostTitle>, pub content: String, pub content_html: String, } impl BlogPost { pub fn get_full_url(&self) -> String { format!("{}/{}", self.posted_date.to_string(), self.url) } pub fn get_reading_time(&self) -> String { let words: Vec<&str> = self.content.split(" ").collect(); let time = words.len() / 200; format!("{}min", time) } } #[derive(Clone, Debug)] pub struct Blog { pub posts: Vec<BlogPost>, } impl Blog { pub fn new() -> Self { Self { posts: Vec::new(), } } fn read_file(&mut self, file_rute: String) -> Result<(), String> { let file_path = Path::new(&file_rute); if !file_path.exists() || !file_path.is_file() { return Err(format!("{} does not exist or is not a file.", file_rute)); } if !file_rute.ends_with(".md") { return Err(format!("{} is not a markdown file.", file_rute)); } let url: String = file_path.file_name().expect("Cannot parse the file name.").to_str().unwrap().replace(".md", ""); let parent_directory = file_path.parent().expect("Cannot get the parent directory."); let parent_name: &str = parent_directory.file_name().expect("Cannot parse the parent directory name.").to_str().unwrap_or(""); let posted_date = BlogPostDate::from(parent_name.to_string()); let blog_post_content: String = fs::read_to_string(&file_rute).expect("Cannot read file."); let table_expression = Regex::new(r"^(---(?P<text>[\s\S]+)---)").unwrap(); let table_captures = table_expression.captures(&blog_post_content).unwrap(); let blog_post_table: &str = &table_captures["text"].trim(); let table_parts: Vec<&str> = blog_post_table.split("\n").collect(); let mut lang: String = String::new(); let mut title: String = String::new(); let mut description: String = String::new(); let mut image: String = String::new(); for table_part in table_parts.iter() { let sub_parts: Vec<&str> = table_part.split(":").collect(); if sub_parts.len() >= 2 { let value: String = sub_parts[1..].join(":").trim().to_string(); match sub_parts[0].trim() { "lang" => { lang = value; }, "title" => { title = value; }, "description" => { description = value; }, "image" => { image = value; }, _ => {}, } } } let mut titles: Vec<BlogPostTitle> = Vec::new(); let blog_post_content: String = blog_post_content.replace(&table_captures["text"], ""); let content: String = blog_post_content.trim().to_string(); let title_expression = Regex::new(r"(?P<size>#{1,6})\s+(?P<text>[\w\s?¿¡!\(\)]+\n)").unwrap(); for title_capture in title_expression.captures_iter(&content) { let size: usize = title_capture["size"].trim().to_string().len(); let text: String = title_capture["text"].split("\n").collect::<Vec<&str>>()[0].trim().to_string(); titles.push(BlogPostTitle::new(size, text)); } let mut comrak_options = comrak::ComrakOptions::default(); comrak_options.extension.header_ids = Some(String::new()); let content_html = comrak::markdown_to_html(&content, &comrak_options); self.posts.push(BlogPost { url, lang, title, description, image, posted_date, titles, content, content_html, }); Ok(()) } fn read(&mut self, rute: String) -> Result<(), String> { let rute_path = Path::new(&rute); if !rute_path.exists() { Err(format!("{} does not exist.", rute)) } else if rute_path.is_dir() { for entry in fs::read_dir(&rute_path).expect("Cannot read the directory.") { let entry = entry.expect("Cannot parse entry file."); let entry_path = entry.path(); if entry_path.is_dir() { self.read(entry_path.display().to_string()).expect("Cannot read directory."); } else if entry_path.is_file() { self.read_file(entry_path.display().to_string()).expect("Cannot read file."); } } Ok(()) } else { self.read_file(rute) } } pub fn get(&mut self) -> Result<(), String> { self.read(format!("{}assets/blog", get_current_directory())) } pub fn get_post(&self, url: &String) -> Option<BlogPost> { for blog_post in self.posts.iter() { if &blog_post.get_full_url() == url { return Some(blog_post.clone()); } } None } }
fn main() { dbg!(solve(5)); dbg!(solve(1001)); } fn solve(n: usize) -> usize { let mut last = 1; let mut sum = 1; let mut stepsize = 2; for _ in 0..n / 2 { for _i in 1..=4 { last = last + stepsize; sum += last; } stepsize += 2; } sum }
use std::rc::Rc; use wasm_bindgen::prelude::*; use web_sys::*; use wasm_bindgen::JsCast; use wasm_bindgen::JsValue; use web_sys::*; use web_sys::WebGl2RenderingContext as GL; use std::borrow::Borrow; pub struct Texture { unit: u32, } impl Texture { pub fn new(gl: &Rc<GL>, path: &str, unit: u32) -> Self { let image = Rc::new(HtmlImageElement::new().unwrap()); let onload_cb = Closure::wrap( onload(gl.clone(), image.clone(), unit)); let image : &HtmlImageElement = image.borrow(); image.set_src(path); image.set_onload(Some(onload_cb.as_ref().unchecked_ref())); onload_cb.forget(); Texture { unit } } } fn onload(gl: Rc<GL>, image: Rc<HtmlImageElement>, unit: u32) -> Box<Fn()> { Box::new(move || { let texture = gl.create_texture(); gl.active_texture(GL::TEXTURE0 + unit); gl.bind_texture(GL::TEXTURE_2D, texture.as_ref()); gl.pixel_storei(GL::UNPACK_FLIP_Y_WEBGL, 1); gl.tex_parameteri(GL::TEXTURE_2D, GL::TEXTURE_MIN_FILTER, GL::NEAREST as i32); gl.tex_parameteri(GL::TEXTURE_2D, GL::TEXTURE_MAG_FILTER, GL::NEAREST as i32); gl.tex_image_2d_with_u32_and_u32_and_html_image_element( GL::TEXTURE_2D, 0, GL::RGBA as i32, GL::RGBA, GL::UNSIGNED_BYTE, &image.borrow(), ).expect("Texture image 2d"); info!("Image loaded!"); }) }
use super::CtagsCommonArgs; use crate::app::Args; use anyhow::Result; use clap::Parser; use maple_core::find_usages::{CtagsSearcher, QueryType}; use maple_core::tools::ctags::TagsGenerator; #[derive(Parser, Debug, Clone)] struct TagsFileArgs { /// Same with the `--kinds-all` option of ctags. #[clap(long, default_value = "*")] kinds_all: String, /// Same with the `--fields` option of ctags. #[clap(long, default_value = "*")] fields: String, /// Same with the `--extras` option of ctags. #[clap(long, default_value = "*")] extras: String, } /// Manipulate the tags file. #[derive(Parser, Debug, Clone)] pub struct TagsFile { /// Arguments for creating tags file. #[clap(flatten)] t_args: TagsFileArgs, /// Ctags common arguments. #[clap(flatten)] c_args: CtagsCommonArgs, /// Search the tag matching the given query. #[clap(long)] query: Option<String>, /// Generate the tags file whether the tags file exists or not. #[clap(long)] force_generate: bool, } impl TagsFile { pub fn run(&self, _args: Args) -> Result<()> { let dir = self.c_args.dir()?; let exclude_opt = self.c_args.exclude_opt(); let tags_generator = TagsGenerator::new( self.c_args.languages.clone(), &self.t_args.kinds_all, &self.t_args.fields, &self.t_args.extras, &self.c_args.files, &dir, &exclude_opt, ); let tags_searcher = CtagsSearcher::new(tags_generator); if let Some(ref query) = self.query { let symbols = tags_searcher.search_symbols(query, QueryType::StartWith, self.force_generate)?; for symbol in symbols { println!("{symbol:?}"); } } Ok(()) } }
extern crate hyper; extern crate hyper_multipart_rfc7578 as hyper_multipart; use hyper::{body::Buf, Body, Client, Method, Request}; use hyper_multipart::client::multipart; use serde::{Deserialize, Serialize}; use serde_json::json; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; #[allow(non_snake_case)] #[derive(Debug, Serialize, Deserialize)] pub struct StoreFile { pub id: String, pub filename: String, pub contentType: String, pub size: i32, pub uploadDate: String, } #[allow(non_snake_case)] #[derive(Debug, Serialize, Deserialize)] pub struct DeleteFilesResponse { pub ids: Vec<String>, pub errors: Vec<String>, } pub async fn list_files(server_url: &String) -> Result<Vec<StoreFile>> { let client = Client::new(); let uri = (String::from(server_url) + "/api/files").parse()?; let res = client.get(uri).await?; let body = hyper::body::aggregate(res).await?; let store_files = serde_json::from_reader(body.reader())?; Ok(store_files) } pub async fn upload_file(server_url: &String, file_path: &String) -> Result<StoreFile> { let uri = String::from(server_url) + "/api/files"; let client = Client::builder().build_http(); let mut form = multipart::Form::default(); let mime_type = mime_guess::from_path(file_path) .first() .unwrap_or(mime_guess::mime::TEXT_PLAIN); form.add_file_with_mime("file", file_path, mime_type)?; let req_builder = Request::post(uri); let req = form.set_body::<multipart::Body>(req_builder)?; match client.request(req).await { Ok(res) => { let body = hyper::body::aggregate(res).await?; let store_file: StoreFile = serde_json::from_reader(body.reader())?; Ok(store_file) } Err(er) => { let error: Box<dyn std::error::Error + Send + Sync> = er.to_string().into(); Err(error) } } } pub async fn delete_files(server_url: &String, ids: &Vec<String>) -> Result<DeleteFilesResponse> { let uri = String::from(server_url) + "/api/files"; let delete_body = json!({ "ids": ids }); let req = Request::builder() .method(Method::DELETE) .uri(uri) .header("content-type", "application/json") .body(Body::from(delete_body.to_string()))?; let client = Client::new(); match client.request(req).await { Ok(res) => { let body = hyper::body::aggregate(res).await?; let response: DeleteFilesResponse = serde_json::from_reader(body.reader())?; Ok(response) } Err(er) => { let error: Box<dyn std::error::Error + Send + Sync> = er.to_string().into(); Err(error) } } } #[cfg(test)] mod tests { use super::*; #[derive(Debug, Serialize, Deserialize)] struct TestConfig { api_url: String, } impl Default for TestConfig { fn default() -> Self { Self { api_url: String::from("http://localhost:3000"), } } } static TEST_CONFIG_NAME: &str = "test"; #[actix_rt::test] async fn test_upload_file() { let config: TestConfig = confy::load(TEST_CONFIG_NAME).unwrap(); let url = config.api_url; let file_url = String::from(file!()); let before_store_files = list_files(&url).await.unwrap(); let new_store_file = upload_file(&url, &file_url).await.unwrap(); let after_store_files = list_files(&url).await.unwrap(); let _ = delete_files(&url, &vec![new_store_file.id]).await.unwrap(); assert!(after_store_files.len() > before_store_files.len()); assert_eq!(new_store_file.filename, "lib.rs"); } #[actix_rt::test] async fn test_list_files() { let config: TestConfig = confy::load(TEST_CONFIG_NAME).unwrap(); let url = config.api_url; let file_url = String::from(file!()); let new_store_file = upload_file(&url, &file_url).await.unwrap(); let store_files = list_files(&url).await.unwrap(); let _ = delete_files(&url, &vec![new_store_file.id]).await.unwrap(); assert!(store_files.len() > 0); } #[actix_rt::test] async fn test_delete_files() { let config: TestConfig = confy::load(TEST_CONFIG_NAME).unwrap(); let url = config.api_url; let file_url = String::from(file!()); let new_store_file = upload_file(&url, &file_url).await.unwrap(); let ids_to_delete = vec![new_store_file.id.clone()]; let delete_response = delete_files(&url, &ids_to_delete).await.unwrap(); assert_eq!(delete_response.ids.len(), 1); assert_eq!(delete_response.ids[0], new_store_file.id); assert_eq!(delete_response.errors.len(), 0); } }
use bit_vec::BitVec; use std::cmp; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> { let file = File::open(filename).expect("no such file"); let buf = BufReader::new(file); buf.lines() .map(|l| l.expect("Could not parse line")) .collect() } fn main() { let lines = lines_from_file("input.txt"); let mut max_id = 0; let mut seats = BitVec::from_elem(128 * 8, false); for line in lines { let mut min = 0; let mut max = 127; for c in line.chars().take(7) { let w = (max - min) / 2 + 1; if c == 'F' { max -= w } else { min += w } } let row = min; min = 0; max = 7; for c in line.chars().skip(7) { let w = (max - min) / 2 + 1; if c == 'L' { max -= w } else { min += w } } let col = min; seats.set(row * 8 + col, true); let id = row * 8 + col; max_id = cmp::max(max_id, id); } dbg!(max_id); 'done: for row in 0..128 { for (i, c) in seats.iter().skip(row * 8).take(8).enumerate() { if row > 4 && !c { dbg!(row * 8 + i); break 'done; } } } }
use std::net::TcpStream; use std::io; use std::sync::Arc; use std::path::Path; use openssl::ssl::{self, SslFiletype, SslMethod, SslVerifyMode}; pub type SslStream = ssl::SslStream<TcpStream>; pub type SslError = ssl::Error; #[derive(Debug, Clone)] pub struct SslContext { inner: Arc<ssl::SslContext> } impl Default for SslContext { fn default() -> SslContext { SslContext { inner: Arc::new(ssl::SslContext::builder(SslMethod::tls()).unwrap().build()) } } } impl SslContext { pub fn new(context: ssl::SslContext) -> Self { SslContext { inner: Arc::new(context) } } pub fn with_cert_and_key<C, K>(cert: C, key: K) -> Result<SslContext, SslError> where C: AsRef<Path>, K: AsRef<Path> { let mut ctx = ssl::SslContext::builder(SslMethod::tls())?; ctx.set_cipher_list("DEFAULT")?; ctx.set_certificate_file(cert.as_ref(), SslFiletype::PEM)?; ctx.set_private_key_file(key.as_ref(), SslFiletype::PEM)?; ctx.set_verify(SslVerifyMode::NONE); Ok(SslContext { inner: Arc::new(ctx.build()) }) } pub fn with_cert_and_key_and_ca<C, K, A>(cert: C, key: K, ca: A) -> Result<SslContext, SslError> where C: AsRef<Path>, K: AsRef<Path>, A: AsRef<Path> { let mut ctx = ssl::SslContext::builder(SslMethod::tls())?; ctx.set_cipher_list("DEFAULT")?; ctx.set_certificate_file(cert.as_ref(), SslFiletype::PEM)?; ctx.set_private_key_file(key.as_ref(), SslFiletype::PEM)?; ctx.set_ca_file(ca.as_ref())?; ctx.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); Ok(SslContext { inner: Arc::new(ctx.build()) }) } pub fn accept(&self, stream: TcpStream) -> Result<SslStream, io::Error> { match ssl::Ssl::new(&*self.inner)?.accept(stream) { Ok(stream) => Ok(stream), Err(err) => Err(io::Error::new(io::ErrorKind::ConnectionAborted, err).into()) } } pub fn connect(&self, stream: TcpStream) -> Result<SslStream, io::Error> { match ssl::Ssl::new(&*self.inner)?.connect(stream) { Ok(stream) => Ok(stream), Err(err) => Err(io::Error::new(io::ErrorKind::ConnectionAborted, err).into()) } } }
#[doc = r" Value read from the register"] pub struct R { bits: u32, } impl super::SUM { #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } } #[doc = r" Value of the field"] pub struct CRC_SUMR { bits: u32, } impl CRC_SUMR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:31 - The most recent CRC sum can be read through this register with selected bit order and 1's complement post-processes."] #[inline] pub fn crc_sum(&self) -> CRC_SUMR { let bits = { const MASK: u32 = 4294967295; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u32 }; CRC_SUMR { bits } } }
use yew::format::Json; use yew::prelude::*; use yew::services::storage::Area; use yew::services::StorageService; use serde_derive::{Deserialize, Serialize}; const PROJECT_STORE_KEY: &str = "org.amethyst-engine.projects"; pub enum Msg {} pub struct ProjectStore { key: &'static str, storage: StorageService, database: ProjectDatabase, } #[derive(Clone, Default, Debug, Serialize, Deserialize)] pub struct ProjectDatabase { projects: Vec<Project>, } impl ProjectDatabase { pub fn new() -> ProjectDatabase { ProjectDatabase { projects: vec![] } } } impl ProjectStore { pub fn new() -> ProjectStore { ProjectStore { key: PROJECT_STORE_KEY, storage: StorageService::new(Area::Local), database: ProjectDatabase::new(), } } /// Adds a project to the storage. Note that this only adds it to the local browser storage. pub fn add_project(&mut self, name: &str) { let new_project = Project::new(name); self.database.projects.push(new_project); let json_data = Json(&self.database.projects); self.storage.store(self.key, json_data); } /// Checks if a project exists or not. Note that this only checks local browser storage. pub fn project_exists(&self, name: &str) -> bool { for project in &self.database.projects { if project.name == name { return true; } } false } } impl Default for ProjectStore { fn default() -> Self { Self::new() } } impl Component for ProjectStore { type Message = Msg; type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { let mut storage = StorageService::new(Area::Local); let Json(database) = storage.restore(PROJECT_STORE_KEY); let database = database.unwrap_or_else(|_| ProjectDatabase::new()); ProjectStore { key: PROJECT_STORE_KEY, storage, database, } } fn update(&mut self, _msg: Self::Message) -> ShouldRender { true } } /// Model that represents an entire Project and its resources #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Project { name: String, } impl Project { pub fn new(name: &str) -> Project { Project { name: name.to_string(), } } } #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Prefab {} impl Prefab { pub fn new() -> Prefab { Prefab {} } }
extern crate kernel32; extern crate win32_error; extern crate winapi; use {OSVersion, Result}; use self::win32_error::Win32Error; use self::winapi::sysinfoapi::MEMORYSTATUSEX; use self::winapi::winnt::OSVERSIONINFOEXW; use semver::{Identifier, Version}; use std::ffi::OsString; use std::mem; use std::os::windows::ffi::OsStringExt; pub type PlatformError = Win32Error; /// Get the operating system. /// /// # Remarks /// /// Returns Windows 8 for version of Windows above 8 (FIXME: /// https://msdn.microsoft.com/en-us/library/windows/desktop/dn481241(v=vs.85). /// aspx). /// /// # Requirements /// /// At least Windows 2000 Professional/Server. pub fn os() -> Result<OSVersion> { let mut buf: OSVERSIONINFOEXW = unsafe { mem::uninitialized() }; buf.dwOSVersionInfoSize = mem::size_of::<OSVERSIONINFOEXW>() as u32; let buf_ptr = &mut buf as *mut OSVERSIONINFOEXW; if unsafe { kernel32::GetVersionExW(mem::transmute(buf_ptr)) } == 0 { return Err(Win32Error::new().into()); } let version = Version { major: u64::from(buf.dwMajorVersion), minor: u64::from(buf.dwMinorVersion), patch: u64::from(buf.dwBuildNumber), pre: Vec::new(), build: vec![ Identifier::AlphaNumeric( OsString::from_wide(&buf.szCSDVersion) .to_string_lossy() .into_owned() ), ], }; Ok(OSVersion { name: format!("Windows {}", version), version, service_pack_version: Version { major: u64::from(buf.wServicePackMajor), minor: u64::from(buf.wServicePackMinor), patch: 0, pre: Vec::new(), build: Vec::new(), }, }) } pub fn total_memory() -> u64 { let mut buf: MEMORYSTATUSEX = unsafe { mem::uninitialized() }; buf.dwLength = mem::size_of::<MEMORYSTATUSEX>() as u32; unsafe { kernel32::GlobalMemoryStatusEx(&mut buf as *mut MEMORYSTATUSEX); } buf.ullTotalPhys }
use std::cell::RefCell; use std::fmt; use std::rc::Rc; use serde::{Deserialize, Serialize}; use super::interrupt::IrqBitmask; use super::sysbus::{BoxedMemory, SysBus}; use super::Bus; use super::VideoInterface; use crate::bitfield::Bit; use crate::num::FromPrimitive; mod render; use render::Point; mod layer; mod mosaic; mod rgb15; mod sfx; mod window; pub use rgb15::Rgb15; pub use window::*; pub mod regs; pub use regs::*; #[allow(unused)] pub mod consts { pub const VIDEO_RAM_SIZE: usize = 128 * 1024; pub const PALETTE_RAM_SIZE: usize = 1 * 1024; pub const OAM_SIZE: usize = 1 * 1024; pub const VRAM_ADDR: u32 = 0x0600_0000; pub const DISPLAY_WIDTH: usize = 240; pub const DISPLAY_HEIGHT: usize = 160; pub const VBLANK_LINES: usize = 68; pub(super) const CYCLES_PIXEL: usize = 4; pub(super) const CYCLES_HDRAW: usize = 960 + 46; pub(super) const CYCLES_HBLANK: usize = 272 - 46; pub(super) const CYCLES_SCANLINE: usize = 1232; pub(super) const CYCLES_VDRAW: usize = 197120; pub(super) const CYCLES_VBLANK: usize = 83776; pub const TILE_SIZE: u32 = 0x20; } pub use self::consts::*; #[derive(Debug, Primitive, Copy, Clone)] pub enum PixelFormat { BPP4 = 0, BPP8 = 1, } #[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)] #[serde(deny_unknown_fields)] pub enum GpuState { HDraw = 0, HBlank, VBlankHDraw, VBlankHBlank, } impl Default for GpuState { fn default() -> GpuState { GpuState::HDraw } } impl GpuState { pub fn is_vblank(&self) -> bool { match self { VBlankHBlank | VBlankHDraw => true, _ => false, } } } use GpuState::*; #[derive(Serialize, Deserialize, Clone)] pub struct Scanline { inner: Vec<Rgb15>, } impl Default for Scanline { fn default() -> Scanline { Scanline { inner: vec![Rgb15::TRANSPARENT; DISPLAY_WIDTH], } } } impl fmt::Debug for Scanline { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "...") } } impl std::ops::Index<usize> for Scanline { type Output = Rgb15; fn index(&self, index: usize) -> &Self::Output { &self.inner[index] } } impl std::ops::IndexMut<usize> for Scanline { fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.inner[index] } } #[derive(Serialize, Deserialize, Debug, Default, Clone)] pub struct Background { pub bgcnt: BgControl, pub bgvofs: u16, pub bghofs: u16, line: Scanline, // for mosaic mosaic_first_row: Scanline, } #[derive(Debug, Default, Copy, Clone)] pub struct AffineMatrix { pub pa: i32, pub pb: i32, pub pc: i32, pub pd: i32, } #[derive(Serialize, Deserialize, Debug, Default, Copy, Clone)] pub struct BgAffine { pub pa: i16, // dx pub pb: i16, // dmx pub pc: i16, // dy pub pd: i16, // dmy pub x: i32, pub y: i32, pub internal_x: i32, pub internal_y: i32, } #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct ObjBufferEntry { pub(super) window: bool, pub(super) alpha: bool, pub(super) color: Rgb15, pub(super) priority: u16, } impl Default for ObjBufferEntry { fn default() -> ObjBufferEntry { ObjBufferEntry { window: false, alpha: false, color: Rgb15::TRANSPARENT, priority: 4, } } } type VideoDeviceRcRefCell = Rc<RefCell<dyn VideoInterface>>; #[derive(Serialize, Deserialize, Clone, DebugStub)] pub struct Gpu { pub state: GpuState, /// how many cycles left until next gpu state ? cycles_left_for_current_state: usize, // registers pub vcount: usize, // VCOUNT pub dispcnt: DisplayControl, pub dispstat: DisplayStatus, pub backgrounds: [Background; 4], pub bg_aff: [BgAffine; 2], pub win0: Window, pub win1: Window, pub winout_flags: WindowFlags, pub winobj_flags: WindowFlags, pub mosaic: RegMosaic, pub bldcnt: BlendControl, pub bldalpha: BlendAlpha, pub bldy: u16, pub palette_ram: BoxedMemory, pub vram: BoxedMemory, pub oam: BoxedMemory, #[debug_stub = "Sprite Buffer"] pub obj_buffer: Vec<ObjBufferEntry>, #[debug_stub = "Frame Buffer"] pub(super) frame_buffer: Vec<u32>, } impl Gpu { pub fn new() -> Gpu { Gpu { dispcnt: DisplayControl(0x80), dispstat: DisplayStatus(0), backgrounds: [ Background::default(), Background::default(), Background::default(), Background::default(), ], bg_aff: [BgAffine::default(); 2], win0: Window::default(), win1: Window::default(), winout_flags: WindowFlags::from(0), winobj_flags: WindowFlags::from(0), mosaic: RegMosaic(0), bldcnt: BlendControl(0), bldalpha: BlendAlpha(0), bldy: 0, state: HDraw, vcount: 0, cycles_left_for_current_state: CYCLES_HDRAW, palette_ram: BoxedMemory::new(vec![0; PALETTE_RAM_SIZE].into_boxed_slice()), vram: BoxedMemory::new(vec![0; VIDEO_RAM_SIZE].into_boxed_slice()), oam: BoxedMemory::new(vec![0; OAM_SIZE].into_boxed_slice()), obj_buffer: vec![Default::default(); DISPLAY_WIDTH * DISPLAY_HEIGHT], frame_buffer: vec![0; DISPLAY_WIDTH * DISPLAY_HEIGHT], } } pub fn skip_bios(&mut self) { for i in 0..2 { self.bg_aff[i].pa = 0x100; self.bg_aff[i].pb = 0; self.bg_aff[i].pc = 0; self.bg_aff[i].pd = 0x100; } } /// helper method that reads the palette index from a base address and x + y pub fn read_pixel_index(&self, addr: u32, x: u32, y: u32, format: PixelFormat) -> usize { match format { PixelFormat::BPP4 => self.read_pixel_index_bpp4(addr, x, y), PixelFormat::BPP8 => self.read_pixel_index_bpp8(addr, x, y), } } #[inline] pub fn read_pixel_index_bpp4(&self, addr: u32, x: u32, y: u32) -> usize { let ofs = addr - VRAM_ADDR + index2d!(u32, x / 2, y, 4); let ofs = ofs as usize; let byte = self.vram.read_8(ofs as u32); if x & 1 != 0 { (byte >> 4) as usize } else { (byte & 0xf) as usize } } #[inline] pub fn read_pixel_index_bpp8(&self, addr: u32, x: u32, y: u32) -> usize { let ofs = addr - VRAM_ADDR; self.vram.read_8(ofs + index2d!(u32, x, y, 8)) as usize } #[inline(always)] pub fn get_palette_color(&self, index: u32, palette_index: u32, offset: u32) -> Rgb15 { if index == 0 || (palette_index != 0 && index % 16 == 0) { return Rgb15::TRANSPARENT; } Rgb15( self.palette_ram .read_16(offset + 2 * index + 0x20 * palette_index), ) } #[inline] pub(super) fn obj_buffer_get(&self, x: usize, y: usize) -> &ObjBufferEntry { &self.obj_buffer[index2d!(x, y, DISPLAY_WIDTH)] } #[inline] pub(super) fn obj_buffer_get_mut(&mut self, x: usize, y: usize) -> &mut ObjBufferEntry { &mut self.obj_buffer[index2d!(x, y, DISPLAY_WIDTH)] } pub fn get_ref_point(&self, bg: usize) -> Point { assert!(bg == 2 || bg == 3); ( self.bg_aff[bg - 2].internal_x, self.bg_aff[bg - 2].internal_y, ) } pub fn render_scanline(&mut self) { if self.dispcnt.enable_obj() { self.render_objs(); } match self.dispcnt.mode() { 0 => { for bg in 0..=3 { if self.dispcnt.enable_bg(bg) { self.render_reg_bg(bg); } } self.finalize_scanline(0, 3); } 1 => { if self.dispcnt.enable_bg(2) { self.render_aff_bg(2); } if self.dispcnt.enable_bg(1) { self.render_reg_bg(1); } if self.dispcnt.enable_bg(0) { self.render_reg_bg(0); } self.finalize_scanline(0, 2); } 2 => { if self.dispcnt.enable_bg(3) { self.render_aff_bg(3); } if self.dispcnt.enable_bg(2) { self.render_aff_bg(2); } self.finalize_scanline(2, 3); } 3 => { self.render_mode3(2); self.finalize_scanline(2, 2); } 4 => { self.render_mode4(2); self.finalize_scanline(2, 2); } _ => panic!("{:?} not supported", self.dispcnt.mode()), } // self.mosaic_sfx(); } fn update_vcount(&mut self, value: usize, irqs: &mut IrqBitmask) { self.vcount = value; let vcount_setting = self.dispstat.vcount_setting(); self.dispstat .set_vcount_flag(vcount_setting == self.vcount as u16); if self.dispstat.vcount_irq_enable() && self.dispstat.get_vcount_flag() { irqs.set_LCD_VCounterMatch(true); } } /// Clears the gpu obj buffer pub fn obj_buffer_reset(&mut self) { for x in self.obj_buffer.iter_mut() { *x = Default::default(); } } pub fn get_frame_buffer(&self) -> &[u32] { &self.frame_buffer } pub fn on_state_completed( &mut self, completed: GpuState, sb: &mut SysBus, irqs: &mut IrqBitmask, video_device: &VideoDeviceRcRefCell, ) { match completed { HDraw => { // Transition to HBlank self.state = HBlank; self.cycles_left_for_current_state = CYCLES_HBLANK; self.dispstat.set_hblank_flag(true); if self.dispstat.hblank_irq_enable() { irqs.set_LCD_HBlank(true); }; sb.io.dmac.notify_hblank(); } HBlank => { self.update_vcount(self.vcount + 1, irqs); if self.vcount < DISPLAY_HEIGHT { self.state = HDraw; self.dispstat.set_hblank_flag(false); self.render_scanline(); // update BG2/3 reference points on the end of a scanline for i in 0..2 { self.bg_aff[i].internal_x += self.bg_aff[i].pb as i16 as i32; self.bg_aff[i].internal_y += self.bg_aff[i].pd as i16 as i32; } self.cycles_left_for_current_state = CYCLES_HDRAW; } else { // latch BG2/3 reference points on vblank for i in 0..2 { self.bg_aff[i].internal_x = self.bg_aff[i].x; self.bg_aff[i].internal_y = self.bg_aff[i].y; } self.dispstat.set_vblank_flag(true); self.dispstat.set_hblank_flag(false); if self.dispstat.vblank_irq_enable() { irqs.set_LCD_VBlank(true); }; sb.io.dmac.notify_vblank(); video_device.borrow_mut().render(&self.frame_buffer); self.obj_buffer_reset(); self.cycles_left_for_current_state = CYCLES_HDRAW; self.state = VBlankHDraw; } } VBlankHDraw => { self.cycles_left_for_current_state = CYCLES_HBLANK; self.state = VBlankHBlank; self.dispstat.set_hblank_flag(true); if self.dispstat.hblank_irq_enable() { irqs.set_LCD_HBlank(true); }; } VBlankHBlank => { self.update_vcount(self.vcount + 1, irqs); if self.vcount < DISPLAY_HEIGHT + VBLANK_LINES - 1 { self.dispstat.set_hblank_flag(false); self.cycles_left_for_current_state = CYCLES_HDRAW; self.state = VBlankHDraw; } else { self.update_vcount(0, irqs); self.dispstat.set_vblank_flag(false); self.render_scanline(); self.cycles_left_for_current_state = CYCLES_HDRAW; self.state = HDraw; } } }; } // Returns the new gpu state pub fn update( &mut self, cycles: usize, sb: &mut SysBus, irqs: &mut IrqBitmask, cycles_to_next_event: &mut usize, video_device: &VideoDeviceRcRefCell, ) { if self.cycles_left_for_current_state <= cycles { let overshoot = cycles - self.cycles_left_for_current_state; self.on_state_completed(self.state, sb, irqs, video_device); // handle the overshoot if overshoot < self.cycles_left_for_current_state { self.cycles_left_for_current_state -= overshoot; } else { panic!("OH SHIT"); } } else { self.cycles_left_for_current_state -= cycles; } if self.cycles_left_for_current_state < *cycles_to_next_event { *cycles_to_next_event = self.cycles_left_for_current_state; } } }
//! The `prelude` exports the most important types of `tini`. pub use crate::ast::{ASTType, AST}; pub use crate::interpreter::{Environment, Interpreter, Value}; pub use crate::lexer::{Lexer, LexerResult}; pub use crate::parser::{ParseResult, Parser}; pub use crate::token::{Token, TokenType}; pub use crate::{Identifier, Position};
fn capitalize_first_letter(s1: &str) -> String { let mut v: Vec<char> = s1.chars().collect(); v[0] = v[0].to_uppercase().nth(0).unwrap(); let s2: String = v.into_iter().collect(); s2 } fn main() { let days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"]; let gifts = ["a partridge in a pear tree", "Two turtle doves", "Three French hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming"]; for day in days.iter() { println!("On the {} day of Christmas my true love gave to me", day); let count = days.iter().position(|x| x == day); match count { Some(x) => { if x == 0 { println!("{}", capitalize_first_letter(gifts[x])); } else { for i in (0..=x).rev() { let gift = gifts[i]; if i == 0 { println!("And {}", gift); } else { println!("{},", gifts[i]); } } } println!(""); }, None => println!("Invalid day of Christmas!"), } } }
//use async_trait::async_trait; use mav::ma::{Dao, MWallet, MAddress}; use mav::{WalletType, NetType}; use crate::{BtcChain, ContextTrait, EeeChain, EthChain, WalletError}; use crate::deref_type; #[derive(Debug, Default)] pub struct Wallet { pub m: MWallet, pub eth_chain: EthChain, pub eee_chain: EeeChain, pub btc_chain: BtcChain, } deref_type!(Wallet,MWallet); impl Wallet { pub async fn has_any(context: &dyn ContextTrait,net_type:&NetType) -> Result<bool, WalletError> { let rb = context.db().wallets_db(); let wrapper = rb.new_wrapper().eq(MWallet::wallet_type,&WalletType::from(net_type).to_string()); let r = MWallet::exist_by_wrapper(rb, "", &wrapper).await?; Ok(r) } pub async fn count(context: &dyn ContextTrait,net_type:&NetType) -> Result<i64, WalletError> { let rb = context.db().wallets_db(); let wrapper = rb.new_wrapper().eq(MWallet::wallet_type,&WalletType::from(net_type).to_string()); let count = MWallet::count_by_wrapper(rb, "", &wrapper).await?; Ok(count) } pub async fn all(context: &dyn ContextTrait,net_type:&NetType) -> Result<Vec<Wallet>, WalletError> { let mut wallets = Vec::new(); let wallet_rb = context.db().wallets_db(); let filter_value = if NetType::Main.eq(net_type) {WalletType::Normal.to_string() }else { WalletType::Test.to_string() }; let wrapper = wallet_rb.new_wrapper().eq(MWallet::wallet_type,filter_value.as_str()); let dws = MWallet::list_by_wrapper(wallet_rb, "",&wrapper).await?; for dw in &dws { let mut wallet = Wallet::default(); wallet.load(context, dw.clone(),net_type).await?; wallets.push(wallet); } Ok(wallets) } pub async fn m_wallet_all(context: &dyn ContextTrait) -> Result<Vec<MWallet>, WalletError> { let dws = MWallet::list(context.db().wallets_db(), "").await?; Ok(dws) } pub async fn find_by_id(context: &dyn ContextTrait, wallet_id: &str,net_type:&NetType) -> Result<Option<Wallet>, WalletError> { let rb = context.db().wallets_db(); let m_wallet = MWallet::fetch_by_id(rb, "", &wallet_id.to_owned()).await?; match m_wallet { Some(m) => { let mut wallet = Wallet::default(); wallet.load(context, m,net_type).await?; Ok(Some(wallet)) } None => Ok(None) } } //todo 当一个助记词在测试链下多次使用时,会造成一个地址对应多个测试钱包 pub async fn find_by_address(context: &dyn ContextTrait, address: &str) -> Result<Option<Wallet>, WalletError> { let wallet_db = context.db().wallets_db(); let m_address = { let addr_wrapper = wallet_db.new_wrapper().eq(&MAddress::address, address); MAddress::list_by_wrapper(wallet_db, "", &addr_wrapper).await? }; if m_address.is_empty() { return Err(WalletError::Custom(format!("wallet address {} is not exist!", address))); } let address = m_address.get(0).unwrap(); Self::find_by_id(context,&address.wallet_id.to_owned(),&NetType::from_chain_type(&address.chain_type)).await } pub async fn m_wallet_by_id(context: &dyn ContextTrait, wallet_id: &str) -> Result<Option<MWallet>, WalletError> { let rb = context.db().wallets_db(); let m_wallet = MWallet::fetch_by_id(rb, "", &wallet_id.to_owned()).await?; Ok(m_wallet) } pub async fn remove_by_id(context: &dyn ContextTrait, wallet_id: &str) -> Result<u64, WalletError> { let rb = context.db().wallets_db(); let mut tx = rb.begin_tx_defer(false).await?; let re = MWallet::remove_by_id(rb, &tx.tx_id, &wallet_id.to_owned()).await?; //todo 删除相关表 rb.commit(&tx.tx_id).await?; tx.manager = None; Ok(re) } pub async fn update_by_id(context: &dyn ContextTrait, m_wallet: &mut MWallet, tx_id: &str) -> Result<u64, WalletError> { let rb = context.db().wallets_db(); let re = m_wallet.update_by_id(rb, tx_id).await?; //todo 其它字段怎么处理? Ok(re) } pub async fn m_wallet_by_name(context: &dyn ContextTrait, name: &str) -> Result<Vec<MWallet>, WalletError> { let rb = context.db().wallets_db(); let wrapper = rb.new_wrapper().eq(&MWallet::name, name); let dws = MWallet::list_by_wrapper(rb, "", &wrapper).await?; Ok(dws) } pub async fn mnemonic_digest(context: &dyn ContextTrait, digest: &str) -> Result<Vec<MWallet>, WalletError> { let rb = context.db().wallets_db(); let wrapper = rb.new_wrapper().eq(MWallet::mnemonic_digest, digest); let ms = MWallet::list_by_wrapper(rb, "", &wrapper).await?; Ok(ms) } pub async fn check_duplicate_mnemonic(context: &dyn ContextTrait, digest: &str, wallet_type: &WalletType) -> Result<Vec<MWallet>, WalletError> { let rb = context.db().wallets_db(); let wrapper ={ let wrapper = rb.new_wrapper().eq(MWallet::mnemonic_digest, digest.to_owned()); if WalletType::Test.eq(wallet_type){ //check test wallet mnemonic whether used in normal wallet wrapper.eq(MWallet::wallet_type, WalletType::Normal.to_string()) }else { wrapper } }; let ms = MWallet::list_by_wrapper(rb, "", &wrapper).await?; Ok(ms) } } /*#[async_trait]*/ impl Wallet { pub async fn load(&mut self, context: &dyn ContextTrait, mw: MWallet,net_type:&NetType) -> Result<(), WalletError> { self.m = mw; { self.eth_chain.load(context, self.m.clone(),net_type).await?; } { self.eee_chain.load(context, self.m.clone(),net_type).await?; } { self.btc_chain.load(context, self.m.clone(),net_type).await?; } Ok(()) } }
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. // Test that we are able to resolve conditional dispatch. Here, the // blanket impl for T:Copy coexists with an impl for Box<T>, because // Box does not impl Copy. #![feature(box_syntax)] trait Get { fn get(&self) -> Self; } trait MyCopy { fn copy(&self) -> Self; } impl MyCopy for u16 { fn copy(&self) -> Self { *self } } impl MyCopy for u32 { fn copy(&self) -> Self { *self } } impl MyCopy for i32 { fn copy(&self) -> Self { *self } } impl<T:Copy> MyCopy for Option<T> { fn copy(&self) -> Self { *self } } impl<T:MyCopy> Get for T { fn get(&self) -> T { self.copy() } } impl Get for Box<i32> { fn get(&self) -> Box<i32> { box get_it(&**self) } } fn get_it<T:Get>(t: &T) -> T { (*t).get() } fn main() { assert_eq!(get_it(&1_u32), 1_u32); assert_eq!(get_it(&1_u16), 1_u16); assert_eq!(get_it(&Some(1_u16)), Some(1_u16)); assert_eq!(get_it(&Box::new(1)), Box::new(1)); }
mod inputs; mod joystick_ps2; mod max7219; mod random; pub use inputs::{InputDevice, InputPeripheral, InputSignal, PollArray}; pub use joystick_ps2::{JoyStick, JoyStickSignal}; pub use max7219::{DotDisplay, DotScreen, Dot}; pub use random::XOrShiftPrng;
use super::*; #[doc(hidden)] #[derive(Debug, PartialEq)] pub struct WrapperConfig { pub active_env: Environment, config: HashMap<Environment, BasicConfig>, } impl WrapperConfig { pub fn default() -> super::Result<WrapperConfig> { WrapperConfig::read_config() } fn read_config() -> super::Result<WrapperConfig> { let file = WrapperConfig::find()?; // Try to open the config file for reading. let mut handle = File::open(&file).map_err(|_| ConfigError::IoError)?; let mut contents = String::new(); handle .read_to_string(&mut contents) .map_err(|_| ConfigError::IoError)?; WrapperConfig::parse(contents, &file) } fn find() -> super::Result<PathBuf> { let cwd = env::current_dir().map_err(|_| ConfigError::NotFound)?; let mut current = cwd.as_path(); loop { let manifest = current.join(super::CONFIG_FILENAME); if fs::metadata(&manifest).is_ok() { return Ok(manifest); } match current.parent() { Some(p) => current = p, None => break, } } Err(ConfigError::NotFound) } fn get_mut(&mut self, env: Environment) -> &mut BasicConfig { match self.config.get_mut(&env) { Some(config) => config, None => panic!("set(): {} config is missing.", env), } } fn get(&self, env: Environment) -> &BasicConfig { match self.config.get(&env) { Some(config) => config, None => panic!("set(): {} config is missing.", env), } } fn active_default_from(filename: Option<&Path>) -> super::Result<WrapperConfig> { let mut defaults = HashMap::new(); if let Some(path) = filename { defaults.insert(Development, BasicConfig::default_from(Development, &path)?); defaults.insert(Staging, BasicConfig::default_from(Staging, &path)?); defaults.insert(Production, BasicConfig::default_from(Production, &path)?); } else { defaults.insert(Development, BasicConfig::default(Development)); defaults.insert(Staging, BasicConfig::default(Staging)); defaults.insert(Production, BasicConfig::default(Production)); } let config = WrapperConfig { active_env: Environment::active()?, config: defaults, }; Ok(config) } pub fn active_default() -> super::Result<BasicConfig> { Ok(BasicConfig::new(Environment::active()?)) } pub fn active(&self) -> &BasicConfig { self.get(self.active_env) } fn parse<P: AsRef<Path>>(src: String, filename: P) -> super::Result<WrapperConfig> { let path = filename.as_ref().to_path_buf(); let table = match src.parse::<toml::Value>() { Ok(toml::Value::Table(table)) => table, Ok(value) => { let err = format!("expected a table, found {}", value.type_str()); return Err(ConfigError::ParseError(src, path, err, Some((1, 1)))); } Err(e) => { return Err(ConfigError::ParseError( src, path, e.to_string(), e.line_col(), )) } }; // Create a config with the defaults; set the env to the active one. let mut config = WrapperConfig::active_default_from(Some(filename.as_ref()))?; // Parse the values from the TOML file. for (entry, value) in table { // Each environment must be a table. let kv_pairs = match value.as_table() { Some(table) => table, None => { return Err(ConfigError::BadType( entry, "a table", value.type_str(), Some(path.clone()), )) } }; let env = entry.as_str().parse::<Environment>().unwrap(); let conf = config.get_mut(env); conf.set_address( kv_pairs .get("address") .unwrap() .as_str() .unwrap() .to_string(), ); let port = kv_pairs.get("port").unwrap().as_str().unwrap(); let port: u16 = port.parse::<u16>().unwrap(); conf.set_port(port); } Ok(config) } }
use std::collections::HashMap; fn main() { let mut sname = String::new(); sname.push_str("hello world"); println!("{}", sname); let user_info = UserInfo{ name:String::from("wuhuarou"), age: 32, }; user_info.get_user_name(); user_info.get_user_age(); #[derive(Debug)] enum IpAddr { V4(String), V6(String), } let v4 = IpAddr::V4(String::from("127.0.0.1")); let v6 = IpAddr::V6(String::from("127.0.0.1")); println!("{:?}, {:?}", v4, v6); let mut scores: HashMap<String, i32> = HashMap::new(); scores.insert(String::from("wuhuarou"), 1); println!("{:?}", scores); println!("Hello, world!"); } struct UserInfo { name: String, age: i32, } impl UserInfo { fn get_user_name(&self) { println!("{}", self.name) } fn get_user_age(&self) { println!("{}", self.age); } }
mod object_ref; pub mod store; pub use self::object_ref::{ErasedResource, ObjectRef}; use crate::watcher; use futures::{Stream, TryStreamExt}; use kube::api::Meta; pub use store::Store; /// Caches objects to a local store /// /// Similar to kube-rs's `Reflector`, and the caching half of client-go's `Reflector` pub fn reflector<K: Meta + Clone, W: Stream<Item = watcher::Result<watcher::Event<K>>>>( mut store: store::Writer<K>, stream: W, ) -> impl Stream<Item = W::Item> { stream.inspect_ok(move |event| store.apply_watcher_event(event)) }
fn main() { let p = "../../."; println!("{}", p.replace("..", "").replace(".", "")); }
//! Worker traits. use std::io; use super::layer::{Confidence, Layer}; use super::context::Context; pub trait Worker { fn examine(&mut self, _ctx: &mut Context, _layer: &Layer) -> Confidence { Confidence::Exact } fn analyze(&mut self, _ctx: &mut Context, _layer: &mut Layer) -> Result<(), io::Error> { Ok(()) } }
use std::sync::mpsc::Sender; use std::thread; use std::sync::{Arc, RwLock}; use conn::{Conn, Event, Message}; use conn::ConnError::IrcError; use failure::Error; use irc::client::IrcClient; use irc::client::Client; use futures::Stream; use futures::Future; pub struct IrcConn { sender: Sender<Event>, name: String, channel_names: Vec<String>, client: IrcClient, } impl IrcConn { pub fn new( nickname: String, server: String, port: u16, sender: Sender<Event>, ) -> Result<Box<Conn>, Error> { let mut config = ::irc::client::data::Config::default(); config.nickname = Some(nickname); config.server = Some(server.clone()); config.port = Some(port); let client = IrcClient::from_config(config)?; let stream = client.stream(); let server_name = server.clone(); let thread_sender = sender.clone(); thread::spawn(move || { use irc; stream .for_each(|ev| { if let irc::proto::Message { command: irc::proto::Command::PRIVMSG(source, contents), .. } = ev { thread_sender .send(Event::Message(Message { sender: source, contents: contents, channel: "test".to_string(), is_mention: false, server: server_name.clone(), })) .unwrap(); } Ok(()) }) .wait() .unwrap(); }); return Ok(Box::new(IrcConn { sender: sender, name: server, channel_names: vec!["test".to_string()], client: client, })); } } impl Conn for IrcConn { fn send_channel_message(&mut self, channel: &str, contents: &str) {} fn channels<'a>(&'a self) -> Box<Iterator<Item = &'a str> + 'a> { Box::new(self.channel_names.iter().map(|s| s.as_str())) } fn name(&self) -> &str { &self.name } }
use std; use core::time::Time; pub struct Task { location: std::string::String, id: u32, repeat: super::Repeat, note: std::string::String, owner: std::string::String } pub enum TaskUpdateType { Start, Amend, Finish, } pub struct TaskUpdate { time: Time, entry_id: u32, update_type: TaskUpdateType } pub struct Reminder { due : Time, entry_id : u32 } pub struct Timer { due : Time }
#[cfg(test)] #[path = "./wumpus_tests.rs"] pub mod wumpus_tests; use game::{Hazzard, RunResult, State, UpdateResult}; use map::{adj_rooms_to, is_adj, RoomNum}; use message::Warning; use player; use rand::{seq::SliceRandom, thread_rng, Rng}; use std::cell::Cell; trait Director { fn get_room(&self, state: &State) -> RoomNum; fn feels_like_moving(&self) -> bool; } pub struct Wumpus { pub room: Cell<RoomNum>, director: Box<dyn Director>, is_awake: Cell<bool> } impl Wumpus { pub fn new(room: RoomNum) -> Self { Wumpus { room: Cell::new(room), is_awake: Cell::new(false), director: box WumpusDirector } } } impl Hazzard for Wumpus { fn try_warn(&self, player_room: RoomNum) -> Option<&str> { if is_adj(player_room, self.room.get()) { Some(Warning::WUMPUS) } else { None } } fn try_update(&self, s: &State) -> Option<UpdateResult> { let is_bumped = !self.is_awake.get() && s.player == self.room.get(); let arrow_shot_awakes_wumpus = !self.is_awake.get() && s.arrow_count < player::ARROW_CAPACITY; if is_bumped || arrow_shot_awakes_wumpus { self.is_awake.set(true); } if self.is_awake.get() && self.director.feels_like_moving() { let next_room = self.director.get_room(s); self.room.set(next_room); if s.is_cheating { println!("Wumpus moved to: {}", next_room); } } if self.is_awake.get() && s.player == self.room.get() { if is_bumped { Some(UpdateResult::BumpAndDie) } else { Some(UpdateResult::Death(RunResult::KilledByWumpus)) } } else if is_bumped { Some(UpdateResult::BumpAndLive) } else { None } } } struct WumpusDirector; impl Director for WumpusDirector { fn get_room(&self, s: &State) -> RoomNum { let (a, b, c) = adj_rooms_to(s.wumpus); let mut adj_rooms = [a, b, c]; adj_rooms.shuffle(&mut thread_rng()); *adj_rooms .iter() .find(|room| **room != s.pit1 && **room != s.pit2) .unwrap() } /// Wumpus feels like moving with a 75% chance. fn feels_like_moving(&self) -> bool { let n = thread_rng().gen_range(1, 5); n > 1 } }
fn main() { let word = "testing"; let word_len = word.len(); if word_len % 2 == 0 { let start = (word_len / 2) - 1; let end = word_len / 2; println!("{}", &word[start..=end]); } else { let start = word_len / 2; println!("{}", word.chars().nth(start).unwrap()); } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::FRAMEFLTR { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_PRR { bits: bool, } impl EMAC_FRAMEFLTR_PRR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_PRW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_PRW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_HUCR { bits: bool, } impl EMAC_FRAMEFLTR_HUCR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_HUCW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_HUCW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_HMCR { bits: bool, } impl EMAC_FRAMEFLTR_HMCR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_HMCW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_HMCW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_DAIFR { bits: bool, } impl EMAC_FRAMEFLTR_DAIFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_DAIFW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_DAIFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_PMR { bits: bool, } impl EMAC_FRAMEFLTR_PMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_PMW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_PMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_DBFR { bits: bool, } impl EMAC_FRAMEFLTR_DBFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_DBFW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_DBFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = "Possible values of the field `EMAC_FRAMEFLTR_PCF`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_FRAMEFLTR_PCFR { #[doc = "The MAC filters all control frames from reaching application"] EMAC_FRAMEFLTR_PCF_ALL, #[doc = "MAC forwards all control frames except PAUSE control frames to application even if they fail the address filter"] EMAC_FRAMEFLTR_PCF_PAUSE, #[doc = "MAC forwards all control frames to application even if they fail the address Filter"] EMAC_FRAMEFLTR_PCF_NONE, #[doc = "MAC forwards control frames that pass the address Filter"] EMAC_FRAMEFLTR_PCF_ADDR, } impl EMAC_FRAMEFLTR_PCFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_ALL => 0, EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_PAUSE => 1, EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_NONE => 2, EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_ADDR => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EMAC_FRAMEFLTR_PCFR { match value { 0 => EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_ALL, 1 => EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_PAUSE, 2 => EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_NONE, 3 => EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_ADDR, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EMAC_FRAMEFLTR_PCF_ALL`"] #[inline(always)] pub fn is_emac_framefltr_pcf_all(&self) -> bool { *self == EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_ALL } #[doc = "Checks if the value of the field is `EMAC_FRAMEFLTR_PCF_PAUSE`"] #[inline(always)] pub fn is_emac_framefltr_pcf_pause(&self) -> bool { *self == EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_PAUSE } #[doc = "Checks if the value of the field is `EMAC_FRAMEFLTR_PCF_NONE`"] #[inline(always)] pub fn is_emac_framefltr_pcf_none(&self) -> bool { *self == EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_NONE } #[doc = "Checks if the value of the field is `EMAC_FRAMEFLTR_PCF_ADDR`"] #[inline(always)] pub fn is_emac_framefltr_pcf_addr(&self) -> bool { *self == EMAC_FRAMEFLTR_PCFR::EMAC_FRAMEFLTR_PCF_ADDR } } #[doc = "Values that can be written to the field `EMAC_FRAMEFLTR_PCF`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_FRAMEFLTR_PCFW { #[doc = "The MAC filters all control frames from reaching application"] EMAC_FRAMEFLTR_PCF_ALL, #[doc = "MAC forwards all control frames except PAUSE control frames to application even if they fail the address filter"] EMAC_FRAMEFLTR_PCF_PAUSE, #[doc = "MAC forwards all control frames to application even if they fail the address Filter"] EMAC_FRAMEFLTR_PCF_NONE, #[doc = "MAC forwards control frames that pass the address Filter"] EMAC_FRAMEFLTR_PCF_ADDR, } impl EMAC_FRAMEFLTR_PCFW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EMAC_FRAMEFLTR_PCFW::EMAC_FRAMEFLTR_PCF_ALL => 0, EMAC_FRAMEFLTR_PCFW::EMAC_FRAMEFLTR_PCF_PAUSE => 1, EMAC_FRAMEFLTR_PCFW::EMAC_FRAMEFLTR_PCF_NONE => 2, EMAC_FRAMEFLTR_PCFW::EMAC_FRAMEFLTR_PCF_ADDR => 3, } } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_PCFW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_PCFW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EMAC_FRAMEFLTR_PCFW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "The MAC filters all control frames from reaching application"] #[inline(always)] pub fn emac_framefltr_pcf_all(self) -> &'a mut W { self.variant(EMAC_FRAMEFLTR_PCFW::EMAC_FRAMEFLTR_PCF_ALL) } #[doc = "MAC forwards all control frames except PAUSE control frames to application even if they fail the address filter"] #[inline(always)] pub fn emac_framefltr_pcf_pause(self) -> &'a mut W { self.variant(EMAC_FRAMEFLTR_PCFW::EMAC_FRAMEFLTR_PCF_PAUSE) } #[doc = "MAC forwards all control frames to application even if they fail the address Filter"] #[inline(always)] pub fn emac_framefltr_pcf_none(self) -> &'a mut W { self.variant(EMAC_FRAMEFLTR_PCFW::EMAC_FRAMEFLTR_PCF_NONE) } #[doc = "MAC forwards control frames that pass the address Filter"] #[inline(always)] pub fn emac_framefltr_pcf_addr(self) -> &'a mut W { self.variant(EMAC_FRAMEFLTR_PCFW::EMAC_FRAMEFLTR_PCF_ADDR) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 6); self.w.bits |= ((value as u32) & 3) << 6; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_SAIFR { bits: bool, } impl EMAC_FRAMEFLTR_SAIFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_SAIFW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_SAIFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_SAFR { bits: bool, } impl EMAC_FRAMEFLTR_SAFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_SAFW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_SAFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_HPFR { bits: bool, } impl EMAC_FRAMEFLTR_HPFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_HPFW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_HPFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_VTFER { bits: bool, } impl EMAC_FRAMEFLTR_VTFER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_VTFEW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_VTFEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 16); self.w.bits |= ((value as u32) & 1) << 16; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FRAMEFLTR_RAR { bits: bool, } impl EMAC_FRAMEFLTR_RAR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FRAMEFLTR_RAW<'a> { w: &'a mut W, } impl<'a> _EMAC_FRAMEFLTR_RAW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 31); self.w.bits |= ((value as u32) & 1) << 31; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Promiscuous Mode"] #[inline(always)] pub fn emac_framefltr_pr(&self) -> EMAC_FRAMEFLTR_PRR { let bits = ((self.bits >> 0) & 1) != 0; EMAC_FRAMEFLTR_PRR { bits } } #[doc = "Bit 1 - Hash Unicast"] #[inline(always)] pub fn emac_framefltr_huc(&self) -> EMAC_FRAMEFLTR_HUCR { let bits = ((self.bits >> 1) & 1) != 0; EMAC_FRAMEFLTR_HUCR { bits } } #[doc = "Bit 2 - Hash Multicast"] #[inline(always)] pub fn emac_framefltr_hmc(&self) -> EMAC_FRAMEFLTR_HMCR { let bits = ((self.bits >> 2) & 1) != 0; EMAC_FRAMEFLTR_HMCR { bits } } #[doc = "Bit 3 - Destination Address (DA) Inverse Filtering"] #[inline(always)] pub fn emac_framefltr_daif(&self) -> EMAC_FRAMEFLTR_DAIFR { let bits = ((self.bits >> 3) & 1) != 0; EMAC_FRAMEFLTR_DAIFR { bits } } #[doc = "Bit 4 - Pass All Multicast"] #[inline(always)] pub fn emac_framefltr_pm(&self) -> EMAC_FRAMEFLTR_PMR { let bits = ((self.bits >> 4) & 1) != 0; EMAC_FRAMEFLTR_PMR { bits } } #[doc = "Bit 5 - Disable Broadcast Frames"] #[inline(always)] pub fn emac_framefltr_dbf(&self) -> EMAC_FRAMEFLTR_DBFR { let bits = ((self.bits >> 5) & 1) != 0; EMAC_FRAMEFLTR_DBFR { bits } } #[doc = "Bits 6:7 - Pass Control Frames"] #[inline(always)] pub fn emac_framefltr_pcf(&self) -> EMAC_FRAMEFLTR_PCFR { EMAC_FRAMEFLTR_PCFR::_from(((self.bits >> 6) & 3) as u8) } #[doc = "Bit 8 - Source Address (SA) Inverse Filtering"] #[inline(always)] pub fn emac_framefltr_saif(&self) -> EMAC_FRAMEFLTR_SAIFR { let bits = ((self.bits >> 8) & 1) != 0; EMAC_FRAMEFLTR_SAIFR { bits } } #[doc = "Bit 9 - Source Address Filter Enable"] #[inline(always)] pub fn emac_framefltr_saf(&self) -> EMAC_FRAMEFLTR_SAFR { let bits = ((self.bits >> 9) & 1) != 0; EMAC_FRAMEFLTR_SAFR { bits } } #[doc = "Bit 10 - Hash or Perfect Filter"] #[inline(always)] pub fn emac_framefltr_hpf(&self) -> EMAC_FRAMEFLTR_HPFR { let bits = ((self.bits >> 10) & 1) != 0; EMAC_FRAMEFLTR_HPFR { bits } } #[doc = "Bit 16 - VLAN Tag Filter Enable"] #[inline(always)] pub fn emac_framefltr_vtfe(&self) -> EMAC_FRAMEFLTR_VTFER { let bits = ((self.bits >> 16) & 1) != 0; EMAC_FRAMEFLTR_VTFER { bits } } #[doc = "Bit 31 - Receive All"] #[inline(always)] pub fn emac_framefltr_ra(&self) -> EMAC_FRAMEFLTR_RAR { let bits = ((self.bits >> 31) & 1) != 0; EMAC_FRAMEFLTR_RAR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Promiscuous Mode"] #[inline(always)] pub fn emac_framefltr_pr(&mut self) -> _EMAC_FRAMEFLTR_PRW { _EMAC_FRAMEFLTR_PRW { w: self } } #[doc = "Bit 1 - Hash Unicast"] #[inline(always)] pub fn emac_framefltr_huc(&mut self) -> _EMAC_FRAMEFLTR_HUCW { _EMAC_FRAMEFLTR_HUCW { w: self } } #[doc = "Bit 2 - Hash Multicast"] #[inline(always)] pub fn emac_framefltr_hmc(&mut self) -> _EMAC_FRAMEFLTR_HMCW { _EMAC_FRAMEFLTR_HMCW { w: self } } #[doc = "Bit 3 - Destination Address (DA) Inverse Filtering"] #[inline(always)] pub fn emac_framefltr_daif(&mut self) -> _EMAC_FRAMEFLTR_DAIFW { _EMAC_FRAMEFLTR_DAIFW { w: self } } #[doc = "Bit 4 - Pass All Multicast"] #[inline(always)] pub fn emac_framefltr_pm(&mut self) -> _EMAC_FRAMEFLTR_PMW { _EMAC_FRAMEFLTR_PMW { w: self } } #[doc = "Bit 5 - Disable Broadcast Frames"] #[inline(always)] pub fn emac_framefltr_dbf(&mut self) -> _EMAC_FRAMEFLTR_DBFW { _EMAC_FRAMEFLTR_DBFW { w: self } } #[doc = "Bits 6:7 - Pass Control Frames"] #[inline(always)] pub fn emac_framefltr_pcf(&mut self) -> _EMAC_FRAMEFLTR_PCFW { _EMAC_FRAMEFLTR_PCFW { w: self } } #[doc = "Bit 8 - Source Address (SA) Inverse Filtering"] #[inline(always)] pub fn emac_framefltr_saif(&mut self) -> _EMAC_FRAMEFLTR_SAIFW { _EMAC_FRAMEFLTR_SAIFW { w: self } } #[doc = "Bit 9 - Source Address Filter Enable"] #[inline(always)] pub fn emac_framefltr_saf(&mut self) -> _EMAC_FRAMEFLTR_SAFW { _EMAC_FRAMEFLTR_SAFW { w: self } } #[doc = "Bit 10 - Hash or Perfect Filter"] #[inline(always)] pub fn emac_framefltr_hpf(&mut self) -> _EMAC_FRAMEFLTR_HPFW { _EMAC_FRAMEFLTR_HPFW { w: self } } #[doc = "Bit 16 - VLAN Tag Filter Enable"] #[inline(always)] pub fn emac_framefltr_vtfe(&mut self) -> _EMAC_FRAMEFLTR_VTFEW { _EMAC_FRAMEFLTR_VTFEW { w: self } } #[doc = "Bit 31 - Receive All"] #[inline(always)] pub fn emac_framefltr_ra(&mut self) -> _EMAC_FRAMEFLTR_RAW { _EMAC_FRAMEFLTR_RAW { w: self } } }
#[derive(Clone)] pub struct Sound { } impl Sound { pub fn init() -> Self { Self { } } } impl Sound { pub fn step(&mut self, cycles: usize) { // TODO: idk } } impl Sound { pub fn read_io_byte(&self, idx: u16) -> u8 { match idx { _ => { //println!("Unhandled Sound Read from Address [{:#04x?}]", idx); 0 } } } pub fn write_io_byte(&mut self, idx: u16, val: u8) { match idx { _ => { println!("Unhandled Sound Write from Address [{:#04x?}] [{:#02x?}]", idx, val); } } } }
/// Configure and start a device `Kernel`. /// /// Additionally, allocate some number of bytes for the async executor. /// /// For example: /// /// ``` /// use drogue_device::kernel::{Kernel, KernelContext}; /// use drogue_device::component::ConnectedComponent; /// struct MyDevice { /// led: ConnectedComponent<LED>, /// } /// /// impl Kernel for MyDevice { /// fn start(&'static self,ctx: &'static KernelContext<Self>) { /// self.led.start( ctx ); /// } /// } /// /// device!( MyDevice => Kernel; 1024 ); /// ``` #[macro_export] macro_rules! device { ($ty:ty => $kernel:expr; $memory:literal) => { $crate::kernel::init_executor!(memory: $memory); static mut KERNEL: Option<$crate::kernel::ConnectedKernel<$ty>> = None; let kernel = unsafe { KERNEL.replace($crate::kernel::ConnectedKernel::new($kernel)); KERNEL.as_ref().unwrap() }; kernel.start(); #[exception] fn DefaultHandler(irqn: i16) { unsafe { KERNEL.as_ref().unwrap().interrupt(irqn); } } $crate::kernel::run_forever() }; }
pub fn run() { println!("\n----- Structs"); enum HockeyPosition { Center, Wing, Defense, Goalie, } struct HockeyPlayer { name: String, number: u8, position: HockeyPosition, goals_ytd: u8, } let mut player = HockeyPlayer { name: String::from("Bryan Rust"), number: 17, position: HockeyPosition::Wing, goals_ytd: 7, }; player.goals_ytd += 1; println!( "{} has scored {} goals this season", player.name, player.goals_ytd ); //////////////////////////////// struct Meters(u8); fn add_distance(d1: Meters, d2: Meters) -> Meters { Meters(d1.0 + d2.0) } let distance1 = Meters(3); let distance2: u8 = 7; let distance4 = Meters(4); // let distance3 = add_distance(distance1, distance2); let distance3 = add_distance(distance1, distance4); ////////////////////////////////// #[derive(Debug)] enum Clock { Sundial{hours: u8}, Digital{hours: u8, minutes: u8}, Analog{hours: u8, minutes: u8, seconds: u8}, } let clock = Clock::Analog { hours: 9, minutes: 25, seconds: 46, }; }
pub mod subfield;
use chrono::NaiveDateTime; use serde::{Deserialize, Deserializer}; pub fn ts_seconds<'de, D>(deserializer: D) -> Result<NaiveDateTime, D::Error> where D: Deserializer<'de> { match <i64>::deserialize(deserializer) { Ok(dt) => { match NaiveDateTime::from_timestamp_opt(dt, 0) { Some(dt) => Ok(dt), None => Err(serde::de::Error::custom(format!("value is not a legal timestamp: {}", dt))), } } Err(e) => Err(e), } } pub mod opt_ts_seconds { use chrono::NaiveDateTime; use serde::Deserializer; use serde::de; use std::fmt; pub fn deserialize<'de, D>(d: D) -> Result<Option<NaiveDateTime>, D::Error> where D: Deserializer<'de> { d.deserialize_option(OptionalNaiveDateTimeVisitor) } struct OptionalNaiveDateTimeVisitor; impl<'de> de::Visitor<'de> for OptionalNaiveDateTimeVisitor { type Value = Option<NaiveDateTime>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "null or a datetime string") } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_some<D>(self, d: D) -> Result<Self::Value, D::Error> where D: de::Deserializer<'de>, { Ok(Some(d.deserialize_u64(NaiveDateTimeVisitor)?)) } } struct NaiveDateTimeVisitor; impl<'de> de::Visitor<'de> for NaiveDateTimeVisitor { type Value = NaiveDateTime; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "null2 or a datetime string") } fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> where E: de::Error, { Ok(NaiveDateTime::from_timestamp(value, 0)) } fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> where E: de::Error, { Ok(NaiveDateTime::from_timestamp(value as i64, 0)) } } }
//! A translation of the `p.` tests in the test directory in the [one true awk //! repo](https://github.com/onetrueawk/awk/tree/master/testdir) into Rust, modified for //! differences in frawk behavior/semantics. //! //! Those changes are: //! * A frawk parsing limitation leads `FNR==1, FNR==5` not to parse; we need parens around the //! comparisons //! * `length` is not syntactic sugar for `length($0)`. //! * frawk prints more digits on floating point values by default. //! * frawk's parser requires semicolons between a last statement and a `}` sometimes //! * frawk's rules aronud comparing strings and numbers are different, e.g. "Russia < 1" is true //! in frawk but false in awk/mawk. use assert_cmd::Command; use std::fs::{read_to_string, File}; use std::io::Write; use tempfile::tempdir; #[cfg(feature = "llvm_backend")] const BACKEND_ARGS: &'static [&'static str] = &["-binterp", "-bllvm", "-bcranelift"]; #[cfg(not(feature = "llvm_backend"))] const BACKEND_ARGS: &'static [&'static str] = &["-binterp", "-bcranelift"]; const COUNTRIES: &'static str = r#"Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "#; fn unordered_output_equals(bs1: &[u8], bs2: &[u8]) { let mut lines1: Vec<_> = bs1.split(|x| *x == b'\n').collect(); let mut lines2: Vec<_> = bs2.split(|x| *x == b'\n').collect(); lines1.sort(); lines2.sort(); if lines1 != lines2 { let pretty_1: Vec<_> = lines1.into_iter().map(String::from_utf8_lossy).collect(); let pretty_2: Vec<_> = lines2.into_iter().map(String::from_utf8_lossy).collect(); assert!( false, "expected (in any order) {:?}, got {:?}", pretty_1, pretty_2 ); } } #[test] fn p_test_1() { let expected = String::from( r#"Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"{ print }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_10() { let expected = String::from( r#"Australia 2968 14 Australia Australia 2968 14 Australia "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$1 == $4"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_11() { let expected = String::from( r#"Russia 8650 262 Asia China 3692 866 Asia India 1269 637 Asia Russia 8650 262 Asia China 3692 866 Asia India 1269 637 Asia "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"/Asia/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_12() { let expected = String::from( r#"Russia China India Russia China India "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$4 ~ /Asia/ { print $1 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_13() { let expected = String::from( r#"Canada USA Brazil Australia Argentina Sudan Algeria Canada USA Brazil Australia Argentina Sudan Algeria "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$4 !~ /Asia/ {print $1 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_14() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"/\$/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_15() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"/\\/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_16() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"/^.$/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_17() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$2 !~ /^[0-9]+$/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_18() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"/(apple|cherry) (pie|tart)/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_19() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { digits = "^[0-9]+$" } $2 !~ digits"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_2() { let expected = String::from( r#"Russia 262 Canada 24 China 866 USA 219 Brazil 116 Australia 14 India 637 Argentina 26 Sudan 19 Algeria 18 Russia 262 Canada 24 China 866 USA 219 Brazil 116 Australia 14 India 637 Argentina 26 Sudan 19 Algeria 18 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"{ print $1, $3 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_20() { let expected = String::from( r#"China 3692 866 Asia India 1269 637 Asia China 3692 866 Asia India 1269 637 Asia "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$4 == "Asia" && $3 > 500"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_21() { let expected = String::from( r#"Russia 8650 262 Asia China 3692 866 Asia India 1269 637 Asia Russia 8650 262 Asia China 3692 866 Asia India 1269 637 Asia "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$4 == "Asia" || $4 == "Europe""#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_21a() { let expected = String::from( r#"Russia 8650 262 Asia China 3692 866 Asia India 1269 637 Asia Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia China 3692 866 Asia India 1269 637 Asia Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"/Asia/ || /Africa/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_22() { let expected = String::from( r#"Russia 8650 262 Asia China 3692 866 Asia India 1269 637 Asia Russia 8650 262 Asia China 3692 866 Asia India 1269 637 Asia "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$4 ~ /^(Asia|Europe)$/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_23() { let expected = String::from( r#"Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"/Canada/, /Brazil/"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_24() { let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); let expected = format!( r#"{filename} Russia 8650 262 Asia {filename} Canada 3852 24 North America {filename} China 3692 866 Asia {filename} USA 3615 219 North America {filename} Brazil 3286 116 South America {filename} Russia 8650 262 Asia {filename} Canada 3852 24 North America {filename} China 3692 866 Asia {filename} USA 3615 219 North America {filename} Brazil 3286 116 South America "#, filename = data_string.as_str() ); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"(FNR == 1), (FNR == 5) { print FILENAME, $0 }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_25() { let expected = String::from( r#" Russia 30.3 Canada 6.2 China 234.6 USA 60.6 Brazil 35.3 Australia 4.7 India 502.0 Argentina 24.3 Sudan 19.6 Algeria 19.6 Russia 30.3 Canada 6.2 China 234.6 USA 60.6 Brazil 35.3 Australia 4.7 India 502.0 Argentina 24.3 Sudan 19.6 Algeria 19.6 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"{ printf "%10s %6.1f\n", $1, 1000 * $3 / $2 }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_26() { let expected = String::from( r#"population of 6 Asian countries in millions is 3530 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"/Asia/ { pop = pop + $3; n = n + 1 } END { print "population of", n,\ "Asian countries in millions is", pop }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_26a() { let expected = String::from( r#"population of 6 Asian countries in millions is 3530 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"/Asia/ { pop += $3; ++n } END { print "population of", n,\ "Asian countries in millions is", pop }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_27() { let expected = String::from( r#"China 866 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"maxpop < $3 { maxpop = $3; country = $1 } END { print country, maxpop }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_28() { let expected = String::from( r#"1:Russia 8650 262 Asia 2:Canada 3852 24 North America 3:China 3692 866 Asia 4:USA 3615 219 North America 5:Brazil 3286 116 South America 6:Australia 2968 14 Australia 7:India 1269 637 Asia 8:Argentina 1072 26 South America 9:Sudan 968 19 Africa 10:Algeria 920 18 Africa 11:Russia 8650 262 Asia 12:Canada 3852 24 North America 13:China 3692 866 Asia 14:USA 3615 219 North America 15:Brazil 3286 116 South America 16:Australia 2968 14 Australia 17:India 1269 637 Asia 18:Argentina 1072 26 South America 19:Sudan 968 19 Africa 20:Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"{ print NR ":" $0 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_29() { let expected = String::from( r#"Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia United States 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia United States 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#" { gsub(/USA/, "United States"); print }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_3() { let expected = String::from( r#"[ Russia] [262 ] [ Canada] [24 ] [ China] [866 ] [ USA] [219 ] [ Brazil] [116 ] [ Australia] [14 ] [ India] [637 ] [ Argentina] [26 ] [ Sudan] [19 ] [ Algeria] [18 ] [ Russia] [262 ] [ Canada] [24 ] [ China] [866 ] [ USA] [219 ] [ Brazil] [116 ] [ Australia] [14 ] [ India] [637 ] [ Argentina] [26 ] [ Sudan] [19 ] [ Algeria] [18 ] "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"{ printf "[%10s] [%-16d]\n", $1, $3 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_30() { let expected = String::from( r#"20 Russia 8650 262 Asia 28 Canada 3852 24 North America 19 China 3692 866 Asia 26 USA 3615 219 North America 29 Brazil 3286 116 South America 27 Australia 2968 14 Australia 19 India 1269 637 Asia 31 Argentina 1072 26 South America 19 Sudan 968 19 Africa 21 Algeria 920 18 Africa 20 Russia 8650 262 Asia 28 Canada 3852 24 North America 19 China 3692 866 Asia 26 USA 3615 219 North America 29 Brazil 3286 116 South America 27 Australia 2968 14 Australia 19 India 1269 637 Asia 31 Argentina 1072 26 South America 19 Sudan 968 19 Africa 21 Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"{ print length($0), $0 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_31() { let expected = String::from( r#"Australia "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"length($1) > max { max = length($1); name = $1 } END { print name }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_32() { let expected = String::from( r#"Rus 8650 262 Asia Can 3852 24 North America Chi 3692 866 Asia USA 3615 219 North America Bra 3286 116 South America Aus 2968 14 Australia Ind 1269 637 Asia Arg 1072 26 South America Sud 968 19 Africa Alg 920 18 Africa Rus 8650 262 Asia Can 3852 24 North America Chi 3692 866 Asia USA 3615 219 North America Bra 3286 116 South America Aus 2968 14 Australia Ind 1269 637 Asia Arg 1072 26 South America Sud 968 19 Africa Alg 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"{ $1 = substr($1, 1, 3); print }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_33() { let expected = String::from( r#" Rus Can Chi USA Bra Aus Ind Arg Sud Alg Rus Can Chi USA Bra Aus Ind Arg Sud Alg "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#" { s = s " " substr($1, 1, 3) } END { print s }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_34() { let expected = String::from( r#"Russia 8.65 262 Asia Canada 3.852 24 North America China 3.692 866 Asia USA 3.615 219 North America Brazil 3.286 116 South America Australia 2.968 14 Australia India 1.269 637 Asia Argentina 1.072 26 South America Sudan 0.968 19 Africa Algeria 0.92 18 Africa Russia 8.65 262 Asia Canada 3.852 24 North America China 3.692 866 Asia USA 3.615 219 North America Brazil 3.286 116 South America Australia 2.968 14 Australia India 1.269 637 Asia Argentina 1.072 26 South America Sudan 0.968 19 Africa Algeria 0.92 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"{ $2 /= 1000; print }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_35() { let expected = String::from( r#"Russia 8650 262 Asia Canada 3852 24 NA China 3692 866 Asia USA 3615 219 NA Brazil 3286 116 SA Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 SA Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia Canada 3852 24 NA China 3692 866 Asia USA 3615 219 NA Brazil 3286 116 SA Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 SA Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = OFS = "\t" } $4 ~ /^North America$/ { $4 = "NA" } $4 ~ /^South America$/ { $4 = "SA" } { print }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_36() { let expected = String::from( r#"Russia 8650 262 Asia 30.289017341040463 Canada 3852 24 North America 6.230529595015576 China 3692 866 Asia 234.56121343445287 USA 3615 219 North America 60.58091286307054 Brazil 3286 116 South America 35.30127814972611 Australia 2968 14 Australia 4.716981132075472 India 1269 637 Asia 501.9700551615445 Argentina 1072 26 South America 24.253731343283583 Sudan 968 19 Africa 19.628099173553718 Algeria 920 18 Africa 19.565217391304348 Russia 8650 262 Asia 30.289017341040463 Canada 3852 24 North America 6.230529595015576 China 3692 866 Asia 234.56121343445287 USA 3615 219 North America 60.58091286307054 Brazil 3286 116 South America 35.30127814972611 Australia 2968 14 Australia 4.716981132075472 India 1269 637 Asia 501.9700551615445 Argentina 1072 26 South America 24.253731343283583 Sudan 968 19 Africa 19.628099173553718 Algeria 920 18 Africa 19.565217391304348 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = OFS = "\t" } { $5 = 1000 * $3 / $2 ; print $1, $2, $3, $4, $5 }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_37() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$1 "" == $2 """#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_38() { let expected = String::from( r#"China 866 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"{ if (maxpop < $3) { maxpop = $3 country = $1 } } END { print country, maxpop }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_39() { let expected = String::from( r#"Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"{ i = 1 while (i <= NF) { print $i i++ } }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_4() { let expected = String::from( r#"1 Russia 8650 262 Asia 2 Canada 3852 24 North America 3 China 3692 866 Asia 4 USA 3615 219 North America 5 Brazil 3286 116 South America 6 Australia 2968 14 Australia 7 India 1269 637 Asia 8 Argentina 1072 26 South America 9 Sudan 968 19 Africa 10 Algeria 920 18 Africa 11 Russia 8650 262 Asia 12 Canada 3852 24 North America 13 China 3692 866 Asia 14 USA 3615 219 North America 15 Brazil 3286 116 South America 16 Australia 2968 14 Australia 17 India 1269 637 Asia 18 Argentina 1072 26 South America 19 Sudan 968 19 Africa 20 Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"{ print NR, $0 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_40() { let expected = String::from( r#"Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"{ for (i = 1; i <= NF; i++) print $i }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_41() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"NR >= 10 { exit } END { if (NR < 10) print FILENAME " has only " NR " lines" }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_42() { let expected = String::from( r#"Asian population in millions is 3530 African population in millions is 74 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"/Asia/ { pop["Asia"] += $3 } /Africa/ { pop["Africa"] += $3 } END { print "Asian population in millions is", pop["Asia"] print "African population in millions is", pop["Africa"] }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_43() { let expected = String::from( r#"Asia:27222 Australia:5936 Africa:3776 South America:8716 North America:14934 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { let output = Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = "\t" } { area[$4] += $2 } END { for (name in area) print name ":" area[name]; }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .output() .unwrap() .stdout; unordered_output_equals(expected.as_bytes(), &output[..]); } } #[test] fn p_test_44() { let expected = String::from( r#"Russia! is 1 Canada! is 1 China! is 1 USA! is 1 Brazil! is 1 Australia! is 1 India! is 1 Argentina! is 1 Sudan! is 1 Algeria! is 1 Russia! is 1 Canada! is 1 China! is 1 USA! is 1 Brazil! is 1 Australia! is 1 India! is 1 Argentina! is 1 Sudan! is 1 Algeria! is 1 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"function fact(n) { if (n <= 1) return 1 else return n * fact(n-1) } { print $1 "! is " fact($1) }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_45() { let expected = String::from( r#"Russia:8650 Canada:3852 China:3692 USA:3615 Brazil:3286 Australia:2968 India:1269 Argentina:1072 Sudan:968 Algeria:920 Russia:8650 Canada:3852 China:3692 USA:3615 Brazil:3286 Australia:2968 India:1269 Argentina:1072 Sudan:968 Algeria:920 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { OFS = ":" ; ORS = "\n\n" } { print $1, $2 }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_46() { let expected = String::from( r#"Russia8650 Canada3852 China3692 USA3615 Brazil3286 Australia2968 India1269 Argentina1072 Sudan968 Algeria920 Russia8650 Canada3852 China3692 USA3615 Brazil3286 Australia2968 India1269 Argentina1072 Sudan968 Algeria920 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#" { print $1 $2 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_47() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let small_path = tmpdir.path().join("tempsmall"); let big_path = tmpdir.path().join("tempbig"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); let small = small_path.clone().into_os_string().into_string().unwrap(); let big = big_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(format!( r#"$3 > 100 {{ print >"{tempbig}" }} $3 <= 100 {{ print >"{tempsmall}" }}"#, tempsmall = small, tempbig = big, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); let got_small = read_to_string(small_path.clone()).unwrap(); assert_eq!( got_small, r#"Canada 3852 24 North America Australia 2968 14 Australia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa Canada 3852 24 North America Australia 2968 14 Australia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "# ); let got_big = read_to_string(big_path.clone()).unwrap(); assert_eq!( got_big, r#"Russia 8650 262 Asia China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America India 1269 637 Asia Russia 8650 262 Asia China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America India 1269 637 Asia "# ); } } #[cfg(not(target_os = "windows"))] #[test] fn p_test_48() { let expected = String::from( r#"Africa:74 Asia:3530 Australia:28 North America:486 South America:284 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = "\t" } { pop[$4] += $3 } END { for (c in pop) print c ":" pop[c] | "sort"; }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_48a() { let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); let expected = format!("{filename} {filename} \n", filename = data_string.as_str()); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { for (i = 1; i < ARGC; i++) printf "%s ", ARGV[i] printf "\n" exit }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_48b() { let expected = String::from( r#"Russia 8650 262 Asia Canada 3852 24 North America USA 3615 219 North America "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { srand(10); k = 3; n = 10 } { if (n <= 0) exit if (rand() <= k/n) { print; k-- } n-- }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } // 48b, in its use of `exit` --- not currently supported by frawk --- inadvertently tests nan // comparison behavior. As a result, we'll keep it around, but will replicate the original `exit` // semantics in the _mod test. #[test] fn p_test_48b_mod() { let expected = String::from( r#"Russia 8650 262 Asia Canada 3852 24 North America USA 3615 219 North America "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { srand(10); k = 3; n = 10 } { if (n <= 0) nextfile if (rand() <= k/n) { print; k-- } n-- }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_49() { let expected = String::from(r#""#); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$1 == "include" { system("cat " $2) }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_5() { let expected = String::from( r#" COUNTRY AREA POP CONTINENT Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = "\t" printf "%10s %6s %5s %15s\n", "COUNTRY", "AREA", "POP", "CONTINENT" } { printf "%10s %6d %5d %15s\n", $1, $2, $3, $4 }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[cfg(not(target_os = "windows"))] #[test] fn p_test_50() { let expected = String::from( r#"Africa:Sudan:38 Africa:Algeria:36 Asia:China:1732 Asia:India:1274 Asia:Russia:524 Australia:Australia:28 North America:USA:438 North America:Canada:48 South America:Brazil:232 South America:Argentina:52 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = "\t" } { pop[$4 ":" $1] += $3 } END { for (cc in pop) print cc ":" pop[cc] | "sort -t: -k 1,1 -k 3nr"; }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_51() { let expected = String::from( r#" Russia 8650 262 Asia: 0 Canada 3852 24 North America: 0 China 3692 866 Asia: 0 USA 3615 219 North America: 0 Brazil 3286 116 South America: 0 Australia 2968 14 Australia: 0 India 1269 637 Asia: 0 Argentina 1072 26 South America: 0 Sudan 968 19 Africa: 0 Algeria 920 18 Africa: 0 Russia 8650 262 Asia: 0 Canada 3852 24 North America: 0 China 3692 866 Asia: 0 USA 3615 219 North America: 0 Brazil 3286 116 South America: 0 Australia 2968 14 Australia: 0 India 1269 637 Asia: 0 Argentina 1072 26 South America: 0 Sudan 968 19 Africa: 0 Algeria 920 18 Africa: 0 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = ":" } { if ($1 != prev) { print "\n" $1 ":" prev = $1 } printf "\t%-10s %6d\n", $2, $3 }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_52() { let expected = String::from( r#" Russia 8650 262 Asia: 0 total 0 Canada 3852 24 North America: 0 total 0 China 3692 866 Asia: 0 total 0 USA 3615 219 North America: 0 total 0 Brazil 3286 116 South America: 0 total 0 Australia 2968 14 Australia: 0 total 0 India 1269 637 Asia: 0 total 0 Argentina 1072 26 South America: 0 total 0 Sudan 968 19 Africa: 0 total 0 Algeria 920 18 Africa: 0 total 0 Russia 8650 262 Asia: 0 total 0 Canada 3852 24 North America: 0 total 0 China 3692 866 Asia: 0 total 0 USA 3615 219 North America: 0 total 0 Brazil 3286 116 South America: 0 total 0 Australia 2968 14 Australia: 0 total 0 India 1269 637 Asia: 0 total 0 Argentina 1072 26 South America: 0 total 0 Sudan 968 19 Africa: 0 total 0 Algeria 920 18 Africa: 0 total 0 World Total 0 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = ":" } { if ($1 != prev) { if (prev) { printf "\t%-10s\t %6d\n", "total", subtotal subtotal = 0 } print "\n" $1 ":" prev = $1 } printf "\t%-10s %6d\n", $2, $3 wtotal += $3 subtotal += $3 } END { printf "\t%-10s\t %6d\n", "total", subtotal printf "\n%-10s\t\t %6d\n", "World Total", wtotal }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_5a() { let expected = String::from( r#" COUNTRY AREA POP'N CONTINENT Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"BEGIN { FS = "\t" printf "%10s\t%6s\t%6s\t%15s\n", "COUNTRY", "AREA", "POP'N", "CONTINENT"} { printf "%10s\t%6d\t%6d\t%15s\n", $1, $2, $3, $4}"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_6() { let expected = String::from( r#"20 "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"END { print NR }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_7() { let expected = String::from( r#"Russia 8650 262 Asia China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America India 1269 637 Asia Russia 8650 262 Asia China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America India 1269 637 Asia "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$3 > 100"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_8() { let expected = String::from( r#"Russia China India Russia China India "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$4 == "Asia" { print $1 }"#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_9() { let expected = String::from( r#"USA 3615 219 North America Sudan 968 19 Africa USA 3615 219 North America Sudan 968 19 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from(r#"$1 >= "S""#)) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } } #[test] fn p_test_table() { let expected = String::from( r#"Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa Russia 8650 262 Asia Canada 3852 24 North America China 3692 866 Asia USA 3615 219 North America Brazil 3286 116 South America Australia 2968 14 Australia India 1269 637 Asia Argentina 1072 26 South America Sudan 968 19 Africa Algeria 920 18 Africa "#, ); let tmpdir = tempdir().unwrap(); let data_path = tmpdir.path().join("test.countries"); let data_string = data_path.clone().into_os_string().into_string().unwrap(); { let mut file = File::create(data_path).unwrap(); write!(file, "{}", COUNTRIES).unwrap(); } for backend_arg in BACKEND_ARGS { Command::cargo_bin("frawk") .unwrap() .arg(String::from(*backend_arg)) .arg(String::from( r#"# table - simple table formatter BEGIN { FS = "\t"; blanks = sprintf("%100s", " ") number = "^[+-]?([0-9]+[.]?[0-9]*|[.][0-9]+)$" } { row[NR] = $0 for (i = 1; i <= NF; i++) { if ($i ~ number) nwid[i] = max(nwid[i], length($i)) wid[i] = max(wid[i], length($i)) } } END { for (r = 1; r <= NR; r++) { n = split(row[r], d) for (i = 1; i <= n; i++) { sep = (i < n) ? " " : "\n" if (d[i] ~ number) printf("%" wid[i] "s%s", numjust(i,d[i]), sep) else printf("%-" wid[i] "s%s", d[i], sep) } } } function max(x, y) { return (x > y) ? x : y } function numjust(n, s) { # position s in field n return s substr(blanks, 1, int((wid[n]-nwid[n])/2)) }"#, )) .arg(data_string.clone()) .arg(data_string.clone()) .assert() .stdout(expected.clone()); } }
pub mod command; pub mod controll; pub mod response; pub mod server; pub mod session;
// 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. #![allow(clippy::uninlined_format_args)] mod grpc_action; mod grpc_client; mod kv_api_impl; mod message; pub use common_meta_api::reply::reply_to_api_result; pub use common_meta_api::reply::reply_to_meta_result; pub use grpc_action::MetaGrpcReq; pub use grpc_action::RequestFor; pub use grpc_client::ClientHandle; pub use grpc_client::MetaGrpcClient; pub use message::ClientWorkerRequest; use once_cell::sync::Lazy; use semver::BuildMetadata; use semver::Prerelease; use semver::Version; pub static METACLI_COMMIT_SEMVER: Lazy<Version> = Lazy::new(|| { let build_semver = option_env!("DATABEND_GIT_SEMVER"); let semver = build_semver.expect("DATABEND_GIT_SEMVER can not be None"); let semver = semver.strip_prefix('v').unwrap_or(semver); Version::parse(semver).unwrap_or_else(|e| panic!("Invalid semver: {:?}: {}", semver, e)) }); /// Oldest compatible nightly metasrv version /// /// - 2022-10-19: after 0.8.79: /// Update min compatible server to 0.8.35: /// Since which, meta-server adds new API kv_api() to replace write_msg() and read_msg(); /// Feature commit: 69a05aca41036976fec37ad7a8b447e2868ef08b 2022-09-14 /// /// - 2023-02-04: since 0.9.24: /// Remove read_msg and write_msg from service definition meta.proto /// Update server.min_cli_ver to 0.8.80, the min ver in which meta-client switched from /// `read_msg/write_msg` to `kv_api` /// /// - 2023-02-16: since 0.9.41: /// Meta client add `Compatible` layer to accept KVAppError or MetaAPIError /// /// - 2023-02-17: since 0.9.42: /// Meta service only responds with MetaAPIError. pub static MIN_METASRV_SEMVER: Version = Version { major: 0, minor: 8, patch: 35, pre: Prerelease::EMPTY, build: BuildMetadata::EMPTY, }; pub fn to_digit_ver(v: &Version) -> u64 { v.major * 1_000_000 + v.minor * 1_000 + v.patch } pub fn from_digit_ver(u: u64) -> Version { Version::new(u / 1_000_000, u / 1_000 % 1_000, u % 1_000) }
use failure::Error; use geometry::Rectangle; use rand::{self, seq, Rng}; use std::cmp::min; use std::fmt; use std::fmt::Formatter; use std::fs::File; use std::fs::OpenOptions; use std::io::{self, Read, Write}; use std::path::Path; use std::str::FromStr; const N_DEFAULTS: [usize; 5] = [3, 5, 10, 25, 5000]; const AVG_RECTANGLE_AREA: u64 = 50; pub fn generate(n: usize, variant: Option<Variant>, allow_rotation: Option<bool>) -> Problem { use rand::distributions::{IndependentSample, Range}; const UPPER: u32 = 200; let n = n.max(3); let mut rng = rand::thread_rng(); let allow_rotation = allow_rotation.unwrap_or_else(|| rng.gen()); let (xr, yr) = match variant { Some(Variant::Fixed(k)) => { let xr = Range::new(1, UPPER); let yr = Range::new(1, k + 1); (xr, yr) } _ => { let range = Range::new(1, UPPER); (range.clone(), range) } }; let rectangles: Vec<Rectangle> = (0..n) .map(|_| { let x = xr.ind_sample(&mut rng); let y = yr.ind_sample(&mut rng); Rectangle::new(x, y) }) .collect(); let variant = variant.unwrap_or_else(|| { if rng.gen() { Variant::Free } else { let largest_side: u32 = rectangles .iter() .map(|r| r.width) .chain(rectangles.iter().map(|r| r.height)) .max() .unwrap(); let sum = rectangles .iter() .map(|r| r.width) .sum::<u32>() .max(rectangles.iter().map(|r| r.height).sum()); let max = largest_side + ((sum - largest_side) / 2); let upper = rng.gen_range(largest_side, max); Variant::Fixed(upper) } }); Problem { variant, allow_rotation, rectangles, source: None, } } #[derive(Clone, Debug, PartialEq)] pub struct Problem { pub variant: Variant, pub allow_rotation: bool, pub rectangles: Vec<Rectangle>, pub source: Option<Rectangle>, } impl Problem { fn generate_from(r: Rectangle, n: usize, v: Variant, allow_rotation: bool) -> Problem { let a = r.area() as usize; if n > a { panic!("{:?} cannot be split into {} rectangles", r, n) } else if n == a { let rectangles = vec![Rectangle::new(1, 1); n]; return Problem { variant: v, allow_rotation, rectangles, source: None, }; } let mut rng = rand::thread_rng(); let mut rectangles = Vec::with_capacity(n as usize); rectangles.push(r); while rectangles.len() < n { let i = seq::sample_indices(&mut rng, rectangles.len(), 1)[0]; let r = rectangles.swap_remove(i); if r.width > 1 || r.height > 1 { let (r1, r2) = r.simple_rsplit(); rectangles.push(r1); rectangles.push(r2); } else { rectangles.push(r); } } Problem { variant: v, allow_rotation, rectangles, source: Some(r), } } fn config_str(&self) -> String { format!( "container height: {v}\nrotations allowed: {r}\nnumber of rectangles: {n}", v = self.variant, r = if self.allow_rotation { "yes" } else { "no" }, n = self.rectangles.len() ) } pub fn digest(&self) -> String { let mut config = self.config_str(); if let Some(source) = self.source { config.push_str(&format!("\nbounding box: {}", source.to_string())); } self.rectangles .iter() .for_each(|r| config.push_str(&format!("\n{}", r.to_string()))); config } pub fn save<P: AsRef<Path>>(&self, path: P) -> io::Result<()> { let mut file = OpenOptions::new().write(true).create(true).open(path)?; file.write_all(self.to_string().as_bytes()) } pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Problem, Error> { let mut content = String::new(); File::open(path)?.read_to_string(&mut content)?; content.parse() } } impl fmt::Display for Problem { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut s = self.config_str(); self.rectangles .iter() .for_each(|r| s.push_str(&format!("\n{}", r.to_string()))); write!(f, "{}", s) } } impl FromStr for Problem { type Err = Error; fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { let mut lines = s.trim().lines(); let l1: Vec<&str> = lines .next() .ok_or_else(|| format_err!("Unexpected end of file: unable to parse problem variant"))? .split_whitespace() .collect(); let variant = match l1.as_slice() { ["container", "height:", "free"] => Variant::Free, ["container", "height:", "fixed", h] => Variant::Fixed(h.parse()?), _ => bail!("Invalid format: {}", l1.join(" ")), }; let l2 = lines.next().ok_or_else(|| { format_err!("Unexpected end of file: unable to parse problem rotation setting") })?; let allow_rotation = match l2 { "rotations allowed: yes" => true, "rotations allowed: no" => false, _ => bail!("Invalid format: {}", l2), }; lines.next(); let rectangles = lines .map(|s| s.parse()) .collect::<Result<Vec<Rectangle>, _>>()?; Ok(Problem { variant, allow_rotation, rectangles, source: None, }) } } #[derive(Default)] pub struct Generator { container: Option<Rectangle>, rectangles: Option<usize>, variant: Option<Variant>, allow_rotation: Option<bool>, } impl Generator { pub fn new() -> Self { Self::default() } pub fn generate(&self) -> Problem { let mut rng = rand::thread_rng(); let mut n = self .rectangles .unwrap_or_else(|| seq::sample_slice(&mut rng, &N_DEFAULTS, 1)[0]); let r = self.container.unwrap_or_else(|| { let area = n as u64 * AVG_RECTANGLE_AREA; Rectangle::gen_with_area(area) }); n = min(n, r.area() as usize); let variant = self .variant .map(|v| match v { Variant::Fixed(_h) => Variant::Fixed(r.height), v => v, }) .unwrap_or_else(|| { if rng.gen() { Variant::Free } else { Variant::Fixed(r.height) } }); let allow_rotation = self.allow_rotation.unwrap_or_else(|| rng.gen()); Problem::generate_from(r, n, variant, allow_rotation) } pub fn rectangles(&mut self, mut n: usize) { if let Some(ref mut r) = self.container { n = min(n, r.area() as usize); } self.rectangles = Some(n); } pub fn allow_rotation(&mut self, b: bool) { self.allow_rotation = Some(b); } pub fn variant(&mut self, v: Variant) { self.variant = Some(v); } pub fn container(&mut self, r: Rectangle) { self.container = Some(r); self.rectangles.map(|n| min(n, r.area() as usize)); } } #[derive(Clone, Copy, Debug, PartialEq, Serialize)] pub enum Variant { Free, Fixed(u32), } impl fmt::Display for Variant { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { Variant::Free => write!(f, "free"), Variant::Fixed(h) => write!(f, "fixed {}", h), } } } impl FromStr for Variant { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let parts: Vec<&str> = s.split_whitespace().collect(); let variant = match &parts[..] { &["free"] => Variant::Free, &["fixed", n] => Variant::Fixed(n.parse()?), _ => bail!("Failed to parse variant"), }; Ok(variant) } } #[cfg(test)] mod tests { #![allow(non_upper_case_globals)] use super::*; const input: &str = "container height: fixed 22\nrotations allowed: no\nnumber of rectangles: 2\n12 8\n10 9"; #[test] fn parsing() { let expected = Problem { variant: Variant::Fixed(22), allow_rotation: false, rectangles: vec![Rectangle::new(12, 8), Rectangle::new(10, 9)], source: None, }; let result: Problem = input.parse().unwrap(); assert_eq!(result, expected); } #[test] fn format_parse() { assert_eq!(input, format!("{}", input.parse::<Problem>().unwrap())) } #[test] fn generate_from() { let r = Rectangle::new(1000, 1000); let p = Problem::generate_from(r, 50, Variant::Free, false); let a: u32 = p.rectangles.into_iter().map(|r| r.height * r.width).sum(); assert_eq!(a, 1000 * 1000); } }
// Copyright 2018 Mattias Cibien // // 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. //! Library aimed at parsing and rolling dices //! for Role-Playing games using [Standard Dice Notation](https://en.wikipedia.org/wiki/Dice_notation#Standard_notation) //! that bears inspiration from the [dicenotation](https://github.com/mattiascibien/dicenotation) library. #![forbid(unsafe_code)] #[macro_use] extern crate lazy_static; use num_traits; use rand; use num_traits::int::PrimInt; use rand::distributions::range::SampleRange; use std::fmt::Debug; use std::str::FromStr; mod parsing; mod rolling; /// Struct represeting a die roll data #[derive(Debug)] pub struct DiceData<T> where T: PrimInt, { /// Number of die to roll num_dice: T, /// Number of faces of each dice num_faces: T, /// Modifies (true for plus, false for minus) modifier: bool, /// Modifier value (alters the result of the die roll) modifier_val: T, } #[cfg(test)] impl<T> PartialEq for DiceData<T> where T: PrimInt, { fn eq(&self, other: &DiceData<T>) -> bool { self.num_dice == other.num_dice && self.num_faces == other.num_faces && self.modifier == other.modifier && self.modifier_val == other.modifier_val } } /// Execute a dice roll based on the given notation /// /// # Examples /// /// Gets the result of rolling 3 die of 5 faces /// /// ``` /// use dicenotation::roll_dice; /// /// let result = roll_dice::<i32>("3d5"); /// ``` /// /// Executes two rolls by summing their values /// /// ``` /// use dicenotation::roll_dice; /// /// let result = roll_dice::<i32>("3d5").unwrap() + roll_dice::<i32>("2d3").unwrap(); /// ``` pub fn roll_dice<T>(notation: &str) -> Result<T, &str> where T: PrimInt + FromStr + SampleRange, <T as FromStr>::Err: Debug, { let dice_data = parsing::parse(notation); let dice_data = match dice_data { Ok(d) => d, Err(e) => return Err(e), }; let result = rolling::roll(dice_data); Ok(result) } pub fn roll_dice_with_fn<T,F>(notation: &str, random: F) -> Result<T, &str> where T: PrimInt + FromStr + SampleRange, <T as FromStr>::Err: Debug, F: Fn(T,T) -> T, { let dice_data = parsing::parse(notation); let dice_data = match dice_data { Ok(d) => d, Err(e) => return Err(e), }; let result = rolling::roll_with_fn(dice_data, &random); Ok(result) } #[cfg(test)] mod test { #[test] fn it_rolls_two_dices_of_three_faces_with_modifier_plus_two_correctly() { let result = super::roll_dice::<i32>("2d3+2").unwrap(); assert!(result >= 4); assert!(result <= 8); } }
use super::{Atom, Expr}; #[derive(Debug, PartialEq, Clone)] pub struct Func { pub args: Vec<Atom>, pub body: Expr, }
use bintree::Tree; use std::fmt; pub fn at_level<T: Copy + fmt::Display>(tree: &Tree<T>, level: usize) -> Vec<T> { assert!(level > 0, "level must be greater than 0"); if let Tree::Node { value, left, right } = tree { if level == 1 { vec![*value] } else { let mut vals = at_level(left, level - 1); vals.extend_from_slice(&at_level(right, level - 1)); vals } } else { vec![] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_at_level() { assert_eq!(at_level(&Tree::<char>::end(), 1), vec![]); assert_eq!(at_level(&Tree::leaf('a'), 1), vec!['a']); assert_eq!(at_level(&Tree::leaf('a'), 2), vec![]); assert_eq!( at_level( &Tree::node( 'a', Tree::leaf('b'), Tree::node('c', Tree::leaf('d'), Tree::leaf('e')) ), 2 ), vec!['b', 'c'] ); } }
use serde_json::builder::{ArrayBuilder, ObjectBuilder}; use serde_json::Value; use errors::*; pub fn build_error(code: RegistryError, message: String) -> Value { ObjectBuilder::new() .insert("errors", ArrayBuilder::new() .push(ObjectBuilder::new() .insert("code", code) .insert("message", message) .unwrap()) .unwrap()) .unwrap() } pub fn ping() -> Value { ObjectBuilder::new().unwrap() }
use pyo3::prelude::*; use pyo3::types::PyDict; use pyo3::wrap_pyfunction; use htmlescape::{encode_attribute, encode_minimal}; #[pyfunction] /// Formats the sum of two numbers as string. fn sum_as_string(a: usize, b: usize) -> PyResult<String> { Ok((a + b).to_string()) } #[pyfunction] fn render_attr(key: &str, value: &str) -> PyResult<String> { Ok(format!(" {}=\"{}\"", key, encode_attribute(value))) } #[pyfunction] fn render_attrs(attrs: &PyDict) -> PyResult<String> { let mut out: String = "".to_owned(); for (key, value) in attrs.iter() { out.push_str(&format!(" {}=\"{}\"", key, value)); } Ok(out) } #[pyfunction] fn escape(html: &str) -> PyResult<String> { Ok(encode_minimal(html)) } #[pymodule] /// A Python module implemented in Rust. fn string_engine(py: Python, m: &PyModule) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(sum_as_string))?; m.add_wrapped(wrap_pyfunction!(render_attr))?; m.add_wrapped(wrap_pyfunction!(render_attrs))?; m.add_wrapped(wrap_pyfunction!(escape))?; Ok(()) }
use std::io; fn fibonacci(nth: u32) -> u32 { let (mut x, mut y) = (1, 1); let mut tmp; for _ in 3..(nth+1) { tmp = x; x = x + y; y = tmp; } x } fn main() { let val: u32; loop { println!("Please input nth of fibonacci."); let mut nth = String::new(); io::stdin().read_line(&mut nth) .expect("Failed to read nth"); val = match nth.trim().parse() { Ok(num) => num, Err(_) => continue, }; break; } println!("{}", fibonacci(val)); }
#![allow(dead_code)] use near_sdk::{serde_json::json, AccountId, PendingContractTx}; use near_sdk_sim::*; use oysterpack_near_stake_token::interface::{BatchId, StakeBatchReceipt}; use oysterpack_near_stake_token::near::NO_DEPOSIT; use oysterpack_near_stake_token::{ domain::{YoctoNear, TGAS}, interface, }; pub struct StakingServiceClient { pub contract_account_id: AccountId, } impl StakingServiceClient { pub fn new(contract_account_id: &str) -> Self { Self { contract_account_id: contract_account_id.to_string(), } } pub fn staking_pool_id(&self, user: &UserAccount) -> AccountId { let result = user.view(PendingContractTx::new( &self.contract_account_id, "staking_pool_id", json!({}), true, )); result.unwrap_json() } pub fn stake_batch_receipt( &self, user: &UserAccount, batch_id: BatchId, ) -> Option<StakeBatchReceipt> { let result = user.view(PendingContractTx::new( &self.contract_account_id, "stake_batch_receipt", json!({ "batch_id": batch_id }), true, )); result.unwrap_json() } pub fn deposit(&self, user: &UserAccount, amount: interface::YoctoNear) -> interface::BatchId { let result = user.call( PendingContractTx::new(&self.contract_account_id, "deposit", json!({}), false), amount.value(), TGAS.value() * 10, ); println!("deposit: {:#?}", result); result.unwrap_json() } pub fn stake(&self, user: &UserAccount) -> ExecutionResult { let result = user.call( PendingContractTx::new(&self.contract_account_id, "stake", json!({}), false), NO_DEPOSIT.value(), TGAS.value() * 200, ); println!("stake: {:#?}", result); result } pub fn claim_receipts(&self, user: &UserAccount) -> ExecutionResult { let result = user.call( PendingContractTx::new( &self.contract_account_id, "claim_receipts", json!({}), false, ), NO_DEPOSIT.value(), TGAS.value() * 10, ); println!("claim_receipts: {:#?}", result); result } pub fn redeem_all(&self, user: &UserAccount) -> Option<BatchId> { let result = user.call( PendingContractTx::new(&self.contract_account_id, "redeem_all", json!({}), false), NO_DEPOSIT.value(), TGAS.value() * 10, ); println!("redeem_all: {:#?}", result); result.unwrap_json() } pub fn unstake(&self, user: &UserAccount) -> ExecutionResult { let result = user.call( PendingContractTx::new(&self.contract_account_id, "unstake", json!({}), false), NO_DEPOSIT.value(), TGAS.value() * 150, ); println!("unstake: {:#?}", result); result } }
use base64; use failure::Error; #[derive(Deserialize, Clone, PartialEq, Eq, Debug)] pub struct BasicAuthentication { pub username: String, pub password: String, } impl BasicAuthentication { /// Takes the value of the 'Authorization' header and tries to construct a /// BasicAuthentication object from it. pub fn parse(header: &str) -> Result<Self, Error> { let parts: Vec<_> = header.splitn(2, ' ').collect(); ensure!(parts.len() == 2, "Invalid Authentication header."); ensure!( parts[0] == "Basic", "Authentication header is not a supported type." ); let bytes = base64::decode(&parts[1])?; let decoded = String::from_utf8(bytes)?; let parts: Vec<_> = decoded.splitn(2, ':').collect(); ensure!(parts.len() == 2, "Invalid basic authentication header."); Ok(Self { username: parts[0].to_string(), password: parts[1].to_string(), }) } pub fn to_string(&self) -> String { format!( "Basic {}", base64::encode(&format!("{}:{}", self.username, self.password)) ) } } impl<T, U> From<(T, U)> for BasicAuthentication where T: AsRef<str>, U: AsRef<str>, { fn from(other: (T, U)) -> Self { Self { username: other.0.as_ref().to_string(), password: other.1.as_ref().to_string(), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_basic_auth() { assert_eq!( BasicAuthentication::parse("Basic dXNlcjpwYXNz").unwrap(), ("user", "pass").into() ); assert_eq!( BasicAuthentication::from(("user", "pass")).to_string(), "Basic dXNlcjpwYXNz" ) } }
use actix_web::{HttpResponse, Json, Path, Query}; use auth::user::User; use bigneon_db::models::*; use db::Connection; use errors::*; use helpers::application; use models::{Paging, PagingParameters, PathParameters, Payload}; pub fn index( (connection, query_parameters): (Connection, Query<PagingParameters>), ) -> Result<HttpResponse, BigNeonError> { //TODO refactor query using paging parameters let regions = Region::all(connection.get())?; let query_parameters = Paging::new(&query_parameters.into_inner()); let region_count = regions.len(); let mut payload = Payload { data: regions, paging: Paging::clone_with_new_total(&query_parameters, region_count as u64), }; payload.paging.limit = region_count as u64; Ok(HttpResponse::Ok().json(&payload)) } pub fn show( (connection, parameters): (Connection, Path<PathParameters>), ) -> Result<HttpResponse, BigNeonError> { let region = Region::find(&parameters.id, connection.get())?; Ok(HttpResponse::Ok().json(&region)) } pub fn create( (connection, new_region, user): (Connection, Json<NewRegion>, User), ) -> Result<HttpResponse, BigNeonError> { let connection = connection.get(); if !user.has_scope(Scopes::RegionWrite, None, connection)? { return application::unauthorized(); } let region = new_region.into_inner().commit(connection)?; Ok(HttpResponse::Created().json(&region)) } pub fn update( (connection, parameters, region_parameters, user): ( Connection, Path<PathParameters>, Json<RegionEditableAttributes>, User, ), ) -> Result<HttpResponse, BigNeonError> { let connection = connection.get(); if !user.has_scope(Scopes::RegionWrite, None, connection)? { return application::unauthorized(); } let region = Region::find(&parameters.id, connection)?; let updated_region = region.update(region_parameters.into_inner(), connection)?; Ok(HttpResponse::Ok().json(updated_region)) }
#[cfg(target_arch = "wasm32")] pub mod web; #[cfg(not(target_arch = "wasm32"))] pub mod egl;
use std::ffi::OsStr; use std::fs::File; use std::iter::{empty, once}; use std::path::{Path, PathBuf}; use log::error; use serde::de::DeserializeOwned; use crate::review::{Review, Reviews}; use crate::{error::Error, recipe::Recipe}; pub struct Context { pub reviews: Vec<Review>, pub recipes: Vec<Recipe>, } impl Context { pub fn new(recipe_dir: &Path, review_dir: &Path) -> Self { let mut recipes = Self::walk_files(&recipe_dir) .filter_map(|path| match Self::read_file(&path) { Ok(recipe) => Some(recipe), Err(read_err) => { error!("File read error: {}", read_err); None } }) .collect::<Vec<Recipe>>(); let mut reviews = Self::walk_files(&review_dir) .flat_map(|path| match Self::read_file(&path) { Ok(reviews) => match reviews { Reviews::Single(review) => { Box::new(once(review)) as Box<dyn Iterator<Item = Review>> } Reviews::List(list) => Box::new(list.into_iter()), }, Err(read_err) => { error!("File read error: {}", read_err); Box::new(empty()) } }) .collect::<Vec<Review>>(); recipes.sort_by_key(|recipe| recipe.name.clone()); reviews.sort_by_key(|review| (review.title.clone(), review.year)); Self { recipes, reviews } } fn read_file<T: DeserializeOwned>(path: &Path) -> Result<T, Error> { let file = File::open(path).map_err(Error::FileReadError)?; serde_yaml::from_reader(file).map_err(|error| Error::YamlError { error, path: path.to_owned(), }) } fn walk_files(dir: &Path) -> impl Iterator<Item = PathBuf> { ignore::Walk::new(&dir).filter_map(|entry| match entry { Ok(entry) => { let extension = entry.path().extension().and_then(OsStr::to_str); if extension == Some("yml") { Some(entry.path().to_owned()) } else { None } } Err(err) => { error!("Invalid entry in directory: {}", err); None } }) } }
fn the_longest<'a>(s1: &'a str, s2: &'a str) -> &'a str { if s1.len() > s2.len() { s1 } else { s2 } } fn the_shortest<'a>(s1: &'a str, s2: &'a str) -> &'a str { if s1.len() < s2.len() { s1 } else { s2 } } fn main() { let s1 = String::from("Apure"); // explicitly borrowing to ensure that // the borrow lasts longer than s2 exists let s1_b = &s1; { let s2 = String::from("Guarico"); let res = the_longest(s1_b, &s2); println!("{} is the longest if you judge by name", res); } let s3_b = &s1; { let s4 = String::from("Guarico"); let res = the_shortest(s3_b, &s4); println!("{} is the shortest if you judge by name", res); } }
use crate::event_handler::BotEventHandler; use serenity::model::prelude::GuildId; use serenity::prelude::Context; use std::sync::atomic::Ordering; pub async fn cache_ready(handler: &BotEventHandler, _ctx: Context, _guild_ids: Vec<GuildId>) { if handler.loop_running.swap(true, Ordering::Relaxed) { // spawn any background tasks here! use tokio::spawn for that } }
use std::{ env, fs::File, io::{self, BufReader, Read}, }; fn main() { let path = env::args().nth(1).unwrap_or_else(|| "Cargo.toml".to_string()); let file = File::open(path).expect("Failed to open path as File"); let mut reader = BufReader::new(file); let bytes_read = read(&mut reader).expect("Failed to read file"); println!("Bytes read: {}, sum: {}", bytes_read.0, bytes_read.1); } fn read<R: Read + Sized>(reader: &mut R) -> std::io::Result<(usize, usize)> { let mut buf = [0u8; 8 * 1024]; let mut sum = 0usize; let mut bytes_read = 0usize; loop { let len = match reader.read(&mut buf[..]) { Ok(0) => return Ok((bytes_read, sum)), Ok(len) => len, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; bytes_read += len; sum += buf.iter().map(|x| usize::from(*x)).sum::<usize>(); } }
use cache::Cache; use gen::legal_moves; use mv_list::{MoveCounter, MoveVec}; use num_cpus; use position::Position; use std::sync::mpsc::channel; use threadpool::ThreadPool; pub fn perft( position: &mut Position, depth: usize, multi_threading_enabled: bool, cache_bytes_per_thread: usize, ) -> usize { if depth == 0 { return 1; } if depth <= 3 { return perft_inner(position, depth); } if !multi_threading_enabled { if cache_bytes_per_thread > 0 { let mut cache = Cache::new(cache_bytes_per_thread).unwrap(); return perft_with_cache_inner(position, depth, &mut cache); } else { return perft_inner(position, depth); } } let pool = ThreadPool::new(num_cpus::get()); let (tx, rx) = channel(); let mut moves = MoveVec::new(); legal_moves(&position, &mut moves); let moves_len = moves.len(); for &mv in moves.iter() { let tx = tx.clone(); let mut position_local = position.clone(); pool.execute(move || { position_local.make(mv); let count: usize; if cache_bytes_per_thread > 0 { let mut cache = Cache::new(cache_bytes_per_thread).unwrap(); count = perft_with_cache_inner(&mut position_local, depth - 1, &mut cache); } else { count = perft_inner(&mut position_local, depth - 1); } tx.send(count).unwrap(); }); } return rx.iter().take(moves_len).sum(); } pub fn perft_inner(position: &mut Position, depth: usize) -> usize { if depth == 0 { return 1; } let mut moves = MoveVec::new(); legal_moves(&position, &mut moves); let state = position.state().clone(); let key = position.hash_key(); let mut count = 0; for &mv in moves.iter() { let capture = position.make(mv); count += perft_inner(position, depth - 1); position.unmake(mv, capture, &state, key); } count } fn perft_with_cache_inner(position: &mut Position, depth: usize, cache: &mut Cache) -> usize { let key = position.hash_key(); let ret = cache.probe(key, depth); if ret.is_some() { return ret.unwrap(); } let mut count = 0; if depth == 1 { let mut counter = MoveCounter::new(); legal_moves(&position, &mut counter); count = counter.moves as usize; } else { let mut moves = MoveVec::new(); legal_moves(&position, &mut moves); let state = position.state().clone(); let key = position.hash_key(); for &mv in moves.iter() { let capture = position.make(mv); count += perft_with_cache_inner(position, depth - 1, cache); position.unmake(mv, capture, &state, key); } } cache.save(key, count, depth as i16); count } #[cfg(test)] mod test { use super::*; use position::{Position, STARTING_POSITION_FEN}; use test; #[test] fn perft_test_3() { let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap(); assert_eq!(perft(&mut position, 3, false, 0), 8902); } #[test] fn perft_test_4() { let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap(); assert_eq!(perft(&mut position, 4, false, 0), 197281); } #[test] fn perft_with_cache_test_3() { let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap(); assert_eq!(perft(&mut position, 3, false, 1024 * 1024), 8902); } #[test] fn perft_with_cache_test_4() { let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap(); assert_eq!(perft(&mut position, 4, false, 1024 * 1024), 197281); } #[bench] fn perft_bench_starting_position(b: &mut test::Bencher) { let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap(); b.iter(|| -> usize { perft(&mut position, 2, false, 0) }); } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - RAMECC interrupt enable register"] pub ier: IER, _reserved1: [u8; 28usize], #[doc = "0x20 - RAMECC monitor 1 configuration register"] pub m1cr: M1CR, #[doc = "0x24 - RAMECC monitor 1 status register"] pub m1sr: M1SR, #[doc = "0x28 - RAMECC monitor 1 failing address register"] pub m1far: M1FAR, #[doc = "0x2c - RAMECC monitor 1 failing data low register"] pub m1fdrl: M1FDRL, #[doc = "0x30 - RAMECC monitor 1 failing data high register"] pub m1fdrh: M1FDRH, #[doc = "0x34 - RAMECC monitor 1 failing error code register"] pub m1fecr: M1FECR, _reserved7: [u8; 8usize], #[doc = "0x40 - RAMECC monitor 2 configuration register"] pub m2cr: M2CR, #[doc = "0x44 - RAMECC monitor 2 status register"] pub m2sr: M2SR, #[doc = "0x48 - RAMECC monitor 2 failing address register"] pub m2far: M2FAR, #[doc = "0x4c - RAMECC monitor 2 failing data low register"] pub m2fdrl: M2FDRL, #[doc = "0x50 - RAMECC monitor 2 failing data high register"] pub m2fdrh: M2FDRH, #[doc = "0x54 - RAMECC monitor 2 failing error code register"] pub m2fecr: M2FECR, } #[doc = "RAMECC interrupt enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ier](ier) module"] pub type IER = crate::Reg<u32, _IER>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IER; #[doc = "`read()` method returns [ier::R](ier::R) reader structure"] impl crate::Readable for IER {} #[doc = "`write(|w| ..)` method takes [ier::W](ier::W) writer structure"] impl crate::Writable for IER {} #[doc = "RAMECC interrupt enable register"] pub mod ier; #[doc = "RAMECC monitor 1 configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m1cr](m1cr) module"] pub type M1CR = crate::Reg<u32, _M1CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M1CR; #[doc = "`read()` method returns [m1cr::R](m1cr::R) reader structure"] impl crate::Readable for M1CR {} #[doc = "`write(|w| ..)` method takes [m1cr::W](m1cr::W) writer structure"] impl crate::Writable for M1CR {} #[doc = "RAMECC monitor 1 configuration register"] pub mod m1cr; #[doc = "RAMECC monitor 1 status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m1sr](m1sr) module"] pub type M1SR = crate::Reg<u32, _M1SR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M1SR; #[doc = "`read()` method returns [m1sr::R](m1sr::R) reader structure"] impl crate::Readable for M1SR {} #[doc = "`write(|w| ..)` method takes [m1sr::W](m1sr::W) writer structure"] impl crate::Writable for M1SR {} #[doc = "RAMECC monitor 1 status register"] pub mod m1sr; #[doc = "RAMECC monitor 1 failing address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m1far](m1far) module"] pub type M1FAR = crate::Reg<u32, _M1FAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M1FAR; #[doc = "`read()` method returns [m1far::R](m1far::R) reader structure"] impl crate::Readable for M1FAR {} #[doc = "`write(|w| ..)` method takes [m1far::W](m1far::W) writer structure"] impl crate::Writable for M1FAR {} #[doc = "RAMECC monitor 1 failing address register"] pub mod m1far; #[doc = "RAMECC monitor 1 failing data low register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m1fdrl](m1fdrl) module"] pub type M1FDRL = crate::Reg<u32, _M1FDRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M1FDRL; #[doc = "`read()` method returns [m1fdrl::R](m1fdrl::R) reader structure"] impl crate::Readable for M1FDRL {} #[doc = "`write(|w| ..)` method takes [m1fdrl::W](m1fdrl::W) writer structure"] impl crate::Writable for M1FDRL {} #[doc = "RAMECC monitor 1 failing data low register"] pub mod m1fdrl; #[doc = "RAMECC monitor 1 failing data high register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m1fdrh](m1fdrh) module"] pub type M1FDRH = crate::Reg<u32, _M1FDRH>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M1FDRH; #[doc = "`read()` method returns [m1fdrh::R](m1fdrh::R) reader structure"] impl crate::Readable for M1FDRH {} #[doc = "`write(|w| ..)` method takes [m1fdrh::W](m1fdrh::W) writer structure"] impl crate::Writable for M1FDRH {} #[doc = "RAMECC monitor 1 failing data high register"] pub mod m1fdrh; #[doc = "RAMECC monitor 1 failing error code register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m1fecr](m1fecr) module"] pub type M1FECR = crate::Reg<u32, _M1FECR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M1FECR; #[doc = "`read()` method returns [m1fecr::R](m1fecr::R) reader structure"] impl crate::Readable for M1FECR {} #[doc = "`write(|w| ..)` method takes [m1fecr::W](m1fecr::W) writer structure"] impl crate::Writable for M1FECR {} #[doc = "RAMECC monitor 1 failing error code register"] pub mod m1fecr; #[doc = "RAMECC monitor 2 configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m2cr](m2cr) module"] pub type M2CR = crate::Reg<u32, _M2CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M2CR; #[doc = "`read()` method returns [m2cr::R](m2cr::R) reader structure"] impl crate::Readable for M2CR {} #[doc = "`write(|w| ..)` method takes [m2cr::W](m2cr::W) writer structure"] impl crate::Writable for M2CR {} #[doc = "RAMECC monitor 2 configuration register"] pub mod m2cr; #[doc = "RAMECC monitor 2 status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m2sr](m2sr) module"] pub type M2SR = crate::Reg<u32, _M2SR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M2SR; #[doc = "`read()` method returns [m2sr::R](m2sr::R) reader structure"] impl crate::Readable for M2SR {} #[doc = "`write(|w| ..)` method takes [m2sr::W](m2sr::W) writer structure"] impl crate::Writable for M2SR {} #[doc = "RAMECC monitor 2 status register"] pub mod m2sr; #[doc = "RAMECC monitor 2 failing address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m2far](m2far) module"] pub type M2FAR = crate::Reg<u32, _M2FAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M2FAR; #[doc = "`read()` method returns [m2far::R](m2far::R) reader structure"] impl crate::Readable for M2FAR {} #[doc = "`write(|w| ..)` method takes [m2far::W](m2far::W) writer structure"] impl crate::Writable for M2FAR {} #[doc = "RAMECC monitor 2 failing address register"] pub mod m2far; #[doc = "RAMECC monitor 2 failing data low register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m2fdrl](m2fdrl) module"] pub type M2FDRL = crate::Reg<u32, _M2FDRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M2FDRL; #[doc = "`read()` method returns [m2fdrl::R](m2fdrl::R) reader structure"] impl crate::Readable for M2FDRL {} #[doc = "`write(|w| ..)` method takes [m2fdrl::W](m2fdrl::W) writer structure"] impl crate::Writable for M2FDRL {} #[doc = "RAMECC monitor 2 failing data low register"] pub mod m2fdrl; #[doc = "RAMECC monitor 2 failing data high register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m2fdrh](m2fdrh) module"] pub type M2FDRH = crate::Reg<u32, _M2FDRH>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M2FDRH; #[doc = "`read()` method returns [m2fdrh::R](m2fdrh::R) reader structure"] impl crate::Readable for M2FDRH {} #[doc = "`write(|w| ..)` method takes [m2fdrh::W](m2fdrh::W) writer structure"] impl crate::Writable for M2FDRH {} #[doc = "RAMECC monitor 2 failing data high register"] pub mod m2fdrh; #[doc = "RAMECC monitor 2 failing error code register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [m2fecr](m2fecr) module"] pub type M2FECR = crate::Reg<u32, _M2FECR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _M2FECR; #[doc = "`read()` method returns [m2fecr::R](m2fecr::R) reader structure"] impl crate::Readable for M2FECR {} #[doc = "`write(|w| ..)` method takes [m2fecr::W](m2fecr::W) writer structure"] impl crate::Writable for M2FECR {} #[doc = "RAMECC monitor 2 failing error code register"] pub mod m2fecr;
extern crate qt_widgets; use qt_widgets::application::Application; use qt_widgets::push_button::PushButton; use qt_widgets::cpp_utils::*; use qt_widgets::qt_core::string::String; use qt_widgets::libc::{c_char, c_int}; fn to_qt_string<S: AsRef<str>>(s: S) -> String { let slice = s.as_ref().as_bytes(); String::from_utf8((slice.as_ptr() as *const c_char, slice.len() as c_int, RustManaged)) } fn from_qt_string(string: &String) -> std::string::String { let buf = string.to_local8_bit(RustManaged); unsafe { let bytes = std::slice::from_raw_parts(buf.const_data() as *const u8, buf.count(()) as usize); std::str::from_utf8_unchecked(bytes).to_string() } } #[test] fn push_button1() { let _app = CppBox::new(Application::new((&mut 0i32, &mut (&mut 0i8 as *mut i8) as *mut *mut i8, CppPointer))); let btn = CppBox::new(PushButton::new((&to_qt_string("first_button"), CppPointer))); let text = from_qt_string(&btn.text(RustManaged)); assert_eq!(&text, "first_button"); }
use rand::Rng; const TOKEN_CHARSET: &[u8] = b"01234567890ABCDEF"; pub fn generate_random_string(string_length: usize) -> String { let mut rng = rand::thread_rng(); let token: String = (0..string_length) .map(|_| { let idx = rng.gen_range(0..TOKEN_CHARSET.len()); TOKEN_CHARSET[idx] as char }) .collect(); token }
pub(crate) fn aligned(value: u64, align: u64) -> u64 { debug_assert_ne!(align, 0); debug_assert_eq!(align.count_ones(), 1); if value == 0 { 0 } else { 1u64 + ((value - 1u64) | (align - 1u64)) } } pub(crate) trait IntegerFitting { fn fits_usize(self) -> bool; fn fits_isize(self) -> bool; fn usize_fits(value: usize) -> bool; fn isize_fits(value: isize) -> bool; } #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] impl IntegerFitting for u64 { fn fits_usize(self) -> bool { self <= usize::max_value() as u64 } fn fits_isize(self) -> bool { self <= isize::max_value() as u64 } fn usize_fits(_value: usize) -> bool { true } fn isize_fits(value: isize) -> bool { value >= 0 } } #[cfg(target_pointer_width = "64")] impl IntegerFitting for u64 { fn fits_usize(self) -> bool { true } fn fits_isize(self) -> bool { self <= isize::max_value() as u64 } fn usize_fits(_value: usize) -> bool { true } fn isize_fits(value: isize) -> bool { value >= 0 } } #[cfg( not( any( target_pointer_width = "16", target_pointer_width = "32", target_pointer_width = "64" ) ) )] impl IntegerFitting for u64 { fn fits_usize(self) -> bool { true } fn fits_isize(self) -> bool { true } fn usize_fits(value: usize) -> bool { value <= u64::max_value() as usize } fn isize_fits(value: isize) -> bool { value >= 0 && value <= u64::max_value() as isize } } #[cfg(target_pointer_width = "16")] impl IntegerFitting for u32 { fn fits_usize(self) -> bool { self <= usize::max_value() as u32 } fn fits_isize(self) -> bool { self <= isize::max_value() as u32 } fn usize_fits(_value: usize) -> bool { true } fn isize_fits(value: isize) -> bool { value >= 0 } } #[cfg(target_pointer_width = "32")] impl IntegerFitting for u32 { fn fits_usize(self) -> bool { true } fn fits_isize(self) -> bool { self <= isize::max_value() as u32 } fn usize_fits(_value: usize) -> bool { true } fn isize_fits(value: isize) -> bool { value >= 0 } } #[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))] impl IntegerFitting for u32 { fn fits_usize(self) -> bool { true } fn fits_isize(self) -> bool { true } fn usize_fits(value: usize) -> bool { value <= u32::max_value() as usize } fn isize_fits(value: isize) -> bool { value >= 0 && value <= u32::max_value() as isize } } pub(crate) fn fits_usize<T: IntegerFitting>(value: T) -> bool { value.fits_usize() } // pub(crate) fn fits_isize<T: IntegerFitting>(value: T) -> bool { // value.fits_isize() // } // pub(crate) fn fits_u64(value: usize) -> bool { // u64::usize_fits(value) // } pub(crate) fn fits_u32(value: usize) -> bool { u32::usize_fits(value) }
pub mod svm_engine_state; pub mod svm_error; pub mod svm_constants; pub mod opcode; mod memory; mod extensions; mod registers; mod instruction_pointer;
use actix_web::{HttpRequest, web}; use actix_web::http::{HeaderValue, StatusCode}; use rand::Rng; use sha2::{Digest, Sha256}; use crate::AppData; use crate::util::{unwrap_tx_error, WebApplicationError}; pub fn configure(cfg: &mut web::ServiceConfig) { cfg.service(web::scope("/api/v1") .route("/keys", web::post().to(gen_key)) .service(web::resource("/counter/{tag}") .route(web::get().to(get_counter)) .route(web::post().to(inc_counter)) ) ).route("/health", web::get().to(health_check)); } #[derive(serde::Deserialize)] struct Email { email: String, } fn health_check(data: web::Data<AppData>) -> Result<String, WebApplicationError> { data.db.with_transaction(|tx| { tx.health_check()?; Ok("imok".to_string()) }).map_err(unwrap_tx_error) } fn gen_key(data: web::Data<AppData>, email: web::Query<Email>) -> Result<String, WebApplicationError> { data.db.with_transaction(|tx| { if tx.email_exists(&email.email)? { return Err(WebApplicationError::new_with_message(StatusCode::BAD_REQUEST, "Email already registered").into()) } let mut key = [0u8;48]; rand::thread_rng().fill(&mut key[..]); let mut prefix = [0u8;6]; rand::thread_rng().fill(&mut prefix); let hashed = hash(&key); tx.insert_api_key(&email.email, &prefix, &hashed)?; Ok(format!("{}.{}", base64::encode(&prefix), base64::encode(&key[..]))) }).map_err(unwrap_tx_error) } fn get_counter(data: web::Data<AppData>, tag: web::Path<String>, req: HttpRequest) -> Result<String, WebApplicationError> { let auth_header = req.headers().get("Authorization"); data.db.with_transaction(|tx| { let (prefix, hashed_key) = extract_key(auth_header)?; let owner_id = tx.get_user_id_by_key(&prefix, &hashed_key)?.ok_or_else(|| WebApplicationError::unauthorized())?; let value = tx.get_counter_by_tag_locking(owner_id, &tag)?.map(|(_, v)| v).unwrap_or(0); Ok(value.to_string()) }).map_err(unwrap_tx_error) } fn inc_counter(data: web::Data<AppData>, tag: web::Path<String>, req: HttpRequest) -> Result<String, WebApplicationError> { let auth_header = req.headers().get("Authorization"); data.db.with_transaction(|tx| { let (prefix, hashed_key) = extract_key(auth_header)?; let owner_id = tx.get_user_id_by_key(&prefix, &hashed_key)?.ok_or_else(|| WebApplicationError::unauthorized())?; let value = loop { let counter = tx.get_counter_by_tag_locking(owner_id, &tag)?; break if let Some((counter_id, value)) = counter { let new_value = value + 1; // safe because db lock is acquired here tx.update_counter(counter_id, new_value)?; new_value } else { let initial = 1; if tx.create_counter(owner_id, &tag, initial)? { initial } else { log::warn!("Failed to create counter, trying update"); continue } } }; Ok(value.to_string()) }).map_err(unwrap_tx_error) } fn hash(bytes: &[u8]) -> Vec<u8> { let mut hasher = Sha256::new(); hasher.input(bytes); hasher.result().to_vec() } fn extract_key(auth: Option<&HeaderValue>) -> Result<(Vec<u8>, Vec<u8>), WebApplicationError> { auth.and_then(|header| { let s = header.to_str().unwrap(); // TODO error check let parts: Vec<&str> = s.split('.').collect(); if parts.len() != 2 { return None } let prefix = base64::decode(parts[0]).ok()?; let key = base64::decode(parts[1]).ok()?; let hashed = hash(&key); Some((prefix, hashed)) }).ok_or_else(|| WebApplicationError::unauthorized()) }
use std::{convert::{TryFrom, TryInto}, fmt}; use crate::*; /// Represents coordinate (x or y) on 2D grid pub type Coordinate = i32; /// Represents position on 2D grid /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#The%20Map> #[derive(Eq, PartialEq, Clone, Copy, fmt::Debug)] pub struct Position { /// X coordinate pub x: Coordinate, /// Y coordinate pub y: Coordinate, } /// Default for Position is no existing: (-1, -1) impl Default for Position { fn default() -> Self { Self::new(-1, -1) } } impl fmt::Display for Position { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } impl Position { /// Creates [`Position`] with given X and Y [`Coordinate`] /// /// # Parameters /// /// - `x` - X coordinate /// - `y` - Y coordinate /// /// # Type parameters /// /// - `T` - type of coordinates /// /// # Returns /// /// [`Position`] with set coordinates /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#The%20Map> pub fn new<T: TryInto<Coordinate> + TryFrom<Coordinate>>(x: T, y: T) -> Self where <T as TryFrom<Coordinate>>::Error: fmt::Debug, <T as TryInto<Coordinate>>::Error: fmt::Debug, { Self { x: x.try_into().unwrap(), y: y.try_into().unwrap(), } } /// Returns the [`Position`] equal to going in a `direction` `units` number /// of times from this [`Position`] /// /// # Parameters /// /// - `self` - Self reference ([`Position `] to translate) /// - `direction` - [`Direction `] to translate to /// - `units` - amount of tiles to translate to /// /// # Returns /// /// Translated [`Position`] /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#The%20Map> pub fn translate(&self, direction: Direction, units: Coordinate) -> Self { match direction { Direction::North => Self::new(self.x, self.y - units), Direction::East => Self::new(self.x + units, self.y), Direction::South => Self::new(self.x, self.y + units), Direction::West => Self::new(self.x - units, self.y), Direction::Center => self.clone(), } } /// Returns the direction that would move you closest to `target` from this /// [`Position`] if you took a single step. In particular, will return /// [`Direction::Center`] if this [`Position`] is equal to the `target`. /// Note that this does not check for potential collisions with other /// units but serves as a basic pathfinding method /// /// # Parameters /// /// - `self` - Self reference ([`Position`] relative to) /// - `target` - [`Position`] to find direction to /// /// # Returns /// /// [`Direction`] (relative to `self`) pointing to nearest to `target` tile /// /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#The%20Map> pub fn direction_to(&self, target: &Self) -> Direction { let mut closest_direction = Direction::Center; let mut closest_distance = target.distance_to(self); for direction in Direction::DIRECTIONS { let ref new_position = self.translate(direction, 1); let distance = target.distance_to(new_position); if distance < closest_distance { closest_direction = direction; closest_distance = distance; } } closest_direction } /// Returns [the Manhattan (rectilinear) distance](https://en.wikipedia.org/wiki/Taxicab_geometry) from this [`Position`] to `other` position /// /// # Parameters /// /// - `self` - Self value ([`Position`] from which to measure) /// - `other` - [`Position`] to which to measure /// /// # Returns /// /// Number of moves from one `self` position to `other` /// /// # See also /// /// Check <https://en.wikipedia.org/wiki/Taxicab_geometry> /// Check <https://www.lux-ai.org/specs-2021#The%20Map> pub fn distance_to(&self, other: &Self) -> f32 { let x_difference = (self.x - other.x).abs(); let y_difference = (self.y - other.y).abs(); (x_difference + y_difference) as f32 } /// Returns `true` if this [`Position`] is adjacent or equal to `other`. /// `false` otherwise /// /// # Parameters /// /// - `self` - Self reference /// - `other` - [`Position`] to check /// /// # Returns /// /// `true` if positions are adjacent /// /// # See also /// /// Check <https://en.wikipedia.org/wiki/Taxicab_geometry> /// Check <https://www.lux-ai.org/specs-2021#The%20Map> pub fn is_adjacent(&self, other: &Self) -> bool { self.distance_to(other) <= 1.0 } /// Returns `true` if this [`Position`] is equal to the `other` position /// object by checking `x`, `y` coordinates. `false` otherwise /// /// # Parameters /// /// - `self` - Self reference /// - `other` - [`Position`] to compare with /// /// # Returns /// /// `true` if positions are equal pub fn equals(&self, other: &Self) -> bool { self == other } /// Convert to command argument /// /// # Parameters /// /// - `self` - Self reference /// /// # Returns /// /// Command argument - coordinates delimited by space pub fn to_argument(&self) -> String { format!("{} {}", self.x, self.y) } }
use crate::context::*; use crate::language_features::rust_analyzer; use crate::types::*; use crate::util::*; use jsonrpc_core::Params; use lsp_types::notification::*; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use serde_json::{self, Value}; use std::fs; use std::io; fn insert_value<'a, 'b, P>( target: &'b mut serde_json::map::Map<String, Value>, mut path: P, local_key: String, value: Value, ) -> Result<(), String> where P: Iterator<Item = &'a str>, P: 'a, { match path.next() { Some(key) => { let maybe_new_target = target .entry(key) .or_insert_with(|| Value::Object(serde_json::Map::new())) .as_object_mut(); if maybe_new_target.is_none() { return Err(format!( "Expected path {:?} to be object, found {:?}", key, &maybe_new_target, )); } insert_value(maybe_new_target.unwrap(), path, local_key, value) } None => match target.insert(local_key, value) { Some(old_value) => Err(format!("Replaced old value: {:?}", old_value)), None => Ok(()), }, } } // Take flattened tables like "a.b = 1" and produce "{"a":{"b":1}}". pub fn explode_string_table(raw_settings: &toml::value::Table) -> Value { let mut settings = serde_json::Map::new(); for (raw_key, raw_value) in raw_settings.iter() { let mut key_parts = raw_key.split('.'); let local_key = match key_parts.next_back() { Some(name) => name, None => { warn!("Got a setting with an empty local name: {:?}", raw_key); continue; } }; let value: Value = match raw_value.clone().try_into() { Ok(value) => value, Err(e) => { warn!("Could not convert setting {:?} to JSON: {}", raw_value, e,); continue; } }; match insert_value(&mut settings, key_parts, local_key.into(), value) { Ok(_) => (), Err(e) => { warn!("Could not set {:?} to {:?}: {}", raw_key, raw_value, e); continue; } } } Value::Object(settings) } pub fn did_change_configuration(params: EditorParams, ctx: &mut Context) { let default_settings = toml::value::Table::new(); let raw_settings = params .as_table() .and_then(|t| t.get("settings")) .and_then(|val| val.as_table()) .unwrap_or(&default_settings); let settings = explode_string_table(raw_settings); let params = DidChangeConfigurationParams { settings }; ctx.notify::<DidChangeConfiguration>(params); } pub fn configuration(params: Params, ctx: &mut Context) -> Result<Value, jsonrpc_core::Error> { let params = params.parse::<ConfigurationParams>()?; let settings = ctx .config .language .get(&ctx.language_id) .and_then(|conf| conf.initialization_options.as_ref()); if settings.is_none() { return Ok(Value::Array(Vec::new())); } // We can now safely unwrap let settings = settings.unwrap(); let items = params .items .iter() .map(|item| { // There's also a `scopeUri`, which lists the file/folder // that the config should apply to. But kak-lsp doesn't // have a concept of per-file configuration and workspaces // are separated by kak-lsp process. item.section .as_ref() // The specification isn't clear about whether you should // reply with just the value or with `json!({ section: <value> })`. // Tests indicate the former. .and_then(|section| settings.get(section)) .map(|v| v.clone()) .unwrap_or(Value::Null) }) .collect::<Vec<Value>>(); Ok(Value::Array(items)) } pub fn workspace_symbol(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = WorkspaceSymbolParams::deserialize(params) .expect("Params should follow WorkspaceSymbolParams structure"); ctx.call::<WorkspaceSymbol, _>(meta, params, move |ctx: &mut Context, meta, result| { editor_workspace_symbol(meta, result, ctx) }); } pub fn editor_workspace_symbol( meta: EditorMeta, result: Option<Vec<SymbolInformation>>, ctx: &mut Context, ) { if result.is_none() { return; } let result = result.unwrap(); let content = format_symbol_information(result, ctx); let command = format!( "lsp-show-workspace-symbol {} {}", editor_quote(&ctx.root_path), editor_quote(&content), ); ctx.exec(meta, command); } #[derive(Deserialize)] struct EditorExecuteCommand { command: String, arguments: String, } pub fn execute_command(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = EditorExecuteCommand::deserialize(params) .expect("Params should follow ExecuteCommand structure"); let req_params = ExecuteCommandParams { command: params.command, // arguments is quoted to avoid parsing issues arguments: serde_json::from_str(&params.arguments).unwrap(), work_done_progress_params: Default::default(), }; match &*req_params.command { "rust-analyzer.applySourceChange" => { rust_analyzer::apply_source_change(meta, req_params, ctx); } _ => { ctx.call::<ExecuteCommand, _>(meta, req_params, move |_: &mut Context, _, _| ()); } } } pub fn apply_document_resource_op( _meta: &EditorMeta, op: ResourceOp, _ctx: &mut Context, ) -> io::Result<()> { match op { ResourceOp::Create(op) => { let path = op.uri.to_file_path().unwrap(); let ignore_if_exists = if let Some(options) = op.options { !options.overwrite.unwrap_or(false) && options.ignore_if_exists.unwrap_or(false) } else { false }; if ignore_if_exists && path.exists() { Ok(()) } else { fs::write(&path, []) } } ResourceOp::Delete(op) => { let path = op.uri.to_file_path().unwrap(); if path.is_dir() { let recursive = if let Some(options) = op.options { options.recursive.unwrap_or(false) } else { false }; if recursive { fs::remove_dir_all(&path) } else { fs::remove_dir(&path) } } else if path.is_file() { fs::remove_file(&path) } else { Ok(()) } } ResourceOp::Rename(op) => { let from = op.old_uri.to_file_path().unwrap(); let to = op.new_uri.to_file_path().unwrap(); let ignore_if_exists = if let Some(options) = op.options { !options.overwrite.unwrap_or(false) && options.ignore_if_exists.unwrap_or(false) } else { false }; if ignore_if_exists && to.exists() { Ok(()) } else { fs::rename(&from, &to) } } } } // TODO handle version, so change is not applied if buffer is modified (and need to show a warning) pub fn apply_edit( meta: EditorMeta, edit: WorkspaceEdit, ctx: &mut Context, ) -> ApplyWorkspaceEditResponse { if let Some(document_changes) = edit.document_changes { match document_changes { DocumentChanges::Edits(edits) => { for edit in edits { apply_annotated_text_edits(&meta, &edit.text_document.uri, &edit.edits, ctx); } } DocumentChanges::Operations(ops) => { for op in ops { match op { DocumentChangeOperation::Edit(edit) => { apply_annotated_text_edits( &meta, &edit.text_document.uri, &edit.edits, ctx, ); } DocumentChangeOperation::Op(op) => { if let Err(e) = apply_document_resource_op(&meta, op, ctx) { error!("failed to apply document change operation: {}", e); return ApplyWorkspaceEditResponse { applied: false, failure_reason: None, failed_change: None, }; } } } } } } } else if let Some(changes) = edit.changes { for (uri, change) in changes { apply_text_edits(&meta, &uri, change, ctx); } } ApplyWorkspaceEditResponse { applied: true, failure_reason: None, failed_change: None, } } #[derive(Deserialize)] struct EditorApplyEdit { edit: String, } pub fn apply_edit_from_editor(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = EditorApplyEdit::deserialize(params).expect("Failed to parse params"); let edit = WorkspaceEdit::deserialize(serde_json::from_str::<Value>(&params.edit).unwrap()) .expect("Failed to parse edit"); apply_edit(meta, edit, ctx); } pub fn apply_edit_from_server( params: Params, ctx: &mut Context, ) -> Result<Value, jsonrpc_core::Error> { let params: ApplyWorkspaceEditParams = params.parse()?; let meta = ctx.meta_for_session(); let response = apply_edit(meta, params.edit, ctx); Ok(serde_json::to_value(response).unwrap()) }
use std::{fmt::Debug, net::{SocketAddr, IpAddr, Ipv4Addr}, sync::Arc}; use std::convert::TryInto; use percent_encoding::{percent_encode, AsciiSet, NON_ALPHANUMERIC}; use serde::{Deserializer, Serializer, de::{Visitor, SeqAccess}, Serialize, Deserialize}; use crate::torrent::TorrentContext; #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum Event { Started, Completed, Stopped, } #[derive(Debug, Serialize)] pub struct Params { #[serde(skip)] pub info_hash: [u8; 20], pub peer_id: String, pub ip: Option<String>, pub port: u16, pub uploaded: usize, pub downloaded: usize, pub left: usize, pub event: Option<Event>, pub compact: i32, } #[derive(Debug,serde::Deserialize)] pub struct Response { #[serde(rename = "failure reason")] pub failure_reason: Option<String>, pub interval: Option<u64>, #[serde(default)] #[serde(deserialize_with = "deserialize_peers")] pub peers: Vec<SocketAddr>, } pub fn deserialize_peers<'de, D>(deserializer: D) -> Result<Vec<SocketAddr>, D::Error> where D: Deserializer<'de>, { struct PeersVisitor; impl<'de> Visitor<'de> for PeersVisitor { type Value = Vec<SocketAddr>; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("byte array") } fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: serde::de::Error, { let len = v.len(); let mut peers = vec![]; if len == 0 { return Ok(peers); } for i in (0..len).step_by(6) { let port = u16::from_be_bytes(v[i + 4..i + 6].try_into().unwrap()); peers.push(SocketAddr::new( IpAddr::V4(Ipv4Addr::new(v[i], v[i + 1], v[i + 2], v[i + 3])), port, )) } Ok(peers) } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { #[derive(Deserialize)] struct PeerDict { peer_id: [u8; 20], ip: IpAddr, port: u16, }; let mut peers = vec![]; while let Some(PeerDict { peer_id, ip, port }) = seq.next_element()? { let address = SocketAddr::new(ip, port); peers.push(address) } Ok(peers) } } deserializer.deserialize_any(PeersVisitor) } #[derive(Debug)] pub enum Error { QueryError(String), HTTPError(reqwest::Error), BencodeError(serde_bencode::Error), URLEncodeError(serde_urlencoded::ser::Error), } impl From<reqwest::Error> for Error { fn from(e: reqwest::Error) -> Self { return Error::HTTPError(e); } } impl From<serde_bencode::Error> for Error { fn from(e: serde_bencode::Error) -> Self { Error::BencodeError(e) } } impl From<serde_urlencoded::ser::Error> for Error { fn from(e: serde_urlencoded::ser::Error) -> Self { Error::URLEncodeError(e) } } pub const FRAGMENT: &AsciiSet = &NON_ALPHANUMERIC .remove(b'~') .remove(b'-') .remove(b'_') .remove(b'.'); pub async fn announce(ctx: Arc<TorrentContext>) -> Result<Response, Error> { let query = serde_urlencoded::to_string(&ctx.params)?; let encoded = percent_encode(&ctx.metainfo.info_hash, FRAGMENT); let tracker_url = format!("{}?info_hash={}&{}", ctx.metainfo.announce, encoded.to_string(), query); info!("announce to {}", tracker_url); let response = reqwest::get(&tracker_url).await?.bytes().await.map_err(|e| Error::HTTPError(e))?; match serde_bencode::from_bytes::<Response>(&response) { Ok(res) => { if let Some(failure_reason) = res.failure_reason { Err(Error::QueryError(failure_reason)) } else { Ok(res) } } Err(e) => Err(Error::BencodeError(e)) } }
use protobuf::product_service_client::ProductServiceClient; use protobuf::{Empty, NewProduct, ProductId}; use tonic::Request; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let mut client = ProductServiceClient::connect("http://[::1]:50051").await?; let new_product = NewProduct { name: "My Cool Product".to_string(), price: Some(25), description: Some("My amazing new product".to_string()), category: Some("toys".to_string()), }; let create_product_resp = client .create_product(Request::new(new_product)) .await? .into_inner(); println!("Created product with ID:\n {}\n", create_product_resp.id); let product_id = ProductId { id: create_product_resp.id, }; let find_product_resp = client .find_product(Request::new(product_id)) .await? .into_inner(); println!("Fetched product:\n {:#?}\n", find_product_resp); let empty = Empty {}; let list_products_resp = client .list_products(Request::new(empty)) .await? .into_inner(); println!("Listed product:\n {:#?}", list_products_resp); Ok(()) }
#[doc = "Reader of register D3PCR1H"] pub type R = crate::R<u32, super::D3PCR1H>; #[doc = "Writer for register D3PCR1H"] pub type W = crate::W<u32, super::D3PCR1H>; #[doc = "Register D3PCR1H `reset()`'s with value 0"] impl crate::ResetValue for super::D3PCR1H { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `PCS19`"] pub type PCS19_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCS19`"] pub struct PCS19_W<'a> { w: &'a mut W, } impl<'a> PCS19_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } #[doc = "Reader of field `PCS20`"] pub type PCS20_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCS20`"] pub struct PCS20_W<'a> { w: &'a mut W, } impl<'a> PCS20_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8); self.w } } #[doc = "Reader of field `PCS21`"] pub type PCS21_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCS21`"] pub struct PCS21_W<'a> { w: &'a mut W, } impl<'a> PCS21_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10); self.w } } #[doc = "Reader of field `PCS25`"] pub type PCS25_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCS25`"] pub struct PCS25_W<'a> { w: &'a mut W, } impl<'a> PCS25_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 18)) | (((value as u32) & 0x03) << 18); self.w } } impl R { #[doc = "Bits 6:7 - D3 Pending request clear input signal selection on Event input x = truncate ((n+32)/2)"] #[inline(always)] pub fn pcs19(&self) -> PCS19_R { PCS19_R::new(((self.bits >> 6) & 0x03) as u8) } #[doc = "Bits 8:9 - D3 Pending request clear input signal selection on Event input x = truncate ((n+32)/2)"] #[inline(always)] pub fn pcs20(&self) -> PCS20_R { PCS20_R::new(((self.bits >> 8) & 0x03) as u8) } #[doc = "Bits 10:11 - D3 Pending request clear input signal selection on Event input x = truncate ((n+32)/2)"] #[inline(always)] pub fn pcs21(&self) -> PCS21_R { PCS21_R::new(((self.bits >> 10) & 0x03) as u8) } #[doc = "Bits 18:19 - D3 Pending request clear input signal selection on Event input x = truncate ((n+32)/2)"] #[inline(always)] pub fn pcs25(&self) -> PCS25_R { PCS25_R::new(((self.bits >> 18) & 0x03) as u8) } } impl W { #[doc = "Bits 6:7 - D3 Pending request clear input signal selection on Event input x = truncate ((n+32)/2)"] #[inline(always)] pub fn pcs19(&mut self) -> PCS19_W { PCS19_W { w: self } } #[doc = "Bits 8:9 - D3 Pending request clear input signal selection on Event input x = truncate ((n+32)/2)"] #[inline(always)] pub fn pcs20(&mut self) -> PCS20_W { PCS20_W { w: self } } #[doc = "Bits 10:11 - D3 Pending request clear input signal selection on Event input x = truncate ((n+32)/2)"] #[inline(always)] pub fn pcs21(&mut self) -> PCS21_W { PCS21_W { w: self } } #[doc = "Bits 18:19 - D3 Pending request clear input signal selection on Event input x = truncate ((n+32)/2)"] #[inline(always)] pub fn pcs25(&mut self) -> PCS25_W { PCS25_W { w: self } } }
use crate::datastructure::intersection::Intersection; use crate::scene::texturecoordinate::TextureCoordinate; use crate::util::vector::Vector; pub fn ambient(intersection: &Intersection) -> Vector { let texture = if let Some(texture) = intersection.triangle.mesh.material.ambient_texture { let coord = map_uv(intersection); texture.at(coord) } else { Vector::new(1., 1., 1.) }; intersection.triangle.material().ambient * texture } pub fn emittance(intersection: &Intersection) -> Vector { let texture = if let Some(texture) = intersection.triangle.mesh.material.emittance_texture { let coord = map_uv(intersection); texture.at(coord) } else { Vector::new(1., 1., 1.) }; intersection.triangle.material().emittance * texture } pub fn map_uv(intersection: &Intersection) -> TextureCoordinate { let texa = intersection.triangle.texture_a(); let texb = intersection.triangle.texture_b(); let texc = intersection.triangle.texture_c(); let e1 = texc - texa; let e2 = texb - texa; // error!("e1: {:?}, e2: {:?}", e1, e2); texa.to_owned() + (e1 * intersection.uv.1) + (e2 * intersection.uv.0) } pub fn diffuse(intersection: &Intersection, hit_pos: Vector, light_pos: Vector) -> Vector { let triangle = intersection.triangle; let texture = if let Some(texture) = intersection.triangle.mesh.material.diffuse_texture { let coord = map_uv(intersection); texture.at(coord) } else { Vector::new(1., 1., 1.) }; let light_dir = (light_pos - hit_pos).unit(); light_dir.dot(triangle.normal()).max(0.) * triangle.material().diffuse * texture } pub fn specular( intersection: &Intersection, hit_pos: Vector, light_pos: Vector, cam_pos: Vector, ) -> Vector { let texture = if let Some(texture) = intersection.triangle.mesh.material.specular_texture { let coord = map_uv(intersection); texture.at(coord) } else { Vector::new(1., 1., 1.) }; let triangle = intersection.triangle; let light_dir = (light_pos - hit_pos).unit(); let reflec = 2f64 * (triangle.normal().dot(light_dir)) * triangle.normal() - light_dir; let spec = 0f64.max((cam_pos - hit_pos).unit().dot(reflec)); spec.powf(triangle.material().shininess) * triangle.material().specular * texture }
use std::path::PathBuf; use structopt::StructOpt; use super::{CliCommand, GlobalFlags}; #[derive(Debug, StructOpt)] pub struct Build { #[structopt(parse(from_os_str))] manifest: PathBuf, } impl CliCommand for Build { fn run(self, _flags: GlobalFlags) -> Result<(), String> { unimplemented!() } }
use std::io::BufWriter; use anyhow::{Context, Result}; use clap::{App, AppSettings, Arg, ArgMatches}; use conllu::io::{ReadSentence, Reader, WriteSentence, Writer}; use stdinout::{Input, Output}; use syntaxdot_encoders::lemma::{BackoffStrategy, EditTree, EditTreeEncoder}; use syntaxdot_encoders::SentenceEncoder; use udgraph::graph::Node; use crate::SyntaxDotApp; static INPUT: &str = "INPUT"; static LABEL_FEATURE: &str = "LABEL_FEATURE"; static OUTPUT: &str = "OUTPUT"; static DEFAULT_CLAP_SETTINGS: &[AppSettings] = &[ AppSettings::DontCollapseArgsInUsage, AppSettings::UnifiedHelpMessage, ]; pub struct Lemma { input: Option<String>, label_feature: String, output: Option<String>, } impl SyntaxDotApp for Lemma { fn app() -> App<'static, 'static> { App::new("lemma") .settings(DEFAULT_CLAP_SETTINGS) .about("Convert lemmas to edit trees") .arg( Arg::with_name(LABEL_FEATURE) .short("f") .long("feature") .value_name("NAME") .help("Name of the feature used for the dependency label") .default_value("edit_tree"), ) .arg(Arg::with_name(INPUT).help("Input data").index(1)) .arg(Arg::with_name(OUTPUT).help("Output data").index(2)) } fn parse(matches: &ArgMatches) -> Result<Self> { let input = matches.value_of(INPUT).map(ToOwned::to_owned); let label_feature = matches.value_of(LABEL_FEATURE).unwrap().into(); let output = matches.value_of(OUTPUT).map(ToOwned::to_owned); Ok(Lemma { input, label_feature, output, }) } fn run(&self) -> Result<()> { let input = Input::from(self.input.as_ref()); let reader = Reader::new(input.buf_read().context("Cannot open input for reading")?); let output = Output::from(self.output.as_ref()); let writer = Writer::new(BufWriter::new( output.write().context("Cannot open output for writing")?, )); self.label_with_encoder(&EditTreeEncoder::new(BackoffStrategy::Form), reader, writer) } } impl Lemma { fn label_with_encoder<R, W>( &self, encoder: &EditTreeEncoder, read: R, mut write: W, ) -> Result<()> where R: ReadSentence, W: WriteSentence, { for sentence in read.sentences() { let mut sentence = sentence.context("Cannot parse sentence")?; let encoded = encoder .encode(&sentence) .context("Cannot dependency-encode sentence")?; for (token, encoding) in sentence.iter_mut().filter_map(Node::token_mut).zip(encoded) { token.misc_mut().insert( self.label_feature.clone(), Some(DisplayEditTree(encoding).to_string()), ); } write .write_sentence(&sentence) .context("Cannot write sentence")?; } Ok(()) } } struct DisplayEditTree(EditTree); impl ToString for DisplayEditTree { fn to_string(&self) -> String { edit_tree_to_string(Some(&self.0)) } } fn edit_tree_to_string(edit_tree: Option<&EditTree>) -> String { match edit_tree { Some(EditTree::MatchNode { pre, suf, left, right, }) => { let left = edit_tree_to_string(left.as_ref().map(AsRef::as_ref)); let right = edit_tree_to_string(right.as_ref().map(AsRef::as_ref)); format!("(m {} {} {} {})", pre, suf, left, right) } Some(EditTree::ReplaceNode { replacee, replacement, }) => { format!( "(r \"{}\" \"{}\")", replacee.iter().collect::<String>(), replacement.iter().collect::<String>() ) } None => "()".to_string(), } }
// 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::io::Cursor; use common_arrow::arrow::array::Array; use common_arrow::arrow::bitmap::Bitmap; use common_arrow::arrow::bitmap::MutableBitmap; use common_arrow::arrow::buffer::Buffer; use common_arrow::arrow::datatypes::Schema; use common_arrow::arrow::io::ipc::read::read_file_metadata; use common_arrow::arrow::io::ipc::read::FileReader; use common_arrow::arrow::io::ipc::write::FileWriter; use common_arrow::arrow::io::ipc::write::WriteOptions as IpcWriteOptions; use crate::BlockEntry; use crate::Column; use crate::ColumnBuilder; use crate::TableDataType; use crate::Value; pub fn bitmap_into_mut(bitmap: Bitmap) -> MutableBitmap { bitmap .into_mut() .map_left(|bitmap| { let mut builder = MutableBitmap::new(); builder.extend_from_bitmap(&bitmap); builder }) .into_inner() } pub fn repeat_bitmap(bitmap: &mut Bitmap, n: usize) -> MutableBitmap { let mut builder = MutableBitmap::new(); for _ in 0..n { builder.extend_from_bitmap(bitmap); } builder } pub fn append_bitmap(bitmap: &mut MutableBitmap, other: &Bitmap) { bitmap.extend_from_bitmap(other) } pub fn constant_bitmap(value: bool, len: usize) -> MutableBitmap { let mut builder = MutableBitmap::new(); builder.extend_constant(len, value); builder } pub fn buffer_into_mut<T: Clone>(mut buffer: Buffer<T>) -> Vec<T> { unsafe { buffer .get_mut() .map(std::mem::take) .unwrap_or_else(|| buffer.to_vec()) } } pub fn serialize_column(col: &Column) -> Vec<u8> { let mut buffer = Vec::new(); let schema = Schema::from(vec![col.arrow_field()]); let mut writer = FileWriter::new(&mut buffer, schema, None, IpcWriteOptions::default()); writer.start().unwrap(); writer .write( &common_arrow::arrow::chunk::Chunk::new(vec![col.as_arrow()]), None, ) .unwrap(); writer.finish().unwrap(); buffer } pub fn deserialize_column(bytes: &[u8]) -> Option<Column> { let mut cursor = Cursor::new(bytes); let metadata = read_file_metadata(&mut cursor).ok()?; let f = metadata.schema.fields[0].clone(); let table_type = TableDataType::from(&f); let data_type = (&table_type).into(); let mut reader = FileReader::new(cursor, metadata, None, None); let col = reader.next()?.ok()?.into_arrays().remove(0); Some(Column::from_arrow(col.as_ref(), &data_type)) } /// Convert a column to a arrow array. pub fn column_to_arrow_array(column: &BlockEntry, num_rows: usize) -> Box<dyn Array> { match &column.value { Value::Scalar(v) => { let builder = ColumnBuilder::repeat(&v.as_ref(), num_rows, &column.data_type); builder.build().as_arrow() } Value::Column(c) => c.as_arrow(), } } pub fn and_validities(lhs: Option<Bitmap>, rhs: Option<Bitmap>) -> Option<Bitmap> { match (lhs, rhs) { (Some(lhs), None) => Some(lhs), (None, Some(rhs)) => Some(rhs), (None, None) => None, (Some(lhs), Some(rhs)) => Some((&lhs) & (&rhs)), } } pub fn or_validities(lhs: Option<Bitmap>, rhs: Option<Bitmap>) -> Option<Bitmap> { match (lhs, rhs) { (Some(lhs), None) => Some(lhs), (None, Some(rhs)) => Some(rhs), (None, None) => None, (Some(lhs), Some(rhs)) => Some((&lhs) | (&rhs)), } }
use std::rc::{Rc, Weak}; use egui::TextEdit; use gfx_maths::{Mat4, Vec3}; use crate::scene::entity::Entity; use super::Component; #[derive(Debug)] pub struct CameraComponent { entity: Weak<Entity>, near: f32, far: f32, fovy: f32, } impl Component for CameraComponent { fn create(entity: &Rc<Entity>) -> Rc<Self> where Self: Sized, { let res = Rc::new(Self { entity: Rc::downgrade(entity), near: 0.01, far: 1000.0, fovy: 60.0, }); if let Some(scene) = entity.scene.upgrade() { scene.set_main_camera(Rc::downgrade(&res)); } res } fn load(&self) {} fn start(&self) {} fn inspector_name(&self) -> &'static str { "CameraComponent" } fn render_inspector(&self, ui: &mut egui::Ui) { ui.horizontal(|ui| { ui.label("Near"); let mut text = self.near.to_string(); ui.add_enabled(false, TextEdit::singleline(&mut text)); }); ui.horizontal(|ui| { ui.label("Far"); let mut text = self.far.to_string(); ui.add_enabled(false, TextEdit::singleline(&mut text)); }); ui.horizontal(|ui| { ui.label("Vertical FOV"); let mut text = self.fovy.to_string(); ui.add_enabled(false, TextEdit::singleline(&mut text)); }); } } #[repr(C)] pub(crate) struct CameraUniformData { pub view_matrix: Mat4, pub projection_matrix: Mat4, pub inv_view_matrix: Mat4, pub inv_projection_matrix: Mat4, pub pos: Vec3, } impl CameraComponent { pub(crate) fn get_cam_data(&self, aspect: f32) -> CameraUniformData { let entity = self.entity.upgrade().unwrap(); CameraUniformData { view_matrix: entity.get_view_matrix(), projection_matrix: Mat4::perspective_vulkan( self.fovy.to_radians(), self.near, self.far, aspect, ), inv_view_matrix: entity.get_inverse_view_matrix(), inv_projection_matrix: Mat4::inverse_perspective_vulkan( self.fovy.to_radians(), self.near, self.far, aspect, ), pos: entity.get_global_position(), } } }
use crate::source::{Source, SourceBuilder}; use actix_web::App; use log::error; use std::collections::BTreeMap; #[derive(Default)] pub struct AtomHub { apps: BTreeMap<&'static str, Source>, } impl AtomHub { pub fn register<T: SourceBuilder>(mut self, _: T) -> Self { let source = T::build_source(); if self.apps.contains_key(source.prefix) { let error_message = format!("duplicate prefix: {prefix}", prefix = source.prefix); error!("{}", error_message); panic!(error_message); } self.apps.insert(source.prefix, source); self } pub fn into_apps(self) -> Vec<App> { self.apps.into_iter().map(|x| x.1.into_app()).collect() } }
//! The wrapper around `WebSocket` API using the Futures API to be used in async rust //! //! # Example //! //! ```rust //! use reqwasm::websocket::{Message, futures::WebSocket}; //! use wasm_bindgen_futures::spawn_local; //! use futures::{SinkExt, StreamExt}; //! //! # macro_rules! console_log { //! # ($($expr:expr),*) => {{}}; //! # } //! # fn no_run() { //! let mut ws = WebSocket::open("wss://echo.websocket.org").unwrap(); //! //! spawn_local({ //! let mut ws = ws.clone(); //! async move { //! ws.send(Message::Text(String::from("test"))).await.unwrap(); //! ws.send(Message::Text(String::from("test 2"))).await.unwrap(); //! } //! }); //! //! spawn_local(async move { //! while let Some(msg) = ws.next().await { //! console_log!(format!("1. {:?}", msg)) //! } //! console_log!("WebSocket Closed") //! }) //! # } //! ``` use crate::websocket::{ events::{CloseEvent, ErrorEvent}, Message, State, WebSocketError, }; use crate::{js_to_js_error, JsError}; use async_broadcast::Receiver; use futures::ready; use futures::{Sink, Stream}; use pin_project::{pin_project, pinned_drop}; use std::cell::RefCell; use std::pin::Pin; use std::rc::Rc; use std::task::{Context, Poll, Waker}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::MessageEvent; /// Wrapper around browser's WebSocket API. #[allow(missing_debug_implementations)] #[pin_project(PinnedDrop)] #[derive(Clone)] pub struct WebSocket { ws: web_sys::WebSocket, sink_wakers: Rc<RefCell<Vec<Waker>>>, #[pin] message_receiver: Receiver<StreamMessage>, #[allow(clippy::type_complexity)] closures: Rc<( Closure<dyn FnMut()>, Closure<dyn FnMut(MessageEvent)>, Closure<dyn FnMut(web_sys::ErrorEvent)>, Closure<dyn FnMut(web_sys::CloseEvent)>, )>, } impl WebSocket { /// Establish a WebSocket connection. /// /// This function may error in the following cases: /// - The port to which the connection is being attempted is being blocked. /// - The URL is invalid. /// /// The error returned is [`JsError`]. See the /// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket#exceptions_thrown) /// to learn more. pub fn open(url: &str) -> Result<Self, JsError> { let wakers: Rc<RefCell<Vec<Waker>>> = Rc::new(RefCell::new(vec![])); let ws = web_sys::WebSocket::new(url).map_err(js_to_js_error)?; let (sender, receiver) = async_broadcast::broadcast(10); let open_callback: Closure<dyn FnMut()> = { let wakers = Rc::clone(&wakers); Closure::wrap(Box::new(move || { for waker in wakers.borrow_mut().drain(..) { waker.wake(); } }) as Box<dyn FnMut()>) }; ws.set_onopen(Some(open_callback.as_ref().unchecked_ref())); // open_callback.forget(); // let message_callback: Closure<dyn FnMut(MessageEvent)> = { let sender = sender.clone(); Closure::wrap(Box::new(move |e: MessageEvent| { let sender = sender.clone(); wasm_bindgen_futures::spawn_local(async move { let _ = sender .broadcast(StreamMessage::Message(parse_message(e))) .await; }) }) as Box<dyn FnMut(MessageEvent)>) }; ws.set_onmessage(Some(message_callback.as_ref().unchecked_ref())); // message_callback.forget(); let error_callback: Closure<dyn FnMut(web_sys::ErrorEvent)> = { let sender = sender.clone(); Closure::wrap(Box::new(move |e: web_sys::ErrorEvent| { let sender = sender.clone(); wasm_bindgen_futures::spawn_local(async move { let _ = sender .broadcast(StreamMessage::ErrorEvent(ErrorEvent { message: e.message(), })) .await; }) }) as Box<dyn FnMut(web_sys::ErrorEvent)>) }; ws.set_onerror(Some(error_callback.as_ref().unchecked_ref())); // error_callback.forget(); let close_callback: Closure<dyn FnMut(web_sys::CloseEvent)> = { Closure::wrap(Box::new(move |e: web_sys::CloseEvent| { let sender = sender.clone(); wasm_bindgen_futures::spawn_local(async move { let close_event = CloseEvent { code: e.code(), reason: e.reason(), was_clean: e.was_clean(), }; let _ = sender .broadcast(StreamMessage::CloseEvent(close_event)) .await; let _ = sender.broadcast(StreamMessage::ConnectionClose).await; }) }) as Box<dyn FnMut(web_sys::CloseEvent)>) }; ws.set_onerror(Some(close_callback.as_ref().unchecked_ref())); // close_callback.forget(); Ok(Self { ws, sink_wakers: wakers, message_receiver: receiver, closures: Rc::new(( open_callback, message_callback, error_callback, close_callback, )), }) } /// Closes the websocket. /// /// See the [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#parameters) /// to learn about parameters passed to this function and when it can return an `Err(_)` /// /// **Note**: If *only one* of the instances of websocket is closed, the entire connection closes. /// This is unlikely to happen in real-world as [`wasm_bindgen_futures::spawn_local`] requires `'static`. pub fn close(self, code: Option<u16>, reason: Option<&str>) -> Result<(), JsError> { let result = match (code, reason) { (None, None) => self.ws.close(), (Some(code), None) => self.ws.close_with_code(code), (Some(code), Some(reason)) => self.ws.close_with_code_and_reason(code, reason), // default code is 1005 so we use it, // see: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#parameters (None, Some(reason)) => self.ws.close_with_code_and_reason(1005, reason), }; result.map_err(js_to_js_error) } /// The current state of the websocket. pub fn state(&self) -> State { let ready_state = self.ws.ready_state(); match ready_state { 0 => State::Connecting, 1 => State::Open, 2 => State::Closing, 3 => State::Closed, _ => unreachable!(), } } /// The extensions in use. pub fn extensions(&self) -> String { self.ws.extensions() } /// The sub-protocol in use. pub fn protocol(&self) -> String { self.ws.protocol() } } #[derive(Clone)] enum StreamMessage { ErrorEvent(ErrorEvent), CloseEvent(CloseEvent), Message(Message), ConnectionClose, } fn parse_message(event: MessageEvent) -> Message { if let Ok(array_buffer) = event.data().dyn_into::<js_sys::ArrayBuffer>() { let array = js_sys::Uint8Array::new(&array_buffer); Message::Bytes(array.to_vec()) } else if let Ok(txt) = event.data().dyn_into::<js_sys::JsString>() { Message::Text(String::from(&txt)) } else { unreachable!("message event, received Unknown: {:?}", event.data()); } } impl Sink<Message> for WebSocket { type Error = WebSocketError; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let ready_state = self.ws.ready_state(); if ready_state == 0 { self.sink_wakers.borrow_mut().push(cx.waker().clone()); Poll::Pending } else { Poll::Ready(Ok(())) } } fn start_send(self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> { let result = match item { Message::Bytes(bytes) => self.ws.send_with_u8_array(&bytes), Message::Text(message) => self.ws.send_with_str(&message), }; match result { Ok(_) => Ok(()), Err(e) => Err(WebSocketError::MessageSendError(js_to_js_error(e))), } } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } } impl Stream for WebSocket { type Item = Result<Message, WebSocketError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let msg = ready!(self.project().message_receiver.poll_next(cx)); match msg { Some(StreamMessage::Message(msg)) => Poll::Ready(Some(Ok(msg))), Some(StreamMessage::ErrorEvent(err)) => { Poll::Ready(Some(Err(WebSocketError::ConnectionError(err)))) } Some(StreamMessage::CloseEvent(e)) => { Poll::Ready(Some(Err(WebSocketError::ConnectionClose(e)))) } Some(StreamMessage::ConnectionClose) => Poll::Ready(None), None => Poll::Ready(None), } } } #[pinned_drop] impl PinnedDrop for WebSocket { fn drop(self: Pin<&mut Self>) { self.ws.close().unwrap(); } } #[cfg(test)] mod tests { use super::*; use futures::{SinkExt, StreamExt}; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); const ECHO_SERVER_URL: &str = env!("ECHO_SERVER_URL"); #[wasm_bindgen_test] async fn websocket_works() { let mut ws = WebSocket::open(ECHO_SERVER_URL).unwrap(); ws.send(Message::Text("test".to_string())).await.unwrap(); // ignore first message // the echo-server used sends it's info in the first message let _ = ws.next().await; assert_eq!( ws.next().await.unwrap().unwrap(), Message::Text("test".to_string()) ) } }
use glam::{vec4, Vec3, Vec4, Mat4}; use image::{Rgba, RgbaImage}; use serde::Deserialize; use std::f32::consts::*; #[derive(Copy, Clone, Default)] pub struct VertexAttributes { pub position: Vec4, pub normal: Vec3, pub frag_pos: Vec3, } impl VertexAttributes { pub fn new(position: Vec3, normal: Vec3) -> Self { Self { position: position.extend(1.0), normal, frag_pos: Vec3::zero(), } } pub fn interpolate(a: VertexAttributes, b: VertexAttributes, c: VertexAttributes, alpha: f32, beta: f32, gamma: f32) -> Self { let mut r = VertexAttributes::default(); r.position = alpha * (a.position / a.position.w) + beta * (b.position / b.position.w) + gamma * (c.position / c.position.w); r.normal = (alpha * a.normal + beta * b.normal + gamma * c.normal).normalize(); r } } #[derive(Copy, Clone, Default)] pub struct FragmentAttributes { pub color: Vec4, pub position: Vec3, pub normal: Vec3, } impl FragmentAttributes { pub fn new(color: Vec4, position: Vec3, normal: Vec3) -> Self { Self { color, position, normal, } } } #[derive(Copy, Clone, Default, Deserialize)] pub struct UniformAttributes { pub light: Light, pub material: Material, pub camera: Camera, pub transform: Transform, pub view_matrix: Mat4, pub model_matrix: Mat4, pub projection_matrix: Mat4, pub normal_matrix: Mat4, } impl UniformAttributes { pub fn calc_model_matrix(&mut self) { let mut transform = Mat4::identity(); let cos = (self.transform.angle * PI).cos(); let sin = (self.transform.angle * PI).sin(); transform.w_axis.z = -self.transform.distance; transform.x_axis.x = cos; transform.x_axis.z = sin; transform.z_axis.x = -sin; transform.z_axis.z = cos; self.model_matrix = transform; self.normal_matrix = transform.inverse().transpose(); } pub fn calc_view_matrix(&mut self) { let mut transform = Mat4::identity(); transform.w_axis.x = -self.camera.position.x; transform.w_axis.y = -self.camera.position.y; transform.w_axis.z = -self.camera.position.z; self.view_matrix = transform; } pub fn calc_projection_matrix(&mut self) { self.projection_matrix = match self.camera.is_perspective { true => Mat4::perspective_rh(self.camera.field_of_view, self.camera.aspect_ratio, -1.0, 1.0), false => Mat4::identity(),// Mat4::orthographic_rh(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0), }; } pub fn calc_matrices(&mut self) { self.calc_model_matrix(); self.calc_view_matrix(); self.calc_projection_matrix(); } } #[derive(Copy, Clone)] pub struct FrameBufferAttributes { pub color: Rgba<u8>, pub depth: f32, } impl FrameBufferAttributes { pub fn new() -> Self { FrameBufferAttributes { color: Rgba([255, 255, 255, 255]), depth: 100.0, } } pub fn get_color(&self) -> Vec4 { vec4(self.color[0] as f32 / 255.0, self.color[1] as f32 / 255.0, self.color[2] as f32 / 255.0, self.color[3] as f32 / 255.0) } } pub struct FrameBuffer { frame_buffer: Vec<Vec<FrameBufferAttributes>>, } impl FrameBuffer { pub fn new(w: usize, h: usize) -> Self { FrameBuffer { frame_buffer: vec![vec![FrameBufferAttributes::new(); w]; h] } } pub fn height(&self) -> usize { self.frame_buffer.len() } pub fn width(&self) -> usize { self.frame_buffer[0].len() } pub fn get(&self, x: usize, y: usize) -> FrameBufferAttributes { self.frame_buffer[y][x] } pub fn set(&mut self, x: usize, y: usize, val: FrameBufferAttributes) { self.frame_buffer[y][x] = val; } pub fn clear(&mut self) { self.frame_buffer = vec![vec![FrameBufferAttributes::new(); self.width()]; self.height()]; } pub fn render(&self) -> RgbaImage { let mut img = RgbaImage::new(self.width() as u32, self.height() as u32); img.enumerate_pixels_mut().for_each(|(x, y, pixel)| { *pixel = self.get(x as usize, y as usize).color }); img } } #[derive(Copy, Clone)] pub enum PrimitiveType { Triangle, Line, } #[derive(Copy, Clone)] pub enum RenderType { Png, Gif, } #[derive(Copy, Clone, Default, Deserialize)] pub struct Light { pub position: Vec3, pub intensity: Vec3, } #[derive(Copy, Clone, Default, Deserialize)] pub struct Material { pub ambient_color: Vec3, pub diffuse_color: Vec3, pub specular_color: Vec3, pub specular_exponent: f32, } #[derive(Copy, Clone, Default, Deserialize)] pub struct Camera { pub is_perspective: bool, pub position: Vec3, pub field_of_view: f32, pub aspect_ratio: f32, } #[derive(Copy, Clone, Default, Deserialize)] pub struct Transform { pub angle: f32, pub distance: f32, }
//! <div align="center"> //! <h1>awto</h1> //! //! <p> //! <strong>Awtomate your 🦀 microservices with awto</strong> //! </p> //! //! </div> //! //! # Awto //! //! Awto treats your rust project as the source of truth for microservices, //! and generates **database tables** and **protobufs** based on your schema and service. //! //! See more on the [repository](https://github.com/awto-rs/awto). pub use awto_macros as macros; pub use lazy_static; pub mod database; pub mod prelude; pub mod protobuf; pub mod schema; pub mod service; #[doc(hidden)] pub mod tests_cfg;
use bevy::{diagnostic::{FrameTimeDiagnosticsPlugin, PrintDiagnosticsPlugin}, math::vec2, math::vec3, prelude::*, render::camera::PerspectiveProjection}; use meshie::{generator::DistributionFn, generator::MeshBuilder, generator::MeshConfig}; // use rand::{FromEntropy, Rng, StdRng}; fn main() { App::build() .add_default_plugins() .add_resource(ClearColor(Color::BLACK)) .add_plugin(FrameTimeDiagnosticsPlugin::default()) .add_plugin(PrintDiagnosticsPlugin::default()) .add_startup_system(setup.system()) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, asset_server: Res<AssetServer>, ) { commands // light .spawn(LightComponents { transform: Transform::from_translation(Vec3::new(40.0, -40.0, 50.0)), ..Default::default() }) // camera .spawn(Camera3dComponents { transform: Transform::new(Mat4::face_toward( Vec3::new(0.0, -15.0, 1500.0), Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), )), perspective_projection: PerspectiveProjection { far: 100000., ..Default::default() }, ..Default::default() }); let mat_handle = asset_server .load("../assets/STSCI-H-p1917b-q-5198x4801.png") .unwrap(); let mut mesh_builder = MeshBuilder { texture_size: vec2(5198., 4807.), config: vec![], }; mesh_builder.config.push(MeshConfig { count: 100, texture_position: bevy::sprite::Rect { min: vec2(592., 863.), max: vec2(601., 871.), }, area: vec3(1000., 1000., 10.), distribution: DistributionFn::Random, }); mesh_builder.config.push(MeshConfig { count: 50, texture_position: bevy::sprite::Rect { min: vec2(674., 857.), max: vec2(685., 869.), }, area: vec3(1000., 1000., 10.), distribution: DistributionFn::Random, }); mesh_builder.config.push(MeshConfig { count: 50, texture_position: bevy::sprite::Rect { min: vec2(526., 854.), max: vec2(543., 871.), }, area: vec3(1000., 1000., 10.), distribution: DistributionFn::Random, }); mesh_builder.config.push(MeshConfig { count: 10, texture_position: bevy::sprite::Rect { min: vec2(613., 880.), max: vec2(656., 917.), }, area: vec3(1000., 1000., 10.), distribution: DistributionFn::Random, }); let mesh = mesh_builder.gen_mesh(); // let mut rng = StdRng::from_entropy(); let mesh_handle = meshes.add(mesh); commands.spawn(PbrComponents { mesh: mesh_handle, material: materials.add(StandardMaterial { // albedo: Color::rgb( // rng.gen_range(0.0, 1.0), // rng.gen_range(0.0, 1.0), // rng.gen_range(0.0, 1.0), // ), albedo_texture: Some(mat_handle), shaded: false, ..Default::default() }), // transform: Transform::from_translation(Vec3::new( // rng.gen_range(-50.0, 50.0), // rng.gen_range(-50.0, 50.0), // 0.0, // )), ..Default::default() }); }
/*! Defines the drawing elements, the high-level drawing unit in Plotters drawing system ## Introduction An element is the drawing unit for Plotter's high-level drawing API. Different from low-level drawing API, an element is a logic unit of component in the image. There are few built-in elements, including `Circle`, `Pixel`, `Rectangle`, `Path`, `Text`, etc. All element can be drawn onto the drawing area using API `DrawingArea::draw(...)`. Plotters use "iterator of elements" as the abstraction of any type of plot. ## Implementing your own element You can also define your own element, `CandleStick` is a good sample of implementing complex element. There are two trait required for an element: - `PointCollection` - the struct should be able to return an iterator of key-points under guest coordinate - `Drawable` - the struct should be able to use performe drawing on a drawing backend with pixel-based coordinate An example of element that draws a red "X" in a red rectangle onto the backend: ```rust use std::iter::{Once, once}; use plotters::element::{PointCollection, Drawable}; use plotters::drawing::backend::{BackendCoord, DrawingErrorKind}; use plotters::prelude::*; // Any example drawing a red X struct RedBoxedX((i32, i32)); // For any reference to RedX, we can convert it into an iterator of points impl <'a> PointCollection<'a, (i32, i32)> for &'a RedBoxedX { type Borrow = &'a (i32, i32); type IntoIter = Once<&'a (i32, i32)>; fn point_iter(self) -> Self::IntoIter { once(&self.0) } } // How to actually draw this element impl <DB:DrawingBackend> Drawable<DB> for RedBoxedX { fn draw<I:Iterator<Item = BackendCoord>>( &self, mut pos: I, backend: &mut DB ) -> Result<(), DrawingErrorKind<DB::ErrorType>> { let pos = pos.next().unwrap(); backend.draw_rect(pos, (pos.0 + 10, pos.1 + 12), &Red, false)?; backend.draw_text("X", &("Arial", 20).into(), pos, &Red) } } fn main() -> Result<(), Box<dyn std::error::Error>> { let root = BitMapBackend::new( "examples/outputs/element-0.png", (640, 480) ).into_drawing_area(); root.draw(&RedBoxedX((200, 200)))?; Ok(()) } ``` ![](https://raw.githubusercontent.com/38/plotters/master/examples/outputs/element-0.png) ## Composable Elements You also have an convenient way to build an element that isn't built into the Plotters library by combining existing elements into a logic group. To build an composable elemnet, you need to use an logic empty element that draws nothing to the backend but denotes the relative zero point of the logical group. Any element defined with pixel based offset coordinate can be added into the group later using the `+` operator. For example, the red boxed X element can be implemented with Composable element in the following way: ```rust use plotters::prelude::*; fn main() -> Result<(), Box<dyn std::error::Error>> { let root = BitMapBackend::new( "examples/outputs/element-1.png", (640, 480) ).into_drawing_area(); let font:FontDesc = ("Arial", 20).into(); root.draw(&(EmptyElement::at((200, 200)) + OwnedText::new("X", (0, 0), &"Arial".into_font().resize(20.0).color(&Red)) + Rectangle::new([(0,0), (10, 12)], &Red) ))?; Ok(()) } ``` ![](https://raw.githubusercontent.com/38/plotters/master/examples/outputs/element-1.png) */ use crate::drawing::backend::{BackendCoord, DrawingBackend, DrawingErrorKind}; use std::borrow::Borrow; mod basic_shapes; pub use basic_shapes::*; mod points; pub use points::*; mod composable; pub use composable::{ComposedElement, EmptyElement}; mod candlestick; pub use candlestick::CandleStick; /// A type which is logically a collection of points, under any given coordinate system pub trait PointCollection<'a, Coord> { /// The item in point iterator type Borrow: Borrow<Coord>; /// The point iterator type IntoIter: IntoIterator<Item = Self::Borrow>; /// framework to do the coordinate mapping fn point_iter(self) -> Self::IntoIter; } /// The trait indicates we are able to draw it on a drawing area pub trait Drawable<DB: DrawingBackend> { /// Actually draws the element. The key points is already translated into the /// image cooridnate and can be used by DC directly fn draw<I: Iterator<Item = BackendCoord>>( &self, pos: I, backend: &mut DB, ) -> Result<(), DrawingErrorKind<DB::ErrorType>>; } trait DynDrawable<DB: DrawingBackend> { fn draw_dyn( &self, points: &mut Iterator<Item = BackendCoord>, backend: &mut DB, ) -> Result<(), DrawingErrorKind<DB::ErrorType>>; } impl<DB: DrawingBackend, T: Drawable<DB>> DynDrawable<DB> for T { fn draw_dyn( &self, points: &mut Iterator<Item = BackendCoord>, backend: &mut DB, ) -> Result<(), DrawingErrorKind<DB::ErrorType>> { T::draw(self, points, backend) } } /// The container for a dynamically dispatched element pub struct DynElement<DB, Coord> where DB: DrawingBackend, Coord: Clone, { points: Vec<Coord>, drawable: Box<dyn DynDrawable<DB>>, } impl<'a, DB: DrawingBackend, Coord: Clone> PointCollection<'a, Coord> for &'a DynElement<DB, Coord> { type Borrow = &'a Coord; type IntoIter = std::slice::Iter<'a, Coord>; fn point_iter(self) -> Self::IntoIter { self.points.iter() } } impl<DB: DrawingBackend, Coord: Clone> Drawable<DB> for DynElement<DB, Coord> { fn draw<I: Iterator<Item = BackendCoord>>( &self, mut pos: I, backend: &mut DB, ) -> Result<(), DrawingErrorKind<DB::ErrorType>> { self.drawable.draw_dyn(&mut pos, backend) } } /// The trait that makes the conversion from the statically dispatched element /// to the dynamically dispatched element pub trait IntoDynElement<DB: DrawingBackend, Coord: Clone> { /// Make the conversion fn into_dyn(self) -> DynElement<DB, Coord>; } impl<T, DB, Coord> IntoDynElement<DB, Coord> for T where T: Drawable<DB> + 'static, for<'a> &'a T: PointCollection<'a, Coord>, Coord: Clone, DB: DrawingBackend, { fn into_dyn(self) -> DynElement<DB, Coord> { DynElement { points: self .point_iter() .into_iter() .map(|x| x.borrow().clone()) .collect(), drawable: Box::new(self), } } }