text
stringlengths
8
4.13M
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), feature(alloc))] #[cfg(not(feature = "std"))] extern crate alloc; pub mod geometry; pub mod node; pub mod number; pub mod result; pub mod style; mod algo;
use std::collections::{BTreeSet, HashMap}; use std::collections::hash_map::Entry; use std::sync::Arc; use command_data_derive::CommandDataChoices; use discorsd::{async_trait, BotState}; use discorsd::commands::{ButtonCommand, InteractionPayload, InteractionUse, Unused, Used}; use discorsd::errors::BotError; use discorsd::http::channel::embed; use discorsd::http::ClientResult; use discorsd::model::components::ButtonStyle; use discorsd::model::ids::{ChannelId, MessageId, UserId}; use discorsd::model::interaction::{ButtonPressData, Token}; use discorsd::model::interaction_response::{InteractionMessage, message}; use discorsd::model::message::{ChannelMessageId, Color}; use itertools::Itertools; use tokio::sync::RwLockWriteGuard; use crate::Bot; use crate::hangman::guess_letter::GuessCommand; use crate::hangman::guess_word::GuessButton; use crate::hangman::random_words::{channel_hist_word, server_hist_word, wordnik_word}; pub mod random_words; pub mod guess_letter; pub mod guess_word; #[derive(CommandDataChoices, Debug, Copy, Clone)] pub enum Source { // todo: change to guild when that's done Wordnik, #[command(default)] Channel, Server, } pub async fn start<D: InteractionPayload + Send + Sync>( state: &BotState<Bot>, word_source: Source, interaction: InteractionUse<D, Unused>, ) -> Result<InteractionUse<D, Used>, BotError> { let channel = interaction.channel; let mut game_guard = state.bot.hangman_games.write().await; match game_guard.entry(channel) { Entry::Occupied(_) => interaction.respond(&state, message(|m| { m.ephemeral(); m.embed(|e| { e.title("Hangman is already running in this channel"); e.description("If the Hangman message has been deleted, press the button to re-start the game"); e.color(Color::RED); }); m.button(state, RestartGame(word_source), |b| { b.label("Restart Game"); b.style(ButtonStyle::Secondary); }); })).await.map_err(Into::into), Entry::Vacant(vacant) => { let res = match word_source { Source::Wordnik => wordnik_word(&state.client.client).await, Source::Channel => channel_hist_word(state, channel, interaction.guild()).await, Source::Server => server_hist_word(state, interaction.guild().ok_or(channel)).await, }; let (word, source) = match res { Ok(word) => word, Err(err) => return interaction.respond(&state, message(|m| { m.ephemeral(); m.embed(|e| { e.title("Error getting word!"); e.description(format!("{err}")); e.color(Color::RED); }); m.button(state, RestartGame(word_source), |b| { b.label("Restart Game"); b.style(ButtonStyle::Secondary); }); })).await.map_err(Into::into) }; let mut hangman = Hangman { token: Token(String::new()), message: ChannelMessageId { channel, message: MessageId(0) }, word, source, guesses: BTreeSet::new(), wrong: 0, feedback: format!("React with a letter to guess!"), questioners: HashMap::new(), }; let interaction = interaction.respond(&state, hangman.message(state)).await?; let message = interaction.get_message(&state).await?; message.react(&state, '❓').await?; hangman.token = interaction.token.clone(); hangman.message.message = message.id; state.reaction_commands.write().await .push(Box::new(GuessCommand( hangman.message, interaction.token.clone()))); vacant.insert(hangman); Ok(interaction) } } } #[derive(Debug, Clone)] struct RestartGame(Source); #[async_trait] impl ButtonCommand for RestartGame { type Bot = Bot; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<ButtonPressData, Unused>, ) -> Result<InteractionUse<ButtonPressData, Used>, BotError> { state.bot.hangman_games.write().await .remove(&interaction.channel); // .map(|h| h.word_source) // .unwrap_or_default(); start(&state, self.0, interaction).await } } #[derive(Debug)] pub struct Hangman { pub token: Token, pub message: ChannelMessageId, pub word: String, pub source: String, pub guesses: BTreeSet<char>, pub wrong: usize, pub feedback: String, pub questioners: HashMap<UserId, MessageId>, } impl Hangman { pub async fn handle_end_game( &self, state: &BotState<Bot>, win: bool, lose: bool, ) -> ClientResult<bool> { if win { self.token.followup(&state, embed(|e| { e.color(Color::GOLD); e.title("You win!"); e.description(format!("The word was {}.\n{}", self.word, self.source)); })).await?; Ok(true) } else if lose { self.token.followup(&state, embed(|e| { e.color(Color::RED); e.title("You lose and the hangman gets to eat"); e.description(format!("The word was {}.\n{}", self.word, self.source)); })).await?; Ok(true) } else { Ok(false) } } pub fn message(&self, state: &BotState<Bot>) -> InteractionMessage { message(|m| { m.embed(|e| { e.title(format!("The hangman is hungry!\n{} letter word.", self.word.len())); e.description(format!("```\n{}\n```", ASCII_ART[self.wrong])); let revealed = self.word.chars() .map(|c| if self.guesses.contains(&c) { c } else { '_' }) .join(" "); e.footer_text(format!("{}\n{}", revealed, self.feedback)); }); m.button(state, GuessButton(self.word.len()), |b| b.label("Guess word")); }) } } pub const ASCII_ART: [&str; 6] = [ r"+-------------+ | | | | | | | | | | +---------+ | | | +--------+---------+--------+ | |", r"+-------------+ | | | O | | | | | | | +---------+ | | | +--------+---------+--------+ | |", r"+-------------+ | | | O | | | + | | | + | | | +---------+ | | | +--------+---------+--------+ | |", r"+-------------+ | | | O | \ | / | \+/ | | | + | | | +---------+ | | | +--------+---------+--------+ | |", r"+-------------+ | | | \ O / | \|/ | + | | | + | / \ | / \ | +---------+ | | | +--------+---------+--------+ | |", r"+-------------+ | | | \ X / | \|/ | + | | | + | / \ | / \ | +---------------------------+ | |", ];
mod flux_agg_tests; mod flags_tests; mod eac_tests; mod utils; mod aca_tests;
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - ADC interrupt and status register"] pub isr: ISR, #[doc = "0x04 - ADC interrupt enable register"] pub ier: IER, #[doc = "0x08 - ADC control register"] pub cr: CR, #[doc = "0x0c - ADC configuration register"] pub cfgr: CFGR, #[doc = "0x10 - ADC configuration register 2"] pub cfgr2: CFGR2, #[doc = "0x14 - ADC sample time register 1"] pub smpr1: SMPR1, #[doc = "0x18 - ADC sample time register 2"] pub smpr2: SMPR2, _reserved7: [u8; 0x04], #[doc = "0x20 - ADC watchdog threshold register 1"] pub tr1: TR1, #[doc = "0x24 - ADC watchdog threshold register 2"] pub tr2: TR2, #[doc = "0x28 - ADC watchdog threshold register 3"] pub tr3: TR3, _reserved10: [u8; 0x04], #[doc = "0x30 - ADC regular sequence register 1"] pub sqr1: SQR1, #[doc = "0x34 - ADC regular sequence register 2"] pub sqr2: SQR2, #[doc = "0x38 - ADC regular sequence register 3"] pub sqr3: SQR3, #[doc = "0x3c - ADC regular sequence register 4"] pub sqr4: SQR4, #[doc = "0x40 - ADC regular data register"] pub dr: DR, _reserved15: [u8; 0x08], #[doc = "0x4c - ADC injected sequence register"] pub jsqr: JSQR, _reserved16: [u8; 0x10], #[doc = "0x60 - ADC offset 1 register"] pub ofr1: OFR1, #[doc = "0x64 - ADC offset 2 register"] pub ofr2: OFR2, #[doc = "0x68 - ADC offset 3 register"] pub ofr3: OFR3, #[doc = "0x6c - ADC offset 4 register"] pub ofr4: OFR4, _reserved20: [u8; 0x10], #[doc = "0x80 - ADC injected channel 1 data register"] pub jdr1: JDR1, #[doc = "0x84 - ADC injected channel 2 data register"] pub jdr2: JDR2, #[doc = "0x88 - ADC injected channel 3 data register"] pub jdr3: JDR3, #[doc = "0x8c - ADC injected channel 4 data register"] pub jdr4: JDR4, _reserved24: [u8; 0x10], #[doc = "0xa0 - ADC Analog Watchdog 2 Configuration Register"] pub awd2cr: AWD2CR, #[doc = "0xa4 - ADC Analog Watchdog 3 Configuration Register"] pub awd3cr: AWD3CR, _reserved26: [u8; 0x08], #[doc = "0xb0 - ADC Differential mode Selection Register"] pub difsel: DIFSEL, #[doc = "0xb4 - ADC Calibration Factors"] pub calfact: CALFACT, _reserved28: [u8; 0x10], #[doc = "0xc8 - ADC option register"] pub or: OR, _reserved29: [u8; 0x023c], #[doc = "0x308 - ADC common control register"] pub ccr: CCR, _reserved30: [u8; 0xe4], #[doc = "0x3f0 - ADC hardware configuration register"] pub hwcfgr0: HWCFGR0, #[doc = "0x3f4 - ADC version register"] pub verr: VERR, #[doc = "0x3f8 - ADC identification register"] pub ipdr: IPDR, #[doc = "0x3fc - ADC size identification register"] pub sidr: SIDR, } #[doc = "ISR (rw) register accessor: ADC interrupt and status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`isr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`isr`] module"] pub type ISR = crate::Reg<isr::ISR_SPEC>; #[doc = "ADC interrupt and status register"] pub mod isr; #[doc = "IER (rw) register accessor: ADC interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ier`] module"] pub type IER = crate::Reg<ier::IER_SPEC>; #[doc = "ADC interrupt enable register"] pub mod ier; #[doc = "CR (rw) register accessor: ADC control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`] module"] pub type CR = crate::Reg<cr::CR_SPEC>; #[doc = "ADC control register"] pub mod cr; #[doc = "CFGR (rw) register accessor: ADC configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cfgr`] module"] pub type CFGR = crate::Reg<cfgr::CFGR_SPEC>; #[doc = "ADC configuration register"] pub mod cfgr; #[doc = "CFGR2 (rw) register accessor: ADC configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cfgr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cfgr2`] module"] pub type CFGR2 = crate::Reg<cfgr2::CFGR2_SPEC>; #[doc = "ADC configuration register 2"] pub mod cfgr2; #[doc = "SMPR1 (rw) register accessor: ADC sample time register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`smpr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`smpr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`smpr1`] module"] pub type SMPR1 = crate::Reg<smpr1::SMPR1_SPEC>; #[doc = "ADC sample time register 1"] pub mod smpr1; #[doc = "SMPR2 (rw) register accessor: ADC sample time register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`smpr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`smpr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`smpr2`] module"] pub type SMPR2 = crate::Reg<smpr2::SMPR2_SPEC>; #[doc = "ADC sample time register 2"] pub mod smpr2; #[doc = "TR1 (rw) register accessor: ADC watchdog threshold register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tr1`] module"] pub type TR1 = crate::Reg<tr1::TR1_SPEC>; #[doc = "ADC watchdog threshold register 1"] pub mod tr1; #[doc = "TR2 (rw) register accessor: ADC watchdog threshold register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tr2`] module"] pub type TR2 = crate::Reg<tr2::TR2_SPEC>; #[doc = "ADC watchdog threshold register 2"] pub mod tr2; #[doc = "TR3 (rw) register accessor: ADC watchdog threshold register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tr3`] module"] pub type TR3 = crate::Reg<tr3::TR3_SPEC>; #[doc = "ADC watchdog threshold register 3"] pub mod tr3; #[doc = "SQR1 (rw) register accessor: ADC regular sequence register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sqr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sqr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sqr1`] module"] pub type SQR1 = crate::Reg<sqr1::SQR1_SPEC>; #[doc = "ADC regular sequence register 1"] pub mod sqr1; #[doc = "SQR2 (rw) register accessor: ADC regular sequence register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sqr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sqr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sqr2`] module"] pub type SQR2 = crate::Reg<sqr2::SQR2_SPEC>; #[doc = "ADC regular sequence register 2"] pub mod sqr2; #[doc = "SQR3 (rw) register accessor: ADC regular sequence register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sqr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sqr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sqr3`] module"] pub type SQR3 = crate::Reg<sqr3::SQR3_SPEC>; #[doc = "ADC regular sequence register 3"] pub mod sqr3; #[doc = "SQR4 (rw) register accessor: ADC regular sequence register 4\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sqr4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sqr4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sqr4`] module"] pub type SQR4 = crate::Reg<sqr4::SQR4_SPEC>; #[doc = "ADC regular sequence register 4"] pub mod sqr4; #[doc = "DR (r) register accessor: ADC regular data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`dr`] module"] pub type DR = crate::Reg<dr::DR_SPEC>; #[doc = "ADC regular data register"] pub mod dr; #[doc = "JSQR (rw) register accessor: ADC injected sequence register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`jsqr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`jsqr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`jsqr`] module"] pub type JSQR = crate::Reg<jsqr::JSQR_SPEC>; #[doc = "ADC injected sequence register"] pub mod jsqr; #[doc = "OFR1 (rw) register accessor: ADC offset 1 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ofr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ofr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ofr1`] module"] pub type OFR1 = crate::Reg<ofr1::OFR1_SPEC>; #[doc = "ADC offset 1 register"] pub mod ofr1; #[doc = "OFR2 (rw) register accessor: ADC offset 2 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ofr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ofr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ofr2`] module"] pub type OFR2 = crate::Reg<ofr2::OFR2_SPEC>; #[doc = "ADC offset 2 register"] pub mod ofr2; #[doc = "OFR3 (rw) register accessor: ADC offset 3 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ofr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ofr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ofr3`] module"] pub type OFR3 = crate::Reg<ofr3::OFR3_SPEC>; #[doc = "ADC offset 3 register"] pub mod ofr3; #[doc = "OFR4 (rw) register accessor: ADC offset 4 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ofr4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ofr4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ofr4`] module"] pub type OFR4 = crate::Reg<ofr4::OFR4_SPEC>; #[doc = "ADC offset 4 register"] pub mod ofr4; #[doc = "JDR1 (r) register accessor: ADC injected channel 1 data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`jdr1::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`jdr1`] module"] pub type JDR1 = crate::Reg<jdr1::JDR1_SPEC>; #[doc = "ADC injected channel 1 data register"] pub mod jdr1; #[doc = "JDR2 (r) register accessor: ADC injected channel 2 data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`jdr2::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`jdr2`] module"] pub type JDR2 = crate::Reg<jdr2::JDR2_SPEC>; #[doc = "ADC injected channel 2 data register"] pub mod jdr2; #[doc = "JDR3 (r) register accessor: ADC injected channel 3 data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`jdr3::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`jdr3`] module"] pub type JDR3 = crate::Reg<jdr3::JDR3_SPEC>; #[doc = "ADC injected channel 3 data register"] pub mod jdr3; #[doc = "JDR4 (r) register accessor: ADC injected channel 4 data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`jdr4::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`jdr4`] module"] pub type JDR4 = crate::Reg<jdr4::JDR4_SPEC>; #[doc = "ADC injected channel 4 data register"] pub mod jdr4; #[doc = "AWD2CR (rw) register accessor: ADC Analog Watchdog 2 Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`awd2cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`awd2cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`awd2cr`] module"] pub type AWD2CR = crate::Reg<awd2cr::AWD2CR_SPEC>; #[doc = "ADC Analog Watchdog 2 Configuration Register"] pub mod awd2cr; #[doc = "AWD3CR (rw) register accessor: ADC Analog Watchdog 3 Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`awd3cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`awd3cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`awd3cr`] module"] pub type AWD3CR = crate::Reg<awd3cr::AWD3CR_SPEC>; #[doc = "ADC Analog Watchdog 3 Configuration Register"] pub mod awd3cr; #[doc = "DIFSEL (rw) register accessor: ADC Differential mode Selection Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`difsel::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`difsel::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`difsel`] module"] pub type DIFSEL = crate::Reg<difsel::DIFSEL_SPEC>; #[doc = "ADC Differential mode Selection Register"] pub mod difsel; #[doc = "CALFACT (rw) register accessor: ADC Calibration Factors\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`calfact::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`calfact::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`calfact`] module"] pub type CALFACT = crate::Reg<calfact::CALFACT_SPEC>; #[doc = "ADC Calibration Factors"] pub mod calfact; #[doc = "OR (rw) register accessor: ADC option register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`or::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`or::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`or`] module"] pub type OR = crate::Reg<or::OR_SPEC>; #[doc = "ADC option register"] pub mod or; #[doc = "CCR (rw) register accessor: ADC common control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr`] module"] pub type CCR = crate::Reg<ccr::CCR_SPEC>; #[doc = "ADC common control register"] pub mod ccr; #[doc = "HWCFGR0 (r) register accessor: ADC hardware configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hwcfgr0::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hwcfgr0`] module"] pub type HWCFGR0 = crate::Reg<hwcfgr0::HWCFGR0_SPEC>; #[doc = "ADC hardware configuration register"] pub mod hwcfgr0; #[doc = "VERR (r) register accessor: ADC version register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`verr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`verr`] module"] pub type VERR = crate::Reg<verr::VERR_SPEC>; #[doc = "ADC version register"] pub mod verr; #[doc = "IPDR (r) register accessor: ADC identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipdr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ipdr`] module"] pub type IPDR = crate::Reg<ipdr::IPDR_SPEC>; #[doc = "ADC identification register"] pub mod ipdr; #[doc = "SIDR (r) register accessor: ADC size identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sidr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sidr`] module"] pub type SIDR = crate::Reg<sidr::SIDR_SPEC>; #[doc = "ADC size identification register"] pub mod sidr;
use sam3x8e; use crate::hal::clock::*; use crate::hal::pin::*; use crate::hal_sam3x8e::core::*; impl PMCConfigure<sam3x8e::PMC> for PMCControl<sam3x8e::PMC> { fn set_hw_device(&mut self, pmc: sam3x8e::PMC) { self.rf = Some(pmc); } } impl PMCRead for PMCControl<sam3x8e::PMC> { fn get_master_clk(&self) -> u32 { match &self.rf { None => 0, Some(x) => x.ckgr_mcfr.read().bits(), } } fn get_main_clock_frequency_hz<'b>(&self) -> u32 { let main_clock_frequency_within_16_slow_clock_cycles = { while self.get_master_clk() & MAINFRDY == 0 {} self.get_master_clk() & MAINF_MASK }; main_clock_frequency_within_16_slow_clock_cycles * SLOW_CLOCK_FREQUENCY_HZ / 16 } } impl PMCWrite<PeripheralListing> for PMCControl<sam3x8e::PMC> { fn enable_peripheral(&self, p: PeripheralListing) { match &self.rf { None => {} Some(x) => x.pmc_pcer0.write_with_zero(|w| unsafe { w.bits(p.offset) }), } } fn disable_peripheral(&self, p: PeripheralListing) { match &self.rf { None => {} Some(x) => x.pmc_pcdr0.write_with_zero(|w| unsafe { w.bits(p.offset) }), } } }
use std::str; use std::sync::{Mutex, RwLock}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::collections::BTreeMap; use rocksdb::{self, DB}; use kite::{Term, TermRef}; use kite::query::term_selector::TermSelector; use key_builder::KeyBuilder; /// Manages the index's "term dictionary" /// /// Because terms can be very long, we don't use their byte-representations as /// keys. We generate a unique number for each one to use instead. /// /// The term dictionary is a mapping between terms and their internal IDs /// (aka. TermRef). It is entirely held in memory and persisted to the disk. pub struct TermDictionaryManager { next_term_ref: AtomicUsize, terms: RwLock<BTreeMap<Term, TermRef>>, write_lock: Mutex<i32>, } impl TermDictionaryManager { /// Generates a new term dictionary pub fn new(db: &DB) -> Result<TermDictionaryManager, rocksdb::Error> { // TODO: Raise error if .next_term_ref already exists // Next term ref try!(db.put(b".next_term_ref", b"1")); Ok(TermDictionaryManager { next_term_ref: AtomicUsize::new(1), terms: RwLock::new(BTreeMap::new()), write_lock: Mutex::new(0), }) } /// Loads the term dictionary from an index pub fn open(db: &DB) -> Result<TermDictionaryManager, rocksdb::Error> { let next_term_ref = match try!(db.get(b".next_term_ref")) { Some(next_term_ref) => { next_term_ref.to_utf8().unwrap().parse::<u32>().unwrap() } None => 1, // TODO: error }; // Read dictionary let mut terms = BTreeMap::new(); let mut iter = db.iterator(); iter.seek(b"t"); while iter.next() { let k = iter.key().unwrap(); if k[0] != b't' { break; } let term_ref = TermRef::new(str::from_utf8(&iter.value().unwrap()).unwrap().parse::<u32>().unwrap()); terms.insert(Term::from_bytes(&k[1..]), term_ref); } Ok(TermDictionaryManager { next_term_ref: AtomicUsize::new(next_term_ref as usize), terms: RwLock::new(terms), write_lock: Mutex::new(0), }) } /// Retrieves the TermRef for the given term pub fn get(&self, term: &Term) -> Option<TermRef> { self.terms.read().unwrap().get(term).cloned() } /// Iterates over terms in the dictionary which match the selector pub fn select(&self, term_selector: &TermSelector) -> Vec<TermRef> { self.terms.read().unwrap().iter() .filter(|&(term, _term_ref)| { term_selector.matches(term) }) .map(|(_term, term_ref)| *term_ref) .collect() } /// Retrieves the TermRef for the given term, adding the term to the /// dictionary if it doesn't exist pub fn get_or_create(&self, db: &DB, term: &Term) -> Result<TermRef, rocksdb::Error> { if let Some(term_ref) = self.get(term) { return Ok(term_ref); } // Term doesn't exist in the term dictionary // Increment next_term_ref let next_term_ref = self.next_term_ref.fetch_add(1, Ordering::SeqCst) as u32; try!(db.put(b".next_term_ref", (next_term_ref + 1).to_string().as_bytes())); // Create term ref let term_ref = TermRef::new(next_term_ref); // Get write lock // Note: We have a separate lock so we don't need to keep an exclusive // lock on the in-memory term dictionary while writing to disk, as this // blocks readers. let _guard = self.write_lock.lock().unwrap(); // It's possible that another thread has written the term to the dictionary // since we checked earlier. If this is the case, We should forget about // writing our TermRef and use the one that has been inserted already. if let Some(term_ref) = self.terms.read().unwrap().get(term) { return Ok(*term_ref); } // Write it to the on-disk term dictionary let kb = KeyBuilder::term_dict_mapping(term.as_bytes()); try!(db.put(kb.key(), next_term_ref.to_string().as_bytes())); // Write it to the term dictionary self.terms.write().unwrap().insert(term.clone(), term_ref);; Ok(term_ref) } }
use super::super::model::table::{ BoxblockTool, CharacterTool, EraserTool, FillShapeTool, LineShapeTool, PenTool, PointlightTool, ShapeTool, TableTool, TerranblockTool, }; use super::atom::btn::{self, Btn}; use super::atom::dropdown::{self, Dropdown}; use super::atom::fa; use super::atom::heading::{self, Heading}; use super::atom::slider::{self, Slider}; use super::atom::text::Text; use super::modal_imported_files::{self, ModalImportedFiles}; use super::molecule::color_pallet::{self, ColorPallet}; use super::molecule::tab_menu::{self, TabMenu}; use super::util::Prop; use crate::arena::block::{self, BlockId}; use crate::arena::resource::{self, ResourceId}; use crate::libs::color::Pallet; use crate::libs::select_list::SelectList; use isaribi::{ style, styled::{Style, Styled}, }; use kagura::prelude::*; pub struct Props { pub tools: Prop<SelectList<TableTool>>, pub block_arena: block::ArenaRef, pub resource_arena: resource::ArenaRef, pub selecting_table_id: BlockId, } pub enum Msg { NoOp, Sub(On), SetSelectedIdx(usize), SetShowSub(bool), SetModal(Modal), CloseModalSub(On), } pub enum On { ChangeSelectedIdx { idx: usize, }, SetSelectedTool { tool: TableTool, }, ChangeTableProps { table_id: BlockId, size: Option<[f32; 2]>, grid_color: Option<Pallet>, background_color: Option<Pallet>, background_image: Option<Option<ResourceId>>, env_light_intensity: Option<f32>, terran_height: Option<f32>, }, } pub struct SideMenu { tools: Prop<SelectList<TableTool>>, selected_idx: usize, block_arena: block::ArenaRef, resource_arena: resource::ArenaRef, selecting_table_id: BlockId, show_sub: bool, modal: Modal, } pub enum Modal { None, SelectTableBackgroundImage, SelectCharacterTexture(CharacterTool), } impl Constructor for SideMenu { fn constructor(props: Self::Props, _: &mut ComponentBuilder<Self::Msg, Self::Sub>) -> Self { let selected_idx = props.tools.selected_idx(); Self { tools: props.tools, selected_idx: selected_idx, block_arena: props.block_arena, resource_arena: props.resource_arena, selecting_table_id: props.selecting_table_id, show_sub: false, modal: Modal::None, } } } impl Component for SideMenu { type Props = Props; type Msg = Msg; type Sub = On; fn init(&mut self, props: Self::Props, _: &mut ComponentBuilder<Self::Msg, Self::Sub>) { self.tools = props.tools; self.block_arena = props.block_arena; if self.selected_idx != self.tools.selected_idx() { self.selected_idx = self.tools.selected_idx(); self.show_sub = true; } } fn update(&mut self, msg: Self::Msg) -> Cmd<Self::Msg, Self::Sub> { match msg { Msg::NoOp => Cmd::none(), Msg::Sub(sub) => Cmd::Sub(sub), Msg::SetSelectedIdx(idx) => { if idx != self.tools.selected_idx() { Cmd::sub(On::ChangeSelectedIdx { idx }) } else { Cmd::none() } } Msg::SetShowSub(show_sub) => { self.show_sub = show_sub; Cmd::none() } Msg::SetModal(modal) => { self.modal = modal; Cmd::none() } Msg::CloseModalSub(sub) => { self.modal = Modal::None; Cmd::sub(sub) } } } fn render(&self, _: Vec<Html>) -> Html { Self::styled(Html::div( Attributes::new().class(Self::class("base")), Events::new(), vec![ self.render_main(), self.render_sub(), match &self.modal { Modal::None => Html::none(), Modal::SelectTableBackgroundImage => self.render_modal_select_image({ let table_id = BlockId::clone(&self.selecting_table_id); move |r_id| { Msg::CloseModalSub(On::ChangeTableProps { table_id, size: None, grid_color: None, background_color: None, background_image: Some(Some(r_id)), env_light_intensity: None, terran_height: None, }) } }), Modal::SelectCharacterTexture(character) => self.render_modal_select_image({ let mut character = CharacterTool::clone(character); move |r_id| { character.tex_id = Some(r_id); Msg::Sub(On::SetSelectedTool { tool: TableTool::Character(character), }) } }), }, ], )) } } impl SideMenu { fn render_modal_select_image(&self, msg: impl FnOnce(ResourceId) -> Msg + 'static) -> Html { ModalImportedFiles::empty( modal_imported_files::Props { resource_arena: resource::ArenaRef::clone(&self.resource_arena), }, Subscription::new({ move |sub| match sub { modal_imported_files::On::Close => Msg::SetModal(Modal::None), modal_imported_files::On::SelectFile(r_id) => msg(r_id), } }), ) } fn render_main(&self) -> Html { Html::div( Attributes::new().class(Self::class("main")), Events::new(), self.tools .iter() .enumerate() .map(|(tool_idx, table_tool)| match table_tool { TableTool::Hr(text) => Html::div( Attributes::new().class(Self::class("main-hr")), Events::new(), vec![Html::text(text as &String)], ), _ => Btn::with_variant( if tool_idx == self.tools.selected_idx() { btn::Variant::Primary } else { btn::Variant::Dark }, Attributes::new(), Events::new().on_click(move |_| Msg::SetSelectedIdx(tool_idx)), vec![match table_tool { TableTool::Hr(..) => unreachable!(), TableTool::Selector => fa::i("fa-mouse-pointer"), TableTool::TableEditor => fa::i("fa-vector-square"), TableTool::Pen(..) => fa::i("fa-pen"), TableTool::Shape(..) => fa::i("fa-shapes"), TableTool::Eraser(..) => fa::i("fa-eraser"), TableTool::Character(..) => fa::i("fa-users"), TableTool::Boxblock(..) => fa::i("fa-cube"), TableTool::Terranblock(..) => fa::i("fa-edit"), TableTool::TerranblockEraser => fa::far_i("far fa-edit"), TableTool::Pointlight(..) => fa::i("fa-lightbulb"), }], ), }) .collect(), ) } fn render_sub(&self) -> Html { if self.show_sub { self.render_sub_opend() } else { self.render_sub_closed() } } fn render_sub_closed(&self) -> Html { Html::div( Attributes::new() .class(Self::class("sub")) .class(Self::class("sub--closed")), Events::new(), vec![Btn::dark( Attributes::new(), Events::new().on_click(|_| Msg::SetShowSub(true)), vec![fa::i("fa-caret-right")], )], ) } fn render_sub_opend(&self) -> Html { let selected_tool_name = self.tools.selected().map(|tool| tool.name()).unwrap_or(""); Html::div( Attributes::new() .class(Self::class("sub")) .class(Self::class("sub--opend")), Events::new(), vec![ Html::div( Attributes::new().class(Self::class("sub-header")), Events::new(), vec![ Html::div( Attributes::new(), Events::new(), vec![Html::text(format!("[{}]ツール", selected_tool_name))], ), Btn::dark( Attributes::new(), Events::new().on_click(|_| Msg::SetShowSub(false)), vec![fa::i("fa-caret-left")], ), ], ), match self.tools.selected() { Some(TableTool::Pen(tool)) => self.render_sub_pen(tool), Some(TableTool::Shape(tool)) => self.render_sub_shape(tool), Some(TableTool::TableEditor) => self.render_sub_table_editor(), Some(TableTool::Eraser(tool)) => self.render_sub_eraser(tool), Some(TableTool::Character(tool)) => self.render_sub_character(tool), Some(TableTool::Boxblock(tool)) => self.render_sub_boxblock(tool), Some(TableTool::Pointlight(tool)) => self.render_sub_pointlight(tool), Some(TableTool::Terranblock(tool)) => self.render_sub_terranblock(tool), _ => Html::div(Attributes::new(), Events::new(), vec![]), }, ], ) } fn render_sub_table_editor(&self) -> Html { Html::div( Attributes::new() .class(Self::class("sub-body")) .class(Self::class("sub-menu")), Events::new(), self.block_arena .map(&self.selecting_table_id, |table: &block::table::Table| { let [width, height] = *table.size(); let bg_image_id = table.background_texture_id(); vec![ Heading::h4( heading::Variant::Dark, Attributes::new(), Events::new(), vec![Html::text("幅(x方向)")], ), Slider::empty( slider::Props { position: slider::Position::Inf { val: width as f64, mid: 20.0, step: 1.0, }, range_is_editable: false, }, Subscription::new({ let table_id = BlockId::clone(&self.selecting_table_id); move |sub| match sub { slider::On::Input(width) => Msg::Sub(On::ChangeTableProps { table_id, size: Some([width as f32, height]), grid_color: None, background_color: None, background_image: None, env_light_intensity: None, terran_height: None, }), _ => Msg::NoOp, } }), ), Heading::h4( heading::Variant::Dark, Attributes::new(), Events::new(), vec![Html::text("奥行き(y方向)")], ), Slider::empty( slider::Props { position: slider::Position::Inf { val: height as f64, mid: 20.0, step: 1.0, }, range_is_editable: false, }, Subscription::new({ let table_id = BlockId::clone(&self.selecting_table_id); move |sub| match sub { slider::On::Input(height) => Msg::Sub(On::ChangeTableProps { table_id, size: Some([width, height as f32]), grid_color: None, background_color: None, background_image: None, env_light_intensity: None, terran_height: None, }), _ => Msg::NoOp, } }), ), Heading::h4( heading::Variant::Dark, Attributes::new(), Events::new(), vec![Html::text("環境光")], ), Slider::empty( slider::Props { position: slider::Position::Linear { val: table.env_light_intensity() as f64, min: 0.0, max: 1.0, step: 0.1, }, range_is_editable: false, }, Subscription::new({ let table_id = BlockId::clone(&self.selecting_table_id); move |sub| match sub { slider::On::Input(env_light_intensity) => { Msg::Sub(On::ChangeTableProps { table_id, size: None, grid_color: None, background_color: None, background_image: None, env_light_intensity: Some(env_light_intensity as f32), terran_height: None, }) } _ => Msg::NoOp, } }), ), Heading::h4( heading::Variant::Dark, Attributes::new(), Events::new(), vec![Html::text("地形ブロックの高さ")], ), Slider::empty( slider::Props { position: slider::Position::Linear { val: table.terran_height() as f64, min: 0.0, max: 2.0, step: 0.1, }, range_is_editable: false, }, Subscription::new({ let table_id = BlockId::clone(&self.selecting_table_id); move |sub| match sub { slider::On::Input(terran_height) => { Msg::Sub(On::ChangeTableProps { table_id, size: None, grid_color: None, background_color: None, background_image: None, env_light_intensity: None, terran_height: Some(terran_height as f32), }) } _ => Msg::NoOp, } }), ), TabMenu::with_children( tab_menu::Props { selected: 0, tabs: vec![String::from("色 1"), String::from("色 2")], controlled: false, }, Subscription::none(), vec![ ColorPallet::empty( color_pallet::Props { default_selected: table.grid_color().clone(), ..Default::default() }, Subscription::new({ let table_id = BlockId::clone(&self.selecting_table_id); move |sub| match sub { color_pallet::On::SelectColor(color) => { Msg::Sub(On::ChangeTableProps { table_id, size: None, grid_color: Some(color), background_color: None, background_image: None, env_light_intensity: None, terran_height: None, }) } } }), ), ColorPallet::empty( color_pallet::Props { default_selected: table.background_color().clone(), ..Default::default() }, Subscription::new({ let table_id = BlockId::clone(&self.selecting_table_id); move |sub| match sub { color_pallet::On::SelectColor(color) => { Msg::Sub(On::ChangeTableProps { table_id, size: None, grid_color: None, background_color: Some(color), background_image: None, env_light_intensity: None, terran_height: None, }) } } }), ), ], ), bg_image_id .and_then(|r_id| { self.resource_arena.get_as::<resource::ImageData>(r_id) }) .map(|bg_image| { Html::img( Attributes::new() .draggable(false) .src(bg_image.url().as_ref()), Events::new(), vec![], ) }) .unwrap_or(Html::none()), Btn::primary( Attributes::new(), Events::new() .on_click(|_| Msg::SetModal(Modal::SelectTableBackgroundImage)), vec![Html::text("画像を選択する")], ), ] }) .unwrap_or(vec![]), ) } fn render_sub_pen(&self, tool: &PenTool) -> Html { Html::div( Attributes::new() .class(Self::class("sub-body")) .class(Self::class("sub-menu")), Events::new(), vec![ Html::div(Attributes::new(), Events::new(), vec![Html::text("線幅")]), Slider::empty( slider::Props { position: slider::Position::Inf { val: tool.line_width, mid: 2.0, step: 0.01, }, range_is_editable: false, }, Subscription::new({ let mut tool = PenTool::clone(tool); move |sub| match sub { slider::On::Input(val) => { tool.line_width = val; Msg::Sub(On::SetSelectedTool { tool: TableTool::Pen(tool), }) } _ => Msg::NoOp, } }), ), ColorPallet::empty( color_pallet::Props { default_selected: tool.pallet.clone(), title: Some(String::from("ペン色")), }, Subscription::new({ let mut tool = PenTool::clone(tool); move |sub| match sub { color_pallet::On::SelectColor(pallet) => { tool.pallet = pallet; Msg::Sub(On::SetSelectedTool { tool: TableTool::Pen(tool), }) } } }), ), ], ) } fn render_sub_shape(&self, tools: &SelectList<ShapeTool>) -> Html { Html::div( Attributes::new().class(Self::class("sub-body")), Events::new(), vec![ Html::div( Attributes::new().class(Self::class("sub-tool-list")), Events::new(), tools .iter() .enumerate() .map(|(tool_idx, shape_tool)| { Btn::with_variant( if tool_idx == tools.selected_idx() { btn::Variant::Primary } else { btn::Variant::Dark }, Attributes::new(), Events::new().on_click({ let mut tools = SelectList::clone(tools); move |sub| { tools.set_selected_idx(tool_idx); Msg::Sub(On::SetSelectedTool { tool: TableTool::Shape(tools), }) } }), match shape_tool { ShapeTool::Line(..) => { vec![fa::i("fa-slash"), Html::text(" 直線")] } ShapeTool::Rect(..) => { vec![fa::far_i("fa-square"), Html::text(" 長方形")] } ShapeTool::Ellipse(..) => { vec![fa::far_i("fa-circle"), Html::text(" 楕円")] } }, ) }) .collect(), ), match tools.selected() { Some(ShapeTool::Line(line_shape)) => { self.render_sub_shape_line(line_shape, tools) } Some(ShapeTool::Rect(fill_shape)) => { self.render_sub_shape_fill(fill_shape, tools) } Some(ShapeTool::Ellipse(fill_shape)) => { self.render_sub_shape_fill(fill_shape, tools) } _ => Html::none(), }, ], ) } fn render_sub_shape_line( &self, line_shape: &LineShapeTool, tools: &SelectList<ShapeTool>, ) -> Html { Html::div( Attributes::new().class(Self::class("sub-menu")), Events::new(), vec![ Html::div(Attributes::new(), Events::new(), vec![Html::text("線幅")]), Slider::empty( slider::Props { position: slider::Position::Inf { val: line_shape.line_width, mid: 2.0, step: 0.01, }, range_is_editable: false, }, Subscription::new({ let mut line_shape = LineShapeTool::clone(line_shape); let mut tools = SelectList::clone(tools); move |sub| match sub { slider::On::Input(val) => { line_shape.line_width = val; if let Some(tool) = tools.selected_mut() { *tool = ShapeTool::Line(line_shape); } Msg::Sub(On::SetSelectedTool { tool: TableTool::Shape(tools), }) } _ => Msg::NoOp, } }), ), ColorPallet::empty( color_pallet::Props { default_selected: line_shape.pallet.clone(), title: Some(String::from("線色")), }, Subscription::new({ let mut line_shape = LineShapeTool::clone(line_shape); let mut tools = SelectList::clone(tools); move |sub| match sub { color_pallet::On::SelectColor(pallet) => { line_shape.pallet = pallet; if let Some(tool) = tools.selected_mut() { *tool = ShapeTool::Line(line_shape); } Msg::Sub(On::SetSelectedTool { tool: TableTool::Shape(tools), }) } } }), ), ], ) } fn render_sub_shape_fill( &self, fill_shape: &FillShapeTool, tools: &SelectList<ShapeTool>, ) -> Html { Html::div( Attributes::new().class(Self::class("sub-menu")), Events::new(), vec![ Html::div(Attributes::new(), Events::new(), vec![Html::text("線幅")]), Slider::empty( slider::Props { position: slider::Position::Inf { val: fill_shape.line_width, mid: 2.0, step: 0.01, }, range_is_editable: false, }, Subscription::new({ let mut fill_shape = FillShapeTool::clone(fill_shape); let mut tools = SelectList::clone(tools); move |sub| match sub { slider::On::Input(val) => { fill_shape.line_width = val; if let Some(tool) = tools.selected_mut() { tool.set_fill(fill_shape); } Msg::Sub(On::SetSelectedTool { tool: TableTool::Shape(tools), }) } _ => Msg::NoOp, } }), ), TabMenu::with_children( tab_menu::Props { selected: 0, tabs: vec![String::from("線色"), String::from("塗り潰し色")], controlled: false, }, Subscription::none(), vec![ ColorPallet::empty( color_pallet::Props { default_selected: fill_shape.line_pallet.clone(), ..Default::default() }, Subscription::new({ let mut fill_shape = FillShapeTool::clone(fill_shape); let mut tools = SelectList::clone(tools); move |sub| match sub { color_pallet::On::SelectColor(pallet) => { fill_shape.line_pallet = pallet; if let Some(tool) = tools.selected_mut() { tool.set_fill(fill_shape); } Msg::Sub(On::SetSelectedTool { tool: TableTool::Shape(tools), }) } } }), ), ColorPallet::empty( color_pallet::Props { default_selected: fill_shape.fill_pallet.clone(), ..Default::default() }, Subscription::new({ let mut fill_shape = FillShapeTool::clone(fill_shape); let mut tools = SelectList::clone(tools); move |sub| match sub { color_pallet::On::SelectColor(pallet) => { fill_shape.fill_pallet = pallet; if let Some(tool) = tools.selected_mut() { tool.set_fill(fill_shape); } Msg::Sub(On::SetSelectedTool { tool: TableTool::Shape(tools), }) } } }), ), ], ), ], ) } fn render_sub_eraser(&self, tool: &EraserTool) -> Html { Html::div( Attributes::new() .class(Self::class("sub-body")) .class(Self::class("sub-menu")), Events::new(), vec![ Html::div(Attributes::new(), Events::new(), vec![Html::text("線幅")]), Slider::empty( slider::Props { position: slider::Position::Inf { val: tool.line_width, mid: 2.0, step: 0.01, }, range_is_editable: false, }, Subscription::new({ let mut tool = EraserTool::clone(tool); move |sub| match sub { slider::On::Input(val) => { tool.line_width = val; Msg::Sub(On::SetSelectedTool { tool: TableTool::Eraser(tool), }) } _ => Msg::NoOp, } }), ), Slider::empty( slider::Props { position: slider::Position::Linear { min: 0.0, max: 100.0, val: tool.alpha as f64, step: 1.0, }, range_is_editable: false, }, Subscription::new({ let mut tool = EraserTool::clone(tool); move |sub| match sub { slider::On::Input(val) => { tool.alpha = val.round() as u8; Msg::Sub(On::SetSelectedTool { tool: TableTool::Eraser(tool), }) } _ => Msg::NoOp, } }), ), ], ) } fn render_sub_character(&self, character: &CharacterTool) -> Html { Html::div( Attributes::new() .class(Self::class("sub-body")) .class(Self::class("sub-menu")), Events::new(), vec![ Text::div("コマサイズ"), Slider::empty( slider::Props { position: slider::Position::Inf { val: character.size, mid: 1.0, step: 0.1, }, range_is_editable: false, }, Subscription::new({ let mut character = CharacterTool::clone(character); move |sub| match sub { slider::On::Input(size) => { character.size = size; Msg::Sub(On::SetSelectedTool { tool: TableTool::Character(character), }) } _ => Msg::NoOp, } }), ), Text::div("キャラクターの身長"), Slider::empty( slider::Props { position: slider::Position::Inf { val: character.height, mid: 1.0, step: 0.1, }, range_is_editable: false, }, Subscription::new({ let mut character = CharacterTool::clone(character); move |sub| match sub { slider::On::Input(tex_scale) => { character.height = tex_scale; Msg::Sub(On::SetSelectedTool { tool: TableTool::Character(character), }) } _ => Msg::NoOp, } }), ), character .tex_id .as_ref() .and_then(|r_id| self.resource_arena.get_as::<resource::ImageData>(r_id)) .map(|bg_image| { Html::img( Attributes::new() .draggable(false) .src(bg_image.url().as_ref()), Events::new(), vec![], ) }) .unwrap_or(Html::none()), Btn::primary( Attributes::new(), Events::new().on_click({ let character = CharacterTool::clone(character); move |_| Msg::SetModal(Modal::SelectCharacterTexture(character)) }), vec![Html::text("画像を選択する")], ), ], ) } fn render_sub_boxblock(&self, boxblock: &BoxblockTool) -> Html { Html::div( Attributes::new() .class(Self::class("sub-body")) .class(Self::class("sub-menu")), Events::new(), vec![ Text::div("幅(x方向)"), Slider::empty( slider::Props { position: slider::Position::Linear { val: boxblock.size[0], min: 0.0, max: 10.0, step: 0.5, }, range_is_editable: false, }, Subscription::new({ let mut boxblock = BoxblockTool::clone(boxblock); move |sub| match sub { slider::On::Input(a) => { boxblock.size[0] = a; Msg::Sub(On::SetSelectedTool { tool: TableTool::Boxblock(boxblock), }) } _ => Msg::NoOp, } }), ), Text::div("奥行き(y方向)"), Slider::empty( slider::Props { position: slider::Position::Linear { val: boxblock.size[1], min: 0.0, max: 10.0, step: 0.5, }, range_is_editable: false, }, Subscription::new({ let mut boxblock = BoxblockTool::clone(boxblock); move |sub| match sub { slider::On::Input(a) => { boxblock.size[1] = a; Msg::Sub(On::SetSelectedTool { tool: TableTool::Boxblock(boxblock), }) } _ => Msg::NoOp, } }), ), Text::div("高さ(z方向)"), Slider::empty( slider::Props { position: slider::Position::Linear { val: boxblock.size[2], min: 0.0, max: 10.0, step: 0.5, }, range_is_editable: false, }, Subscription::new({ let mut boxblock = BoxblockTool::clone(boxblock); move |sub| match sub { slider::On::Input(a) => { boxblock.size[2] = a; Msg::Sub(On::SetSelectedTool { tool: TableTool::Boxblock(boxblock), }) } _ => Msg::NoOp, } }), ), Dropdown::with_children( dropdown::Props { variant: btn::Variant::DarkLikeMenu, direction: dropdown::Direction::Bottom, text: match &boxblock.shape { block::boxblock::Shape::Cube => String::from("立方体"), block::boxblock::Shape::Sphere => String::from("球体"), block::boxblock::Shape::Cyliner => String::from("円柱"), }, toggle_type: dropdown::ToggleType::Click, }, Subscription::none(), vec![ Btn::menu( Attributes::new(), Events::new().on_click({ let mut boxblock = BoxblockTool::clone(boxblock); move |_| { boxblock.shape = block::boxblock::Shape::Cube; Msg::Sub(On::SetSelectedTool { tool: TableTool::Boxblock(boxblock), }) } }), vec![Html::text("立方体")], ), Btn::menu( Attributes::new(), Events::new().on_click({ let mut boxblock = BoxblockTool::clone(boxblock); move |_| { boxblock.shape = block::boxblock::Shape::Sphere; Msg::Sub(On::SetSelectedTool { tool: TableTool::Boxblock(boxblock), }) } }), vec![Html::text("球体")], ), Btn::menu( Attributes::new(), Events::new().on_click({ let mut boxblock = BoxblockTool::clone(boxblock); move |_| { boxblock.shape = block::boxblock::Shape::Cyliner; Msg::Sub(On::SetSelectedTool { tool: TableTool::Boxblock(boxblock), }) } }), vec![Html::text("円柱")], ), ], ), ColorPallet::empty( color_pallet::Props { default_selected: boxblock.color.clone(), title: Some(String::from("ブロック色")), }, Subscription::new({ let mut boxblock = BoxblockTool::clone(boxblock); move |sub| match sub { color_pallet::On::SelectColor(a) => { boxblock.color = a; Msg::Sub(On::SetSelectedTool { tool: TableTool::Boxblock(boxblock), }) } } }), ), ], ) } fn render_sub_terranblock(&self, terranblock: &TerranblockTool) -> Html { Html::div( Attributes::new() .class(Self::class("sub-body")) .class(Self::class("sub-menu")), Events::new(), vec![ Dropdown::with_children( dropdown::Props { direction: dropdown::Direction::Bottom, text: String::from(if terranblock.is_fillable { "塗りつぶし" } else { "1つずつ配置" }), variant: btn::Variant::DarkLikeMenu, toggle_type: dropdown::ToggleType::Click, }, Subscription::none(), vec![ Btn::menu( Attributes::new(), Events::new().on_click({ let mut terranblock = TerranblockTool::clone(terranblock); move |_| { terranblock.is_fillable = false; Msg::Sub(On::SetSelectedTool { tool: TableTool::Terranblock(terranblock), }) } }), vec![Html::text("1つずつ配置")], ), Btn::menu( Attributes::new(), Events::new().on_click({ let mut terranblock = TerranblockTool::clone(terranblock); move |_| { terranblock.is_fillable = true; Msg::Sub(On::SetSelectedTool { tool: TableTool::Terranblock(terranblock), }) } }), vec![Html::text("塗りつぶし")], ), ], ), ColorPallet::empty( color_pallet::Props { default_selected: terranblock.color.clone(), title: Some(String::from("ブロック色")), }, Subscription::new({ let mut terranblock = TerranblockTool::clone(terranblock); move |sub| match sub { color_pallet::On::SelectColor(a) => { terranblock.color = a; Msg::Sub(On::SetSelectedTool { tool: TableTool::Terranblock(terranblock), }) } } }), ), ], ) } fn render_sub_pointlight(&self, pointlight: &PointlightTool) -> Html { Html::div( Attributes::new() .class(Self::class("sub-body")) .class(Self::class("sub-menu")), Events::new(), vec![ Text::div("明るさ"), Slider::empty( slider::Props { position: slider::Position::Linear { val: pointlight.light_intensity, min: 0.0, max: 20.0, step: 0.1, }, range_is_editable: false, }, Subscription::new({ let mut pointlight = PointlightTool::clone(pointlight); move |sub| match sub { slider::On::Input(a) => { pointlight.light_intensity = a; Msg::Sub(On::SetSelectedTool { tool: TableTool::Pointlight(pointlight), }) } _ => Msg::NoOp, } }), ), Text::div("減衰開始距離"), Slider::empty( slider::Props { position: slider::Position::Linear { val: pointlight.light_attenation, min: 0.0, max: 10.0, step: 0.5, }, range_is_editable: false, }, Subscription::new({ let mut pointlight = PointlightTool::clone(pointlight); move |sub| match sub { slider::On::Input(a) => { pointlight.light_attenation = a; Msg::Sub(On::SetSelectedTool { tool: TableTool::Pointlight(pointlight), }) } _ => Msg::NoOp, } }), ), ColorPallet::empty( color_pallet::Props { default_selected: pointlight.color.clone(), title: Some(String::from("光源色")), }, Subscription::new({ let mut pointlight = PointlightTool::clone(pointlight); move |sub| match sub { color_pallet::On::SelectColor(a) => { pointlight.color = a; Msg::Sub(On::SetSelectedTool { tool: TableTool::Pointlight(pointlight), }) } } }), ), ], ) } } impl Styled for SideMenu { fn style() -> Style { style! { ".base" { "background-color": format!("{}", crate::libs::color::color_system::gray(100,8)); "color": format!("{}", crate::libs::color::color_system::gray(100,0)); "position": "relative"; "height": "100%"; } ".main" { "display": "grid"; "grid-auto-flow": "row"; "padding": "0.65em"; "row-gap": "0.65em"; "align-content": "start"; "align-items": "center"; "height": "100%"; "border-right": format!("0.1em solid {}", crate::libs::color::color_system::gray(100, 9)); } ".sub" { "position": "absolute"; "left": "100%"; "top": "0"; } ".sub--closed" { "padding": "0.65em"; } ".sub--opend" { "background-color": format!("{}", crate::libs::color::color_system::gray(100,8)); "min-width": "20rem"; "max-width": "10vw"; "height": "100%"; "display": "grid"; "grid-template-rows": "max-content 1fr"; "grid-template-columns": "1fr"; "border-right": format!("0.1em solid {}", crate::libs::color::color_system::gray(100, 9)); } ".sub-header" { "display": "grid"; "grid-template-columns": "1fr max-content"; "align-items": "center"; "padding": "0.65em"; "border-bottom": format!("0.1em solid {}", crate::libs::color::color_system::gray(100, 9)); } ".sub-body" { "padding": "0.65em"; } ".sub-tool-list" { "display": "grid"; "grid-template-columns": "1fr 1fr"; "grid-auto-flow": "row"; "column-gap": "0.65em"; "row-gap": "0.65em"; "padding-bottom": "0.65em"; } ".sub-menu" { "display": "grid"; "grid-template-columns": "100%"; "grid-auto-rows": "max-content"; "grid-auto-flow": "row"; "row-gap": "0.65rem"; "justify-items": "stretch"; "overflow-y": "scroll"; } ".sub-menu img" { "width": "100%"; } } } }
use zmq::Message; use zmq::Socket; use zmq::SNDMORE; use std::str; use std::thread::sleep; use std::time::Duration; #[derive(Debug)] pub enum RecvType { bytes(Vec<u8>), string(String), matrix(Vec<Vec<u8>>), } pub fn take_id(socket: &Socket) -> Vec<u8> { socket.recv_bytes(0).unwrap() } pub fn recv(socket: &Socket) -> RecvType { let mut data = socket.recv_multipart(0).unwrap(); let mut stringRes = String::new(); let mut isString = true; for d in &data { match str::from_utf8(d) { Ok(s) => stringRes += s, Err(_) => { isString = false; break }, }; } if !isString { if data.len() == 1 { return RecvType::bytes(data.pop().unwrap()) } else { //println!("RecvType::matrix(data) {:?}", data.len()); return RecvType::matrix(data) } } else { return RecvType::string(stringRes) } } // Data can be Vec<Vec<u8>> or Vec<String> or Vec<str> pub fn send_vecs<I, T>(socket: &Socket, data: I, identity: &Vec<u8>) -> Result<usize, usize> where I: IntoIterator<Item = T> + std::fmt::Debug, T: Into<Message>, { // println!("send_vecs {:?}", data); socket.send(identity, SNDMORE); let result = socket.send_multipart(data, 0); match result { Ok(T) => Ok(0), Err(Error) => Err(0), } } // Data can be Vec<u8> or &str pub fn send<T>(socket: &Socket, data: T, identity: &Vec<u8>) -> Result<usize, usize> where T: Into<Message> + std::fmt::Debug, { // println!("send {:?} to {:?}", data, String::from_utf8(identity.to_vec()).unwrap()); socket.send(identity, SNDMORE); let result = socket.send(data, 0); match result { Ok(T) => Ok(0), Err(Error) => Err(0), } } pub fn publish<T>(socket: &Socket, data: T, topic: &str) -> Result<usize, usize> where T: Into<Message> + std::clone::Clone + std::fmt::Debug, { println!("pushing {}", topic); for _ in 0..100 { socket.send(topic.as_bytes(), zmq::SNDMORE); match socket.send(data.clone(), 0){ Ok(T) => continue, Err(Error) => return Err(0), }; } sleep(Duration::from_millis(10)); return Ok(0) } pub fn publish_vecs<I, T>(socket: &Socket, data: I, topic: &str) -> Result<usize, usize> where I: IntoIterator<Item = T> + std::clone::Clone + std::fmt::Debug, T: Into<Message>, { //println!("+++++++++++++++++++++++++ {:?} data {:?}", topic, data); for _ in 0..1004 { socket.send(topic.as_bytes(), zmq::SNDMORE); match socket.send_multipart(data.clone(), 0){ Ok(T) => continue, Err(Error) => return Err(0), }; } sleep(Duration::from_millis(10)); return Ok(0) }
use std::io::{BufReader, Cursor, ErrorKind, Read, Seek, SeekFrom}; use std::sync::mpsc::{self, Receiver, SyncSender}; use anyhow::{Context, Error, Result}; use byteorder::{BigEndian, ReadBytesExt}; use crate::protocol::Packet; /// Size of the packet header. Fixed size: 6 bytes. pub const HEADER_SIZE: usize = 6; /// Max size of the data field => variable (depends on data_length field). pub const DATA_MAX_SIZE: usize = 65536; /// Size of the buffer used by `Reader`. /// BUFFER_SIZE = primary header length + data field max length. pub const BUFFER_SIZE: usize = HEADER_SIZE + DATA_MAX_SIZE; /// Size of the channel to communicate with the reader const CHANNEL_SIZE: usize = 1024; /// Custom abstraction of standard `BufReader` pub struct Reader<R> { reader: BufReader<R>, header_buf: Vec<u8>, data_buf: Vec<u8>, channel: SyncSender<Packet>, } impl<R: Read + Unpin> Reader<R> { pub fn new(src: R) -> (Reader<R>, Receiver<Packet>) { let (sender, receiver) = mpsc::sync_channel(CHANNEL_SIZE); let reader = BufReader::with_capacity(BUFFER_SIZE, src); ( Reader { reader, header_buf: Vec::with_capacity(HEADER_SIZE), // known size data_buf: Vec::new(), // variable size channel: sender, }, receiver, ) } pub fn run(&mut self) -> Result<()> { loop { let should_stop = self.read()?; let pkt = self.parse()?; self.channel.send(pkt)?; if should_stop { break; } } Ok(()) } fn read(&mut self) -> Result<bool, Error> { // Reading he primary header of the packet (fixed size: 48bits = 6 u8) self.header_buf.resize(HEADER_SIZE, 0); // still needs to be populated let res = self.reader.read_exact(&mut self.header_buf); match res { Ok(_) => Ok(false), Err(ref err) if err.kind() == ErrorKind::UnexpectedEof => return Ok(true), Err(e) => Err(e), } .with_context(|| format!("Could not read the header of size `{}`", HEADER_SIZE))?; // Parsing the header to get the Packet Data Length // As specified by the protocol: #octets = PKT_DATA_LENGTH + 1 let data_len = self.parse_pkt_length() + 1; // Reading the data field, which includes the secondary header self.data_buf.resize(data_len, 0); self.reader .read_exact(&mut self.data_buf) .with_context(|| format!("Could not read the body of size `{}`", data_len))?; Ok(false) } fn parse(&self) -> Result<Packet, Error> { let pkt = Packet::from_buffers(&self.header_buf, &self.data_buf); Ok(pkt) } /// Since the reading was successfull: this method is not expected to panick! fn parse_pkt_length(&self) -> usize { let mut cursor = Cursor::new(&self.header_buf); cursor .seek(SeekFrom::Start(4)) .expect("Fixed size vector: should reach this position"); cursor .read_u16::<BigEndian>() .expect("Reading exactly 16 bits: should parse u16") as usize } } #[cfg(test)] mod test { use super::*; type TestResult = Result<(), Box<dyn std::error::Error>>; const VALID_SOURCE: [u8; 22] = [ 8, 115, 193, 35, 0, 15, 0, 0, 18, 52, 0, 171, 205, 239, 165, 165, 90, 90, 195, 60, 193, 248, ]; const WRONG_SOURCE: [u8; 8] = [8, 115, 193, 35, 0, 15, 0, 0]; #[test] fn get_correct_buffers() -> TestResult { let (mut reader, receiver) = Reader::new(&VALID_SOURCE[..]); reader.run()?; let pkt = receiver.recv()?; let (header, data) = pkt.into_buffers(); let correct_header: Vec<u8> = vec![8, 115, 193, 35, 0, 15]; assert_eq!(&header, &correct_header); let correct_data: Vec<u8> = vec![ 0, 0, 18, 52, 0, 171, 205, 239, 165, 165, 90, 90, 195, 60, 193, 248, ]; assert_eq!(&data, &correct_data); Ok(()) } #[test] #[should_panic] fn invalid_source() { let (mut reader, _) = Reader::new(&WRONG_SOURCE[..]); reader.read().unwrap(); } }
// src/vm.rs use super::frame::*; use crate::code::*; use crate::compiler::*; use crate::evaluator::*; use crate::object::*; use std::cell::*; use std::collections::*; use std::convert::TryInto; use std::rc::*; const STACK_SIZE: usize = 2048; pub const GLOBALS_SIZE: usize = 65536; const MAX_FRAMES: usize = 1024; pub const TRUE: Object = Object::Boolean(Boolean { value: true }); pub const FALSE: Object = Object::Boolean(Boolean { value: false }); pub const NULL: Object = Object::Null(Null {}); pub struct Vm { pub constants: Rc<RefCell<Vec<Object>>>, pub stack: Vec<Option<Object>>, pub sp: usize, // Always points to the next value. Top of stack is stack[sp-1] globals: Rc<RefCell<Vec<Option<Object>>>>, frames: Vec<Frame>, frame_index: usize, pub last_popped_stack_elem: Option<Object>, } impl Vm { pub fn new(bytecode: Bytecode) -> Vm { let main_fn = CompiledFunction { instructions: bytecode.instuctions, num_locals: 0, num_parameters: 0, }; let main_closure = Closure { func: main_fn, free: Vec::new(), }; let mut frames: Vec<Frame> = vec![ Frame::new( Closure { func: CompiledFunction { instructions: Instructions::new(), num_locals: 0, num_parameters: 0, }, free: Vec::new(), }, 0 ); MAX_FRAMES ]; let main_frame = Frame::new(main_closure, 0); frames[0] = main_frame; Vm { constants: Rc::clone(&bytecode.constants), stack: vec![None; STACK_SIZE], sp: 0, // Always points to the next value. Top of stack is stack[sp-1] globals: Rc::new(RefCell::new(vec![None; GLOBALS_SIZE])), frames: frames, frame_index: 1, last_popped_stack_elem: None, } } // pub fn stack_top(&self) -> Option<Object> { // if self.sp == 0 { // None // } else { // self.stack[(self.sp - 1) as usize].clone() // } // } pub fn run(&mut self) -> Result<(), String> { let mut ip: usize; let mut ins: &Instructions; let mut op: Opcode; while self.current_frame().ip < self.current_frame().instructions().0.len() as i64 - 1 { self.current_frame().ip += 1; ip = self.current_frame().ip as usize; ins = self.current_frame().instructions(); op = Opcode::from(ins.0[ip]); match op { Opcode::OpConstant => { let src = ins.0[(ip + 1)..(ip + 3)].try_into().expect("wrong size"); let const_index = read_u16(src); self.current_frame().ip += 2; let obj = self.constants.borrow()[const_index as usize].clone(); self.push(obj)?; } Opcode::OpAdd | Opcode::OpSub | Opcode::OpMul | Opcode::OpDiv => { self.execute_binary_operation(op)?; } Opcode::OpPop => { self.pop(); } Opcode::OpTrue => { self.push(TRUE)?; } Opcode::OpFalse => { self.push(FALSE)?; } Opcode::OpEqual | Opcode::OpNotEqual | Opcode::OpGreaterThan => { self.execute_comparison(op)?; } Opcode::OpBang => { self.execute_bang_operator()?; } Opcode::OpMinus => { self.execute_minus_operator()?; } Opcode::OpJump => { let src = ins.0[(ip + 1)..(ip + 3)].try_into().expect("wrong size"); let pos = read_u16(src) as i64; self.current_frame().ip = pos - 1; } Opcode::OpJumpNotTruthy => { let src = ins.0[(ip + 1)..(ip + 3)].try_into().expect("wrong size"); let pos = read_u16(src) as i64; self.current_frame().ip += 2; let condition = self.pop(); if !is_truthy(&condition) { self.current_frame().ip = pos - 1; } } Opcode::OpNull => { self.push(NULL)?; } Opcode::OpSetGlobal => { let src = ins.0[(ip + 1)..(ip + 3)].try_into().expect("wrong size"); let global_index = read_u16(src) as usize; self.current_frame().ip += 2; self.globals.borrow_mut()[global_index] = self.pop(); } Opcode::OpGetGlobal => { let src = ins.0[(ip + 1)..(ip + 3)].try_into().expect("wrong size"); let global_index = read_u16(src) as usize; self.current_frame().ip += 2; let obj = self.globals.borrow_mut()[global_index] .as_ref() .unwrap() .clone(); // TODO: can unwrap? self.push(obj)?; } Opcode::OpArray => { let src = ins.0[(ip + 1)..(ip + 3)].try_into().expect("wrong size"); let num_elements = read_u16(src) as usize; self.current_frame().ip += 2; let array = self.build_array(self.sp - num_elements, self.sp); self.sp -= num_elements; self.push(array)?; } Opcode::OpHash => { let src = ins.0[(ip + 1)..(ip + 3)].try_into().expect("wrong size"); let num_elements = read_u16(src) as usize; self.current_frame().ip += 2; let hash = self.build_hash(self.sp - num_elements, self.sp)?; self.sp -= num_elements; self.push(hash)?; } Opcode::OpIndex => { let index = self.pop(); let left = self.pop(); self.execute_index_expression(&left, &index)?; } Opcode::OpCall => { let num_args = ins.0[ip + 1] as usize; self.current_frame().ip += 1; self.execute_call(num_args)?; } Opcode::OpReturnValue => { let return_value = self.pop(); let base_pointer = self.pop_frame().base_pointer; self.sp = base_pointer - 1; self.push(return_value.unwrap())?; } Opcode::OpReturn => { let base_pointer = self.pop_frame().base_pointer; self.sp = base_pointer - 1; self.push(NULL)?; } Opcode::OpSetLocal => { let local_index = ins.0[ip + 1] as usize; self.current_frame().ip += 1; let base_pointer = self.current_frame().base_pointer; self.stack[base_pointer + local_index] = self.pop(); } Opcode::OpGetLocal => { let local_index = ins.0[ip + 1] as usize; self.current_frame().ip += 1; let base_pointer = self.current_frame().base_pointer; let obj = self.stack[base_pointer + local_index].as_ref().unwrap(); // TODO: can unwrap? let obj_clone = obj.clone(); self.push(obj_clone)?; } Opcode::OpGetBuiltin => { let builtin_index = ins.0[ip + 1] as usize; self.current_frame().ip += 1; let definition = get_builtin_by_name(&get_builtin_names()[builtin_index]).unwrap(); //TODO: can unwrap? self.push(Object::Builtin(definition))?; } Opcode::OpClosure => { let src = ins.0[(ip + 1)..(ip + 3)].try_into().expect("wrong size"); let const_index = read_u16(src) as usize; let num_free = ins.0[ip + 3] as usize; self.current_frame().ip += 3; self.push_closure(const_index, num_free)?; } Opcode::OpGetFree => { let free_index = ins.0[ip + 1] as usize; self.current_frame().ip += 1; let current_closure = &self.current_frame().cl; let free = current_closure.free[free_index].as_ref().unwrap().clone(); self.push(free)?; } } } Ok(()) } pub fn push(&mut self, o: Object) -> Result<(), String> { if self.sp >= STACK_SIZE { return Err(String::from("stack overflow")); } self.stack[self.sp] = Some(o); self.sp += 1; Ok(()) } pub fn pop(&mut self) -> Option<Object> { let o = std::mem::replace(&mut self.stack[self.sp - 1], None); self.last_popped_stack_elem = o.clone(); self.sp -= 1; o } // pub fn last_popped_stack_elem(&self) -> Option<Object> { // self.stack[self.sp].clone() // } fn execute_binary_operation(&mut self, op: Opcode) -> Result<(), String> { let right = self.pop(); let left = self.pop(); if let Some(Object::Integer(Integer { value })) = &left { let left_value = value; if let Some(Object::Integer(Integer { value })) = &right { let right_value = value; return self.execute_binary_integer_operation(op, *left_value, *right_value); } } else if let Some(Object::StringObj(StringObj { value })) = &left { let left_value = value; if let Some(Object::StringObj(StringObj { value })) = &right { let right_value = value; return self.execute_binary_string_operation(op, left_value, right_value); } } Err(format!( "unsupported types for binary operation: {} {}", get_type(&left), get_type(&right), )) } fn execute_binary_integer_operation( &mut self, op: Opcode, left_value: i64, right_value: i64, ) -> Result<(), String> { let result = match op { Opcode::OpAdd => left_value + right_value, Opcode::OpSub => left_value - right_value, Opcode::OpMul => left_value * right_value, Opcode::OpDiv => left_value / right_value, _ => return Err(format!("unknown integer operator: {:?}", op)), }; self.push(Object::Integer(Integer { value: result }))?; Ok(()) } fn execute_comparison(&mut self, op: Opcode) -> Result<(), String> { let right = self.pop(); let left = self.pop(); if let Some(Object::Integer(Integer { value })) = right { let right_value = value; if let Some(Object::Integer(Integer { value })) = left { let left_value = value; return self.execute_integer_comparison(op, left_value, right_value); } } match op { Opcode::OpEqual => return self.push(native_bool_to_boolean_object(left == right)), Opcode::OpNotEqual => return self.push(native_bool_to_boolean_object(left != right)), _ => { return Err(format!( "unknown operator: {:?} ({:?} {:?})", op, left, right )); } } } fn execute_integer_comparison( &mut self, op: Opcode, left: i64, right: i64, ) -> Result<(), String> { match op { Opcode::OpEqual => self.push(native_bool_to_boolean_object(right == left)), Opcode::OpNotEqual => self.push(native_bool_to_boolean_object(right != left)), Opcode::OpGreaterThan => self.push(native_bool_to_boolean_object(left > right)), _ => return Err(format!("unknown operator: {:?}", op)), } } fn execute_bang_operator(&mut self) -> Result<(), String> { let operand = self.pop(); match operand { Some(TRUE) => self.push(FALSE), Some(FALSE) => self.push(TRUE), Some(NULL) => self.push(TRUE), _ => self.push(FALSE), } } fn execute_minus_operator(&mut self) -> Result<(), String> { let operand = self.pop(); match operand { Some(Object::Integer(Integer { value })) => { return self.push(Object::Integer(Integer { value: -value })); } _ => { return Err(format!( "unsupported type for negation: {}", get_type(&operand) )) } } } pub fn new_with_globals_store(bytecode: Bytecode, s: Rc<RefCell<Vec<Option<Object>>>>) -> Vm { let main_fn = CompiledFunction { instructions: bytecode.instuctions.clone(), num_locals: 0, num_parameters: 0, }; let main_closure = Closure { func: main_fn, free: Vec::new(), }; let main_frame = Frame::new(main_closure, 0); let mut frames: Vec<Frame> = vec![ Frame::new( Closure { func: CompiledFunction { instructions: Instructions::new(), num_locals: 0, num_parameters: 0, }, free: Vec::new() }, 0 ); MAX_FRAMES ]; frames[0] = main_frame; Vm { constants: bytecode.constants, stack: vec![None; STACK_SIZE], sp: 0, // Always points to the next value. Top of stack is stack[sp-1] globals: Rc::clone(&s), frames: frames, frame_index: 1, last_popped_stack_elem: None, } } fn execute_binary_string_operation( &mut self, op: Opcode, left: &str, right: &str, ) -> Result<(), String> { if op != Opcode::OpAdd { return Err(format!("unknown string operator: {:?}", op)); } self.push(Object::StringObj(StringObj { value: format!("{}{}", left, right), })) } fn build_array(&mut self, start_index: usize, end_index: usize) -> Object { let mut elements: Vec<Object> = vec![NULL; end_index - start_index]; let mut i = start_index; while i < end_index { elements[i - start_index] = std::mem::replace(&mut self.stack[i], None).unwrap(); i += 1; } Object::Array(Array { elements: elements }) } fn build_hash(&self, start_index: usize, end_index: usize) -> Result<Object, String> { let mut hashed_pairs: HashMap<HashKey, Object> = HashMap::new(); let mut i = start_index; while i < end_index { let key = &self.stack[i]; let value = &self.stack[i + 1]; if let Some(key_obj) = key { if let Some(hashable) = key_obj.as_hashable() { let hash_key = hashable.hash_key(); if let Some(value_obj) = value { hashed_pairs.insert(hash_key, value_obj.clone()); } else { return Err(format!("uninitialized value")); } } else { return Err(format!("unusable as hash key: {}", get_type(&key))); } } else { return Err(format!("unusable as hash key: {}", get_type(&key))); } i += 2; } Ok(Object::Hash(Hash { pairs: hashed_pairs, })) } fn execute_index_expression( &mut self, left: &Option<Object>, index: &Option<Object>, ) -> Result<(), String> { if let Some(Object::Array(Array { elements })) = left { if let Some(Object::Integer(Integer { value })) = index { return self.execute_array_index(elements, *value); } } else if let Some(Object::Hash(Hash { pairs })) = left { return self.execute_hash_index(pairs, index); } Err(format!("index operator not supported: {}", get_type(&left))) } fn execute_array_index(&mut self, elements: &Vec<Object>, index: i64) -> Result<(), String> { let max = elements.len() as i64 - 1; if index < 0 || index > max { return self.push(NULL); } self.push(elements[index as usize].clone()) } fn execute_hash_index( &mut self, pairs: &HashMap<HashKey, Object>, index: &Option<Object>, ) -> Result<(), String> { if let Some(key) = index { if let Some(hash_key) = key.as_hashable() { if let Some(value) = pairs.get(&hash_key.hash_key()) { return self.push(value.clone()); } else { return self.push(NULL); } } else { return Err(format!("unusable as hash key: {}", get_type(&index))); } } else { return Err(format!("unusable as hash key: {}", get_type(&index))); } } fn current_frame(&mut self) -> &mut Frame { &mut self.frames[self.frame_index - 1] } fn push_frame(&mut self, f: Frame) { self.frames[self.frame_index] = f; self.frame_index += 1; } fn pop_frame(&mut self) -> Frame { self.frame_index -= 1; self.frames[self.frame_index].clone() } // fn call_function(&mut self, func: CompiledFunction, num_args: usize) -> Result<(), String> { // if num_args != func.num_parameters { // return Err(format!( // "wrong number of arguments: want={}, got={}", // func.num_parameters, num_args // )); // } // let frame = Frame::new(func.clone(), self.sp - num_args); // self.sp = frame.base_pointer + func.num_locals; // self.push_frame(frame); // return Ok(()); // } fn execute_call(&mut self, num_args: usize) -> Result<(), String> { let callee = self.stack[self.sp - 1 - num_args].clone(); if let Some(Object::Closure(cl)) = callee { return self.call_closure(&cl, num_args); } else if let Some(Object::Builtin(builtin)) = callee { return self.call_builtin(&builtin, num_args); } else { return Err(format!("calling non-function and no-built-in")); } } fn call_builtin(&mut self, builtin: &Builtin, num_args: usize) -> Result<(), String> { let mut v: Vec<Object> = Vec::new(); for i in 0..num_args { v.push(std::mem::replace(&mut self.stack[self.sp - num_args + i], None).unwrap()); } let func = builtin.func; let result = func(&v)?; self.sp = self.sp - num_args - 1; self.push(result)?; Ok(()) } fn call_closure(&mut self, cl: &Closure, num_args: usize) -> Result<(), String> { if num_args != cl.func.num_parameters { return Err(format!( "wrong number of arguments: want={}, got={}", cl.func.num_parameters, num_args )); } let num_locals = cl.func.num_locals; let frame = Frame::new(cl.clone(), self.sp - num_args); let base_pointer = frame.base_pointer; self.push_frame(frame); self.sp = base_pointer + num_locals; Ok(()) } fn push_closure(&mut self, const_index: usize, num_free: usize) -> Result<(), String> { let constant = self.constants.borrow()[const_index].clone(); if let Object::CompiledFunction(function) = constant { let mut free: Vec<Option<Object>> = vec![None; num_free]; let mut i = 0; while i < num_free { free[i] = self.stack[self.sp - num_free + i].clone(); i += 1; } self.sp -= num_free; let closure = Closure { func: function, free: free, }; self.push(Object::Closure(closure)) } else { Err(format!("not a function: {:?}", constant)) } } } fn native_bool_to_boolean_object(input: bool) -> Object { if input { Object::Boolean(Boolean { value: true }) } else { Object::Boolean(Boolean { value: false }) } } pub fn get_type(obj: &Option<Object>) -> &str { if obj.is_some() { obj.as_ref().unwrap().get_type() } else { "None" } } fn is_truthy(obj: &Option<Object>) -> bool { if let Some(Object::Boolean(Boolean { value })) = obj { return *value; } else if let Some(NULL) = obj { return false; } true }
use std::io; use std::borrow::Borrow; use super::url::Url; use super::git2::{self, Oid}; use super::{pkt_line, Capability, Capabilities, Result}; #[derive(Debug)] pub struct UploadPack { head: Oid, refs: Vec<(String, Oid)>, capabilities: Capabilities, } #[derive(Debug)] pub enum Response { UploadPack(UploadPack), Error(&'static str), } pub fn prepare(repo: &git2::Repository, url: &Url) -> Result<Response> { let service = url.query_pairs() .find(|&(ref key, _)| key == "service") .map(|(_, id)| id.clone()); let service = service.as_ref().map(Borrow::borrow); match service { Some("git-upload-pack") => { let head = repo.head()?.target().expect("TODO: Better handling of non-HEAD containing repos"); let refs = repo.references()? .map(|r| { let r = r?; let name = r.name() .expect("TODO: Better handling of non-unicode refs") .to_owned(); let target = r.resolve()? .target() .expect("Resolved references always have a target"); Ok((name, target)) }) .collect::<::std::result::Result<_, git2::Error>>()?; // TODO: Sort refs by name in C locale let capabilities = Capabilities::new(vec![ Capability::SideBand, Capability::SideBand64K, Capability::MultiAck, Capability::MultiAckDetailed, ]); Ok(Response::UploadPack(UploadPack { head: head, refs: refs, capabilities: capabilities, })) } Some(_) => Ok(Response::Error("Unknown git service name")), None => Ok(Response::Error("Please upgrade your git client.")), } } impl UploadPack { pub fn write_to(&self, mut writer: &mut io::Write) -> Result<()> { pkt_line::write_str(&mut writer, "# service=git-upload-pack")?; pkt_line::flush(&mut writer)?; pkt_line::write_str(&mut writer, format!("{} HEAD\0{}", self.head, self.capabilities))?; for &(ref name, ref target) in &self.refs { pkt_line::write_str(&mut writer, format!("{} {}", target, name))?; } pkt_line::flush(&mut writer)?; Ok(()) } } impl Response { pub fn status_code(&self) -> u16 { match *self { Response::UploadPack(_) => 200, Response::Error(_) => 403, } } pub fn mime_type(&self) -> &'static str { match *self { Response::UploadPack(_) => "application/x-git-upload-pack-advertisement", Response::Error(_) => "text/plain; charset=utf-8", } } pub fn write_to(&self, mut writer: &mut io::Write) -> Result<()> { match *self { Response::UploadPack(ref pack) => pack.write_to(writer)?, Response::Error(ref msg) => writer.write_all(msg.as_bytes())?, } Ok(()) } }
use fancy_regex::Regex; use select::{document::Document, predicate::Name}; use std::io::Write; use std::thread; use std::time::Duration; const UAGENT: &str = "RarSpyder/1.0 (Linux x86_64;) Rust/1.44.0-nightly"; lazy_static::lazy_static! { /// sk, c, i, r, r2 static ref CAPS: Vec<Regex> = vec![ Regex::new(r"(?<=var value_sk = ')(.*)(?=')").unwrap(), Regex::new(r"(?<=var value_c = ')(.*)(?=')").unwrap(), Regex::new(r"(?<=var value_i = ')(.*)(?=')").unwrap(), Regex::new(r"(?<=&r=)(\d+)(?=')").unwrap(), Regex::new(r#"(?<="&r=)(\d+)(?=")"#).unwrap(), ]; } pub struct Captcha { base_url: String, /// rarbg captcha internal sk: String, /// rarbg captcha internal cid: String, /// rarbg captcha internal i: String, /// rarbg captcha internal r: String, /// rarbg captcha internal r2: String, /// rarbg captcha internal captcha_id: String, } impl Captcha { pub fn new(base_url: String) -> Self { Self { base_url, sk: String::new(), cid: String::new(), i: String::new(), r: String::new(), r2: String::new(), captcha_id: String::new(), } } /// Method `solve` solves the captcha returning the cookie required for operation pub async fn solve(&mut self) -> Result<Option<String>, reqwest::Error> { // Create a dummy request so that we get redirected to the captcha page let res = reqwest::ClientBuilder::new() .cookie_store(true) .user_agent(UAGENT) .build()? .get( format!( "https://{}/torrents.php?category[]=14,48,17,44,45,47", self.base_url ) .as_str(), ) .query(&[("search", "blade runner 2049")]) .send() .await?; if res.url().path() != "/threat_defence.php" { return Ok(None); } let document = Document::from(res.text().await.unwrap().as_ref()); let script = document .find(Name("script")) .filter_map(|x| x.first_child().and_then(|y| y.as_text())) .collect::<Vec<_>>() .pop() .expect("No script tag found"); let secrets = CAPS .iter() .map(|x| { x.captures(script) .unwrap() .unwrap() .get(1) .unwrap() .as_str() }) .collect::<Vec<_>>(); self.sk = secrets[0].into(); self.cid = secrets[1].into(); self.i = secrets[2].into(); self.r = secrets[3].into(); self.r2 = secrets[4].into(); self.generate_captcha().await?; self.get_captcha().await?; self.solve_captcha().await } // Function acts as the stage 2 of the captcha process async fn generate_captcha(&mut self) -> Result<(), reqwest::Error> { let _ = reqwest::ClientBuilder::new() .cookie_store(true) .user_agent(UAGENT) .build()? .get(format!("https://{}/threat_defence_ajax.php", self.base_url).as_str()) .query(&[ ("sk", self.sk.as_str()), ("cid", self.cid.as_str()), ("i", self.i.as_str()), ("r", self.r.as_str()), ]) .header("Cookie", format!("sk={}", self.sk.as_str())) .send() .await?; // sleep for 3.5s as required by rarbg for the captcha img to generate thread::sleep(Duration::from_millis(3500)); Ok(()) } async fn get_captcha(&mut self) -> Result<(), reqwest::Error> { let res = reqwest::ClientBuilder::new() .cookie_store(true) .user_agent(UAGENT) .build()? .get(format!("https://{}/threat_defence.php", self.base_url).as_str()) .query(&[ ("defence", "2"), ("sk", self.sk.as_str()), ("cid", self.cid.as_str()), ("i", self.i.as_str()), ("ref_cookie", self.base_url.as_str()), ("r", self.r2.as_str()), ]) .header("Cookie", format!("sk={}", self.sk.as_str())) .send() .await?; let doc = Document::from(res.text().await?.as_ref()); self.captcha_id = doc .find(Name("input")) .filter(|x| x.attr("name") == Some("captcha_id")) .filter_map(|x| x.attr("value")) .collect::<Vec<_>>() .pop() .unwrap() .to_string(); let mut img_selector = doc.find(Name("img")); img_selector.next(); let img = img_selector.next().unwrap().attr("src").unwrap(); let res = reqwest::ClientBuilder::new() .cookie_store(true) .user_agent(UAGENT) .build() .unwrap() .get(format!("https://rarbgproxied.org{}", img).as_str()) .header("Cookie", format!("sk={}", self.sk.as_str())) .send() .await .unwrap(); let mut file = std::fs::File::create(format!("{}.png", self.sk.as_str())).unwrap(); let bytes = res.bytes().await.unwrap(); file.write_all(&bytes).unwrap(); Ok(()) } async fn solve_captcha(&mut self) -> Result<Option<String>, reqwest::Error> { let mut lt = leptess::LepTess::new(None, "eng").unwrap(); lt.set_image(format!("{}.png", self.sk.as_str()).as_str()); lt.set_source_resolution(70); let code = lt.get_utf8_text().unwrap(); let res = reqwest::ClientBuilder::new() .cookie_store(true) .user_agent(UAGENT) .redirect(reqwest::redirect::Policy::none()) .build()? .get(format!("https://{}/threat_defence.php", self.base_url).as_str()) .query(&[ ("defence", "2"), ("sk", self.sk.as_str()), ("cid", self.cid.as_str()), ("i", self.i.as_str()), ("ref_cookie", "rarbgproxied.org"), ("r", self.r2.as_str()), ("solve_string", code.as_str().trim_end()), ("captcha_id", self.captcha_id.as_str()), ("submitted_bot_captcha", "1"), ]) .header("Cookie", format!("sk={}", self.sk.as_str())) .send() .await?; Ok(Some( res.cookies() .map(|x| format!("{}={}", x.name(), x.value())) .collect::<Vec<_>>() .join("; "), )) } }
use crate::models::media::{MediaBase, MediaStatus}; #[inline] pub fn na_str() -> String { "N/A".to_string() } #[inline] pub fn na_long_str() -> String { "Not Available".to_string() } /// Returns formated time from minutes pub fn format_time(time_minutes: f64) -> String { let minutes = (time_minutes % 60.0).floor(); let hours = ((time_minutes / 60.0) % 24.0).floor(); let days = (time_minutes / 60.0 / 24.0).floor(); if days > 0.0 { return format!("{} days, {}:{:02}", days, hours, minutes); } if hours > 0.0 { return format!("{} hours, {} minutes", hours, minutes); } format!("{} minutes", minutes) } pub fn synopsis(text: impl ToString, length: usize) -> String { let mut synopsis = text.to_string(); if synopsis.is_empty() || length == 0 { return "N/A".to_string(); } // TODO parse markdown links and images // TODO hide/remove spoilers // TODO strip html tags // TODO a better solution would be to find a extensible // markdown parser // even if it means making a local nodejs server just to turn // anilist markdown to proper markdown that can be accepted by Discord synopsis = markdown::parse_markdown_links(synopsis); synopsis = markdown::parse_markdown(synopsis); let newline_regex = regex::Regex::new("(\n{2,})").unwrap(); synopsis = newline_regex.replace_all(&synopsis, "").to_string(); synopsis = synopsis.replace("~~~", "\n"); if synopsis.len() > length { let end = synopsis.char_indices().map(|(i, _)| i).nth(length).unwrap(); let mut trimmed = synopsis[0..end].to_string(); trimmed = trimmed.split_at(trimmed.rfind(' ').unwrap()).0.to_string(); trimmed = markdown::clean_spoilers(trimmed); trimmed.push_str(" ..."); synopsis = trimmed; } markdown::strip_html_tags(&synopsis).join("") } pub fn num_to_emoji(num: u32) -> String { match num { 0 => ":zero:", 1 => ":one:", 2 => ":two:", 3 => ":three:", 4 => ":four:", 5 => ":five:", 6 => ":six:", 7 => ":seven:", 8 => ":eight:", 9 => ":nine:", _ => unreachable!("Input should not be a number above 9."), } .to_string() } pub fn media_base_to_legend(media: &[MediaBase]) -> Option<String> { let mut statuses = media .iter() .map(|media| media.status.clone()) .collect::<Vec<_>>(); statuses.sort_by(|a, b| b.cmp(&a)); statuses.dedup_by_key(|status| status.clone()); let legend: String = statuses .iter() .map(MediaStatus::to_string_with_emoji) .collect::<Vec<_>>() .join(" - "); Some(legend).filter(String::is_empty) } mod markdown { use regex::Regex; pub(crate) fn clean_spoilers(content: String) -> String { let content = content.replace("~!", "||").replace("!~", "||"); let spoiler_pairs: Vec<_> = content.match_indices("||").collect(); if spoiler_pairs.len() % 2 != 0 { let index = spoiler_pairs[spoiler_pairs.len() - 1].0; return content.split_at(index).0.to_string(); } content } pub(crate) fn parse_markdown(mut content: String) -> String { let re = Regex::new(r"(img|webm|youtube)[0-9]{0,3}%?\((.*?)\)").unwrap(); for cap in re.captures_iter(content.clone().as_str()) { match &cap[1] { "img" | "webm" => { content = content.replace(&cap[0], format!("[image]({})", &cap[2]).as_str()) } "youtube" => { content = content.replace(&cap[0], format!("[video]({})", &cap[2]).as_str()) } _ => (), } } content } pub(crate) fn parse_markdown_links(mut content: String) -> String { let re = Regex::new(r"\[ (img|webm)[0-9]{0,3}%?\((.*?)\) ]\((.*?)\)").unwrap(); for cap in re.captures_iter(content.clone().as_str()) { content = content.replace(&cap[0], format!("[image link]({})", &cap[3]).as_str()); } content } use html5ever::tendril::TendrilSink; use html5ever::{parse_document, ParseOpts}; use markup5ever_rcdom::{Node, NodeData, RcDom}; // Code from the dissolve crate pub(crate) fn strip_html_tags(input: &str) -> Vec<String> { let dom = parse_document(RcDom::default(), ParseOpts::default()) .from_utf8() .one(input.as_bytes()); let doc = dom.document; get_text(&doc) } /// Helper function to return text in text nodes in pre-order traversal. fn get_text(element: &Node) -> Vec<String> { match element.data { NodeData::Text { ref contents } => { let mut text = vec![(&**contents.borrow()).to_owned()]; for child in &*element.children.borrow() { text.append(&mut get_text(child)); } text } _ => { let mut text = vec![]; for child in &*element.children.borrow() { text.append(&mut get_text(child)); } text } } } }
pub mod auth; pub mod multer; pub mod config; pub mod limit;
use crate::build::{build_internal, finalize}; use crate::cmd::{cfg_spinner, run_stage}; use crate::errors::*; use crate::parse::ServeOpts; use crate::thread::{spawn_thread, ThreadHandle}; use console::{style, Emoji}; use indicatif::{MultiProgress, ProgressBar}; use std::env; use std::io::Write; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex}; // Emojis for stages static BUILDING_SERVER: Emoji<'_, '_> = Emoji("📡", ""); static SERVING: Emoji<'_, '_> = Emoji("🛰️ ", ""); /// Returns the exit code if it's non-zero. macro_rules! handle_exit_code { ($code:expr) => {{ let (stdout, stderr, code) = $code; if code != 0 { return ::std::result::Result::Ok(code); } (stdout, stderr) }}; } /// Builds the server for the app, program arguments having been interpreted. This needs to know if we've built as part of this process /// so it can show an accurate progress count. This also takes a `MultiProgress` so it can be used truly atomically (which will have /// build spinners already on it if necessary). This also takes a `Mutex<String>` to inform the caller of the path of the server /// executable. fn build_server( dir: PathBuf, spinners: &MultiProgress, did_build: bool, exec: Arc<Mutex<String>>, is_release: bool, ) -> Result< ThreadHandle<impl FnOnce() -> Result<i32, ExecutionError>, Result<i32, ExecutionError>>, ExecutionError, > { let num_steps = match did_build { true => 4, false => 2, }; let target = dir.join(".perseus/server"); // Server building message let sb_msg = format!( "{} {} Building server", style(format!("[{}/{}]", num_steps - 1, num_steps)) .bold() .dim(), BUILDING_SERVER ); // We'll parallelize the building of the server with any build commands that are currently running // We deliberately insert the spinner at the end of the list let sb_spinner = spinners.insert(num_steps - 1, ProgressBar::new_spinner()); let sb_spinner = cfg_spinner(sb_spinner, &sb_msg); let sb_target = target; let sb_thread = spawn_thread(move || { let (stdout, _stderr) = handle_exit_code!(run_stage( vec![&format!( // This sets Cargo to tell us everything, including the executable path to the server "{} build --message-format json {}", env::var("PERSEUS_CARGO_PATH").unwrap_or_else(|_| "cargo".to_string()), if is_release { "--release" } else { "" } )], &sb_target, &sb_spinner, &sb_msg )?); let msgs: Vec<&str> = stdout.trim().split('\n').collect(); // If we got to here, the exit code was 0 and everything should've worked // The last message will just tell us that the build finished, the second-last one will tell us the executable path let msg = msgs.get(msgs.len() - 2); let msg = match msg { // We'll parse it as a Serde `Value`, we don't need to know everything that's in there Some(msg) => serde_json::from_str::<serde_json::Value>(msg) .map_err(|err| ExecutionError::GetServerExecutableFailed { source: err })?, None => return Err(ExecutionError::ServerExectutableMsgNotFound), }; let server_exec_path = msg.get("executable"); let server_exec_path = match server_exec_path { // We'll parse it as a Serde `Value`, we don't need to know everything that's in there Some(server_exec_path) => match server_exec_path.as_str() { Some(server_exec_path) => server_exec_path, None => return Err(ExecutionError::ParseServerExecutableFailed { err: "expected 'executable' field to be string".to_string() }), }, None => return Err(ExecutionError::ParseServerExecutableFailed { err: "expected 'executable' field in JSON map in second-last message, not present" .to_string() }), }; // And now the main thread needs to know about this let mut exec_val = exec.lock().unwrap(); *exec_val = server_exec_path.to_string(); Ok(0) }); Ok(sb_thread) } /// Runs the server at the given path, handling any errors therewith. This will likely be a black hole until the user manually terminates /// the process. fn run_server( exec: Arc<Mutex<String>>, dir: PathBuf, did_build: bool, ) -> Result<i32, ExecutionError> { let target = dir.join(".perseus/server"); let num_steps = match did_build { true => 4, false => 2, }; // First off, handle any issues with the executable path let exec_val = exec.lock().unwrap(); if exec_val.is_empty() { return Err(ExecutionError::ParseServerExecutableFailed { err: "mutex value empty, implies uncaught thread termination (please report this as a bug)" .to_string() }); } let server_exec_path = (*exec_val).to_string(); // Manually run the generated binary (invoking in the right directory context for good measure if it ever needs it in future) let child = Command::new(&server_exec_path) .current_dir(target) // We should be able to access outputs in case there's an error .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .map_err(|err| ExecutionError::CmdExecFailed { cmd: server_exec_path, source: err, })?; // Figure out what host/port the app will be live on let host = env::var("HOST").unwrap_or_else(|_| "localhost".to_string()); let port = env::var("PORT") .unwrap_or_else(|_| "8080".to_string()) .parse::<u16>() .map_err(|err| ExecutionError::PortNotNumber { source: err })?; // Give the user a nice informational message println!( " {} {} Your app is now live on <http://{host}:{port}>! To change this, re-run this command with different settings of the HOST/PORT environment variables.", style(format!("[{}/{}]", num_steps, num_steps)).bold().dim(), SERVING, host=host, port=port ); // Wait on the child process to finish (which it shouldn't unless there's an error), then perform error handling let output = child.wait_with_output().unwrap(); let exit_code = match output.status.code() { Some(exit_code) => exit_code, // If we have an exit code, use it None if output.status.success() => 0, // If we don't, but we know the command succeeded, return 0 (success code) None => 1, // If we don't know an exit code but we know that the command failed, return 1 (general error code) }; // Print `stderr` only if there's something therein and the exit code is non-zero if !output.stderr.is_empty() && exit_code != 0 { // We don't print any failure message other than the actual error right now (see if people want something else?) std::io::stderr().write_all(&output.stderr).unwrap(); return Ok(1); } Ok(0) } /// Builds the subcrates to get a directory that we can serve and then serves it. If possible, this will return the path to the server /// executable so that it can be used in deployment. pub fn serve(dir: PathBuf, opts: ServeOpts) -> Result<(i32, Option<String>), ExecutionError> { let spinners = MultiProgress::new(); let did_build = !opts.no_build; let should_run = !opts.no_run; // We need to have a way of knowing what the executable path to the server is let exec = Arc::new(Mutex::new(String::new())); // We can begin building the server in a thread without having to deal with the rest of the build stage yet let sb_thread = build_server( dir.clone(), &spinners, did_build, Arc::clone(&exec), opts.release, )?; // Only build if the user hasn't set `--no-build`, handling non-zero exit codes if did_build { let (sg_thread, wb_thread) = build_internal(dir.clone(), &spinners, 4, opts.release)?; let sg_res = sg_thread .join() .map_err(|_| ExecutionError::ThreadWaitFailed)??; let wb_res = wb_thread .join() .map_err(|_| ExecutionError::ThreadWaitFailed)??; if sg_res != 0 { return Ok((sg_res, None)); } else if wb_res != 0 { return Ok((wb_res, None)); } } // Handle errors from the server building let sb_res = sb_thread .join() .map_err(|_| ExecutionError::ThreadWaitFailed)??; if sb_res != 0 { return Ok((sb_res, None)); } // And now we can run the finalization stage (only if `--no-build` wasn't specified) if did_build { finalize(&dir.join(".perseus"))?; } // Now actually run that executable path if we should if should_run { let exit_code = run_server(Arc::clone(&exec), dir, did_build)?; Ok((exit_code, None)) } else { // The user doesn't want to run the server, so we'll give them the executable path instead let exec_str: String = (*exec.lock().unwrap()).to_string(); println!("Not running server because `--no-run` was provided. You can run it manually by running the following executable in `.perseus/server/`.\n{}", &exec_str); Ok((0, Some(exec_str))) } }
use crate::components::player::PlayerType; use oxygengine::prelude::*; #[derive(Debug, Copy, Clone)] pub enum GamePhase { Start, Game, End(Option<PlayerType>), Restart, } impl Default for GamePhase { fn default() -> Self { Self::Start } } impl GamePhase { pub fn is_game(self) -> bool { matches!(self, Self::Game) } pub fn is_restart(self) -> bool { matches!(self, Self::Restart) } } #[derive(Default)] pub struct Globals { pub camera: Option<Entity>, pub map_size: Option<Vec2>, pub phase: GamePhase, } impl Globals { pub fn start(&mut self, camera: Entity) { self.reset(); self.camera = Some(camera); } pub fn reset(&mut self) { self.camera = None; self.map_size = None; self.phase = GamePhase::Start; } }
#[doc = "Reader of register INTS"] pub type R = crate::R<u32, super::INTS>; #[doc = "Reader of field `FIFO`"] pub type FIFO_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Triggered when the sample FIFO reaches a certain level.\\n This level can be programmed via the FCS_THRESH field."] #[inline(always)] pub fn fifo(&self) -> FIFO_R { FIFO_R::new((self.bits & 0x01) != 0) } }
pub mod uniform;
#![cfg_attr(test, feature(test))] #![allow(unused_macros, unused_assignments)] #[cfg(test)] extern crate hex; #[cfg(test)] extern crate test; pub mod mem; mod util; // cryptographic hash function (CHF) pub mod hash; // Key derivation function (KDF) pub mod kdf; pub mod mac; pub mod blockmode; pub mod aeadcipher; pub mod blockcipher; pub mod streamcipher; #[cfg(feature = "openssh")] pub mod openssh; pub mod encoding;
// Definition for singly-linked list. struct Solution(); #[derive(PartialEq, Eq, Clone, Debug)] pub struct ListNode { pub val: i32, pub next: Option<Box<ListNode>> } impl ListNode { #[inline] fn new(val: i32) -> Self { ListNode { next: None, val } } } impl Solution { pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { if head.is_none() { return None; } let mut prev: Option<Box<ListNode>> = None; let mut curr: Option<Box<ListNode>> = head; while curr.is_some() { //拿走了Option,留下None在原地 let mut node = curr.take().unwrap(); println!("node:{:?}",node); // println!("first curr{:?}",curr); curr = node.next;//curr指向未翻转以及这一次循环也不会参与翻转的链表,拿走了部分的所有权 println!("{:?}",node); node.next = prev;//prev指向curr前面那部分,这一部分,又指向了prev,拿走了prev的所有权 // println!("node second:{:?}",node); prev = Some(node);//prev又拿走了node的所有权 println!("prev:{:?}",prev); println!("curr:{:?}",curr); println!("*******************"); println!("*******************"); } prev } } fn main(){ Solution::reverse_list(Some(Box::new(ListNode{val:1,next:Some(Box::new(ListNode{val:2,next:Some(Box::new(ListNode{val:3,next:Some(Box::new(ListNode{val:4,next:Some(Box::new(ListNode{val:5,next:None}))}))}))}))}))); }
fn main() { // Some target(e.g. wasm32-unknown-unknown) won't have this flag // defined since it has not features. let features = std::env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or_default(); let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); let out_path = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap()); let bindings_builder = bindgen::Builder::default().use_core().ctypes_prefix("cty"); if features.contains("sse4.1") || features.contains("sse2") { let bindings = bindings_builder .header("BLAKE2/sse/blake2.h") .generate() .expect("unable to generate bindings"); bindings .write_to_file(out_path.join("bindings.rs")) .expect("unable to write bindings"); cc::Build::new() .file("BLAKE2/sse/blake2b.c") .compile("libblake2b.a"); } else { let bindings = bindings_builder .header("BLAKE2/ref/blake2.h") .generate() .expect("unable to generate bindings"); bindings .write_to_file(out_path.join("bindings.rs")) .expect("unable to write bindings"); let mut build = cc::Build::new(); if target_arch == "riscv64" { // Blake2b only requires a small part of libc, e.g., stdint.h for // common type definitions, as well as prototypes for memory related // functions. It's thus fine to use libc headers from picolibc as // stubs here. build.include("/usr/lib/picolibc/riscv64-unknown-elf/include"); } build .file("BLAKE2/ref/blake2b-ref.c") .compile("libblake2b.a"); } }
use std::fmt; use itertools::izip; use super::*; use super::Spectrum; crate const LAMBDA_START: u32 = 400; crate const LAMBDA_END: u32 = 700; crate const NUM_SAMPLES: usize = 60; #[derive(Copy, Clone)] pub struct SampledSpectrum { pub c: [Float; NUM_SAMPLES], } impl Spectrum for SampledSpectrum { fn new(value: impl Into<Float>) -> Self { Self { c: [value.into(); NUM_SAMPLES], } } fn from_sampled(samples: &[SampledSpectrumData]) -> Self { let samples: Vec<_> = if !is_sorted(samples) { let mut samples: Vec<_> = samples.to_vec(); samples.sort_unstable(); samples } else { samples.to_vec() }; let mut r = Self::new(0.0); for (i, c) in r.iter_mut().enumerate() { // compute average of given SPD over 'ith' sample's range let lambda_start = float(LAMBDA_START as f32) .lerp(float(LAMBDA_END as f32), float(i as f32 / NUM_SAMPLES as f32)); let lambda_end = float(LAMBDA_START as f32) .lerp(float(LAMBDA_END as f32), float((i + 1) as f32 / NUM_SAMPLES as f32)); *c = average_samples(&samples[..], lambda_start, lambda_end); } r } fn from_rgb(rgb: [Float; 3], ty: SpectrumType) -> Self { let mut r = SampledSpectrum::new(0.0); let rgb_const = match ty { SpectrumType::Reflectance => &*RGB_REFL, SpectrumType::Illumination => &*RGB_ILLUM, }; if rgb[0] <= rgb[1] && rgb[0] <= rgb[2] { // red smallest r += rgb_const.white * rgb[0]; if rgb[1] <= rgb[2] { // green 2nd smallest r += rgb_const.cyan * (rgb[1] - rgb[0]); r += rgb_const.blue * (rgb[2] - rgb[1]); } else { // blue 2nd smallest r += rgb_const.cyan * (rgb[2] - rgb[0]); r += rgb_const.green * (rgb[1] - rgb[2]); } } else if rgb[1] <= rgb[0] && rgb[1] <= rgb[2] { // green smallest r += rgb_const.white * rgb[1]; if rgb[0] <= rgb[2] { // red 2nd smallest r += rgb_const.magenta * (rgb[0] - rgb[1]); r += rgb_const.blue * (rgb[2] - rgb[0]); } else { // blue 2nd smallest r += rgb_const.magenta * (rgb[2] - rgb[0]); r += rgb_const.red * (rgb[1] - rgb[2]); } } else { // blue smallest r += rgb_const.white * rgb[2]; if rgb[1] <= rgb[2] { // red 2nd smallest r += rgb_const.yellow * (rgb[0] - rgb[2]); r += rgb_const.green * (rgb[1] - rgb[0]); } else { // green 2nd smallest r += rgb_const.yellow * (rgb[1] - rgb[2]); r += rgb_const.red * (rgb[0] - rgb[1]); } } r.clamp(None, None) } fn from_xyz(xyz: [Float; 3], ty: SpectrumType) -> Self { let rgb = xyz_to_rgb(xyz); Self::from_rgb(rgb, ty) } fn y(&self) -> Float { let mut yy = float(0.0); for (c, y) in izip!(self.iter(), XYZ.y.iter()) { yy += *y * *c; } let scale = float(LAMBDA_END - LAMBDA_START) / float(CIE_Y_INTEGRAL * NUM_SAMPLES as f32); yy * scale } fn to_xyz(&self) -> [Float; 3] { let mut xyz = [float(0.0); 3]; let XyzSampledSpectrums { x, y, z } = &*XYZ; for (c, x, y, z) in izip!(self.iter(), x.iter(), y.iter(), z.iter()) { xyz[0] += *x * *c; xyz[1] += *y * *x; xyz[2] += *z * *c; } let scale = float(LAMBDA_END - LAMBDA_START) / float(CIE_Y_INTEGRAL * NUM_SAMPLES as f32); xyz[0] *= scale; xyz[1] *= scale; xyz[2] *= scale; xyz } fn to_rgb_spectrum(&self) -> RgbSpectrum { unimplemented!() } } impl fmt::Debug for SampledSpectrum { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SampledSpectrum {{ ... }}") } } impl PartialEq for SampledSpectrum { fn eq(&self, other: &Self) -> bool { **self == **other } } spectrum_impl!(SampledSpectrum);
#[derive(Debug)] pub enum LSPError { NotADigit, InvalidLength, } pub fn lsp(digits: &str, length: usize) -> Result<u32, LSPError> { if length == 0 { Ok(1) } else if length > digits.len() { Err(LSPError::InvalidLength) } else { let mut max_product = 0; for series in digits.as_bytes().windows(length) { let mut product = 1; for byte in series { product *= (*byte as char).to_digit(10).ok_or(LSPError::NotADigit)?; } if product > max_product { max_product = product; } } Ok(max_product) } }
use clap::{App, AppSettings}; use minitt_util::cli::{cli_completion_generation, GenShellSubCommand}; use structopt::StructOpt; #[derive(StructOpt)] #[structopt( about, name = "agda-tac", global_settings(&[AppSettings::ColoredHelp]) )] pub struct CliOptions { /// The input file to type-check (Notice: file should be UTF-8 encoded) #[structopt(name = "FILE")] pub file: Option<String>, /// Path to your agda executable #[structopt(long, name = "path")] pub agda: Option<String>, /// Print all commands that `agda-tac` sends to `agda` #[structopt(alias = "dc", long)] pub debug_command: bool, /// Check Agda version. #[structopt(alias = "check", long)] pub validate: bool, /// Allow working with existing files. #[structopt(alias = "allow-exist", long)] pub allow_existing_file: bool, /// Disable completion/hints/colored output in interaction #[structopt(short = "p", long)] pub plain: bool, /// Print all responses that `agda` sends to `agda-tac` #[structopt(alias = "dr", long)] pub debug_response: bool, #[structopt(subcommand)] completion: Option<GenShellSubCommand>, } fn app<'a, 'b>() -> App<'a, 'b> { let extra_help = "For extra help please head to \ https://github.com/ice1000/agda-mode/issues/new"; // Introduced a variable because stupid CLion :( let app: App = CliOptions::clap(); app.after_help(extra_help) } pub fn pre() -> CliOptions { let args: CliOptions = CliOptions::from_clap(&app().get_matches()); cli_completion_generation(&args.completion, app); args }
use async_trait::async_trait; #[cfg(not(target_arch = "wasm32"))] pub(crate) type HyperClient<C> = hyper::Client<C, hyper::Body>; #[cfg(all(feature = "tokio-rt", not(target_arch = "wasm32")))] pub(crate) type HttpsConnector = hyper_tls::HttpsConnector<hyper::client::HttpConnector>; #[cfg(all(feature = "tokio-rt", not(target_arch = "wasm32")))] pub(crate) type HyperHttpsClient = HyperClient<HttpsConnector>; #[cfg(target_arch = "wasm32")] pub struct WasmClient; /// A low level HTTP trait. #[async_trait(?Send)] pub trait HttpLowLevel<M = http::Method, H = http::HeaderMap> { /// Send a request and receive a response. async fn send( &self, method: M, uri: &str, headers: H, body: Vec<u8>, ) -> crate::Result<http::Response<Vec<u8>>>; } #[cfg(not(target_arch = "wasm32"))] #[async_trait(?Send)] impl<C> HttpLowLevel for HyperClient<C> where C: hyper::client::connect::Connect + Clone + Send + Sync + 'static, { async fn send( &self, method: http::Method, uri: &str, headers: http::HeaderMap, body: Vec<u8>, ) -> crate::Result<http::Response<Vec<u8>>> { // Making a builder let mut builder = http::Request::builder().method(method).uri(uri); // Adding headers if let Some(h) = builder.headers_mut() { *h = headers; } // Building it to a request let request = builder.body(body.into())?; // Sending and waiting for a response let response = self.request(request).await?; if response.status().is_success() { let (parts, body) = response.into_parts(); let body = hyper::body::to_bytes(body).await?.to_vec(); let response = http::Response::from_parts(parts, body); Ok(response) } else { return Err(response.status().into()); } } } #[cfg(target_arch = "wasm32")] #[async_trait(?Send)] impl HttpLowLevel for WasmClient { async fn send( &self, method: http::Method, uri: &str, headers: http::HeaderMap, body: Vec<u8>, ) -> crate::Result<http::Response<Vec<u8>>> { use js_sys::{Array, ArrayBuffer, Reflect, Uint8Array}; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; // Options to configure the request let mut opts = web_sys::RequestInit::new(); // Specifying the method opts.method(method.as_str()); // Pinning the body. let body_pinned = std::pin::Pin::new(body); if body_pinned.len() > 0 { // Creating a JS Typed Array which is a view to into wasm's linear memory. // It could be invalidated if the contents is moved, which is why // we are using `Pin`. // Read more [here](https://docs.rs/js-sys/0.3.51/js_sys/struct.Uint8Array.html#unsafety). let uint_8_array = unsafe { Uint8Array::view(&body_pinned) }; opts.body(Some(&uint_8_array)); } // Setting the request mode opts.mode(web_sys::RequestMode::Cors); // Making a request let request = web_sys::Request::new_with_str_and_init(&uri, &opts)?; // Adding headers for (name, value) in headers .iter() .map(|(x, y)| (x.as_str(), y.to_str().unwrap())) { request.headers().set(name, value)?; } let scope = WindowOrWorker::new(); // Fetching the request let promise = match scope { WindowOrWorker::Window(window) => window.fetch_with_request(&request), WindowOrWorker::Worker(worker) => worker.fetch_with_request(&request), }; // Converting a JS Promise to a Rust Future and awaiting let res = JsFuture::from(promise).await?; debug_assert!(res.is_instance_of::<web_sys::Response>()); let res: web_sys::Response = res.dyn_into().unwrap(); // Taking the response body let promise_array = res.array_buffer()?; let array = JsFuture::from(promise_array).await?; debug_assert!(array.is_instance_of::<js_sys::ArrayBuffer>()); let buf: ArrayBuffer = array.dyn_into().unwrap(); // Making a uint8 array let slice = Uint8Array::new(&buf); // Converting it to a Vec let body = slice.to_vec(); // Making a builder let mut builder = http::Response::builder().status(res.status()); // Adding headers for i in js_sys::try_iter(&res.headers())?.unwrap() { let array: Array = i?.into(); let values = array.values(); let prop = String::from("value").into(); let key = Reflect::get(values.next()?.as_ref(), &prop)? .as_string() .unwrap(); let value = Reflect::get(values.next()?.as_ref(), &prop)? .as_string() .unwrap(); builder = builder.header(&key, &value); } // Building it to a response let response = builder.body(body)?; if response.status().is_success() { Ok(response) } else { return Err(response.status().into()); } } } #[cfg(target_arch = "wasm32")] enum WindowOrWorker { Window(web_sys::Window), Worker(web_sys::WorkerGlobalScope), } #[cfg(target_arch = "wasm32")] impl WindowOrWorker { fn new() -> Self { use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; #[wasm_bindgen] extern "C" { type Global; #[wasm_bindgen(method, getter, js_name = Window)] fn window(this: &Global) -> wasm_bindgen::JsValue; #[wasm_bindgen(method, getter, js_name = WorkerGlobalScope)] fn worker(this: &Global) -> wasm_bindgen::JsValue; } let global: Global = js_sys::global().unchecked_into(); if !global.window().is_undefined() { Self::Window(global.unchecked_into()) } else if !global.worker().is_undefined() { Self::Worker(global.unchecked_into()) } else { panic!("Only supported in a browser or web worker"); } } }
//! Components for constructing HTTP responses. pub use tsukuyomi_macros::Responder; // re-export from izanami. #[doc(no_inline)] pub use izanami::http::{ body::Body as ResponseBody, response::{IntoResponse, Response}, }; use { crate::{ error::Error, // future::{Poll, TryFuture}, input::Input, upgrade::{NeverUpgrade, Upgrade}, util::Never, }, serde::Serialize, std::marker::PhantomData, }; /// Create an instance of `Response<T>` with the provided body and content type. fn make_response<T>(body: T, content_type: &'static str) -> Response where T: Into<ResponseBody>, { let mut response = Response::new(body.into()); response.headers_mut().insert( http::header::CONTENT_TYPE, http::header::HeaderValue::from_static(content_type), ); response } /// A trait that abstracts the "reply" to the client. /// /// # Derivation /// /// The custom derive `Responder` is provided for reduce boilerplates around /// trait implementations. /// /// The macro has a parameter `#[response(preset = "..")]`, which specifies /// the path to a type that implements a trait [`Preset`]: /// /// ``` /// # use tsukuyomi::output::{Json, Responder}; /// use serde::Serialize; /// /// #[derive(Debug, Serialize, Responder)] /// #[response(preset = "Json")] /// struct Post { /// title: String, /// text: String, /// } /// # fn main() {} /// ``` /// /// You can specify the additional trait bounds to type parameters /// by using the parameter `#[response(bound = "..")]`: /// /// ``` /// # use tsukuyomi::output::{Json, Responder}; /// # use serde::Serialize; /// #[derive(Debug, Responder)] /// #[response( /// preset = "Json", /// bound = "T: Serialize", /// bound = "U: Serialize", /// )] /// struct CustomValue<T, U> { /// t: T, /// u: U, /// } /// # fn main() {} /// ``` /// /// [`Preset`]: ./trait.Preset.html pub trait Responder { /// The type of asynchronous object to be ran after upgrading the protocol. type Upgrade: Upgrade; /// The error type that will be thrown by this responder. type Error: Into<Error>; /// The asynchronous task converted from this responder. type Respond: Respond<Upgrade = Self::Upgrade, Error = Self::Error>; /// Converts itself into a `Respond`. fn respond(self) -> Self::Respond; } /// The asynchronous task that generates a reply to client. pub trait Respond { type Upgrade: Upgrade; type Error: Into<Error>; fn poll_respond( &mut self, input: &mut Input<'_>, ) -> Poll<(Response, Option<Self::Upgrade>), Self::Error>; } impl<T> Respond for T where T: TryFuture, T::Ok: IntoResponse, { type Upgrade = NeverUpgrade; type Error = T::Error; fn poll_respond( &mut self, input: &mut Input<'_>, ) -> Poll<(Response, Option<Self::Upgrade>), Self::Error> { let output = futures01::try_ready!(self.poll_ready(input)); Ok((output.into_response(), None).into()) } } /// a branket impl of `Responder` for `IntoResponse`s. impl<T> Responder for T where T: IntoResponse, { type Upgrade = crate::upgrade::NeverUpgrade; type Error = Never; type Respond = self::impl_responder_for_T::IntoResponseRespond<T>; #[inline] fn respond(self) -> Self::Respond { self::impl_responder_for_T::IntoResponseRespond(Some(self)) } } #[allow(nonstandard_style)] mod impl_responder_for_T { use super::*; #[allow(missing_debug_implementations)] pub struct IntoResponseRespond<T>(pub(super) Option<T>); impl<T> TryFuture for IntoResponseRespond<T> { type Ok = T; type Error = Never; #[inline] fn poll_ready(&mut self, _: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> { let output = self.0.take().expect("the future has already been polled."); Ok(output.into()) } } } mod impl_responder_for_either { use { super::{Respond, Responder}, crate::{error::Error, input::Input, output::Response, util::Either}, futures01::Poll, }; impl<L, R> Responder for Either<L, R> where L: Responder, R: Responder, { type Upgrade = crate::util::Either<L::Upgrade, R::Upgrade>; type Error = Error; type Respond = EitherRespond<L::Respond, R::Respond>; fn respond(self) -> Self::Respond { match self { Either::Left(l) => EitherRespond::Left(l.respond()), Either::Right(r) => EitherRespond::Right(r.respond()), } } } #[allow(missing_debug_implementations)] pub enum EitherRespond<L, R> { Left(L), Right(R), } impl<L, R> Respond for EitherRespond<L, R> where L: Respond, R: Respond, { type Upgrade = crate::util::Either<L::Upgrade, R::Upgrade>; type Error = Error; fn poll_respond( &mut self, input: &mut Input<'_>, ) -> Poll<(Response, Option<Self::Upgrade>), Self::Error> { match self { EitherRespond::Left(l) => { let (res, upgrade) = futures01::try_ready!(l.poll_respond(input).map_err(Into::into)); Ok((res, upgrade.map(crate::util::Either::Left)).into()) } EitherRespond::Right(r) => { let (res, upgrade) = futures01::try_ready!(r.poll_respond(input).map_err(Into::into)); Ok((res, upgrade.map(crate::util::Either::Right)).into()) } } } } } /// A function to create a `Responder` using the specified `TryFuture`. pub fn respond<R, U>(respond: R) -> ResponderFn<R> where R: Respond, { ResponderFn(respond) } #[derive(Debug, Copy, Clone)] pub struct ResponderFn<R>(R); impl<R> Responder for ResponderFn<R> where R: Respond, { type Upgrade = R::Upgrade; type Error = R::Error; type Respond = R; #[inline] fn respond(self) -> Self::Respond { self.0 } } /// Creates a `Responder` from a function that returns its result immediately. /// /// The passed function can access the request context once when called. pub fn oneshot<F, T, E>(f: F) -> Oneshot<F> where F: FnOnce(&mut Input<'_>) -> Result<T, E>, T: IntoResponse, E: Into<Error>, { Oneshot(f) } #[derive(Debug, Copy, Clone)] pub struct Oneshot<F>(F); mod oneshot { use { super::{Error, Input, IntoResponse, Oneshot, Responder}, crate::future::{Poll, TryFuture}, }; impl<F, T, E> Responder for Oneshot<F> where F: FnOnce(&mut Input<'_>) -> Result<T, E>, T: IntoResponse, E: Into<Error>, { type Upgrade = crate::upgrade::NeverUpgrade; type Error = E; type Respond = OneshotRespond<F>; #[inline] fn respond(self) -> Self::Respond { OneshotRespond(Some(self.0)) } } #[allow(missing_debug_implementations)] pub struct OneshotRespond<F>(Option<F>); impl<F, T, E> TryFuture for OneshotRespond<F> where F: FnOnce(&mut Input<'_>) -> Result<T, E>, E: Into<Error>, { type Ok = T; type Error = E; fn poll_ready(&mut self, input: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> { let f = self.0.take().expect("the future has already polled"); f(input).map(Into::into) } } } /// A trait representing the *preset* for deriving the implementation of `Responder`. pub trait Preset<T> { type Upgrade: Upgrade; type Error: Into<Error>; type Respond: Respond<Upgrade = Self::Upgrade, Error = Self::Error>; fn respond(this: T) -> Self::Respond; } /// Creates a `Responder` using the specified preset and data. pub fn render<T, P>(data: T) -> Rendered<T, P> where P: Preset<T>, { Rendered(data, PhantomData) } /// Creates a JSON responder from the specified data. #[inline] pub fn json<T>(data: T) -> Rendered<T, Json> where T: Serialize, { render(data) } /// Creates a JSON response with pretty output from the specified data. #[inline] pub fn json_pretty<T>(data: T) -> Rendered<T, JsonPretty> where T: Serialize, { render(data) } /// Creates an HTML response using the specified data. #[inline] pub fn html<T>(data: T) -> Rendered<T, Html> where T: Into<ResponseBody>, { render(data) } /// A `Responder` that uses the specified preset. #[allow(missing_debug_implementations)] pub struct Rendered<T, P>(T, PhantomData<P>); impl<T, P> Responder for Rendered<T, P> where P: Preset<T>, { type Upgrade = P::Upgrade; type Error = P::Error; type Respond = P::Respond; fn respond(self) -> Self::Respond { P::respond(self.0) } } #[allow(missing_debug_implementations)] pub struct Json(()); mod json { use super::*; use { crate::{ future::{Poll, TryFuture}, upgrade::NeverUpgrade, }, serde::Serialize, }; impl<T> Preset<T> for Json where T: Serialize, { type Upgrade = NeverUpgrade; type Error = Error; type Respond = JsonRespond<T>; fn respond(this: T) -> Self::Respond { JsonRespond(this) } } #[allow(missing_debug_implementations)] pub struct JsonRespond<T>(T); impl<T> TryFuture for JsonRespond<T> where T: Serialize, { type Ok = Response; type Error = Error; fn poll_ready(&mut self, _: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> { let body = serde_json::to_vec(&self.0).map_err(crate::error::internal_server_error)?; Ok(crate::output::make_response(body, "application/json").into()) } } } #[allow(missing_debug_implementations)] pub struct JsonPretty(()); mod json_pretty { use super::*; use { crate::{ future::{Poll, TryFuture}, upgrade::NeverUpgrade, }, serde::Serialize, }; impl<T> Preset<T> for JsonPretty where T: Serialize, { type Upgrade = NeverUpgrade; type Error = Error; type Respond = JsonPrettyRespond<T>; fn respond(this: T) -> Self::Respond { JsonPrettyRespond(this) } } #[allow(missing_debug_implementations)] pub struct JsonPrettyRespond<T>(T); impl<T> TryFuture for JsonPrettyRespond<T> where T: Serialize, { type Ok = Response; type Error = Error; fn poll_ready(&mut self, _: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> { let body = serde_json::to_vec_pretty(&self.0) // .map_err(crate::error::internal_server_error)?; Ok(crate::output::make_response(body, "application/json").into()) } } } #[allow(missing_debug_implementations)] pub struct Html(()); mod html { use super::*; use crate::{ future::{Poll, TryFuture}, upgrade::NeverUpgrade, }; impl<T> Preset<T> for Html where T: Into<ResponseBody>, { type Upgrade = NeverUpgrade; type Error = Error; type Respond = HtmlRespond; fn respond(this: T) -> Self::Respond { HtmlRespond(Some(this.into())) } } #[allow(missing_debug_implementations)] pub struct HtmlRespond(Option<ResponseBody>); impl TryFuture for HtmlRespond { type Ok = Response; type Error = Error; fn poll_ready(&mut self, _: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> { let body = self.0.take().expect("the future has already been polled."); Ok(crate::output::make_response(body, "text/html").into()) } } }
use nannou::prelude::*; pub struct IntColor { r: i32, g: i32, b: i32, } impl IntColor { pub fn new(r: i32, g: i32, b: i32) -> IntColor { IntColor { r, g, b } } pub fn as_srgb(&self) -> Srgba { srgba((self.r as f32) / 256.0, (self.g as f32) / 256.0, (self.b as f32) / 256.0, 1.0) } pub fn as_srgba(&self, alpha: f32) -> Srgba { srgba((self.r as f32) / 256.0, (self.g as f32) / 256.0, (self.b as f32) / 256.0, alpha) } }
//! Networking primitives //! mod tcp; mod udp; pub use self::tcp::{TcpListener, TcpStream}; pub use self::udp::UdpSocket;
//! This crate is an implementation of behavior trees in Rust. It is largely //! based on behavior trees as described by Marzinotto et al. ^1 and was //! designed to be used on an actual robot using LCM for communication. //! //! A nice overview of behavior trees can be found on //! [Craft AI's website](http://www.craft.ai/blog/bt-101-behavior-trees-grammar-basics/). //! //! 1: Marzinotto, Alejandro, et al. "Towards a unified behavior trees //! framework for robot control." Robotics and Automation (ICRA), 2014 IEEE //! International Conference on. IEEE, 2014. #[macro_use] extern crate log; mod bt; pub use crate::bt::BehaviorTree; pub mod node; mod status; pub use crate::status::Status; pub mod std_nodes;
use crate::*; use reusable_fmt::fmt; pub struct Generator; impl Generator { pub fn child_account_creation( coin_type: &str, child_address: u128, auth_key_prefix: &str, all_currencies: bool, initial_bal: u64, ) -> String { TEMPLATE_CHILD_ACC_CREATE!( coin_type, child_address = child_address, auth_key_prefix = auth_key_prefix, all_currencies = all_currencies, initial_bal = initial_bal ) } pub fn payment_p2p( coin_type: &str, receiver: u128, amount: u64, meta_hex: Option<&str>, meta_sig_hex: Option<&str>, ) -> String { let mut b1 = String::new(); let mut b2 = String::new(); let metadata = meta_hex .map(|h| { b1 = format!("x\"{}\"", h); b1.as_str() }) .unwrap_or("Vector::empty<u8>()"); let meta_sig = meta_sig_hex .map(|h| { b2 = format!("x\"{}\"", h); b2.as_str() }) .unwrap_or("Vector::empty<u8>()"); TEMPLATE_PAYMENT_P2P!( coin_type, receiver = receiver, amount = amount, metadata = metadata, meta_sig = meta_sig ) } }
use anyhow::{anyhow, Result}; use log::debug; use std::cell::RefCell; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use structopt::StructOpt; use tree_sitter::{Language, Parser, Query, QueryCursor}; #[derive(StructOpt)] struct Opt { #[structopt(long, parse(from_os_str))] root: PathBuf, #[structopt(long, parse(from_os_str))] output: PathBuf, } struct App { lang: Language, output: RefCell<File>, include_query: Query, definition_query: Query, use_query: Query, } impl App { fn new(opt: &Opt) -> Result<Self> { let output = RefCell::new(File::create(&opt.output)?); let lang = tree_sitter_coremake::language(); Ok(Self { lang, output, include_query: Query::new(lang, "(include (string_literal) @glob)")?, definition_query: Query::new( lang, "(definition (identifier) @identifier (block) @block)", )?, use_query: Query::new(lang, "(use_statement (identifier) @identifier)")?, }) } fn parse_real(&self, proj: &Path) -> Result<()> { let mut parser = Parser::new(); parser.set_language(self.lang)?; debug!("Parsing {:?}", proj); let text = std::fs::read_to_string(proj)?; let text = text.as_bytes(); let tree = parser .parse(text, None) .ok_or_else(|| anyhow!("Could not parse input"))?; let mut cursor = QueryCursor::new(); for include in cursor.matches(&self.include_query, tree.root_node(), text) { let pattern = include.captures[0].node.utf8_text(text)?.trim_matches('"'); let base = proj.parent().ok_or_else(|| anyhow!("No parent"))?; let walker = globwalk::GlobWalkerBuilder::from_patterns(base, &[pattern]) .build()? .into_iter() .filter_map(Result::ok); for proj in walker { self.parse_real(proj.path())?; } } let mut output = self.output.borrow_mut(); for def in cursor.matches(&self.definition_query, tree.root_node(), text) { let from = def.captures[0].node.utf8_text(text)?; let mut cursor = QueryCursor::new(); for use_target in cursor.matches(&self.use_query, def.captures[1].node, text) { let to = use_target.captures[0].node.utf8_text(text)?; writeln!(output, " \"{}\" -> \"{}\";", from, to)?; } } Ok(()) } fn parse(&self, proj: &Path) -> Result<()> { { let mut output = self.output.borrow_mut(); writeln!(output, "digraph Uses {{")?; writeln!(output, " ratio=1.3;")?; } self.parse_real(proj)?; let mut output = self.output.borrow_mut(); writeln!(output, "}}")?; Ok(()) } } fn main() -> Result<()> { env_logger::init(); let opt = Opt::from_args(); App::new(&opt)?.parse(&opt.root)?; Ok(()) }
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or distributed except according to those terms. Please review the Licences for the // specific language governing permissions and limitations relating to use of the SAFE Network // Software. //! get_if_addrs-sys #![doc( html_logo_url = "https://raw.githubusercontent.com/maidsafe/QA/master/Images/ maidsafe_logo.png", html_favicon_url = "http://maidsafe.net/img/favicon.ico", html_root_url = "http://maidsafe.github.io/get_if_addrs" )] // For explanation of lint checks, run `rustc -W help` or see // https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid( exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings )] #![deny( bad_style, deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true )] #![warn( trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] #![allow( box_pointers, missing_copy_implementations, missing_debug_implementations, variant_size_differences )] #![cfg_attr( feature = "cargo-clippy", deny(clippy, unicode_not_nfc, wrong_pub_self_convention, option_unwrap_used) )] #![cfg_attr(feature = "cargo-clippy", allow(use_debug, too_many_arguments))] #![cfg(target_os = "android")] extern crate libc; use libc::*; #[allow(missing_docs)] #[repr(C)] #[derive(Debug)] pub struct ifaddrs { pub ifa_next: *mut ifaddrs, pub ifa_name: *mut c_char, pub ifa_flags: ::c_uint, pub ifa_addr: *mut ::sockaddr, pub ifa_netmask: *mut ::sockaddr, pub ifa_ifu: *mut ::sockaddr, pub ifa_data: *mut ::c_void, } extern "C" { pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; pub fn freeifaddrs(ifa: *mut ::ifaddrs); }
#[macro_use] extern crate clap; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::{BufReader, SeekFrom}; use std::path::Path; mod args; mod errors; use crate::args::Config; fn main() { match args::parse_command_line() { Ok(config) => { for filename in &config.filenames { println!("Hex dump of {}", filename); if let Err(e) = hex_dump_file(Path::new(&filename), &config) { eprintln!("Failed to process '{}'.\nReason: {}", filename, e); } } } Err(e) => eprintln!("Error parsing command line: {}", e), } } /// Prints a hex dump of the given file. How the hex dump is printed is governed by the configs. fn hex_dump_file(filename: &Path, config: &Config) -> io::Result<()> { // How does the user want us to print the offset? let print_offset: fn(u64) = match (config.uppercase, config.octal, config.decimal) { (true, false, false) => |n| print!("{:08X}:", n), (_, true, false) => |n| print!("{:12o}:", n), (_, false, true) => |n| print!("{:10}:", n), (false, false, false) | _ => |n| print!("{:08x}:", n), }; let mut file = BufReader::new(File::open(filename)?); // Skip over 'skip' bytes. file.seek(SeekFrom::Start(config.skip as u64))?; // Limit ourselves to 'length' bytes. let mut file = file.take(config.length as u64); let mut buffer = vec![0; config.width]; let mut offset = config.skip; loop { match file.read(&mut buffer) { Ok(0) => break, Ok(len) => { print_offset(offset); hex_dump_line( &buffer[..len], buffer.len(), config.uppercase, config.octal, config.decimal, ); offset += len as u64; } Err(e) => return Err(e), } } Ok(()) } /// Prints a hex dump of a line supplied in a buffer. fn hex_dump_line(buffer: &[u8], max_size: usize, uppercase: bool, octal: bool, decimal: bool) { // How does the user want us to print each byte? let print_byte: fn(u8) = match (uppercase, octal, decimal) { (true, false, false) => |n| print!("{:02X} ", n), (_, true, false) => |n| print!("{:03o} ", n), (_, false, true) => |n| print!("{:03} ", n), (false, false, false) | _ => |n| print!("{:02x} ", n), }; // Print the buffer as numbers in the requested format, inserting an extra space before every 8th number. for i in 0..max_size { if i.trailing_zeros() >= 3 { print!(" "); } if i < buffer.len() { let b = buffer[i]; print_byte(b); } else { print!(" "); } } print!(" "); // Print the buffer as ASCII, replacing non-printable characters with a '.'. for b in buffer { print!( "{}", if *b >= 32 && *b < 127 { *b as char } else { '.' } ); } println!(); }
#![crate_id = "docker#0.1"] #![comment = "Rust Docker Client"] #![license = "MIT/ASL2"] #![crate_type = "dylib"] #![crate_type = "rlib"] #![feature (globs, macro_rules)] extern crate collections; extern crate debug; extern crate serialize; mod http; pub mod common; pub mod docker;
use std::sync::Arc; use eyre::Report; use crate::{ core::{commands::CommandData, Context}, embeds::EmbedData, embeds::OsuTrackerMapsEmbed, pagination::{OsuTrackerMapsPagination, Pagination}, util::{ constants::{GENERAL_ISSUE, OSUTRACKER_ISSUE}, numbers, MessageExt, }, BotResult, }; pub(super) async fn maps_(ctx: Arc<Context>, data: CommandData<'_>, pp: u32) -> BotResult<()> { let entries = match ctx.clients.custom.get_osutracker_pp_groups().await { Ok(groups) => match groups.into_iter().find(|group| group.number == pp) { Some(group) => group.list, None => { error!("received no osutracker pp group with number={pp}"); return data.error(&ctx, GENERAL_ISSUE).await; } }, Err(err) => { let _ = data.error(&ctx, OSUTRACKER_ISSUE).await; return Err(err.into()); } }; let pages = numbers::div_euclid(10, entries.len()); let initial = &entries[..entries.len().min(10)]; let embed = OsuTrackerMapsEmbed::new(pp, initial, (1, pages)) .into_builder() .build(); let response_raw = data.create_message(&ctx, embed.into()).await?; if entries.len() <= 10 { return Ok(()); } let response = response_raw.model().await?; let pagination = OsuTrackerMapsPagination::new(response, pp, entries); let owner = data.author()?.id; tokio::spawn(async move { if let Err(err) = pagination.start(&ctx, owner, 60).await { warn!("{:?}", Report::new(err)); } }); Ok(()) }
use crate::logic::main::{get_distance, get_slope}; use crate::Wall; use macroquad::prelude::*; use std::collections::BTreeMap; pub struct Display { pub x: f32, pub y: f32, pub w: f32, pub h: f32, } impl Display { pub fn draw( &self, slits: Vec<Option<(f32, Vec2, &Wall)>>, sprite_slits: Vec<Vec<(f32, Vec2, &Wall)>>, camera_position: Vec2, use_new: bool, ) { let cy = self.h / 2.0; draw_rectangle(self.x, self.y, self.w, cy, DARKGRAY); draw_rectangle(self.x, self.y + cy, self.w, cy, GRAY); let slit_count = slits.len() as f32; let slit_width: f32 = self.w / slit_count; slits.iter().enumerate().for_each(|(i, slit)| { if let Some((distance_ratio, point, wall)) = slit { let slit_height = self.h * distance_ratio; let wall_length = wall.get_length(); let (m1, m2) = (get_slope(camera_position, *point), wall.slope()); let ray_angle = m1.atan(); let brightness = 0.2 + (ray_angle - m2.atan()).abs(); let start_d = get_distance(*point, wall.get_start()); let wall_len_ratio = start_d / wall_length; let texture_width = wall.texture.width(); let texture_slit_width = texture_width / wall_length / slit_count; let dest_size = vec2(slit_width, slit_height); let source = Rect::new( wall_len_ratio * texture_width + i as f32 * texture_slit_width, 0.0, texture_slit_width, texture_width, ); draw_texture_ex( wall.texture, self.x + (i as f32 * slit_width), self.y + cy - slit_height / 2.0, Color::from_vec(vec4(brightness, brightness, brightness, 1.0)), DrawTextureParams { dest_size: Some(dest_size), source: Some(source), rotation: 0.0, pivot: None, flip_x: false, flip_y: false, }, ) } }); if use_new { //let mut re_ordered_sprite_slits: Vec<Vec<(f32, Vec2, &Wall)>> = Vec::new(); let mut ordered_sprite_slits: BTreeMap<usize, Vec<(usize, f32, Vec2, &Wall)>> = BTreeMap::new(); sprite_slits.iter().enumerate().for_each(|(j, slits)| { slits.iter().enumerate().for_each(|(i, slit)| { let (a, b, c) = *slit; if let Some(inner_slits) = ordered_sprite_slits.get_mut(&i) { inner_slits.push((j, a, b, c)); } else { ordered_sprite_slits.insert(i, vec![(j, a, b, c)]); } }); }); ordered_sprite_slits.values().for_each(|slits| { slits .iter() .for_each(|(i, distance_ratio_s, point_s, wall_s)| { let i = *i as f32; let slit_height = self.h * distance_ratio_s; let wall_length = wall_s.get_length(); let wall_start = wall_s.get_start(); let start_d = get_distance(*point_s, wall_start); let wall_len_ratio = start_d / wall_length; let texture_width = wall_s.texture.width(); let texture_slit_width = texture_width / wall_length / slit_count; let dest_size = vec2(slit_width, slit_height); let source = Rect::new( wall_len_ratio * texture_width + i * texture_slit_width, 0.0, texture_slit_width, texture_width, ); draw_texture_ex( wall_s.texture, self.x + (i * slit_width), self.y + cy - slit_height / 2.0, //WHITE, Color::from_vec(vec4(1.0, 1.0, 1.0, 2.0 - distance_ratio_s)), DrawTextureParams { dest_size: Some(dest_size), source: Some(source), rotation: 0.0, pivot: None, flip_x: false, flip_y: false, }, ) }); }); } else { sprite_slits.iter().enumerate().for_each(|(i, slits)| { slits .iter() .for_each(|(distance_ratio_s, point_s, wall_s)| { let slit_height = self.h * distance_ratio_s; let wall_length = wall_s.get_length(); let wall_start = wall_s.get_start(); let start_d = get_distance(*point_s, wall_start); let wall_len_ratio = start_d / wall_length; let texture_width = wall_s.texture.width(); let texture_slit_width = texture_width / wall_length / slit_count; let dest_size = vec2(slit_width, slit_height); let source = Rect::new( wall_len_ratio * texture_width + i as f32 * texture_slit_width, 0.0, texture_slit_width, texture_width, ); draw_texture_ex( wall_s.texture, self.x + (i as f32 * slit_width), self.y + cy - slit_height / 2.0, //WHITE, Color::from_vec(vec4(1.0, 1.0, 1.0, 2.0 - distance_ratio_s)), DrawTextureParams { dest_size: Some(dest_size), source: Some(source), rotation: 0.0, pivot: None, flip_x: false, flip_y: false, }, ) }); }); } } }
use anyhow::{anyhow, Context, Result}; use clap::{Arg, ArgAction}; use file_utils::{prepare_and_check_input_paths, set_extension, translate_to_output_path}; use render::RenderOptions; use std::collections::{BTreeMap, HashMap}; use std::fs::File; use std::io::BufReader; mod diagnostics; mod dirgraphsvg; mod file_utils; mod gsn; mod render; mod yaml_fix; use diagnostics::Diagnostics; use dirgraphsvg::escape_text; use gsn::{GsnDocumentNode, GsnNode, Module, ModuleInformation}; const MODULE_INFORMATION_NODE: &str = "module"; /// /// Main entry point. /// /// fn main() -> Result<()> { let app = clap::command!() .arg( Arg::new("INPUT") .help("Sets the input file(s) to use. Only relative paths are accepted.") .action(ArgAction::Append) .required(true), ) .arg( Arg::new("CHECKONLY") .help("Only check the input file(s), but do not output graphs.") .short('c') .long("check") .action(ArgAction::SetTrue) .help_heading("CHECKS"), ) .arg( Arg::new("EXCLUDED_MODULE") .help("Exclude this module from reference checks.") .short('x') .long("exclude") .action(ArgAction::Append) .help_heading("CHECKS"), ) .arg( Arg::new("NO_ARGUMENT_VIEW") .help("Do not output of argument view for provided input files.") .short('N') .long("no-arg") .action(ArgAction::SetTrue) .help_heading("OUTPUT"), ) .arg( Arg::new("COMPLETE_VIEW") .help("Output the complete view to file with name <COMPLETE_VIEW>.") .short('f') .long("full") .action(ArgAction::Set) .default_value("complete.svg") .conflicts_with_all(["CHECKONLY", "NO_COMPLETE_VIEW"]) .help_heading("OUTPUT"), ) .arg( Arg::new("NO_COMPLETE_VIEW") .help("Do not output the complete view.") .short('F') .long("no-full") .action(ArgAction::SetTrue) .conflicts_with("COMPLETE_VIEW") .help_heading("OUTPUT"), ) .arg( Arg::new("ARCHITECTURE_VIEW") .help("Output the architecture view to file with name <ARCHITECTURE_VIEW>.") .short('a') .long("arch") .action(ArgAction::Set) .default_value("architecture.svg") .conflicts_with_all(["CHECKONLY", "NO_ARCHITECTURE_VIEW"]) .help_heading("OUTPUT"), ) .arg( Arg::new("NO_ARCHITECTURE_VIEW") .help("Do not output the architecture view.") .short('A') .long("no-arch") .action(ArgAction::SetTrue) .conflicts_with("ARCHITECTURE_VIEW") .help_heading("OUTPUT"), ) .arg( Arg::new("EVIDENCES") .help("Output list of all evidences to file with name <EVIDENCES>.") .short('e') .long("evidences") .action(ArgAction::Set) .default_value("evidences.md") .conflicts_with_all(["CHECKONLY", "NO_EVIDENCES"]) .help_heading("OUTPUT"), ) .arg( Arg::new("NO_EVIDENCES") .help("Do not output list of all evidences.") .short('E') .long("no-evidences") .action(ArgAction::SetTrue) .conflicts_with("EVIDENCES") .help_heading("OUTPUT"), ) .arg( Arg::new("OUTPUT_DIRECTORY") .help("Emit all output files to directory <OUTPUT_DIRECTORY>.") .short('o') .long("output-dir") .action(ArgAction::Set) .default_value(".") .conflicts_with("CHECKONLY") .help_heading("OUTPUT"), ) .arg( Arg::new("LAYERS") .help("Output additional layer. Can be used multiple times.") .short('l') .long("layer") .action(ArgAction::Append) .use_value_delimiter(true) .conflicts_with("CHECKONLY") .help_heading("OUTPUT MODIFICATION"), ) .arg( Arg::new("STYLESHEETS") .help("Links a stylesheet in SVG output. Can be used multiple times.") .short('s') .long("stylesheet") .action(ArgAction::Append) .conflicts_with("CHECKONLY") .help_heading("OUTPUT MODIFICATION"), ) .arg( Arg::new("EMBED_CSS") .help("Embed stylehseets instead of linking them.") .short('t') .long("embed-css") .action(ArgAction::SetTrue) .conflicts_with("CHECKONLY") .help_heading("OUTPUT MODIFICATION"), ) // .arg( // Arg::new("MASK_MODULE") // .help("Do not unroll this module in the complete view.") // .short('m') // .long("mask") // .multiple_occurrences(true) // .takes_value(true) // .requires("COMPLETE_VIEW") // .help_heading("OUTPUT MODIFICATION"), // ) .arg( Arg::new("NO_LEGEND") .help("Do not output a legend based on module information.") .short('G') .long("no-legend") .action(ArgAction::SetTrue) .conflicts_with("CHECKONLY") .help_heading("OUTPUT MODIFICATION"), ) .arg( Arg::new("FULL_LEGEND") .help("Output a legend based on all module information.") .short('g') .long("full-legend") .action(ArgAction::SetTrue) .conflicts_with("CHECKONLY") .help_heading("OUTPUT MODIFICATION"), ); let matches = app.get_matches(); let mut inputs: Vec<String> = matches .get_many::<String>("INPUT") .into_iter() .flatten() .cloned() .collect(); let layers = matches .get_many::<String>("LAYERS") .into_iter() .flatten() .map(AsRef::as_ref) .collect::<Vec<_>>(); let excluded_modules = matches .get_many::<String>("EXCLUDED_MODULE") .into_iter() .flatten() .map(AsRef::as_ref) .collect::<Vec<_>>(); let mut diags = Diagnostics::default(); let mut nodes = BTreeMap::<String, GsnNode>::new(); // Module name to module mapping let mut modules: HashMap<String, Module> = HashMap::new(); // Read input let common_ancestors = prepare_and_check_input_paths(&mut inputs)?; read_inputs(&inputs, &mut nodes, &mut modules, &mut diags)?; // Validate validate_and_check(&mut nodes, &modules, &mut diags, &excluded_modules, &layers); if diags.errors == 0 && !matches.get_flag("CHECKONLY") { let render_options = RenderOptions::from(&matches); // Output views print_outputs(nodes, &modules, &render_options, common_ancestors)?; } // Output diagnostic messages output_messages(&diags) } /// /// Read inputs /// /// fn read_inputs( inputs: &[String], nodes: &mut BTreeMap<String, GsnNode>, modules: &mut HashMap<String, Module>, diags: &mut Diagnostics, ) -> Result<()> { for input in inputs { let reader = BufReader::new(File::open(input).context(format!("Failed to open file {input}"))?); let mut n: BTreeMap<String, GsnDocumentNode> = serde_yaml::from_reader(reader) .map(|n: yaml_fix::YamlFixMap<String, GsnDocumentNode>| n.into_inner()) .map_err(|e| { anyhow!(format!( "No valid GSN element can be found starting from line {}.\n\ This typically means that the YAML is completely invalid, or \n\ the `text:` attribute is missing for an element.\n\ Original error message: {}.", e.location() .map(|e| e.line().to_string()) .unwrap_or_else(|| "unknown".to_owned()), e )) }) .context(format!("Failed to parse YAML from file {input}"))?; let meta: ModuleInformation = match n.remove_entry(MODULE_INFORMATION_NODE) { Some((_, GsnDocumentNode::ModuleInformation(x))) => x, _ => { let module_name = escape_text(input); ModuleInformation { name: module_name.to_owned(), brief: None, extends: None, additional: BTreeMap::new(), } } }; // Add filename and module name to module list let module = meta.name.to_owned(); if let std::collections::hash_map::Entry::Vacant(e) = modules.entry(module.to_owned()) { e.insert(Module { relative_module_path: input.to_owned().to_owned(), meta, }); } else { diags.add_error( Some(&module), format!( "C06: Module name {} in {} was already present in {}.", module, input, modules.get(&module).unwrap().relative_module_path // unwrap is ok, otherwise Entry would not have been Vacant ), ); } // Check for duplicates, since they might be in separate files. let node_names: Vec<String> = n.keys().cloned().collect(); for node_name in node_names { if let Some((k, v)) = n.remove_entry(&node_name) { if let std::collections::btree_map::Entry::Vacant(e) = nodes.entry(k.to_owned()) { match v { GsnDocumentNode::GsnNode(mut x) => { // Remember module for node x.module = module.to_owned(); e.insert(x); } _ => unreachable!(), // There can be only one MetaNode } } else { diags.add_error( Some(&module), format!( "C07: Element {} in {} was already present in {}.", k, input, nodes.get(&k).unwrap().module // unwrap is ok, otherwise Entry would not have been Vacant ), ); break; } } } } if nodes.is_empty() { Err(anyhow!("No input elements found.")) } else { Ok(()) } } /// /// Validate and check modules /// /// /// /// fn validate_and_check( nodes: &mut BTreeMap<String, GsnNode>, modules: &HashMap<String, Module>, diags: &mut Diagnostics, excluded_modules: &[&str], layers: &Vec<&str>, ) { for (module_name, module_info) in modules { // Validation for well-formedness is done unconditionally. gsn::validation::validate_module(diags, module_name, module_info, nodes); if diags.errors > 0 { break; } } if diags.errors == 0 { gsn::extend_modules(diags, nodes, modules); gsn::check::check_nodes(diags, nodes, excluded_modules); if !layers.is_empty() { gsn::check::check_layers(diags, nodes, layers); } } } /// /// Print outputs /// /// /// /// fn print_outputs( nodes: BTreeMap<String, GsnNode>, modules: &HashMap<String, Module>, render_options: &RenderOptions, common_ancestors: String, ) -> Result<()> { let output_path = &render_options.output_directory; if !render_options.skip_argument { for (module_name, module) in modules { let output_path = set_extension( &translate_to_output_path(output_path, &module.relative_module_path, None)?, "svg", ); let mut output_file = Box::new( File::create(&output_path) .context(format!("Failed to open output file {output_path}"))?, ) as Box<dyn std::io::Write>; render::render_argument( &mut output_file, module_name, modules, &nodes, render_options, )?; } } if modules.len() > 1 { if let Some(architecture_filename) = &render_options.architecture_filename { let arch_output_path = translate_to_output_path( output_path, architecture_filename, Some(&common_ancestors), )?; let mut output_file = File::create(&arch_output_path) .context(format!("Failed to open output file {arch_output_path}"))?; let deps = crate::gsn::calculate_module_dependencies(&nodes); render::render_architecture( &mut output_file, modules, deps, render_options, &arch_output_path, output_path, )?; } if let Some(complete_filename) = &render_options.complete_filename { let output_path = translate_to_output_path(output_path, complete_filename, Some(&common_ancestors))?; let mut output_file = File::create(&output_path) .context(format!("Failed to open output file {output_path}"))?; render::render_complete(&mut output_file, &nodes, render_options)?; } } if let Some(evidences_filename) = &render_options.evidences_filename { let output_path = translate_to_output_path(output_path, evidences_filename, Some(&common_ancestors))?; let mut output_file = File::create(&output_path) .context(format!("Failed to open output file {output_path}"))?; render::render_evidences(&mut output_file, &nodes, render_options)?; } Ok(()) } /// /// Render to dot-file if not only validation is active. /// Output summary of warnings and errors. /// fn output_messages(diags: &Diagnostics) -> Result<()> { for msg in &diags.messages { eprintln!("{msg}"); } if diags.errors == 0 { if diags.warnings > 0 { eprintln!("Warning: {} warnings detected.", diags.warnings); } Ok(()) } else { Err(anyhow!( "{} errors and {} warnings detected.", diags.errors, diags.warnings )) } } #[cfg(test)] mod test { use crate::diagnostics::Diagnostics; #[test] fn check_output_messages_errors() { let d = Diagnostics { warnings: 2, errors: 3, ..Default::default() }; let res = crate::output_messages(&d); assert!(res.is_err()); assert_eq!( format!("{:?}", res), "Err(3 errors and 2 warnings detected.)" ); } #[test] fn check_output_messages_warnings() { let d = Diagnostics { warnings: 5, errors: 0, ..Default::default() }; let res = crate::output_messages(&d); assert!(res.is_ok()); assert_eq!(format!("{:?}", res), "Ok(())"); } #[test] fn check_output_messages_no() { let d = Diagnostics { warnings: 0, errors: 0, ..Default::default() }; let res = crate::output_messages(&d); assert!(res.is_ok()); assert_eq!(format!("{:?}", res), "Ok(())"); } }
pub const _BEGIN: &str = "\u{001b}"; pub const _END: &str = "\u{001b}[0m"; #[macro_export] macro_rules! color { ($name:ident, $color:expr) => { /// A Wrapper struct generated by the color! macro that wraps /// struct formatter output in terminal escape sequences. pub struct $name<T>(pub T); impl<T: core::fmt::Debug> core::fmt::Debug for $name<T> { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "{}{}{:?}{}", $crate::macros::_BEGIN, $color, self.0, $crate::macros::_END) } } impl<T: core::fmt::Display> core::fmt::Display for $name<T> { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "{}{}{}{}", $crate::macros::_BEGIN, $color, self.0, $crate::macros::_END) } } impl<T> core::ops::Deref for $name<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> core::ops::DerefMut for $name<T> { //type Target = T; fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } } }
#[doc = "Reader of register RCC_APB4RSTCLRR"] pub type R = crate::R<u32, super::RCC_APB4RSTCLRR>; #[doc = "Writer for register RCC_APB4RSTCLRR"] pub type W = crate::W<u32, super::RCC_APB4RSTCLRR>; #[doc = "Register RCC_APB4RSTCLRR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_APB4RSTCLRR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "LTDCRST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LTDCRST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing releases the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<LTDCRST_A> for bool { #[inline(always)] fn from(variant: LTDCRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LTDCRST`"] pub type LTDCRST_R = crate::R<bool, LTDCRST_A>; impl LTDCRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LTDCRST_A { match self.bits { false => LTDCRST_A::B_0X0, true => LTDCRST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == LTDCRST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == LTDCRST_A::B_0X1 } } #[doc = "Write proxy for field `LTDCRST`"] pub struct LTDCRST_W<'a> { w: &'a mut W, } impl<'a> LTDCRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LTDCRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(LTDCRST_A::B_0X0) } #[doc = "Writing releases the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(LTDCRST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "DSIRST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DSIRST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing releases the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<DSIRST_A> for bool { #[inline(always)] fn from(variant: DSIRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DSIRST`"] pub type DSIRST_R = crate::R<bool, DSIRST_A>; impl DSIRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DSIRST_A { match self.bits { false => DSIRST_A::B_0X0, true => DSIRST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == DSIRST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == DSIRST_A::B_0X1 } } #[doc = "Write proxy for field `DSIRST`"] pub struct DSIRST_W<'a> { w: &'a mut W, } impl<'a> DSIRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DSIRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(DSIRST_A::B_0X0) } #[doc = "Writing releases the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(DSIRST_A::B_0X1) } #[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 = "DDRPERFMRST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DDRPERFMRST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing releases the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<DDRPERFMRST_A> for bool { #[inline(always)] fn from(variant: DDRPERFMRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DDRPERFMRST`"] pub type DDRPERFMRST_R = crate::R<bool, DDRPERFMRST_A>; impl DDRPERFMRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DDRPERFMRST_A { match self.bits { false => DDRPERFMRST_A::B_0X0, true => DDRPERFMRST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == DDRPERFMRST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == DDRPERFMRST_A::B_0X1 } } #[doc = "Write proxy for field `DDRPERFMRST`"] pub struct DDRPERFMRST_W<'a> { w: &'a mut W, } impl<'a> DDRPERFMRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DDRPERFMRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(DDRPERFMRST_A::B_0X0) } #[doc = "Writing releases the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(DDRPERFMRST_A::B_0X1) } #[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 = "USBPHYRST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USBPHYRST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing releases the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<USBPHYRST_A> for bool { #[inline(always)] fn from(variant: USBPHYRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `USBPHYRST`"] pub type USBPHYRST_R = crate::R<bool, USBPHYRST_A>; impl USBPHYRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> USBPHYRST_A { match self.bits { false => USBPHYRST_A::B_0X0, true => USBPHYRST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == USBPHYRST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == USBPHYRST_A::B_0X1 } } #[doc = "Write proxy for field `USBPHYRST`"] pub struct USBPHYRST_W<'a> { w: &'a mut W, } impl<'a> USBPHYRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USBPHYRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(USBPHYRST_A::B_0X0) } #[doc = "Writing releases the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(USBPHYRST_A::B_0X1) } #[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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } impl R { #[doc = "Bit 0 - LTDCRST"] #[inline(always)] pub fn ltdcrst(&self) -> LTDCRST_R { LTDCRST_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 4 - DSIRST"] #[inline(always)] pub fn dsirst(&self) -> DSIRST_R { DSIRST_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 8 - DDRPERFMRST"] #[inline(always)] pub fn ddrperfmrst(&self) -> DDRPERFMRST_R { DDRPERFMRST_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 16 - USBPHYRST"] #[inline(always)] pub fn usbphyrst(&self) -> USBPHYRST_R { USBPHYRST_R::new(((self.bits >> 16) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - LTDCRST"] #[inline(always)] pub fn ltdcrst(&mut self) -> LTDCRST_W { LTDCRST_W { w: self } } #[doc = "Bit 4 - DSIRST"] #[inline(always)] pub fn dsirst(&mut self) -> DSIRST_W { DSIRST_W { w: self } } #[doc = "Bit 8 - DDRPERFMRST"] #[inline(always)] pub fn ddrperfmrst(&mut self) -> DDRPERFMRST_W { DDRPERFMRST_W { w: self } } #[doc = "Bit 16 - USBPHYRST"] #[inline(always)] pub fn usbphyrst(&mut self) -> USBPHYRST_W { USBPHYRST_W { w: self } } }
pub mod loader; pub mod file_loader; use std::result::Result; use std::error::Error; use std::vec::Vec; use postgres::{UserInfo, ConnectTarget, IntoConnectParams, ConnectParams}; #[derive(Debug, Clone)] pub struct Config { pub database_config: DatabaseConfig, pub database_pool_config: DatabasePoolConfig, } #[derive(Debug, Clone)] pub struct DatabaseConfig { pub name: String, pub user: String, pub password: String, pub host: String, pub port: u16, } #[derive(Debug, Clone)] pub struct DatabasePoolConfig { pub size: u32, pub idle_time: u64, } impl IntoConnectParams for DatabaseConfig { fn into_connect_params(self) -> Result<ConnectParams, Box<Error + Sync + Send>> { Ok(ConnectParams { // The target server. target: ConnectTarget::Tcp(self.host), port: Some(self.port), user: Some(UserInfo { user: self.user, password: Some(self.password), }), database: Some(self.name), options: Vec::new(), }) } }
use crate::{ util::{constants::GENERAL_ISSUE, MessageExt}, BotResult, CommandData, Context, MessageBuilder, }; use std::sync::Arc; #[command] #[only_guilds()] #[authority()] #[short_desc("Toggle availability of song commands in a server")] #[long_desc( "Toggle whether song commands can be used in this server. \ Defaults to `true`" )] #[aliases("songstoggle", "songtoggle")] async fn togglesongs(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { _togglesongs(ctx, data, None).await } async fn _togglesongs( ctx: Arc<Context>, data: CommandData<'_>, value: Option<bool>, ) -> BotResult<()> { let guild_id = data.guild_id().unwrap(); let mut with_lyrics = false; let update_fut = ctx.update_guild_config(guild_id, |config| { config.with_lyrics = if value.is_some() { value } else { Some(!config.with_lyrics()) }; with_lyrics = config.with_lyrics(); }); if let Err(why) = update_fut.await { let _ = data.error(&ctx, GENERAL_ISSUE).await; return Err(why); } let content = if with_lyrics { "Song commands can now be used in this server" } else { "Song commands can no longer be used in this server" }; let builder = MessageBuilder::new().embed(content); data.create_message(&ctx, builder).await?; Ok(()) }
use maud::{html, Markup}; mod footer; pub use footer::footer; const LOGO_SVG: &str = include_str!("../../../static/logo.svg"); const LOGO_MONOCHROME_SVG: &str = include_str!("../../../static/logo-monochrome.svg"); const MAX_WIDTH_CONTAINER_CLASSES: &str = "max-w-5xl m-auto px-4"; mod header; pub use header::{head, header}; pub fn base(inner: Markup) -> Markup { html! { (head()) body class=" bg-background text-text font-sans min-h-screen flex flex-col " { (constrained_width(header())) (inner) (footer()) } } } pub fn base_constrained(inner: Markup) -> Markup { base(constrained_width(inner)) } pub fn constrained_width(inner: Markup) -> Markup { html! { div ."w-full ".(MAX_WIDTH_CONTAINER_CLASSES) { (inner) } } } pub(crate) mod buttons; pub(crate) mod posts; pub(crate) mod newsletter;
#![allow(unused_must_use)] use std::io; fn main() { let mut stderr = io::stderr(); stderr.write_str("Hello stderr\n"); }
use mpi::{self, traits::*}; use mpi_session::prelude::*; use mpi_session::topology::ZeroRank; struct Server; type ServerRank = mpi_session::key::RankKey<Server>; fn main() -> Result<(), Box<std::error::Error>> { let universe = mpi::initialize().unwrap(); let comm = universe.world(); let size = comm.size(); let rank = comm.rank(); /// The Session type defines the communication protocol. This type provides a type safe /// communication pattern over an MPI communicator. /// /// This particular protocol performs an "MPI_Allgather" and is then done. type MyProtocol = AllGather<i32, Publish<ZeroRank, ServerRank, Gather<ServerRank, i32, Eps>>>; // Constructing a session is still unsafe since the starting state of the communicator cannot // be statically verified. let session = unsafe { Session::<MyProtocol, _>::from_comm(comm) }; let mut ints = vec![0; size as usize]; let session = session.all_gather(&rank, &mut ints[..]); let session = match session.split() { Split::Left(p) => p.publish(1), Split::Right(p) => p.receive(), }; let session = match session.split() { Split::Left(g) => { let mut ranks = vec![0; comm.size() as usize]; let session = g.gather(&comm.rank(), &mut ranks[..]); println!("{}: {:?}", comm.rank(), ranks); session } Split::Right(g) => g.gather(&comm.rank()), }; let comm = session.done(); assert_eq!(size, comm.size()); assert_eq!(rank, comm.rank()); Ok(()) }
extern crate lyon; use sort_polygons::Polygon; use gerber_types::*; use std::io::Write; use conv::TryFrom; #[derive(Clone, Debug)] pub struct GerberBuilder { cf: gerber_types::CoordinateFormat, commands: Vec<gerber_types::Command>, } const VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub trait IntoCommand { fn into_command(self) -> gerber_types::Command; } impl IntoCommand for FunctionCode { fn into_command(self) -> gerber_types::Command { self.into() } } impl IntoCommand for gerber_types::GCode { fn into_command(self) -> gerber_types::Command { gerber_types::FunctionCode::GCode(self).into() } } impl IntoCommand for gerber_types::ExtendedCode { fn into_command(self) -> gerber_types::Command { self.into() } } impl IntoCommand for gerber_types::Operation { fn into_command(self) -> gerber_types::Command { gerber_types::FunctionCode::DCode( gerber_types::DCode::Operation(self) ).into() } } impl GerberBuilder { pub fn new(cf: gerber_types::CoordinateFormat, layer_type: Part, layer_func: FileFunction, file_polarity: bool) -> Self { GerberBuilder { cf: cf, commands: vec![ // gerbv doesn't seem to parse these: ExtendedCode::FileAttribute( FileAttribute::GenerationSoftware( GenerationSoftware::new("SAM", "svg2gerber", Some(VERSION)) ) ).into(), ExtendedCode::FileAttribute( FileAttribute::Part(layer_type) ).into(), ExtendedCode::FileAttribute( FileAttribute::FileFunction(layer_func) ).into(), ExtendedCode::FileAttribute( FileAttribute::FilePolarity(if file_polarity {FilePolarity::Positive} else {FilePolarity::Negative}) ).into(), //FunctionCode::GCode( GCode::Comment("Ucamco ex. 1: Two square boxes".to_string())).into(), ExtendedCode::CoordinateFormat(cf).into(), ExtendedCode::Unit(Unit::Millimeters).into(), // gerbv complains if there are no apertures defined ExtendedCode::ApertureDefinition( ApertureDefinition { code: 10, aperture: Aperture::Circle(Circle { diameter: 0.01, hole_diameter: None }), } ).into(), ExtendedCode::LoadPolarity(Polarity::Dark).into(), // this is the default, this makes our intentions explicit FunctionCode::GCode( GCode::InterpolationMode(InterpolationMode::Linear) ).into(), ], } } // this function should not require a mutable self, but then how can we call it in // a function that mutates self? pub fn vertex_to_coords(&self, vertex: &lyon::math::Point) -> Coordinates { // seriously?! this gerber library seems unnecessarily complicated Coordinates::new( CoordinateNumber::try_from( vertex.x as f64).unwrap(), // mirror vertical axis, as SVG and gerber use different conventions // TODO: this is a bit hackish, no? where shall we put this instead? CoordinateNumber::try_from(-vertex.y as f64).unwrap(), self.cf ) } pub fn push<F: IntoCommand>(&mut self, cmd: F) { self.commands.push(cmd.into_command()); } pub fn publish<W: Write>(&mut self, writer: &mut W) { // append EOF marker self.push(FunctionCode::MCode(MCode::EndOfFile)); self.commands.serialize(writer).unwrap(); } pub fn start_region(&mut self) { // start a new region self.push(GCode::RegionMode(true)); } pub fn end_region(&mut self) { // end region self.push(GCode::RegionMode(false)); } pub fn set_polarity(&mut self, polarity: bool) { if polarity { // true = positive = add self.push(ExtendedCode::LoadPolarity(Polarity::Dark)); } else { // false = negative = clear self.push(ExtendedCode::LoadPolarity(Polarity::Clear)); } } pub fn add_polygon(&mut self, poly: &Polygon) { self.start_region(); // goto last point let pt = self.vertex_to_coords(poly.vertices.last().unwrap()); self.push(gerber_types::Operation::Move(pt)); // now convert the full polygon for ref v in &poly.vertices { let pt = self.vertex_to_coords(&v); self.push(gerber_types::Operation::Interpolate(pt, None)); } self.end_region(); } }
pub mod cli; pub mod gpu; pub mod server; use actix_rt; use std::error::Error; use cli::Config; use server::Server; pub fn run(config: Config) -> Result<(), Box<dyn Error>> { actix_rt::System::new("Server thread").block_on(async move { let server = Server::new(config); server.run().await.unwrap(); }); Ok(()) }
use std::{ env, fs::{self, File}, io::Write, path::Path, error::Error, }; const ASSETS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/webapp/dist"); fn main() -> Result<(), Box<dyn Error>> { let dest = Path::new(&env::var("OUT_DIR")?).join("assets.rs"); let mut fh = File::create(dest)?; writeln!(&mut fh, "{{")?; writeln!(&mut fh, " let mut assets = std::collections::HashMap::new();")?; for asset in fs::read_dir(ASSETS_DIR)? { let asset = asset?; if asset.file_type()?.is_file() { writeln!(&mut fh, r#" assets.insert("/{name}", include_bytes!("{path}").to_vec()); "#, name = asset.file_name().to_string_lossy(), path = asset.path().display() )?; } } writeln!(&mut fh, " assets")?; writeln!(&mut fh, "}};")?; Ok(()) }
use fnv::FnvHashMap; use crate::config::{Entity, Position}; /// A structure to keep information for [`Entity`] as a key. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct EntityMap<T> { // we have a global type to allocate in on stack. // because most of the time no changes are made to the [`EntityMap`]. global: T, columns: FnvHashMap<usize, T>, rows: FnvHashMap<usize, T>, cells: FnvHashMap<Position, T>, } impl<T> EntityMap<T> { /// Creates an empty [`EntityMap`]. pub fn new(global: T) -> Self { Self { global, rows: FnvHashMap::default(), columns: FnvHashMap::default(), cells: FnvHashMap::default(), } } /// Get a value for an [`Entity`]. pub fn get(&self, entity: Entity) -> &T { if self.rows.is_empty() && self.columns.is_empty() && self.cells.is_empty() { return &self.global; } match entity { Entity::Column(col) => self.columns.get(&col).unwrap_or(&self.global), Entity::Row(row) => self.rows.get(&row).unwrap_or(&self.global), Entity::Cell(row, col) => { // todo: optimize; // // Cause we can change rows/columns/cells separately we need to check them separately. // But we often doing this checks in `Grid::fmt` and I believe if we could optimize it it could be beneficial. // // Haven't found a solution for that yet. // // I was wondering if there is a hash function like. // Apparently it doesn't make sense cause we will reset columns/rows on cell insert which is not what we want. // // ``` // hash(column, row) == hash(column) == hash(row) // ``` // // ref: https://opendsa-server.cs.vt.edu/ODSA/Books/Everything/html/Sparse.html // ref: https://users.rust-lang.org/t/make-hash-return-same-value-whather-the-order-of-element-of-a-tuple/69932/13 self.cells .get(&(row, col)) .or_else(|| self.columns.get(&col)) .or_else(|| self.rows.get(&row)) .unwrap_or(&self.global) } Entity::Global => &self.global, } } /// Removes a value for an [`Entity`]. pub fn remove(&mut self, entity: Entity) { match entity { Entity::Global => { self.cells.clear(); self.rows.clear(); self.columns.clear(); } Entity::Column(col) => self.cells.retain(|&(_, c), _| c != col), Entity::Row(row) => self.cells.retain(|&(r, _), _| r != row), Entity::Cell(row, col) => { self.cells.remove(&(row, col)); } } } } impl<T: Clone> EntityMap<T> { /// Set a value for an [`Entity`]. pub fn insert(&mut self, entity: Entity, value: T) { match entity { Entity::Column(col) => { for &row in self.rows.keys() { self.cells.insert((row, col), value.clone()); } self.columns.insert(col, value); } Entity::Row(row) => { for &col in self.columns.keys() { self.cells.insert((row, col), value.clone()); } self.rows.insert(row, value); } Entity::Cell(row, col) => { self.cells.insert((row, col), value); } Entity::Global => { self.remove(Entity::Global); self.global = value } } } }
use std::mem; use egui_glow::EguiGlow; use glutin::{PossiblyCurrent, event::Event, event_loop::ControlFlow}; use thiserror::Error; use crate::{multi_window::{MultiWindow, NewWindowRequest}, windows::MyWindows}; /// A window being tracked by a `MultiWindow`. All tracked windows will be forwarded all events /// received on the `MultiWindow`'s event loop. #[enum_dispatch] pub trait TrackedWindow { /// Handles one event from the event loop. Returns true if the window needs to be kept alive, /// otherwise it will be closed. Window events should be checked to ensure that their ID is one /// that the TrackedWindow is interested in. fn handle_event(&mut self, event: &glutin::event::Event<()>, other_windows: Vec<&mut crate::windows::MyWindows>, egui: &mut EguiGlow, gl_window: &mut glutin::WindowedContext<PossiblyCurrent>, gl: &mut glow::Context) -> TrackedWindowControl; } pub struct TrackedWindowContainer { pub gl_window: IndeterminateWindowedContext, pub gl: Option<glow::Context>, pub egui: Option<EguiGlow>, pub window: MyWindows } impl TrackedWindowContainer { pub fn create<TE>( window: MyWindows, window_builder: glutin::window::WindowBuilder, event_loop: &glutin::event_loop::EventLoopWindowTarget<TE>, ) -> Result<TrackedWindowContainer, DisplayCreationError> { // let window_builder = glutin::window::WindowBuilder::new() // .with_resizable(true) // .with_inner_size(glutin::dpi::LogicalSize { // width: 800.0, // height: 600.0, // }) // .with_title("egui_glow example"); let gl_window = glutin::ContextBuilder::new() .with_depth_buffer(0) .with_srgb(true) .with_stencil_buffer(0) .with_vsync(true) .build_windowed(window_builder, event_loop)?; Ok(TrackedWindowContainer { window, gl_window: IndeterminateWindowedContext::NotCurrent(gl_window), gl: None, egui: None }) } pub fn is_event_for_window(&self, event: &glutin::event::Event<()>) -> bool { // Check if the window ID matches, if not then this window can pass on the event. match (event, &self.gl_window) { (Event::WindowEvent { window_id: id, event: _, .. }, IndeterminateWindowedContext::PossiblyCurrent(gl_window))=> { gl_window.window().id() == *id }, (Event::WindowEvent { window_id: id, event: _, .. }, IndeterminateWindowedContext::NotCurrent(gl_window))=> { gl_window.window().id() == *id }, _ => true // we weren't able to check the window ID, maybe this window is not initialized yet. we should run it. } } pub fn handle_event_outer(&mut self, event: &glutin::event::Event<()>, other_windows:Vec<&mut crate::windows::MyWindows>) -> TrackedWindowControl { // Activate this gl_window so we can use it. // We cannot activate it without full ownership, so temporarily move the gl_window into the current scope. // It *must* be returned at the end. let gl_window = mem::replace(&mut self.gl_window, IndeterminateWindowedContext::None); let mut gl_window = match gl_window { IndeterminateWindowedContext::PossiblyCurrent(w) => unsafe {w.make_current().unwrap()}, IndeterminateWindowedContext::NotCurrent(w) => unsafe {w.make_current().unwrap()}, IndeterminateWindowedContext::None => panic!("there's no window context???"), }; // Now that the window is active, create a context if it is missing. match (self.gl.as_ref(), self.egui.as_ref()) { (None, None) => { let gl = unsafe { glow::Context::from_loader_function(|s| gl_window.get_proc_address(s)) }; unsafe { use glow::HasContext as _; gl.enable(glow::FRAMEBUFFER_SRGB); } let egui = egui_glow::EguiGlow::new(&gl_window, &gl); self.gl = Some(gl); self.egui = Some(egui); }, (Some(_), Some(_)) => (), _ => { panic!("Partially initialized window"); } }; let result = match (self.gl.as_mut(), self.egui.as_mut()) { (Some(gl), Some(egui)) => { let result = self.window.handle_event(event, other_windows, egui, &mut gl_window, gl); if let ControlFlow::Exit = result.requested_control_flow { // This window wants to go away. Close it. egui.destroy(gl); }; result }, _ => { panic!("Window wasn't fully initialized"); } }; match mem::replace(&mut self.gl_window, IndeterminateWindowedContext::PossiblyCurrent(gl_window)){ IndeterminateWindowedContext::None => (), _ => { panic!("Window had a GL context while we were borrowing it?"); } } result // self.gl_window.makecurr // We have to take ownership of it, because make_current() // let gl_window = mem::replace(&mut self.egui_window.gl_window, WindowedContext::None); // let gl_window = match gl_window { // WindowedContext::PossiblyCurrent(w) => unsafe {w.make_current().unwrap()}, // WindowedContext::NotCurrent(w) => unsafe {w.make_current().unwrap()}, // WindowedContext::None => panic!("there's no window context???"), // }; } } pub enum IndeterminateWindowedContext { PossiblyCurrent(glutin::WindowedContext<glutin::PossiblyCurrent>), NotCurrent(glutin::WindowedContext<glutin::NotCurrent>), None } pub struct TrackedWindowControl { pub requested_control_flow: ControlFlow, pub windows_to_create: Vec<NewWindowRequest> } #[derive(Error, Debug)] pub enum DisplayCreationError { #[error("couldn't create window {0}")] Creation(#[from] glutin::CreationError), #[error("couldn't create context {0:?}")] Context(#[from] glutin::ContextError) }
// Position Component #[derive(PartialEq, PartialOrd, Debug, Copy, Clone)] pub struct Position { pub x: i32, pub y: i32, } // Size Component #[derive(PartialEq, PartialOrd, Debug)] pub struct Size { pub height: i32, pub width: i32, } #[derive(PartialEq, PartialOrd, Debug, Copy, Clone)] pub struct Health(pub i32); #[derive(PartialEq, PartialOrd, Debug)] pub enum Component { Position(Position), Size(Size), Health(Health), }
//! Nodes that have a constant behavior. use crate::{ node::{Node, Tickable}, status::Status, }; /// Implements a node that always returns that it has failed. /// /// This node potentially takes a child node. If it does, then it will tick that /// node until it is completed, disregard the child's status, and return that it /// failed. If it does not have a child node, it will simply fail on every tick. /// /// # State /// /// **Initialized:** Before being ticked after either being created or reset. /// /// **Running:** While child is running. If no child, then never. /// /// **Succeeded:** Never. /// /// **Failed:** After child finishes. If no child, always. /// /// # Children /// /// One optional child. The child will be reset every time this node is reset. /// /// # Examples /// /// An `AlwaysFail` node always fails when it has no child: /// /// ``` /// # use aspen::std_nodes::*; /// # use aspen::Status; /// # use aspen::node::Tickable; /// let mut node = AlwaysFail::new(); /// assert_eq!(node.tick(&mut ()), Status::Failed); /// ``` /// /// If the child is considered running, so is this node: /// /// ``` /// # use aspen::std_nodes::*; /// # use aspen::Status; /// # use aspen::node::Tickable; /// let mut node = AlwaysFail::with_child(AlwaysRunning::new()); /// assert_eq!(node.tick(&mut ()), Status::Running); /// ``` /// /// If the child is done running, its status is disregarded: /// /// ``` /// # use aspen::std_nodes::*; /// # use aspen::Status; /// # use aspen::node::Tickable; /// let mut node = AlwaysFail::with_child(AlwaysSucceed::new()); /// assert_eq!(node.tick(&mut ()), Status::Failed); /// ``` pub struct AlwaysFail<'a, W> { /// Optional child node. child: Option<Node<'a, W>>, } impl<'a, W> AlwaysFail<'a, W> where W: 'a, { /// Construct a new AlwaysFail node. pub fn new() -> Node<'a, W> { Node::new(AlwaysFail { child: None }) } /// Construct a new AlwaysFail node that has a child. pub fn with_child(child: Node<'a, W>) -> Node<'a, W> { Node::new(AlwaysFail { child: Some(child) }) } } impl<'a, W> Tickable<W> for AlwaysFail<'a, W> { fn tick(&mut self, world: &mut W) -> Status { if let Some(ref mut child) = self.child { if !child.tick(world).is_done() { return Status::Running; } } Status::Failed } fn reset(&mut self) { if let Some(ref mut child) = self.child { child.reset(); } } fn children(&self) -> Vec<&Node<W>> { if let Some(ref child) = self.child { vec![child] } else { Vec::new() } } /// Returns the string "AlwaysFail". fn type_name(&self) -> &'static str { "AlwaysFail" } } /// Convenience macro for creating AlwaysFail nodes. /// /// # Examples /// /// Without a child: /// /// ``` /// # #[macro_use] extern crate aspen; /// # use aspen::node::Node; /// # fn main() { /// let fail: Node<()> = AlwaysFail! {}; /// # } /// ``` /// /// With a child: /// /// ``` /// # #[macro_use] extern crate aspen; /// # fn main() { /// let fail_child = AlwaysFail! { /// Condition!{ |a: &u32| *a < 12 } /// }; /// # } /// ``` #[macro_export] macro_rules! AlwaysFail { ( $e:expr ) => { $crate::std_nodes::AlwaysFail::with_child($e) }; ( ) => { $crate::std_nodes::AlwaysFail::new() }; } /// Implements a node that always returns that it has succeeded. /// /// This node potentially takes a child node. If it does, then it will tick that /// node until it is completed, disregard the child's status, and return that it /// succeeded. If it does not have a child node, it will simply succeed on /// every tick. /// /// # State /// /// **Initialized:** Before being ticked after either being created or reset. /// /// **Running:** While child is running. If no child, then never. /// /// **Succeeded:** After child finished. If no child, always. /// /// **Failed:** Never. /// /// # Children /// /// One optional child. The child will be reset every time this node is reset. /// /// # Examples /// /// An `AlwaysSucceed` node always succeeds when it has no child: /// /// ``` /// # use aspen::std_nodes::*; /// # use aspen::Status; /// # use aspen::node::Tickable; /// let mut node = AlwaysSucceed::new(); /// assert_eq!(node.tick(&mut ()), Status::Succeeded); /// ``` /// /// If the child is considered running, so is this node: /// /// ``` /// # use aspen::std_nodes::*; /// # use aspen::Status; /// # use aspen::node::Tickable; /// let mut node = AlwaysSucceed::with_child(AlwaysRunning::new()); /// assert_eq!(node.tick(&mut ()), Status::Running); /// ``` /// /// If the child is done running, its status is disregarded: /// /// ``` /// # use aspen::std_nodes::*; /// # use aspen::Status; /// # use aspen::node::Tickable; /// let mut node = AlwaysSucceed::with_child(AlwaysFail::new()); /// assert_eq!(node.tick(&mut ()), Status::Succeeded); /// ``` pub struct AlwaysSucceed<'a, W> { /// Optional child node. child: Option<Node<'a, W>>, } impl<'a, W> AlwaysSucceed<'a, W> where W: 'a, { /// Construct a new [`AlwaysSucceed`] node. pub fn new() -> Node<'a, W> { Node::new(AlwaysSucceed { child: None }) } /// Construct a new [`AlwaysSucceed`] node with a child. pub fn with_child(child: Node<'a, W>) -> Node<'a, W> { Node::new(AlwaysSucceed { child: Some(child) }) } } impl<'a, W> Tickable<W> for AlwaysSucceed<'a, W> { fn tick(&mut self, world: &mut W) -> Status { if let Some(ref mut child) = self.child { if !child.tick(world).is_done() { return Status::Running; } } Status::Succeeded } fn children(&self) -> Vec<&Node<W>> { if let Some(ref child) = self.child { vec![child] } else { Vec::new() } } fn reset(&mut self) { if let Some(ref mut child) = self.child { child.reset(); } } /// Returns the string "AlwaysSucceed". fn type_name(&self) -> &'static str { "AlwaysSucceed" } } /// Convenience macro for creating AlwaysSucceed nodes. /// /// # Examples /// /// Without a child: /// /// ``` /// # #[macro_use] extern crate aspen; /// # use aspen::node::Node; /// # fn main() { /// let succeed: Node<()> = AlwaysSucceed! {}; /// # } /// ``` /// /// With a child: /// /// ``` /// # #[macro_use] extern crate aspen; /// # fn main() { /// let succeed_child = AlwaysSucceed! { /// Condition!{ |a: &u32| *a < 12 } /// }; /// # } /// ``` #[macro_export] macro_rules! AlwaysSucceed { ( $e:expr ) => { $crate::std_nodes::AlwaysSucceed::with_child($e) }; ( ) => { $crate::std_nodes::AlwaysSucceed::new() }; } /// Implements a node that always returns that it is currently running. /// /// # State /// /// **Initialized:** Before being ticked after either being created or reset. /// /// **Running:** Always. /// /// **Succeeded:** Never. /// /// **Failed:** Never. /// /// # Children /// /// None. /// /// # Examples /// /// An `AlwaysRunning` node is always running: /// /// ``` /// # use aspen::std_nodes::*; /// # use aspen::Status; /// # use aspen::node::Tickable; /// let mut node = AlwaysRunning::new(); /// assert_eq!(node.tick(&mut ()), Status::Running); /// ``` pub struct AlwaysRunning; impl AlwaysRunning { /// Construct a new AlwaysRunning node. pub fn new<W>() -> Node<'static, W> { Node::new(AlwaysRunning {}) } } impl<W> Tickable<W> for AlwaysRunning { fn tick(&mut self, _: &mut W) -> Status { Status::Running } fn reset(&mut self) { // No-op } /// Returns the string "AlwaysRunning". fn type_name(&self) -> &'static str { "AlwaysRunning" } } /// Convenience macro for creating AlwaysRunning nodes. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate aspen; /// # use aspen::node::Node; /// # fn main() { /// let running: Node<()> = AlwaysRunning! {}; /// # } /// ``` #[macro_export] macro_rules! AlwaysRunning { ( ) => { $crate::std_nodes::AlwaysRunning::new() }; } #[cfg(test)] mod tests { use crate::{ node::Tickable, status::Status, std_nodes::{AlwaysFail, AlwaysRunning, AlwaysSucceed, YesTick}, }; #[test] fn always_fail() { assert_eq!(AlwaysFail::new().tick(&mut ()), Status::Failed); } #[test] fn always_fail_child() { let mut succeed = AlwaysFail::with_child(YesTick::new(Status::Succeeded)); let succeed_res = succeed.tick(&mut ()); drop(succeed); assert_eq!(succeed_res, Status::Failed); let mut run = AlwaysFail::with_child(YesTick::new(Status::Running)); let run_res = run.tick(&mut ()); drop(run); assert_eq!(run_res, Status::Running); let mut fail = AlwaysFail::with_child(YesTick::new(Status::Failed)); let fail_res = fail.tick(&mut ()); drop(fail); assert_eq!(fail_res, Status::Failed); } #[test] fn always_succeed() { assert_eq!(AlwaysSucceed::new().tick(&mut ()), Status::Succeeded); } #[test] fn always_succeed_child() { let mut succeed = AlwaysSucceed::with_child(YesTick::new(Status::Succeeded)); let succeed_res = succeed.tick(&mut ()); drop(succeed); assert_eq!(succeed_res, Status::Succeeded); let mut run = AlwaysSucceed::with_child(YesTick::new(Status::Running)); let run_res = run.tick(&mut ()); drop(run); assert_eq!(run_res, Status::Running); let mut fail = AlwaysSucceed::with_child(YesTick::new(Status::Failed)); let fail_res = fail.tick(&mut ()); drop(fail); assert_eq!(fail_res, Status::Succeeded); } #[test] fn always_running() { assert_eq!(AlwaysRunning::new().tick(&mut ()), Status::Running); } }
const STARTING_MISSLES: i32 = 8; const READY_AMOUNT:i32 = 2; fn main() { let mut missiles:i32 = 9; let ready:i32 = 2; missiles = missiles - ready; let ( new_missless, new_ready): (i32, i32) = (STARTING_MISSLES, READY_AMOUNT); println!("Firing {} of my {} missiles...", ready, missiles); println!("Firing {} of my {} missiles...", STARTING_MISSLES, READY_AMOUNT); println!("Firing {} of my {} missiles...", new_ready, new_missless); }
use rand::prelude::*; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use std::{array, iter::repeat_with, ops::Not}; use zoon::{format, *}; // ------ ------ // States // ------ ------ static ADJECTIVES: &[&'static str] = &[ "pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy", ]; static COLOURS: &[&'static str] = &[ "red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange", ]; static NOUNS: &[&'static str] = &[ "table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard", ]; static NEXT_ID: AtomicUsize = AtomicUsize::new(1); #[static_ref] fn selected_row() -> &'static Mutable<Option<ID>> { Mutable::new(None) } #[static_ref] fn rows() -> &'static MutableVec<Arc<Row>> { MutableVec::new() } type ID = usize; struct Row { id: ID, label: Mutable<String>, } // ------ ------ // Signals // ------ ------ fn rows_exist() -> impl Signal<Item = bool> { rows().signal_vec_cloned().is_empty().map(Not::not) } // ------ ------ // Commands // ------ ------ fn create_row() -> Arc<Row> { let mut generator = SmallRng::from_entropy(); let label = format!( "{} {} {}", ADJECTIVES.choose(&mut generator).unwrap_throw(), COLOURS.choose(&mut generator).unwrap_throw(), NOUNS.choose(&mut generator).unwrap_throw(), ); Arc::new(Row { id: NEXT_ID.fetch_add(1, Ordering::SeqCst), label: Mutable::new(label), }) } fn create_rows(count: usize) { rows() .lock_mut() .replace_cloned(repeat_with(create_row).take(count).collect()) } fn append_rows(count: usize) { rows() .lock_mut() .extend(repeat_with(create_row).take(count)); } fn update_rows(step: usize) { let rows = rows().lock_ref(); for position in (0..rows.len()).step_by(step) { rows[position].label.lock_mut().push_str(" !!!"); } } fn clear_rows() { rows().lock_mut().clear() } fn swap_rows() { let mut rows = rows().lock_mut(); if rows.len() < 999 { return; } rows.swap(1, 998) } fn select_row(id: ID) { selected_row().set(Some(id)) } fn remove_row(id: ID) { rows().lock_mut().retain(|row| row.id != id); } // ------ ------ // View // ------ ------ fn root() -> RawHtmlEl { RawHtmlEl::new("div") .attr("class", "container") .children(array::IntoIter::new([ jumbotron(), table(), RawHtmlEl::new("span") .attr("class", "preloadicon glyphicon glyphicon-remove") .attr("aria-hidden", ""), ])) } fn jumbotron() -> RawHtmlEl { RawHtmlEl::new("div").attr("class", "jumbotron").child( RawHtmlEl::new("div") .attr("class", "row") .children(array::IntoIter::new([ RawHtmlEl::new("div") .attr("class", "col-md-6") .child(RawHtmlEl::new("h1").child("MoonZoon")), RawHtmlEl::new("div") .attr("class", "col-md-6") .child(action_buttons()), ])), ) } fn action_buttons() -> RawHtmlEl { RawHtmlEl::new("div") .attr("class", "row") .children(array::IntoIter::new([ action_button("run", "Create 1,000 rows", || create_rows(1_000)), action_button("runlots", "Create 10,000 rows", || create_rows(10_000)), action_button("add", "Append 1,000 rows", || append_rows(1_000)), action_button("update", "Update every 10th row", || update_rows(10)), action_button("clear", "Clear", clear_rows), action_button("swaprows", "Swap Rows", swap_rows), ])) } fn action_button(id: &'static str, title: &'static str, on_click: fn()) -> RawHtmlEl { RawHtmlEl::new("div") .attr("class", "col-sm-6 smallpad") .child( RawHtmlEl::new("button") .attr("id", id) .attr("class", "btn btn-primary btn-block") .attr("type", "button") .event_handler(move |_: events::Click| on_click()) .child(title), ) } fn table() -> RawHtmlEl { RawHtmlEl::new("table") .attr("class", "table table-hover table-striped test-data") .child_signal(rows_exist().map(|rows_exist| { rows_exist.then(|| { RawHtmlEl::new("tbody") .attr("id", "tbody") .children_signal_vec(rows().signal_vec_cloned().map(row)) }) })) } fn row(row: Arc<Row>) -> RawHtmlEl { let id = row.id; RawHtmlEl::new("tr") .attr_signal( "class", selected_row().signal_ref(move |selected_id| ((*selected_id)? == id).then(|| "danger")), ) .children(array::IntoIter::new([ row_id(id), row_label(id, row.label.signal_cloned()), row_remove_button(id), RawHtmlEl::new("td").attr("class", "col-md-6"), ])) } fn row_id(id: ID) -> RawHtmlEl { RawHtmlEl::new("td").attr("class", "col-md-1").child(id) } fn row_label(id: ID, label: impl Signal<Item = String> + Unpin + 'static) -> RawHtmlEl { RawHtmlEl::new("td").attr("class", "col-md-4").child( RawHtmlEl::new("a") .event_handler(move |_: events::Click| select_row(id)) .child(Text::with_signal(label)), ) } fn row_remove_button(id: ID) -> RawHtmlEl { RawHtmlEl::new("td").attr("class", "col-md-1").child( RawHtmlEl::new("a") .event_handler(move |_: events::Click| remove_row(id)) .child( RawHtmlEl::new("span") .attr("class", "glyphicon glyphicon-remove remove") .attr("aria-hidden", "true"), ), ) } // ------ ------ // Start // ------ ------ #[wasm_bindgen(start)] pub fn start() { start_app("main", root); }
#[doc = "Register `NDAT2` reader"] pub type R = crate::R<NDAT2_SPEC>; #[doc = "Register `NDAT2` writer"] pub type W = crate::W<NDAT2_SPEC>; #[doc = "Field `ND32` reader - New data"] pub type ND32_R = crate::BitReader; #[doc = "Field `ND32` writer - New data"] pub type ND32_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND33` reader - New data"] pub type ND33_R = crate::BitReader; #[doc = "Field `ND33` writer - New data"] pub type ND33_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND34` reader - New data"] pub type ND34_R = crate::BitReader; #[doc = "Field `ND34` writer - New data"] pub type ND34_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND35` reader - New data"] pub type ND35_R = crate::BitReader; #[doc = "Field `ND35` writer - New data"] pub type ND35_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND36` reader - New data"] pub type ND36_R = crate::BitReader; #[doc = "Field `ND36` writer - New data"] pub type ND36_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND37` reader - New data"] pub type ND37_R = crate::BitReader; #[doc = "Field `ND37` writer - New data"] pub type ND37_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND38` reader - New data"] pub type ND38_R = crate::BitReader; #[doc = "Field `ND38` writer - New data"] pub type ND38_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND39` reader - New data"] pub type ND39_R = crate::BitReader; #[doc = "Field `ND39` writer - New data"] pub type ND39_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND40` reader - New data"] pub type ND40_R = crate::BitReader; #[doc = "Field `ND40` writer - New data"] pub type ND40_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND41` reader - New data"] pub type ND41_R = crate::BitReader; #[doc = "Field `ND41` writer - New data"] pub type ND41_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND42` reader - New data"] pub type ND42_R = crate::BitReader; #[doc = "Field `ND42` writer - New data"] pub type ND42_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND43` reader - New data"] pub type ND43_R = crate::BitReader; #[doc = "Field `ND43` writer - New data"] pub type ND43_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND44` reader - New data"] pub type ND44_R = crate::BitReader; #[doc = "Field `ND44` writer - New data"] pub type ND44_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND45` reader - New data"] pub type ND45_R = crate::BitReader; #[doc = "Field `ND45` writer - New data"] pub type ND45_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND46` reader - New data"] pub type ND46_R = crate::BitReader; #[doc = "Field `ND46` writer - New data"] pub type ND46_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND47` reader - New data"] pub type ND47_R = crate::BitReader; #[doc = "Field `ND47` writer - New data"] pub type ND47_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND48` reader - New data"] pub type ND48_R = crate::BitReader; #[doc = "Field `ND48` writer - New data"] pub type ND48_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND49` reader - New data"] pub type ND49_R = crate::BitReader; #[doc = "Field `ND49` writer - New data"] pub type ND49_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND50` reader - New data"] pub type ND50_R = crate::BitReader; #[doc = "Field `ND50` writer - New data"] pub type ND50_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND51` reader - New data"] pub type ND51_R = crate::BitReader; #[doc = "Field `ND51` writer - New data"] pub type ND51_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND52` reader - New data"] pub type ND52_R = crate::BitReader; #[doc = "Field `ND52` writer - New data"] pub type ND52_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND53` reader - New data"] pub type ND53_R = crate::BitReader; #[doc = "Field `ND53` writer - New data"] pub type ND53_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND54` reader - New data"] pub type ND54_R = crate::BitReader; #[doc = "Field `ND54` writer - New data"] pub type ND54_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND55` reader - New data"] pub type ND55_R = crate::BitReader; #[doc = "Field `ND55` writer - New data"] pub type ND55_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND56` reader - New data"] pub type ND56_R = crate::BitReader; #[doc = "Field `ND56` writer - New data"] pub type ND56_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND57` reader - New data"] pub type ND57_R = crate::BitReader; #[doc = "Field `ND57` writer - New data"] pub type ND57_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND58` reader - New data"] pub type ND58_R = crate::BitReader; #[doc = "Field `ND58` writer - New data"] pub type ND58_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND59` reader - New data"] pub type ND59_R = crate::BitReader; #[doc = "Field `ND59` writer - New data"] pub type ND59_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND60` reader - New data"] pub type ND60_R = crate::BitReader; #[doc = "Field `ND60` writer - New data"] pub type ND60_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND61` reader - New data"] pub type ND61_R = crate::BitReader; #[doc = "Field `ND61` writer - New data"] pub type ND61_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND62` reader - New data"] pub type ND62_R = crate::BitReader; #[doc = "Field `ND62` writer - New data"] pub type ND62_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ND63` reader - New data"] pub type ND63_R = crate::BitReader; #[doc = "Field `ND63` writer - New data"] pub type ND63_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - New data"] #[inline(always)] pub fn nd32(&self) -> ND32_R { ND32_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - New data"] #[inline(always)] pub fn nd33(&self) -> ND33_R { ND33_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - New data"] #[inline(always)] pub fn nd34(&self) -> ND34_R { ND34_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - New data"] #[inline(always)] pub fn nd35(&self) -> ND35_R { ND35_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - New data"] #[inline(always)] pub fn nd36(&self) -> ND36_R { ND36_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - New data"] #[inline(always)] pub fn nd37(&self) -> ND37_R { ND37_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - New data"] #[inline(always)] pub fn nd38(&self) -> ND38_R { ND38_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - New data"] #[inline(always)] pub fn nd39(&self) -> ND39_R { ND39_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - New data"] #[inline(always)] pub fn nd40(&self) -> ND40_R { ND40_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - New data"] #[inline(always)] pub fn nd41(&self) -> ND41_R { ND41_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - New data"] #[inline(always)] pub fn nd42(&self) -> ND42_R { ND42_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - New data"] #[inline(always)] pub fn nd43(&self) -> ND43_R { ND43_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - New data"] #[inline(always)] pub fn nd44(&self) -> ND44_R { ND44_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - New data"] #[inline(always)] pub fn nd45(&self) -> ND45_R { ND45_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - New data"] #[inline(always)] pub fn nd46(&self) -> ND46_R { ND46_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - New data"] #[inline(always)] pub fn nd47(&self) -> ND47_R { ND47_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - New data"] #[inline(always)] pub fn nd48(&self) -> ND48_R { ND48_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - New data"] #[inline(always)] pub fn nd49(&self) -> ND49_R { ND49_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - New data"] #[inline(always)] pub fn nd50(&self) -> ND50_R { ND50_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - New data"] #[inline(always)] pub fn nd51(&self) -> ND51_R { ND51_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - New data"] #[inline(always)] pub fn nd52(&self) -> ND52_R { ND52_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - New data"] #[inline(always)] pub fn nd53(&self) -> ND53_R { ND53_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - New data"] #[inline(always)] pub fn nd54(&self) -> ND54_R { ND54_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - New data"] #[inline(always)] pub fn nd55(&self) -> ND55_R { ND55_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - New data"] #[inline(always)] pub fn nd56(&self) -> ND56_R { ND56_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - New data"] #[inline(always)] pub fn nd57(&self) -> ND57_R { ND57_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - New data"] #[inline(always)] pub fn nd58(&self) -> ND58_R { ND58_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - New data"] #[inline(always)] pub fn nd59(&self) -> ND59_R { ND59_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - New data"] #[inline(always)] pub fn nd60(&self) -> ND60_R { ND60_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - New data"] #[inline(always)] pub fn nd61(&self) -> ND61_R { ND61_R::new(((self.bits >> 29) & 1) != 0) } #[doc = "Bit 30 - New data"] #[inline(always)] pub fn nd62(&self) -> ND62_R { ND62_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - New data"] #[inline(always)] pub fn nd63(&self) -> ND63_R { ND63_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - New data"] #[inline(always)] #[must_use] pub fn nd32(&mut self) -> ND32_W<NDAT2_SPEC, 0> { ND32_W::new(self) } #[doc = "Bit 1 - New data"] #[inline(always)] #[must_use] pub fn nd33(&mut self) -> ND33_W<NDAT2_SPEC, 1> { ND33_W::new(self) } #[doc = "Bit 2 - New data"] #[inline(always)] #[must_use] pub fn nd34(&mut self) -> ND34_W<NDAT2_SPEC, 2> { ND34_W::new(self) } #[doc = "Bit 3 - New data"] #[inline(always)] #[must_use] pub fn nd35(&mut self) -> ND35_W<NDAT2_SPEC, 3> { ND35_W::new(self) } #[doc = "Bit 4 - New data"] #[inline(always)] #[must_use] pub fn nd36(&mut self) -> ND36_W<NDAT2_SPEC, 4> { ND36_W::new(self) } #[doc = "Bit 5 - New data"] #[inline(always)] #[must_use] pub fn nd37(&mut self) -> ND37_W<NDAT2_SPEC, 5> { ND37_W::new(self) } #[doc = "Bit 6 - New data"] #[inline(always)] #[must_use] pub fn nd38(&mut self) -> ND38_W<NDAT2_SPEC, 6> { ND38_W::new(self) } #[doc = "Bit 7 - New data"] #[inline(always)] #[must_use] pub fn nd39(&mut self) -> ND39_W<NDAT2_SPEC, 7> { ND39_W::new(self) } #[doc = "Bit 8 - New data"] #[inline(always)] #[must_use] pub fn nd40(&mut self) -> ND40_W<NDAT2_SPEC, 8> { ND40_W::new(self) } #[doc = "Bit 9 - New data"] #[inline(always)] #[must_use] pub fn nd41(&mut self) -> ND41_W<NDAT2_SPEC, 9> { ND41_W::new(self) } #[doc = "Bit 10 - New data"] #[inline(always)] #[must_use] pub fn nd42(&mut self) -> ND42_W<NDAT2_SPEC, 10> { ND42_W::new(self) } #[doc = "Bit 11 - New data"] #[inline(always)] #[must_use] pub fn nd43(&mut self) -> ND43_W<NDAT2_SPEC, 11> { ND43_W::new(self) } #[doc = "Bit 12 - New data"] #[inline(always)] #[must_use] pub fn nd44(&mut self) -> ND44_W<NDAT2_SPEC, 12> { ND44_W::new(self) } #[doc = "Bit 13 - New data"] #[inline(always)] #[must_use] pub fn nd45(&mut self) -> ND45_W<NDAT2_SPEC, 13> { ND45_W::new(self) } #[doc = "Bit 14 - New data"] #[inline(always)] #[must_use] pub fn nd46(&mut self) -> ND46_W<NDAT2_SPEC, 14> { ND46_W::new(self) } #[doc = "Bit 15 - New data"] #[inline(always)] #[must_use] pub fn nd47(&mut self) -> ND47_W<NDAT2_SPEC, 15> { ND47_W::new(self) } #[doc = "Bit 16 - New data"] #[inline(always)] #[must_use] pub fn nd48(&mut self) -> ND48_W<NDAT2_SPEC, 16> { ND48_W::new(self) } #[doc = "Bit 17 - New data"] #[inline(always)] #[must_use] pub fn nd49(&mut self) -> ND49_W<NDAT2_SPEC, 17> { ND49_W::new(self) } #[doc = "Bit 18 - New data"] #[inline(always)] #[must_use] pub fn nd50(&mut self) -> ND50_W<NDAT2_SPEC, 18> { ND50_W::new(self) } #[doc = "Bit 19 - New data"] #[inline(always)] #[must_use] pub fn nd51(&mut self) -> ND51_W<NDAT2_SPEC, 19> { ND51_W::new(self) } #[doc = "Bit 20 - New data"] #[inline(always)] #[must_use] pub fn nd52(&mut self) -> ND52_W<NDAT2_SPEC, 20> { ND52_W::new(self) } #[doc = "Bit 21 - New data"] #[inline(always)] #[must_use] pub fn nd53(&mut self) -> ND53_W<NDAT2_SPEC, 21> { ND53_W::new(self) } #[doc = "Bit 22 - New data"] #[inline(always)] #[must_use] pub fn nd54(&mut self) -> ND54_W<NDAT2_SPEC, 22> { ND54_W::new(self) } #[doc = "Bit 23 - New data"] #[inline(always)] #[must_use] pub fn nd55(&mut self) -> ND55_W<NDAT2_SPEC, 23> { ND55_W::new(self) } #[doc = "Bit 24 - New data"] #[inline(always)] #[must_use] pub fn nd56(&mut self) -> ND56_W<NDAT2_SPEC, 24> { ND56_W::new(self) } #[doc = "Bit 25 - New data"] #[inline(always)] #[must_use] pub fn nd57(&mut self) -> ND57_W<NDAT2_SPEC, 25> { ND57_W::new(self) } #[doc = "Bit 26 - New data"] #[inline(always)] #[must_use] pub fn nd58(&mut self) -> ND58_W<NDAT2_SPEC, 26> { ND58_W::new(self) } #[doc = "Bit 27 - New data"] #[inline(always)] #[must_use] pub fn nd59(&mut self) -> ND59_W<NDAT2_SPEC, 27> { ND59_W::new(self) } #[doc = "Bit 28 - New data"] #[inline(always)] #[must_use] pub fn nd60(&mut self) -> ND60_W<NDAT2_SPEC, 28> { ND60_W::new(self) } #[doc = "Bit 29 - New data"] #[inline(always)] #[must_use] pub fn nd61(&mut self) -> ND61_W<NDAT2_SPEC, 29> { ND61_W::new(self) } #[doc = "Bit 30 - New data"] #[inline(always)] #[must_use] pub fn nd62(&mut self) -> ND62_W<NDAT2_SPEC, 30> { ND62_W::new(self) } #[doc = "Bit 31 - New data"] #[inline(always)] #[must_use] pub fn nd63(&mut self) -> ND63_W<NDAT2_SPEC, 31> { ND63_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "FDCAN New Data 2 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ndat2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ndat2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct NDAT2_SPEC; impl crate::RegisterSpec for NDAT2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ndat2::R`](R) reader structure"] impl crate::Readable for NDAT2_SPEC {} #[doc = "`write(|w| ..)` method takes [`ndat2::W`](W) writer structure"] impl crate::Writable for NDAT2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets NDAT2 to value 0"] impl crate::Resettable for NDAT2_SPEC { const RESET_VALUE: Self::Ux = 0; }
extern crate tvdb; extern crate gtk; extern crate gdk; #[macro_use] extern crate quick_error; mod backend; mod frontend { pub mod cli; pub mod gtk3; } use std::env; fn main() { let mut arguments = env::args(); if arguments.next().unwrap().ends_with("tv-renamer-gtk") { frontend::gtk3::interface(); } else { frontend::cli::interface(arguments); } }
fn main() { let mut x = 10; for _ in 1 .. x { x -= 1; print!("."); } }
// Copyright 2017-2021 Parity Technologies // // 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. #![doc = include_str!("../README.md")] #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] #[macro_use] #[doc(hidden)] pub extern crate alloc; #[cfg(feature = "derive")] #[allow(unused_imports)] #[macro_use] extern crate parity_scale_codec_derive; #[cfg(all(feature = "std", test))] #[macro_use] extern crate serde_derive; #[cfg(feature = "derive")] pub use parity_scale_codec_derive::*; #[cfg(feature = "std")] #[doc(hidden)] pub mod alloc { pub use std::boxed; pub use std::vec; pub use std::string; pub use std::borrow; pub use std::collections; pub use std::sync; pub use std::rc; pub use std::alloc; } mod codec; mod compact; mod joiner; mod keyedvec; #[cfg(feature = "bit-vec")] mod bit_vec; #[cfg(feature = "generic-array")] mod generic_array; mod decode_all; mod decode_finished; mod depth_limit; mod encode_append; mod encode_like; mod error; #[cfg(feature = "max-encoded-len")] mod max_encoded_len; #[cfg(feature = "max-encoded-len")] mod const_encoded_len; pub use self::error::Error; pub use self::codec::{ Input, Output, Decode, Encode, Codec, EncodeAsRef, WrapperTypeEncode, WrapperTypeDecode, OptionBool, DecodeLength, FullCodec, FullEncode, decode_vec_with_len, }; #[cfg(feature = "std")] pub use self::codec::IoReader; pub use self::compact::{Compact, HasCompact, CompactAs, CompactLen, CompactRef}; pub use self::joiner::Joiner; pub use self::keyedvec::KeyedVec; pub use self::decode_all::DecodeAll; pub use self::decode_finished::DecodeFinished; pub use self::depth_limit::DecodeLimit; pub use self::encode_append::EncodeAppend; pub use self::encode_like::{EncodeLike, Ref}; #[cfg(feature = "max-encoded-len")] pub use max_encoded_len::MaxEncodedLen; #[cfg(feature = "max-encoded-len")] pub use const_encoded_len::ConstEncodedLen; /// Derive macro for [`MaxEncodedLen`][max_encoded_len::MaxEncodedLen]. /// /// # Examples /// /// ``` /// # use parity_scale_codec::{Encode, MaxEncodedLen}; /// #[derive(Encode, MaxEncodedLen)] /// struct Example; /// ``` /// /// ``` /// # use parity_scale_codec::{Encode, MaxEncodedLen}; /// #[derive(Encode, MaxEncodedLen)] /// struct TupleStruct(u8, u32); /// /// assert_eq!(TupleStruct::max_encoded_len(), u8::max_encoded_len() + u32::max_encoded_len()); /// ``` /// /// ``` /// # use parity_scale_codec::{Encode, MaxEncodedLen}; /// #[derive(Encode, MaxEncodedLen)] /// enum GenericEnum<T> { /// A, /// B(T), /// } /// /// assert_eq!(GenericEnum::<u8>::max_encoded_len(), u8::max_encoded_len() + u8::max_encoded_len()); /// assert_eq!(GenericEnum::<u128>::max_encoded_len(), u8::max_encoded_len() + u128::max_encoded_len()); /// ``` /// /// # Within other macros /// /// Sometimes the `MaxEncodedLen` trait and macro are used within another macro, and it can't be /// guaranteed that the `parity_scale_codec` module is available at the call site. In that case, the /// macro should reexport the `parity_scale_codec` module and specify the path to the reexport: /// /// ```ignore /// pub use parity_scale_codec as codec; /// /// #[derive(Encode, MaxEncodedLen)] /// #[codec(crate = $crate::codec)] /// struct Example; /// ``` #[cfg(all(feature = "derive", feature = "max-encoded-len"))] pub use parity_scale_codec_derive::MaxEncodedLen; #[cfg(feature = "bytes")] pub use self::codec::decode_from_bytes;
// Copyright 2018-2020 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Substrate is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Substrate. If not, see <http://www.gnu.org/licenses/>. //! Definition of macros that hides boilerplate of defining external environment //! for a wasm module. //! //! Most likely you should use `define_env` macro. #[macro_export] macro_rules! convert_args { () => (vec![]); ( $( $t:ty ),* ) => ( vec![ $( { use $crate::wasm::env_def::ConvertibleToWasm; <$t>::VALUE_TYPE }, )* ] ); } #[macro_export] macro_rules! gen_signature { ( ( $( $params: ty ),* ) ) => ( { parity_wasm::elements::FunctionType::new(convert_args!($($params),*), None) } ); ( ( $( $params: ty ),* ) -> $returns: ty ) => ( { parity_wasm::elements::FunctionType::new(convert_args!($($params),*), Some({ use $crate::wasm::env_def::ConvertibleToWasm; <$returns>::VALUE_TYPE })) } ); } #[macro_export] macro_rules! gen_signature_dispatch { ( $needle_name:ident, $needle_sig:ident ; $name:ident ( $ctx:ident $( , $names:ident : $params:ty )* ) $( -> $returns:ty )* , $($rest:tt)* ) => { if stringify!($name).as_bytes() == $needle_name { let signature = gen_signature!( ( $( $params ),* ) $( -> $returns )* ); if $needle_sig == &signature { return true; } } else { gen_signature_dispatch!($needle_name, $needle_sig ; $($rest)*); } }; ( $needle_name:ident, $needle_sig:ident ; ) => { }; } /// Unmarshall arguments and then execute `body` expression and return its result. macro_rules! unmarshall_then_body { ( $body:tt, $ctx:ident, $args_iter:ident, $( $names:ident : $params:ty ),* ) => ({ $( let $names : <$params as $crate::wasm::env_def::ConvertibleToWasm>::NativeType = $args_iter.next() .and_then(|v| <$params as $crate::wasm::env_def::ConvertibleToWasm> ::from_typed_value(v.clone())) .expect( "precondition: all imports should be checked against the signatures of corresponding functions defined by `define_env!` macro by the user of the macro; signatures of these functions defined by `$params`; calls always made with arguments types of which are defined by the corresponding imports; thus types of arguments should be equal to type list in `$params` and length of argument list and $params should be equal; thus this can never be `None`; qed; " ); )* $body }) } /// Since we can't specify the type of closure directly at binding site: /// /// ```nocompile /// let f: FnOnce() -> Result<<u32 as ConvertibleToWasm>::NativeType, _> = || { /* ... */ }; /// ``` /// /// we use this function to constrain the type of the closure. #[inline(always)] pub fn constrain_closure<R, F>(f: F) -> F where F: FnOnce() -> Result<R, sp_sandbox::HostError>, { f } #[macro_export] macro_rules! unmarshall_then_body_then_marshall { ( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) -> $returns:ty => $body:tt ) => ({ let body = $crate::wasm::env_def::macros::constrain_closure::< <$returns as $crate::wasm::env_def::ConvertibleToWasm>::NativeType, _ >(|| { unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*) }); let r = body()?; return Ok(sp_sandbox::ReturnValue::Value({ use $crate::wasm::env_def::ConvertibleToWasm; r.to_typed_value() })) }); ( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) => $body:tt ) => ({ let body = $crate::wasm::env_def::macros::constrain_closure::<(), _>(|| { unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*) }); body()?; return Ok(sp_sandbox::ReturnValue::Unit) }) } #[macro_export] macro_rules! define_func { ( < E: $seal_ty:tt > $name:ident ( $ctx: ident $(, $names:ident : $params:ty)*) $(-> $returns:ty)* => $body:tt ) => { fn $name< E: $seal_ty >( $ctx: &mut $crate::wasm::Runtime<E>, args: &[sp_sandbox::Value], ) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> { #[allow(unused)] let mut args = args.iter(); unmarshall_then_body_then_marshall!( args, $ctx, ( $( $names : $params ),* ) $( -> $returns )* => $body ) } }; } #[macro_export] macro_rules! register_func { ( $reg_cb:ident, < E: $seal_ty:tt > ; ) => {}; ( $reg_cb:ident, < E: $seal_ty:tt > ; $name:ident ( $ctx:ident $( , $names:ident : $params:ty )* ) $( -> $returns:ty )* => $body:tt $($rest:tt)* ) => { $reg_cb( stringify!($name).as_bytes(), { define_func!( < E: $seal_ty > $name ( $ctx $(, $names : $params )* ) $( -> $returns )* => $body ); $name::<E> } ); register_func!( $reg_cb, < E: $seal_ty > ; $($rest)* ); }; } /// Define a function set that can be imported by executing wasm code. /// /// **NB**: Be advised that all functions defined by this macro /// will panic if called with unexpected arguments. /// /// It's up to the user of this macro to check signatures of wasm code to be executed /// and reject the code if any imported function has a mismatched signature. macro_rules! define_env { ( $init_name:ident , < E: $seal_ty:tt > , $( $name:ident ( $ctx:ident $( , $names:ident : $params:ty )* ) $( -> $returns:ty )* => $body:tt , )* ) => { pub struct $init_name; impl $crate::wasm::env_def::ImportSatisfyCheck for $init_name { fn can_satisfy(name: &[u8], func_type: &parity_wasm::elements::FunctionType) -> bool { gen_signature_dispatch!( name, func_type ; $( $name ( $ctx $(, $names : $params )* ) $( -> $returns )* , )* ); return false; } } impl<E: Ext> $crate::wasm::env_def::FunctionImplProvider<E> for $init_name { fn impls<F: FnMut(&[u8], $crate::wasm::env_def::HostFunc<E>)>(f: &mut F) { register_func!(f, < E: $seal_ty > ; $( $name ( $ctx $( , $names : $params )* ) $( -> $returns)* => $body )* ); } } }; } #[cfg(test)] mod tests { use crate::exec::Ext; use crate::gas::Gas; use crate::wasm::tests::MockExt; use crate::wasm::Runtime; use parity_wasm::elements::FunctionType; use parity_wasm::elements::ValueType; use sp_runtime::traits::Zero; use sp_sandbox::{ReturnValue, Value}; #[test] fn macro_unmarshall_then_body_then_marshall_value_or_trap() { fn test_value( _ctx: &mut u32, args: &[sp_sandbox::Value], ) -> Result<ReturnValue, sp_sandbox::HostError> { let mut args = args.iter(); unmarshall_then_body_then_marshall!( args, _ctx, (a: u32, b: u32) -> u32 => { if b == 0 { Err(sp_sandbox::HostError) } else { Ok(a / b) } } ) } let ctx = &mut 0; assert_eq!( test_value(ctx, &[Value::I32(15), Value::I32(3)]).unwrap(), ReturnValue::Value(Value::I32(5)), ); assert!(test_value(ctx, &[Value::I32(15), Value::I32(0)]).is_err()); } #[test] fn macro_unmarshall_then_body_then_marshall_unit() { fn test_unit( ctx: &mut u32, args: &[sp_sandbox::Value], ) -> Result<ReturnValue, sp_sandbox::HostError> { let mut args = args.iter(); unmarshall_then_body_then_marshall!( args, ctx, (a: u32, b: u32) => { *ctx = a + b; Ok(()) } ) } let ctx = &mut 0; let result = test_unit(ctx, &[Value::I32(2), Value::I32(3)]).unwrap(); assert_eq!(result, ReturnValue::Unit); assert_eq!(*ctx, 5); } #[test] fn macro_define_func() { define_func!( <E: Ext> seal_gas (_ctx, amount: u32) => { let amount = Gas::from(amount); if !amount.is_zero() { Ok(()) } else { Err(sp_sandbox::HostError) } }); let _f: fn( &mut Runtime<MockExt>, &[sp_sandbox::Value], ) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> = seal_gas::<MockExt>; } #[test] fn macro_gen_signature() { assert_eq!(gen_signature!((i32)), FunctionType::new(vec![ValueType::I32], None),); assert_eq!( gen_signature!( (i32, u32) -> u32 ), FunctionType::new(vec![ValueType::I32, ValueType::I32], Some(ValueType::I32)), ); } #[test] fn macro_unmarshall_then_body() { let args = vec![Value::I32(5), Value::I32(3)]; let mut args = args.iter(); let ctx: &mut u32 = &mut 0; let r = unmarshall_then_body!( { *ctx = a + b; a * b }, ctx, args, a: u32, b: u32 ); assert_eq!(*ctx, 8); assert_eq!(r, 15); } #[test] fn macro_define_env() { use crate::wasm::env_def::ImportSatisfyCheck; define_env!(Env, <E: Ext>, seal_gas( _ctx, amount: u32 ) => { let amount = Gas::from(amount); if !amount.is_zero() { Ok(()) } else { Err(sp_sandbox::HostError) } }, ); assert!(Env::can_satisfy(b"seal_gas", &FunctionType::new(vec![ValueType::I32], None))); assert!(!Env::can_satisfy(b"not_exists", &FunctionType::new(vec![], None))); } }
use crate::{rejection::AzumaRejection, AZUMA_DB}; use bson::{bson, doc, from_bson, oid::ObjectId, to_bson, Bson::Document}; use pbkdf2::pbkdf2_simple; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize)] pub struct User { #[serde(rename = "_id")] pub id: ObjectId, pub name: String, pub password: String, pub icon: Option<String>, pub status: Option<String>, } impl User { pub fn new(name: String, password: String) -> Result<User, AzumaRejection> { let coll = AZUMA_DB.collection("users"); match coll.find_one(Some(doc! { "name": name.clone() }), None) { Ok(doc) => match doc { None => match pbkdf2_simple(&password, 100000) { Ok(hashed_password) => { let user = User { id: ObjectId::new().unwrap(), name, password: hashed_password, icon: None, status: None, }; match coll.insert_one( to_bson(&user).unwrap().as_document().unwrap().clone(), None, ) { Ok(_) => Ok(user), Err(_) => Err(AzumaRejection::InternalServerError), } } Err(_) => Err(AzumaRejection::InternalServerError), }, Some(_) => Err(AzumaRejection::AlreadyExists), }, Err(_) => Err(AzumaRejection::InternalServerError), } } pub fn get(name: String) -> Result<User, AzumaRejection> { let coll = AZUMA_DB.collection("users"); match coll.find_one(Some(doc! { "name": name }), None) { Ok(doc) => match doc { Some(doc) => match from_bson::<User>(Document(doc)) { Ok(user_result) => Ok(user_result), Err(_) => Err(AzumaRejection::InternalServerError), }, None => Err(AzumaRejection::NotFound), }, Err(_) => Err(AzumaRejection::InternalServerError), } } pub fn get_by_id(id: ObjectId) -> Result<User, AzumaRejection> { let coll = AZUMA_DB.collection("users"); match coll.find_one(Some(doc! { "_id": id }), None) { Ok(doc) => match doc { Some(doc) => match from_bson::<User>(Document(doc)) { Ok(user_result) => Ok(user_result), Err(_) => Err(AzumaRejection::InternalServerError), }, None => Err(AzumaRejection::NotFound), }, Err(_) => Err(AzumaRejection::InternalServerError), } } }
use chrono; pub type Duration = chrono::Duration; pub type DateTime = chrono::DateTime<chrono::Local>; pub fn from_utc_timestamp(t: i64) -> DateTime { let t = chrono::NaiveDateTime::from_timestamp(t, 0); let t: chrono::DateTime<chrono::Utc> = chrono::DateTime::from_utc(t, chrono::Utc); return chrono::DateTime::from(t); } pub struct DayTime { pub sunrise: DateTime, pub sunset: DateTime, } impl DayTime { pub fn from_utc(sunrise_utc: i64, sunset_utc: i64) -> DayTime { DayTime { sunrise: from_utc_timestamp(sunrise_utc), sunset: from_utc_timestamp(sunset_utc), } } pub fn at_night(&self, datetime: &DateTime) -> bool { datetime.time() < self.sunrise.time() || datetime.time() > self.sunset.time() } } #[derive(Copy, Clone)] pub struct Spot { pub duration: Duration, pub risetime: DateTime, } impl Spot { pub fn is_spottable(&self, now: DateTime) -> bool { now >= self.risetime && now < self.risetime + self.duration } pub fn at_night(&self, daytime: &DayTime) -> bool { daytime.at_night(&self.risetime) } } pub fn find_upcoming(spots: &Vec<Spot>, daytime: Option<&DayTime>, now: DateTime) -> Option<Spot> { // count upcoming spots for spot in spots { if spot.risetime > now { match daytime { Some(dt) => { if spot.at_night(&dt) { return Some(spot.clone()); } } _ => return Some(spot.clone()), } } } return None; } pub fn find_current(spots: &Vec<Spot>, daytime: Option<&DayTime>, now: DateTime) -> Option<Spot> { // count upcoming spots for spot in spots { if spot.is_spottable(now) { match daytime { Some(dt) => { return match spot.at_night(&dt) { true => Some(spot.clone()), _ => None, } } _ => return Some(spot.clone()), } } } return None; }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - DBGMCU Identity Code Register"] pub idc: IDC, #[doc = "0x04 - DBGMCU Configuration Register"] pub cr: CR, _reserved2: [u8; 0x2c], #[doc = "0x34 - DBGMCU APB3 peripheral freeze register CPU1"] pub apb3fz1: APB3FZ1, #[doc = "0x38 - DBGMCU APB3 peripheral freeze register CPU2"] pub apb3fz2: APB3FZ2, #[doc = "0x3c - DBGMCU APB1L peripheral freeze register"] pub apb1lfz1: APB1LFZ1, #[doc = "0x40 - DBGMCU APB1L peripheral freeze register CPU2"] pub apb1lfz2: APB1LFZ2, _reserved6: [u8; 0x08], #[doc = "0x4c - DBGMCU APB2 peripheral freeze register"] pub apb2fz1: APB2FZ1, #[doc = "0x50 - DBGMCU APB2 peripheral freeze register CPU2"] pub apb2fz2: APB2FZ2, #[doc = "0x54 - DBGMCU APB4 peripheral freeze register"] pub apb4fz1: APB4FZ1, #[doc = "0x58 - DBGMCU APB4 peripheral freeze register CPU2"] pub apb4fz2: APB4FZ2, } #[doc = "IDC (r) register accessor: DBGMCU Identity Code Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`idc::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`idc`] module"] pub type IDC = crate::Reg<idc::IDC_SPEC>; #[doc = "DBGMCU Identity Code Register"] pub mod idc; #[doc = "CR (rw) register accessor: DBGMCU Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`] module"] pub type CR = crate::Reg<cr::CR_SPEC>; #[doc = "DBGMCU Configuration Register"] pub mod cr; #[doc = "APB3FZ1 (rw) register accessor: DBGMCU APB3 peripheral freeze register CPU1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb3fz1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb3fz1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb3fz1`] module"] pub type APB3FZ1 = crate::Reg<apb3fz1::APB3FZ1_SPEC>; #[doc = "DBGMCU APB3 peripheral freeze register CPU1"] pub mod apb3fz1; #[doc = "APB3FZ2 (rw) register accessor: DBGMCU APB3 peripheral freeze register CPU2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb3fz2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb3fz2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb3fz2`] module"] pub type APB3FZ2 = crate::Reg<apb3fz2::APB3FZ2_SPEC>; #[doc = "DBGMCU APB3 peripheral freeze register CPU2"] pub mod apb3fz2; #[doc = "APB1LFZ1 (rw) register accessor: DBGMCU APB1L peripheral freeze register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1lfz1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb1lfz1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1lfz1`] module"] pub type APB1LFZ1 = crate::Reg<apb1lfz1::APB1LFZ1_SPEC>; #[doc = "DBGMCU APB1L peripheral freeze register"] pub mod apb1lfz1; #[doc = "APB1LFZ2 (rw) register accessor: DBGMCU APB1L peripheral freeze register CPU2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1lfz2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb1lfz2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1lfz2`] module"] pub type APB1LFZ2 = crate::Reg<apb1lfz2::APB1LFZ2_SPEC>; #[doc = "DBGMCU APB1L peripheral freeze register CPU2"] pub mod apb1lfz2; #[doc = "APB2FZ1 (rw) register accessor: DBGMCU APB2 peripheral freeze register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2fz1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb2fz1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb2fz1`] module"] pub type APB2FZ1 = crate::Reg<apb2fz1::APB2FZ1_SPEC>; #[doc = "DBGMCU APB2 peripheral freeze register"] pub mod apb2fz1; #[doc = "APB2FZ2 (rw) register accessor: DBGMCU APB2 peripheral freeze register CPU2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2fz2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb2fz2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb2fz2`] module"] pub type APB2FZ2 = crate::Reg<apb2fz2::APB2FZ2_SPEC>; #[doc = "DBGMCU APB2 peripheral freeze register CPU2"] pub mod apb2fz2; #[doc = "APB4FZ1 (rw) register accessor: DBGMCU APB4 peripheral freeze register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb4fz1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb4fz1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb4fz1`] module"] pub type APB4FZ1 = crate::Reg<apb4fz1::APB4FZ1_SPEC>; #[doc = "DBGMCU APB4 peripheral freeze register"] pub mod apb4fz1; #[doc = "APB4FZ2 (rw) register accessor: DBGMCU APB4 peripheral freeze register CPU2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb4fz2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb4fz2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb4fz2`] module"] pub type APB4FZ2 = crate::Reg<apb4fz2::APB4FZ2_SPEC>; #[doc = "DBGMCU APB4 peripheral freeze register CPU2"] pub mod apb4fz2;
#[doc = "Register `DDRPHYC_RIDR` reader"] pub type R = crate::R<DDRPHYC_RIDR_SPEC>; #[doc = "Field `PUBMNR` reader - PUBMNR"] pub type PUBMNR_R = crate::FieldReader; #[doc = "Field `PUBMDR` reader - PUBMDR"] pub type PUBMDR_R = crate::FieldReader; #[doc = "Field `PUBMJR` reader - PUBMJR"] pub type PUBMJR_R = crate::FieldReader; #[doc = "Field `PHYMNR` reader - PHYMNR"] pub type PHYMNR_R = crate::FieldReader; #[doc = "Field `PHYMDR` reader - PHYMDR"] pub type PHYMDR_R = crate::FieldReader; #[doc = "Field `PHYMJR` reader - PHYMJR"] pub type PHYMJR_R = crate::FieldReader; #[doc = "Field `UDRID` reader - UDRID"] pub type UDRID_R = crate::FieldReader; impl R { #[doc = "Bits 0:3 - PUBMNR"] #[inline(always)] pub fn pubmnr(&self) -> PUBMNR_R { PUBMNR_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - PUBMDR"] #[inline(always)] pub fn pubmdr(&self) -> PUBMDR_R { PUBMDR_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - PUBMJR"] #[inline(always)] pub fn pubmjr(&self) -> PUBMJR_R { PUBMJR_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - PHYMNR"] #[inline(always)] pub fn phymnr(&self) -> PHYMNR_R { PHYMNR_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:19 - PHYMDR"] #[inline(always)] pub fn phymdr(&self) -> PHYMDR_R { PHYMDR_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - PHYMJR"] #[inline(always)] pub fn phymjr(&self) -> PHYMJR_R { PHYMJR_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 24:31 - UDRID"] #[inline(always)] pub fn udrid(&self) -> UDRID_R { UDRID_R::new(((self.bits >> 24) & 0xff) as u8) } } #[doc = "DDRPHYC revision ID register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrphyc_ridr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DDRPHYC_RIDR_SPEC; impl crate::RegisterSpec for DDRPHYC_RIDR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ddrphyc_ridr::R`](R) reader structure"] impl crate::Readable for DDRPHYC_RIDR_SPEC {} #[doc = "`reset()` method sets DDRPHYC_RIDR to value 0x0041_0010"] impl crate::Resettable for DDRPHYC_RIDR_SPEC { const RESET_VALUE: Self::Ux = 0x0041_0010; }
#[doc = "Register `HR7` reader"] pub type R = crate::R<HR7_SPEC>; #[doc = "Field `H7` reader - Hash data x Refer to Section 24.7.4: HASH digest registers introduction."] pub type H7_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - Hash data x Refer to Section 24.7.4: HASH digest registers introduction."] #[inline(always)] pub fn h7(&self) -> H7_R { H7_R::new(self.bits) } } #[doc = "HASH supplementary digest register 7\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr7::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct HR7_SPEC; impl crate::RegisterSpec for HR7_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`hr7::R`](R) reader structure"] impl crate::Readable for HR7_SPEC {} #[doc = "`reset()` method sets HR7 to value 0"] impl crate::Resettable for HR7_SPEC { const RESET_VALUE: Self::Ux = 0; }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use crate::context::TraceContext; use chrome_trace::Args; use futures::task_local; use lazy_static::lazy_static; use std::sync::atomic::{AtomicUsize, Ordering}; mod future; mod stream; lazy_static! { static ref TASK_COUNTER: AtomicUsize = AtomicUsize::new(0); static ref EVENT_COUNTER: AtomicUsize = AtomicUsize::new(0); } task_local! { static TASK_ID: usize = TASK_COUNTER.fetch_add(1, Ordering::SeqCst) } /// Returns a counter representing the ID of the current task. This ID is arbitrary /// and unrelated to the way Tokio idenfies tasks internally. fn get_task_id() -> usize { TASK_ID.with(|n| *n) } /// Returns the value of a monotonically increasing counter, to help give events /// in the trace unique identifiers. fn new_event_id() -> usize { EVENT_COUNTER.fetch_add(1, Ordering::SeqCst) } /// A type representing an event ID, as used by `traced_with_id`. #[derive(Clone, Copy)] pub struct EventId { id: usize, } impl EventId { /// Get a new event ID for `traced_with_id`. Events with the same ID but different names are /// nested by the event viewer. pub fn new() -> Self { Self { id: new_event_id() } } } impl Default for EventId { fn default() -> Self { Self::new() } } /// The `Traced<T>` trait adds the `traced()` method to `Future`s and `Stream`s. /// The type parameter has no significance beyond the type level, but allows for blanket /// impls for all types implementing `Future` and `Stream` without causing overlap. pub trait Traced<T>: Sized { /// The type of the wrapped Future or Stream that is being returned from /// this trait. type Wrapper; /// A combinator that returns a wrapper that will add some statistics about /// the execution of the wrapped Future or Stream to the given /// [TraceContext] as events of name `name` and additional optional `args` fn traced<N: ToString>( self, context: &TraceContext, name: N, args: Option<Args>, ) -> Self::Wrapper; /// Similar to [Traced::traced], but also lets you set the EventId fn traced_with_id<N: ToString>( self, context: &TraceContext, name: N, args: Option<Args>, id: EventId, ) -> Self::Wrapper; } #[cfg(test)] mod tests { use super::*; use std::time::{Duration, Instant}; use futures::{future, Future, Stream}; use tokio::{ self, timer::{Delay, Interval}, }; use crate::context::TraceContext; #[test] fn future() { let context = TraceContext::default(); context.enable(); // Need to use `future::lazy` to ensure that there's no delay between setting the // deadline for the Delay and actually starting execution of the Future on tokio's // threadpool. Otherwise, the run time reported by the trace will be shorter than // expected. let sleep = future::lazy(|| Delay::new(Instant::now() + Duration::from_millis(10))) .map_err(|_| ()) .traced(&context, "my_event", None); tokio::run(sleep); // Check that the future was logged. let trace = context.snapshot(); assert_eq!(2, trace.trace_events.len()); assert_eq!("my_event", trace.trace_events[0].name); // Check that the future ran for as long as expected. let start = trace.trace_events[0].ts.unwrap(); let end = trace.trace_events[1].ts.unwrap(); println!("{:?}", end - start); assert!(end - start >= Duration::from_millis(10)); } #[test] fn stream() { let context = TraceContext::default(); context.enable(); // Need to use `future::lazy` to ensure that there's no delay between setting the // deadline for the Interval and actually starting execution of the Stream on tokio's // threadpool. Otherwise, the run time reported by the trace will be shorter than // expected. let sleeps = future::lazy({ let context = context.clone(); move || { // Set the Interval to start 5ms in the future to ensure that we observe // 4 full polls. Interval::new( Instant::now() + Duration::from_millis(5), Duration::from_millis(5), ) .take(4) .traced(&context, "my_stream", None) .collect() .then(|_| Ok(())) } }); tokio::run(sleeps); // Check that the future was logged. let trace = context.snapshot(); assert_eq!(2, trace.trace_events.len()); assert_eq!("my_stream", trace.trace_events[0].name); // Check that the future ran for as long as expected. let start = trace.trace_events[0].ts.unwrap(); let end = trace.trace_events[1].ts.unwrap(); assert!(end - start >= Duration::from_millis(20)); } }
use crate::{ binary, types::{Marshal, StatBuffer}, }; const MAX_VARINT_LEN64: usize = 10; #[derive(Default)] pub struct Encoder { buffer: Vec<u8>, } impl Encoder { pub fn new() -> Self { Encoder { buffer: Vec::new() } } pub fn uvarint(&mut self, v: u64) { let mut scratch = [0u8; MAX_VARINT_LEN64]; let ln = binary::put_uvarint(&mut scratch[..], v); self.write_bytes(&scratch[..ln]); } pub fn string(&mut self, text: impl AsRef<str>) { let bytes = text.as_ref().as_bytes(); self.byte_string(bytes); } pub fn byte_string(&mut self, source: impl AsRef<[u8]>) { self.uvarint(source.as_ref().len() as u64); self.write_bytes(source.as_ref()); } pub fn write<T>(&mut self, value: T) where T: Copy + Marshal + StatBuffer, { let mut buffer = T::buffer(); value.marshal(buffer.as_mut()); self.write_bytes(buffer.as_ref()); } pub fn write_bytes(&mut self, b: &[u8]) { self.buffer.extend_from_slice(b); } pub fn get_buffer(self) -> Vec<u8> { self.buffer } pub fn get_buffer_ref(&self) -> &[u8] { self.buffer.as_ref() } }
#[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_force(number_of_links: u8, link_length: f64, potential_distance: f64, potential_stiffness: f64, temperature: f64) -> f64 { super::force(&number_of_links, &link_length, &potential_distance, &potential_stiffness, &temperature) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_nondimensional_force(number_of_links: u8, nondimensional_potential_distance: f64, nondimensional_potential_stiffness: f64) -> f64 { super::nondimensional_force(&number_of_links, &nondimensional_potential_distance, &nondimensional_potential_stiffness) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, potential_distance: f64, potential_stiffness: f64, temperature: f64) -> f64 { super::helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &potential_distance, &potential_stiffness, &temperature) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_helmholtz_free_energy_per_link(number_of_links: u8, link_length: f64, hinge_mass: f64, potential_distance: f64, potential_stiffness: f64, temperature: f64) -> f64 { super::helmholtz_free_energy_per_link(&number_of_links, &link_length, &hinge_mass, &potential_distance, &potential_stiffness, &temperature) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_relative_helmholtz_free_energy(number_of_links: u8, link_length: f64, potential_distance: f64, potential_stiffness: f64, temperature: f64) -> f64 { super::relative_helmholtz_free_energy(&number_of_links, &link_length, &potential_distance, &potential_stiffness, &temperature) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_relative_helmholtz_free_energy_per_link(number_of_links: u8, link_length: f64, potential_distance: f64, potential_stiffness: f64, temperature: f64) -> f64 { super::relative_helmholtz_free_energy_per_link(&number_of_links, &link_length, &potential_distance, &potential_stiffness, &temperature) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_nondimensional_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_potential_distance: f64, nondimensional_potential_stiffness: f64, temperature: f64) -> f64 { super::nondimensional_helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_nondimensional_helmholtz_free_energy_per_link(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_potential_distance: f64, nondimensional_potential_stiffness: f64, temperature: f64) -> f64 { super::nondimensional_helmholtz_free_energy_per_link(&number_of_links, &link_length, &hinge_mass, &nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_nondimensional_relative_helmholtz_free_energy(number_of_links: u8, nondimensional_potential_distance: f64, nondimensional_potential_stiffness: f64) -> f64 { super::nondimensional_relative_helmholtz_free_energy(&number_of_links, &nondimensional_potential_distance, &nondimensional_potential_stiffness) } #[no_mangle] pub extern fn physics_single_chain_fjc_thermodynamics_modified_canonical_asymptotic_strong_potential_nondimensional_relative_helmholtz_free_energy_per_link(number_of_links: u8, nondimensional_potential_distance: f64, nondimensional_potential_stiffness: f64) -> f64 { super::nondimensional_relative_helmholtz_free_energy_per_link(&number_of_links, &nondimensional_potential_distance, &nondimensional_potential_stiffness) }
use rocket::http::ContentType; use rocket::response::{Response, Result}; use std::io::Cursor; #[derive(Serialize, Deserialize)] pub struct Health { pub code: bool, } pub fn get_health() -> Health { Health { code: true } } #[get("/healthz")] pub fn healthz() -> Result<'static> { Response::build() .header(ContentType::JSON) .sized_body(Cursor::new(serde_json::to_string(&get_health()).unwrap())) .ok() }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ //! Module that defines basic types and traits for implementations of mysql //! based [crate::Connection]. mod ext; mod imp; use std::fmt::Debug; use anyhow::Error; use auto_impl::auto_impl; use futures_ext::BoxFuture; use mysql_async::{ Conn, QueryResult as MysqlQueryResult, TextProtocol, Transaction, TransactionOptions, }; pub use ext::{MysqlConnectionExt, MysqlTransactionExt}; /// Boxed version of [MysqlConnection] that can be used in async code, because /// it is Send and Sync. It is also the type used in [crate::Connection] enum pub type BoxMysqlConnection = Box<dyn MysqlConnection + Send + Sync + 'static>; /// Boxed version of [MysqlTransaction] that can be used in async code, because /// it is Send and Sync. pub type BoxMysqlTransaction = Box<dyn MysqlTransaction + Send + Sync + 'static>; type QueryResult<T> = MysqlQueryResult<T, TextProtocol>; type QueryProcess<T> = Box<dyn FnOnce(QueryResult<T>) -> BoxFuture<QueryResult<T>, Error> + Send + 'static>; /// Alias for the Boxed function that processes [mysql_async::QueryResult] in /// [MysqlConnection::query] method. pub type ConQueryProcess = QueryProcess<Conn>; /// Alias for the Boxed function that processes [mysql_async::QueryResult] in /// [MysqlTransaction::query] method. pub type TraQueryProcess = QueryProcess<Transaction<Conn>>; /// The main trait of this module, implementations of this trait can be used /// with the sql's queries macro as part of [crate::Connection]. #[auto_impl(Box)] pub trait MysqlConnection: Debug { /// Perform the string query and process the [mysql_async::QueryResult]. /// A frequent pattern is to extract some values from the QueryResult and /// send it through a [::futures_old::sync::oneshot::channel] to retrieve it. fn query(&self, query: String, process: ConQueryProcess) -> BoxFuture<(), Error>; /// Return a transaction for this connection with provided options. fn transaction_with_options( &self, options: TransactionOptions, ) -> BoxFuture<BoxMysqlTransaction, Error>; /// A way for making [BoxMysqlConnection] implement Clone fn box_clone(&self) -> BoxMysqlConnection; /// Useful shortcut for creating a transaction with default transaction /// options. fn transaction(&self) -> BoxFuture<BoxMysqlTransaction, Error> { self.transaction_with_options(TransactionOptions::new()) } } impl Clone for BoxMysqlConnection { fn clone(&self) -> Self { self.box_clone() } } /// A transaction returned from [MysqlConnection::transaction_with_options] /// have to return a Boxed version of this trait. pub trait MysqlTransaction { /// Perform the string query and process the [mysql_async::QueryResult]. /// A frequent pattern is to extract some values from the QueryResult and /// send it through a [::futures_old::sync::oneshot::channel] to retrieve it. fn query( self: Box<Self>, query: String, process: TraQueryProcess, ) -> BoxFuture<BoxMysqlTransaction, Error>; /// Commit this transaction and drop it. fn commit(self: Box<Self>) -> BoxFuture<(), Error>; /// Rollback this transaction and drop it. fn rollback(self: Box<Self>) -> BoxFuture<(), Error>; }
use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::net::SocketAddr; use rand; use rand::Rng; use time::Duration; use uuid::Uuid; use member; use member::{Member, MemberState, StateChange}; pub struct MemberList { members: Vec<Member>, periodic_index: usize, } impl MemberList { pub fn new(me: Member) -> Self { MemberList { members: vec![me], periodic_index: 0, } } pub fn available_nodes(&self) -> Vec<Member> { self.members.iter().filter(|ref m| m.state() != MemberState::Left).cloned().collect() } pub fn to_map(&self) -> HashMap<Uuid, Member> { self.members.iter().map(|ref m| (m.host_key().clone(), (*m).clone())).collect() } fn mut_myself(&mut self) -> &mut Member { for member in self.members.iter_mut() { if member.is_myself() { return member; } } panic!("Could not find myself as member"); } pub fn reincarnate_self(&mut self) -> Member { let myself = self.mut_myself(); myself.reincarnate(); myself.clone() } pub fn leave(&mut self) -> Member { let myself = self.mut_myself(); myself.set_state(MemberState::Left); myself.reincarnate(); myself.clone() } pub fn next_random_member(&mut self) -> Option<Member> { if self.periodic_index == 0 { rand::thread_rng().shuffle(&mut self.members); } let other_members: Vec<_> = self.members.iter().filter(|&m| m.is_remote()).collect(); if other_members.len() == 0 { None } else { self.periodic_index = (self.periodic_index + 1) % other_members.len(); Some(other_members[self.periodic_index].clone()) } } pub fn time_out_nodes(&mut self, expired_hosts: HashSet<SocketAddr>) -> (Vec<Member>, Vec<Member>) { let mut suspect_members = Vec::new(); let mut down_members = Vec::new(); for mut member in self.members.iter_mut() { if let Some(remote_host) = member.remote_host() { if !expired_hosts.contains(&remote_host) { continue; } if member.state() == MemberState::Alive { member.set_state(MemberState::Suspect); suspect_members.push(member.clone()); } else if member.state() == MemberState::Suspect && member.state_change_older_than(Duration::seconds(3)) { member.set_state(MemberState::Down); down_members.push(member.clone()); } } } (suspect_members, down_members) } pub fn mark_node_alive(&mut self, src_addr: &SocketAddr) -> Option<Member> { for mut member in self.members.iter_mut() { if member.remote_host() == Some(*src_addr) && member.state() != MemberState::Alive { member.set_state(MemberState::Alive); return Some(member.clone()) } } None } pub fn apply_state_changes(&mut self, state_changes: Vec<StateChange>, from: &SocketAddr) -> (Vec<Member>, Vec<Member>) { let mut current_members = self.to_map(); let mut changed_nodes = Vec::new(); let mut new_nodes = Vec::new(); let my_host_key = self.mut_myself().host_key(); for state_change in state_changes { let new_member_data = state_change.member(); let old_member_data = current_members.entry(new_member_data.host_key()); if new_member_data.host_key() == my_host_key { if new_member_data.state() != MemberState::Alive { let myself = self.reincarnate_self(); changed_nodes.push(myself.clone()); } } else { match old_member_data { Entry::Occupied(mut entry) => { let new_member = member::most_recent_member_data(&new_member_data, entry.get()).clone(); let new_host = new_member.remote_host().or(entry.get().remote_host()).unwrap(); let new_member = new_member.member_by_changing_host(new_host); if new_member.state() != entry.get().state() { entry.insert(new_member.clone()); changed_nodes.push(new_member); } }, Entry::Vacant(entry) => { let new_host = new_member_data.remote_host().unwrap_or(*from); let new_member = new_member_data.member_by_changing_host(new_host); entry.insert(new_member.clone()); new_nodes.push(new_member); } }; } } self.members = current_members.values().cloned().collect(); (new_nodes, changed_nodes) } pub fn hosts_for_indirect_ping(&self, host_count: usize, target: &SocketAddr) -> Vec<SocketAddr> { let mut possible_members: Vec<_> = self.members .iter() .filter(|m| m.state() == MemberState::Alive && m.is_remote() && m.remote_host() != Some(*target)) .map(|m| m.remote_host().unwrap()) .collect(); rand::thread_rng().shuffle(&mut possible_members); possible_members.iter().take(host_count).cloned().collect() } pub fn has_member(&self, remote_host: &SocketAddr) -> bool { self.members.iter().any(|ref m| m.remote_host() == Some(*remote_host)) } pub fn add_member(&mut self, member: Member) { self.members.push(member) } }
fn main() { let mut x: u64 = 0; loop { io::println(fmt!("%?", x)); io::stdout().flush(); x += 1; } }
/* n: 10 k: 3 k_cd: 3 2 1 [ 5 4 3 2 1 3 2 3 3 1 ] ^ */ use std::io::{self, prelude::*}; use std::error::Error; /// We could re-write this to pass through the array only once. Right now, the worst case is /// when `arr.len() == k`, where we do two whole passes. fn num_k_countdowns(arr: &[u32], k: u32) -> usize { assert_ne!(k, 0); let n = arr.len(); if k as usize > n { return 0; } let k_countdown = (1..=k).rev(); let is_k_countdown = |i| -> bool { arr[i..i + k as usize].iter().copied().eq(k_countdown.clone()) }; (0..arr.len() - k as usize + 1).filter(|&i| is_k_countdown(i)).count() } type Res<T> = Result<T, Box<dyn Error>>; fn main() -> Res<()> { run_tests(io::stdin().lock().lines()) } /// Panics on malformed input. fn run_tests(mut lines: impl Iterator<Item = io::Result<String>>) -> Res<()> { let line = lines.next().unwrap()?; let t = line.parse()?; for test_no in 1..=t { let ans = one_test(&mut lines)?; println!("Case #{}: {}", test_no, ans); } Ok(()) } /// Panics on malformed input. fn one_test(lines: &mut impl Iterator<Item = io::Result<String>>) -> Res<usize> { let line = lines.next().unwrap()?; let mut words = line.split_whitespace(); let n: usize = words.next().unwrap().parse()?; let k: u32 = words.next().unwrap().parse()?; assert!(words.next().is_none()); let line = lines.next().unwrap()?; let words = line.split_whitespace(); let arr: Vec<_> = words.map(|w| w.parse::<u32>()).collect::<Result<_, _>>()?; assert_eq!(arr.len(), n); Ok(num_k_countdowns(&arr, k)) }
// (C) Copyright 2019 Hewlett Packard Enterprise Development LP use std::convert::TryFrom; use pest::Parser; use snafu::ResultExt; use crate::dockerfile_parser::Instruction; use crate::error::*; use crate::parser::{DockerfileParser, Pair, Rule}; /// Parses a string into a single instruction using a particular syntax rule. /// /// This is technically over-constrained as we could just parse any single /// instruction using `Rule::step`, however doing so isn't ideal for /// per-instruction unit tests. pub fn parse_single(input: &str, rule: Rule) -> Result<Instruction> { let record = DockerfileParser::parse(rule, input) .context(ParseError)? .next() .ok_or(Error::UnknownParseError)?; Instruction::try_from(record) } pub fn parse_direct<T, F>(input: &str, rule: Rule, func: F) -> Result<T> where F: Fn(Pair) -> Result<T> { let pair = DockerfileParser::parse(rule, input) .context(ParseError)? .next() .ok_or(Error::UnknownParseError)?; func(pair) }
use std::thread; use std::time::Duration; use std::sync::{Mutex, Arc}; /// Philosopher has a name, a fork to their left, and a fork to their right. `left` and `right` are /// the table-fork indexes (0-4) of the respective forks. struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { /// Creates a Philosopher with the specified `name`, `left` (fork index) and `right` (fork // index) values fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, } } /// Locks left fork mutex, sleeps 150ms, locks right fork mutex, sleeps 1s fn eat(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); println!("{} has picked up the left fork", self.name); thread::sleep(Duration::from_millis(150)); let _right = table.forks[self.right].lock().unwrap(); println!("{} is eating.", self.name); thread::sleep(Duration::from_millis(1000)); println!("{} is done eating.", self.name); } } /// Table has a collection of "forks", which are simply mutexes (as a fork can only be used by one /// person at a time) struct Table { forks: Vec<Mutex<()>>, } fn main() { // Create a new Table with 5 forks, and provide it with atomic reference counting so that we // can access the table from different threads let table = Arc::new(Table { forks: vec![ Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), ]}); // Create 5 philosophers, specifying the table-fork indexes of the fork to their left and the // fork to their right. Note the "Michel Foucault" philosopher is left-handed, and will thus // grab the fork to his left before grabbing the one to his right. let philosophers = vec![ Philosopher::new("Judith Butler", 0, 1), Philosopher::new("Gilles Deleuze", 1, 2), Philosopher::new("Karl Marx", 2, 3), Philosopher::new("Emma Goldman", 3, 4), Philosopher::new("Michel Foucault", 0, 4), // Michel Foucault is left-handed ]; // Map each philosopher to a new thread and tell them to eat let handles: Vec<_> = philosophers.into_iter().map(|p| { // Increment the table reference count by cloning it let table = table.clone(); thread::spawn(move || { p.eat(&table); }) }).collect(); // Loop through thread handles and block the main thread until they are all complete for h in handles { h.join().unwrap(); } }
use std::path::Path; mod feed_config { use serde::Deserialize; #[derive(Deserialize)] pub(crate) struct FeedConfig { pub(crate) feeds: Vec<Feed>, } #[derive(Deserialize)] pub(crate) struct Feed { pub(crate) title: String, pub(crate) url: String, } } #[derive(Debug)] pub enum Error { Io(std::io::Error), Toml(toml::de::Error), } impl From<std::io::Error> for Error { fn from(e: std::io::Error) -> Error { Error::Io(e) } } impl From<toml::de::Error> for Error { fn from(e: toml::de::Error) -> Error { Error::Toml(e) } } #[derive(Debug)] pub struct Site { pub title: String, pub url: String, } #[derive(Debug)] pub struct Article { pub title: String, pub url: String, } pub fn read_config<P: AsRef<Path>>(path: P) -> Result<Vec<Site>, Error> { let s = std::fs::read_to_string(path)?; let config: feed_config::FeedConfig = toml::de::from_str(&s)?; Ok(config .feeds .iter() .map(|f| Site { title: f.title.clone(), url: f.url.clone(), }) .collect()) }
#[doc = "Register `SMPR2` reader"] pub type R = crate::R<SMPR2_SPEC>; #[doc = "Register `SMPR2` writer"] pub type W = crate::W<SMPR2_SPEC>; #[doc = "Field `SMPx_x` reader - Sample time bits"] pub type SMPX_X_R = crate::FieldReader<SMPX_X_A>; #[doc = "Sample time bits\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u32)] pub enum SMPX_X_A { #[doc = "0: 1.5 ADC clock cycles"] Cycles15 = 0, #[doc = "1: 7.5 ADC clock cycles"] Cycles75 = 1, #[doc = "2: 13.5 ADC clock cycles"] Cycles135 = 2, #[doc = "3: 28.5 ADC clock cycles"] Cycles285 = 3, #[doc = "4: 41.5 ADC clock cycles"] Cycles415 = 4, #[doc = "5: 55.5 ADC clock cycles"] Cycles555 = 5, #[doc = "6: 71.5 ADC clock cycles"] Cycles715 = 6, #[doc = "7: 239.5 ADC clock cycles"] Cycles2395 = 7, } impl From<SMPX_X_A> for u32 { #[inline(always)] fn from(variant: SMPX_X_A) -> Self { variant as _ } } impl crate::FieldSpec for SMPX_X_A { type Ux = u32; } impl SMPX_X_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<SMPX_X_A> { match self.bits { 0 => Some(SMPX_X_A::Cycles15), 1 => Some(SMPX_X_A::Cycles75), 2 => Some(SMPX_X_A::Cycles135), 3 => Some(SMPX_X_A::Cycles285), 4 => Some(SMPX_X_A::Cycles415), 5 => Some(SMPX_X_A::Cycles555), 6 => Some(SMPX_X_A::Cycles715), 7 => Some(SMPX_X_A::Cycles2395), _ => None, } } #[doc = "1.5 ADC clock cycles"] #[inline(always)] pub fn is_cycles1_5(&self) -> bool { *self == SMPX_X_A::Cycles15 } #[doc = "7.5 ADC clock cycles"] #[inline(always)] pub fn is_cycles7_5(&self) -> bool { *self == SMPX_X_A::Cycles75 } #[doc = "13.5 ADC clock cycles"] #[inline(always)] pub fn is_cycles13_5(&self) -> bool { *self == SMPX_X_A::Cycles135 } #[doc = "28.5 ADC clock cycles"] #[inline(always)] pub fn is_cycles28_5(&self) -> bool { *self == SMPX_X_A::Cycles285 } #[doc = "41.5 ADC clock cycles"] #[inline(always)] pub fn is_cycles41_5(&self) -> bool { *self == SMPX_X_A::Cycles415 } #[doc = "55.5 ADC clock cycles"] #[inline(always)] pub fn is_cycles55_5(&self) -> bool { *self == SMPX_X_A::Cycles555 } #[doc = "71.5 ADC clock cycles"] #[inline(always)] pub fn is_cycles71_5(&self) -> bool { *self == SMPX_X_A::Cycles715 } #[doc = "239.5 ADC clock cycles"] #[inline(always)] pub fn is_cycles239_5(&self) -> bool { *self == SMPX_X_A::Cycles2395 } } #[doc = "Field `SMPx_x` writer - Sample time bits"] pub type SMPX_X_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, SMPX_X_A>; impl<'a, REG, const O: u8> SMPX_X_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u32>, { #[doc = "1.5 ADC clock cycles"] #[inline(always)] pub fn cycles1_5(self) -> &'a mut crate::W<REG> { self.variant(SMPX_X_A::Cycles15) } #[doc = "7.5 ADC clock cycles"] #[inline(always)] pub fn cycles7_5(self) -> &'a mut crate::W<REG> { self.variant(SMPX_X_A::Cycles75) } #[doc = "13.5 ADC clock cycles"] #[inline(always)] pub fn cycles13_5(self) -> &'a mut crate::W<REG> { self.variant(SMPX_X_A::Cycles135) } #[doc = "28.5 ADC clock cycles"] #[inline(always)] pub fn cycles28_5(self) -> &'a mut crate::W<REG> { self.variant(SMPX_X_A::Cycles285) } #[doc = "41.5 ADC clock cycles"] #[inline(always)] pub fn cycles41_5(self) -> &'a mut crate::W<REG> { self.variant(SMPX_X_A::Cycles415) } #[doc = "55.5 ADC clock cycles"] #[inline(always)] pub fn cycles55_5(self) -> &'a mut crate::W<REG> { self.variant(SMPX_X_A::Cycles555) } #[doc = "71.5 ADC clock cycles"] #[inline(always)] pub fn cycles71_5(self) -> &'a mut crate::W<REG> { self.variant(SMPX_X_A::Cycles715) } #[doc = "239.5 ADC clock cycles"] #[inline(always)] pub fn cycles239_5(self) -> &'a mut crate::W<REG> { self.variant(SMPX_X_A::Cycles2395) } } impl R { #[doc = "Bits 0:31 - Sample time bits"] #[inline(always)] pub fn smpx_x(&self) -> SMPX_X_R { SMPX_X_R::new(self.bits) } } impl W { #[doc = "Bits 0:31 - Sample time bits"] #[inline(always)] #[must_use] pub fn smpx_x(&mut self) -> SMPX_X_W<SMPR2_SPEC, 0> { SMPX_X_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "sample time register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`smpr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`smpr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SMPR2_SPEC; impl crate::RegisterSpec for SMPR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`smpr2::R`](R) reader structure"] impl crate::Readable for SMPR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`smpr2::W`](W) writer structure"] impl crate::Writable for SMPR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets SMPR2 to value 0"] impl crate::Resettable for SMPR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[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::MI2CCFG { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct STRDISR { bits: bool, } impl STRDISR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct SMPCNTR { bits: u8, } impl SMPCNTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct SDAENDLYR { bits: u8, } impl SDAENDLYR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct SCLENDLYR { bits: u8, } impl SCLENDLYR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct MI2CRSTR { bits: bool, } impl MI2CRSTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct SDADLYR { bits: u8, } impl SDADLYR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = "Possible values of the field `ARBEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ARBENR { #[doc = "Enable multi-master bus arbitration support for this i2c master value."] ARBEN, #[doc = "Disable multi-master bus arbitration support for this i2c master value."] ARBDIS, } impl ARBENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { ARBENR::ARBEN => true, ARBENR::ARBDIS => false, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ARBENR { match value { true => ARBENR::ARBEN, false => ARBENR::ARBDIS, } } #[doc = "Checks if the value of the field is `ARBEN`"] #[inline] pub fn is_arben(&self) -> bool { *self == ARBENR::ARBEN } #[doc = "Checks if the value of the field is `ARBDIS`"] #[inline] pub fn is_arbdis(&self) -> bool { *self == ARBENR::ARBDIS } } #[doc = "Possible values of the field `I2CLSB`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum I2CLSBR { #[doc = "Byte data is transmitted MSB first onto the bus/read from the bus value."] MSBFIRST, #[doc = "Byte data is transmitted LSB first onto the bus/read from the bus value."] LSBFIRST, } impl I2CLSBR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { I2CLSBR::MSBFIRST => false, I2CLSBR::LSBFIRST => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> I2CLSBR { match value { false => I2CLSBR::MSBFIRST, true => I2CLSBR::LSBFIRST, } } #[doc = "Checks if the value of the field is `MSBFIRST`"] #[inline] pub fn is_msbfirst(&self) -> bool { *self == I2CLSBR::MSBFIRST } #[doc = "Checks if the value of the field is `LSBFIRST`"] #[inline] pub fn is_lsbfirst(&self) -> bool { *self == I2CLSBR::LSBFIRST } } #[doc = "Possible values of the field `ADDRSZ`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADDRSZR { #[doc = "Use 7b addressing for I2C master transactions value."] ADDRSZ7, #[doc = "Use 10b addressing for I2C master transactions value."] ADDRSZ10, } impl ADDRSZR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { ADDRSZR::ADDRSZ7 => false, ADDRSZR::ADDRSZ10 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ADDRSZR { match value { false => ADDRSZR::ADDRSZ7, true => ADDRSZR::ADDRSZ10, } } #[doc = "Checks if the value of the field is `ADDRSZ7`"] #[inline] pub fn is_addrsz7(&self) -> bool { *self == ADDRSZR::ADDRSZ7 } #[doc = "Checks if the value of the field is `ADDRSZ10`"] #[inline] pub fn is_addrsz10(&self) -> bool { *self == ADDRSZR::ADDRSZ10 } } #[doc = r" Proxy"] pub struct _STRDISW<'a> { w: &'a mut W, } impl<'a> _STRDISW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SMPCNTW<'a> { w: &'a mut W, } impl<'a> _SMPCNTW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SDAENDLYW<'a> { w: &'a mut W, } impl<'a> _SDAENDLYW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SCLENDLYW<'a> { w: &'a mut W, } impl<'a> _SCLENDLYW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _MI2CRSTW<'a> { w: &'a mut W, } impl<'a> _MI2CRSTW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SDADLYW<'a> { w: &'a mut W, } impl<'a> _SDADLYW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ARBEN`"] pub enum ARBENW { #[doc = "Enable multi-master bus arbitration support for this i2c master value."] ARBEN, #[doc = "Disable multi-master bus arbitration support for this i2c master value."] ARBDIS, } impl ARBENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ARBENW::ARBEN => true, ARBENW::ARBDIS => false, } } } #[doc = r" Proxy"] pub struct _ARBENW<'a> { w: &'a mut W, } impl<'a> _ARBENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ARBENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable multi-master bus arbitration support for this i2c master value."] #[inline] pub fn arben(self) -> &'a mut W { self.variant(ARBENW::ARBEN) } #[doc = "Disable multi-master bus arbitration support for this i2c master value."] #[inline] pub fn arbdis(self) -> &'a mut W { self.variant(ARBENW::ARBDIS) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `I2CLSB`"] pub enum I2CLSBW { #[doc = "Byte data is transmitted MSB first onto the bus/read from the bus value."] MSBFIRST, #[doc = "Byte data is transmitted LSB first onto the bus/read from the bus value."] LSBFIRST, } impl I2CLSBW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { I2CLSBW::MSBFIRST => false, I2CLSBW::LSBFIRST => true, } } } #[doc = r" Proxy"] pub struct _I2CLSBW<'a> { w: &'a mut W, } impl<'a> _I2CLSBW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: I2CLSBW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Byte data is transmitted MSB first onto the bus/read from the bus value."] #[inline] pub fn msbfirst(self) -> &'a mut W { self.variant(I2CLSBW::MSBFIRST) } #[doc = "Byte data is transmitted LSB first onto the bus/read from the bus value."] #[inline] pub fn lsbfirst(self) -> &'a mut W { self.variant(I2CLSBW::LSBFIRST) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ADDRSZ`"] pub enum ADDRSZW { #[doc = "Use 7b addressing for I2C master transactions value."] ADDRSZ7, #[doc = "Use 10b addressing for I2C master transactions value."] ADDRSZ10, } impl ADDRSZW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ADDRSZW::ADDRSZ7 => false, ADDRSZW::ADDRSZ10 => true, } } } #[doc = r" Proxy"] pub struct _ADDRSZW<'a> { w: &'a mut W, } impl<'a> _ADDRSZW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ADDRSZW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Use 7b addressing for I2C master transactions value."] #[inline] pub fn addrsz7(self) -> &'a mut W { self.variant(ADDRSZW::ADDRSZ7) } #[doc = "Use 10b addressing for I2C master transactions value."] #[inline] pub fn addrsz10(self) -> &'a mut W { self.variant(ADDRSZW::ADDRSZ10) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 24 - Disable detection of clock stretch events smaller than 1 cycle"] #[inline] pub fn strdis(&self) -> STRDISR { let bits = { const MASK: bool = true; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) != 0 }; STRDISR { bits } } #[doc = "Bits 16:23 - Number of Base clk cycles to wait before sampling the SCL clock to determine if a clock stretch event has occured"] #[inline] pub fn smpcnt(&self) -> SMPCNTR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; SMPCNTR { bits } } #[doc = "Bits 12:15 - Number of IOCLK cycles to delay the SDA output en (all transitions affected). Used to delay data relative to clock"] #[inline] pub fn sdaendly(&self) -> SDAENDLYR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 }; SDAENDLYR { bits } } #[doc = "Bits 8:11 - Number of IOCLK cycles to delay the rising edge of the SCL output en (clock will go low on this edge). Used to allow clock shaping."] #[inline] pub fn sclendly(&self) -> SCLENDLYR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 }; SCLENDLYR { bits } } #[doc = "Bit 6 - Not used. To reset the module, toggle the SMOD_EN for the module"] #[inline] pub fn mi2crst(&self) -> MI2CRSTR { let bits = { const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; MI2CRSTR { bits } } #[doc = "Bits 4:5 - Delay to enable on the SDA output. Values are 0x0-0x3."] #[inline] pub fn sdadly(&self) -> SDADLYR { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 }; SDADLYR { bits } } #[doc = "Bit 2 - Enables multi-master arbitration for the I2C master. If the bus is known to have only a single master, this function can be disabled to save clock cycles on I2C transactions"] #[inline] pub fn arben(&self) -> ARBENR { ARBENR::_from({ const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 1 - Direction of data transmit and receive, MSB(0) or LSB(1) first. Default per I2C specification is MSB first. This applies to both read and write data, and read data will be bit"] #[inline] pub fn i2clsb(&self) -> I2CLSBR { I2CLSBR::_from({ const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 0 - Sets the I2C master device address size to either 7b (0) or 10b (1)."] #[inline] pub fn addrsz(&self) -> ADDRSZR { ADDRSZR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 24 - Disable detection of clock stretch events smaller than 1 cycle"] #[inline] pub fn strdis(&mut self) -> _STRDISW { _STRDISW { w: self } } #[doc = "Bits 16:23 - Number of Base clk cycles to wait before sampling the SCL clock to determine if a clock stretch event has occured"] #[inline] pub fn smpcnt(&mut self) -> _SMPCNTW { _SMPCNTW { w: self } } #[doc = "Bits 12:15 - Number of IOCLK cycles to delay the SDA output en (all transitions affected). Used to delay data relative to clock"] #[inline] pub fn sdaendly(&mut self) -> _SDAENDLYW { _SDAENDLYW { w: self } } #[doc = "Bits 8:11 - Number of IOCLK cycles to delay the rising edge of the SCL output en (clock will go low on this edge). Used to allow clock shaping."] #[inline] pub fn sclendly(&mut self) -> _SCLENDLYW { _SCLENDLYW { w: self } } #[doc = "Bit 6 - Not used. To reset the module, toggle the SMOD_EN for the module"] #[inline] pub fn mi2crst(&mut self) -> _MI2CRSTW { _MI2CRSTW { w: self } } #[doc = "Bits 4:5 - Delay to enable on the SDA output. Values are 0x0-0x3."] #[inline] pub fn sdadly(&mut self) -> _SDADLYW { _SDADLYW { w: self } } #[doc = "Bit 2 - Enables multi-master arbitration for the I2C master. If the bus is known to have only a single master, this function can be disabled to save clock cycles on I2C transactions"] #[inline] pub fn arben(&mut self) -> _ARBENW { _ARBENW { w: self } } #[doc = "Bit 1 - Direction of data transmit and receive, MSB(0) or LSB(1) first. Default per I2C specification is MSB first. This applies to both read and write data, and read data will be bit"] #[inline] pub fn i2clsb(&mut self) -> _I2CLSBW { _I2CLSBW { w: self } } #[doc = "Bit 0 - Sets the I2C master device address size to either 7b (0) or 10b (1)."] #[inline] pub fn addrsz(&mut self) -> _ADDRSZW { _ADDRSZW { w: self } } }
extern crate log; extern crate chrono; extern crate allegro; extern crate allegro_primitives; extern crate allegro_font; extern crate rand; pub mod logger;
#![cfg_attr(not(feature = "std"), no_std)] #![feature(const_if_match, const_loop, track_caller, proc_macro_hygiene)] #![feature(asm)] #![feature(associated_type_bounds)] #![feature(simd_ffi)] // lol sorry jam pub mod crc32; pub mod params; #[doc(hidden)] pub mod cpp; #[doc(hidden)] pub mod common; #[doc(inline)] pub use common::root::*; #[doc(inline)] pub use cpp::root::*; // Find the hash40 of a given string pub const fn hash40(string: &str) -> u64 { let bytes = string.as_bytes(); ((bytes.len() as u64) << 32) + crc32::crc32(bytes) as u64 } impl phx::Hash40 { pub fn new(string: &str) -> Self { Self { hash: hash40(string), } } pub fn new_raw(raw: u64) -> Self { Self { hash: raw } } } mod lua_const; #[repr(C)] pub struct CppHash40MapEntry<T> { pub next: *mut Self, pub key: phx::Hash40, pub also_key: phx::Hash40, pub value: T } #[repr(C)] #[derive(Debug, Copy, Clone)] // really bad, don't do this :P pub struct CppHash40Map<T: Sized> { pub buckets: *const *mut CppHash40MapEntry<T>, pub bucket_count: u64 } impl<T: Sized> CppHash40Map<T> { pub fn get<'a>(&'a self, key: &phx::Hash40) -> Option<&'a T> { if !self.buckets.is_null() { unsafe { let bucket_idx = key.hash % self.bucket_count; let mut current = *self.buckets.add(bucket_idx as usize); if !current.is_null() { current = (*current).next; while !current.is_null() { let current_key = (*current).key; if current_key != *key && (current_key.hash % self.bucket_count) != bucket_idx { break; } if current_key == *key && (*current).also_key == *key { return Some(&(*current).value); } current = (*current).next; } } None } } else { None } } pub fn get_mut(&mut self, key: &phx::Hash40) -> Option<&mut T> { let bucket_idx = key.hash % self.bucket_count; if !self.buckets.is_null() { unsafe { let mut current = *self.buckets.add(bucket_idx as usize); if !current.is_null() { current = (*current).next; while !current.is_null() { let current_key = (*current).key; if current_key != *key && (current_key.hash % self.bucket_count) != bucket_idx { break; } if current_key == *key && (*current).also_key == *key { return Some(&mut (*current).value); } current = (*current).next; } } None } } else { None } } }
mod version; pub use self::version::SdpVersion; pub use self::version::parse_version; pub use self::version::parse_version_line; mod session_name; pub use self::session_name::SdpSessionName; pub use self::session_name::parse_session_name; pub use self::session_name::parse_session_name_line; mod origin; pub use self::origin::SdpOrigin; pub use self::origin::parse_origin; pub use self::origin::parse_origin_line; mod timing; pub use self::timing::SdpTiming; pub use self::timing::parse_timing; pub use self::timing::parse_time_line; mod connection; pub use self::connection::SdpConnection; pub use self::connection::parse_connection; pub use self::connection::parse_connection_name; use crate::SdpOptionalAttribute; use crate::parse::slice_to_string; use nom::{ IResult, bytes::complete::{tag,take_until}, combinator::map_res }; pub fn parse_email_line(input: &[u8]) -> IResult<&[u8], SdpOptionalAttribute> { let (input, _) = tag("e=")(input)?; let (input, output) = map_res(take_until("\r"), slice_to_string)(input)?; let (input, _) = tag("\r\n")(input)?; Ok((input, SdpOptionalAttribute::Email(output))) } pub fn parse_phone_line(input: &[u8]) -> IResult<&[u8], SdpOptionalAttribute> { let (input, _) = tag("e=")(input)?; let (input, output) = map_res(take_until("\r"), slice_to_string)(input)?; let (input, _) = tag("\r\n")(input)?; Ok((input, SdpOptionalAttribute::Phone(output))) } pub fn parse_information_line(input: &[u8]) -> IResult<&[u8], SdpOptionalAttribute> { let (input, _) = tag("i=")(input)?; let (input, output) = map_res(take_until("\r"), slice_to_string)(input)?; let (input, _) = tag("\r\n")(input)?; Ok((input, SdpOptionalAttribute::Information(output))) } pub fn parse_uri_line(input: &[u8]) -> IResult<&[u8], SdpOptionalAttribute> { let (input, _) = tag("u=")(input)?; let (input, output) = map_res(take_until("\r"), slice_to_string)(input)?; let (input, _) = tag("\r\n")(input)?; Ok((input, SdpOptionalAttribute::Uri(output))) }
pub fn add_to_waitlist() { println!("{}", "哈哈行,Hello, world!111111111"); }
pub mod http; pub mod paths;
mod utils; // mod shaders; // pub mod renderer; /// This module contains all the information needed to load a GLSL shader file formatted /// to work with MPV and parses them into portable packages. pub mod shader_loader; /// Main AniSS container pub mod ani_ss; pub use ani_ss::AniSS;
// RC algorithm // https://en.wikipedia.org/wiki/RC_algorithm // // The RC algorithms are a set of symmetric-key encryption algorithms invented by Ron Rivest. // The "RC" may stand for either Rivest's cipher or, more informally, Ron's code.[1] // Despite the similarity in their names, the algorithms are for the most part unrelated. // There have been six RC algorithms so far: // // RC1 was never published. // RC2 was a 64-bit block cipher developed in 1987. // RC3 was broken before ever being used. // RC4 is a stream cipher. // RC5 is a 32/64/128-bit block cipher developed in 1994. // RC6, a 128-bit block cipher based heavily on RC5, was an AES finalist developed in 1997. const PI_TABLE: [u8; 256] = [ 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, ]; const MIN_KEY_LEN: usize = 1; // In bytes const MAX_KEY_LEN: usize = 128; // In bytes #[inline] fn key_expansion(key: &[u8], t1: usize) -> [u16; 64] { let t = key.len(); assert!(t >= MIN_KEY_LEN && t <= MAX_KEY_LEN); let t8: usize = (t1 + 7) >> 3; let tm: usize = (255 % (2u32.pow((8 + t1 - 8 * t8) as u32))) as usize; let mut buf: [u8; 128] = [0; 128]; buf[..t].copy_from_slice(&key[..t]); for i in t..128 { let pos: u32 = (u32::from(buf[i - 1]) + u32::from(buf[i - t])) & 0xff; buf[i] = PI_TABLE[pos as usize]; } buf[128 - t8] = PI_TABLE[(buf[128 - t8] & tm as u8) as usize]; for i in (0..128 - t8).rev() { let pos: usize = (buf[i + 1] ^ buf[i + t8]) as usize; buf[i] = PI_TABLE[pos]; } let mut ek: [u16; 64] = [0; 64]; for i in 0..64 { ek[i] = (u16::from(buf[2 * i + 1]) << 8) + u16::from(buf[2 * i]) } ek } #[inline] fn mix(ek: &[u16; 64], r: &mut [u16; 4], j: &mut usize) { r[0] = r[0] .wrapping_add(ek[*j]) .wrapping_add(r[3] & r[2]) .wrapping_add(!r[3] & r[1]); *j += 1; r[0] = (r[0] << 1) | (r[0] >> 15); r[1] = r[1] .wrapping_add(ek[*j]) .wrapping_add(r[0] & r[3]) .wrapping_add(!r[0] & r[2]); *j += 1; r[1] = (r[1] << 2) | (r[1] >> 14); r[2] = r[2] .wrapping_add(ek[*j]) .wrapping_add(r[1] & r[0]) .wrapping_add(!r[1] & r[3]); *j += 1; r[2] = (r[2] << 3) | (r[2] >> 13); r[3] = r[3] .wrapping_add(ek[*j]) .wrapping_add(r[2] & r[1]) .wrapping_add(!r[2] & r[0]); *j += 1; r[3] = (r[3] << 5) | (r[3] >> 11); } #[inline] fn reverse_mix(ek: &[u16; 64], r: &mut [u16; 4], j: &mut usize) { r[3] = (r[3] << 11) | (r[3] >> 5); r[3] = r[3] .wrapping_sub(ek[*j]) .wrapping_sub(r[2] & r[1]) .wrapping_sub(!r[2] & r[0]); *j -= 1; r[2] = (r[2] << 13) | (r[2] >> 3); r[2] = r[2] .wrapping_sub(ek[*j]) .wrapping_sub(r[1] & r[0]) .wrapping_sub(!r[1] & r[3]); *j -= 1; r[1] = (r[1] << 14) | (r[1] >> 2); r[1] = r[1] .wrapping_sub(ek[*j]) .wrapping_sub(r[0] & r[3]) .wrapping_sub(!r[0] & r[2]); *j -= 1; r[0] = (r[0] << 15) | (r[0] >> 1); r[0] = r[0] .wrapping_sub(ek[*j]) .wrapping_sub(r[3] & r[2]) .wrapping_sub(!r[3] & r[1]); *j = j.wrapping_sub(1); } #[inline] fn mash(ek: &[u16; 64], r: &mut [u16; 4]) { r[0] = r[0].wrapping_add(ek[(r[3] & 63) as usize]); r[1] = r[1].wrapping_add(ek[(r[0] & 63) as usize]); r[2] = r[2].wrapping_add(ek[(r[1] & 63) as usize]); r[3] = r[3].wrapping_add(ek[(r[2] & 63) as usize]); } #[inline] fn reverse_mash(ek: &[u16; 64], r: &mut [u16; 4]) { r[3] = r[3].wrapping_sub(ek[(r[2] & 63) as usize]); r[2] = r[2].wrapping_sub(ek[(r[1] & 63) as usize]); r[1] = r[1].wrapping_sub(ek[(r[0] & 63) as usize]); r[0] = r[0].wrapping_sub(ek[(r[3] & 63) as usize]); } /// RC2, KEY-LEN 128-bits, BLOCK-LEN 128-bits #[derive(Clone)] pub struct Rc2FixedSize { inner: Rc2, } impl core::fmt::Debug for Rc2FixedSize { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("Rc2FixedSize").finish() } } impl Rc2FixedSize { pub const KEY_LEN: usize = 16; pub const BLOCK_LEN: usize = 16; pub fn new(key: &[u8]) -> Self { assert_eq!(key.len(), Self::KEY_LEN); let inner = Rc2::new(key); Self { inner } } pub fn encrypt(&self, block: &mut [u8]) { debug_assert_eq!(block.len(), Self::BLOCK_LEN); self.inner.encrypt_two_blocks(block); } pub fn decrypt(&self, block: &mut [u8]) { debug_assert_eq!(block.len(), Self::BLOCK_LEN); self.inner.decrypt_two_blocks(block); } } // A Description of the RC2(r) Encryption Algorithm (RC2 (also known as ARC2)) // https://tools.ietf.org/html/rfc2268 // https://en.wikipedia.org/wiki/RC2 /// RC2 (also known as ARC2) #[derive(Clone)] pub struct Rc2 { ek: [u16; 64], } impl core::fmt::Debug for Rc2 { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("Rc2").finish() } } impl Rc2 { pub const BLOCK_LEN: usize = 8; // In bytes pub const MIN_KEY_LEN: usize = MIN_KEY_LEN; // In bytes pub const MAX_KEY_LEN: usize = MAX_KEY_LEN; // In bytes pub fn new(key: &[u8]) -> Self { Self::with_effective_key_len(key, key.len() * 8) } // effective key length: in bits pub fn with_effective_key_len(key: &[u8], effective_key_len: usize) -> Self { assert!(key.len() >= Self::MIN_KEY_LEN && key.len() <= Self::MAX_KEY_LEN); let ek = key_expansion(key, effective_key_len); Self { ek } } pub fn encrypt(&self, block: &mut [u8]) { debug_assert_eq!(block.len(), Self::BLOCK_LEN); let mut r: [u16; 4] = [ (u16::from(block[1]) << 8) + u16::from(block[0]), (u16::from(block[3]) << 8) + u16::from(block[2]), (u16::from(block[5]) << 8) + u16::from(block[4]), (u16::from(block[7]) << 8) + u16::from(block[6]), ]; let mut j = 0; for i in 0..16 { mix(&self.ek, &mut r, &mut j); if i == 4 || i == 10 { mash(&self.ek, &mut r); } } block[0] = (r[0] & 0xff) as u8; block[1] = (r[0] >> 8) as u8; block[2] = (r[1] & 0xff) as u8; block[3] = (r[1] >> 8) as u8; block[4] = (r[2] & 0xff) as u8; block[5] = (r[2] >> 8) as u8; block[6] = (r[3] & 0xff) as u8; block[7] = (r[3] >> 8) as u8; } pub fn decrypt(&self, block: &mut [u8]) { debug_assert_eq!(block.len(), Self::BLOCK_LEN); let mut r: [u16; 4] = [ (u16::from(block[1]) << 8) + u16::from(block[0]), (u16::from(block[3]) << 8) + u16::from(block[2]), (u16::from(block[5]) << 8) + u16::from(block[4]), (u16::from(block[7]) << 8) + u16::from(block[6]), ]; let mut j = 63; for i in 0..16 { reverse_mix(&self.ek, &mut r, &mut j); if i == 4 || i == 10 { reverse_mash(&self.ek, &mut r); } } block[0] = r[0] as u8; block[1] = (r[0] >> 8) as u8; block[2] = r[1] as u8; block[3] = (r[1] >> 8) as u8; block[4] = r[2] as u8; block[5] = (r[2] >> 8) as u8; block[6] = r[3] as u8; block[7] = (r[3] >> 8) as u8; } // NOTE: // 使块大小变成 16 bytes,跟主流的对称分组密码一样。 pub fn encrypt_two_blocks(&self, blocks: &mut [u8]) { debug_assert_eq!(blocks.len(), Self::BLOCK_LEN * 2); self.encrypt(&mut blocks[0..8]); self.encrypt(&mut blocks[8..16]); } pub fn decrypt_two_blocks(&self, blocks: &mut [u8]) { debug_assert_eq!(blocks.len(), Self::BLOCK_LEN * 2); self.decrypt(&mut blocks[0..8]); self.decrypt(&mut blocks[8..16]); } } #[test] fn test_rc2() { // 5. Test vectors // https://tools.ietf.org/html/rfc2268#section-5 let key = hex::decode("0000000000000000").unwrap(); let effective_key_len = 63; let plaintext = hex::decode("0000000000000000").unwrap(); let c = Rc2::with_effective_key_len(&key, effective_key_len); let mut ciphertext = plaintext.clone(); c.encrypt(&mut ciphertext); assert_eq!( &ciphertext[..], &hex::decode("ebb773f993278eff").unwrap()[..] ); let key = hex::decode("ffffffffffffffff").unwrap(); let effective_key_len = 64; let plaintext = hex::decode("ffffffffffffffff").unwrap(); let c = Rc2::with_effective_key_len(&key, effective_key_len); let mut ciphertext = plaintext.clone(); c.encrypt(&mut ciphertext); assert_eq!( &ciphertext[..], &hex::decode("278b27e42e2f0d49").unwrap()[..] ); let key = hex::decode("3000000000000000").unwrap(); let effective_key_len = 64; let plaintext = hex::decode("1000000000000001").unwrap(); let c = Rc2::with_effective_key_len(&key, effective_key_len); let mut ciphertext = plaintext.clone(); c.encrypt(&mut ciphertext); assert_eq!( &ciphertext[..], &hex::decode("30649edf9be7d2c2").unwrap()[..] ); let key = hex::decode("88").unwrap(); let effective_key_len = 64; let plaintext = hex::decode("0000000000000000").unwrap(); let c = Rc2::with_effective_key_len(&key, effective_key_len); let mut ciphertext = plaintext.clone(); c.encrypt(&mut ciphertext); assert_eq!( &ciphertext[..], &hex::decode("61a8a244adacccf0").unwrap()[..] ); let key = hex::decode("88bca90e90875a").unwrap(); let effective_key_len = 64; let plaintext = hex::decode("0000000000000000").unwrap(); let c = Rc2::with_effective_key_len(&key, effective_key_len); let mut ciphertext = plaintext.clone(); c.encrypt(&mut ciphertext); assert_eq!( &ciphertext[..], &hex::decode("6ccf4308974c267f").unwrap()[..] ); let key = hex::decode("88bca90e90875a7f0f79c384627bafb2").unwrap(); let effective_key_len = 64; let plaintext = hex::decode("0000000000000000").unwrap(); let c = Rc2::with_effective_key_len(&key, effective_key_len); let mut ciphertext = plaintext.clone(); c.encrypt(&mut ciphertext); assert_eq!( &ciphertext[..], &hex::decode("1a807d272bbe5db1").unwrap()[..] ); let key = hex::decode("88bca90e90875a7f0f79c384627bafb2").unwrap(); let effective_key_len = 128; let plaintext = hex::decode("0000000000000000").unwrap(); let c = Rc2::with_effective_key_len(&key, effective_key_len); let mut ciphertext = plaintext.clone(); c.encrypt(&mut ciphertext); assert_eq!( &ciphertext[..], &hex::decode("2269552ab0f85ca6").unwrap()[..] ); let key = hex::decode( "88bca90e90875a7f0f79c384627bafb216f80a6f85920584\ c42fceb0be255daf1e", ) .unwrap(); let effective_key_len = 129; let plaintext = hex::decode("0000000000000000").unwrap(); let c = Rc2::with_effective_key_len(&key, effective_key_len); let mut ciphertext = plaintext.clone(); c.encrypt(&mut ciphertext); assert_eq!( &ciphertext[..], &hex::decode("5b78d3a43dfff1f1").unwrap()[..] ); }
use crate::table::responses::*; use crate::{table::prelude::*, ContinuationNextTableName}; use azure_core::prelude::*; use azure_core::{headers::add_optional_header, AppendToUrlQuery}; use futures::stream::{unfold, Stream}; use http::method::Method; use http::status::StatusCode; use std::convert::TryInto; #[cfg(test)] use std::println as debug; #[derive(Debug, Clone)] pub struct ListTablesBuilder<'a> { table_service_client: &'a TableServiceClient, filter: Option<Filter<'a>>, select: Option<Select<'a>>, top: Option<Top>, continuation_next_table_name: Option<ContinuationNextTableName>, client_request_id: Option<ClientRequestId<'a>>, } impl<'a> ListTablesBuilder<'a> { pub(crate) fn new(table_service_client: &'a TableServiceClient) -> Self { Self { table_service_client, filter: None, select: None, top: None, continuation_next_table_name: None, client_request_id: None, } } setters! { filter: Filter<'a> => Some(filter), select: Select<'a> => Some(select), top: Top => Some(top), continuation_next_table_name: ContinuationNextTableName => Some(continuation_next_table_name), client_request_id: ClientRequestId<'a> => Some(client_request_id), } pub async fn execute( &self, ) -> Result<ListTablesResponse, Box<dyn std::error::Error + Sync + Send>> { let mut url = self.table_service_client.url().to_owned(); self.filter.append_to_url_query(&mut url); self.select.append_to_url_query(&mut url); self.top.append_to_url_query(&mut url); self.continuation_next_table_name .append_to_url_query(&mut url); debug!("list tables url = {}", url); let request = self.table_service_client.prepare_request( url.as_str(), &Method::GET, &|mut request| { request = add_optional_header(&self.client_request_id, request); request = request.header("Accept", "application/json;odata=fullmetadata"); request }, None, )?; debug!("request == {:#?}\n", request); let response = self .table_service_client .http_client() .execute_request_check_status(request.0, StatusCode::OK) .await?; Ok((&response).try_into()?) } pub fn stream( self, ) -> impl Stream<Item = Result<ListTablesResponse, Box<dyn std::error::Error + Sync + Send>>> + 'a { #[derive(Debug, Clone, PartialEq)] enum States { Init, ContinuationNextTableName(ContinuationNextTableName), } unfold(Some(States::Init), move |next_marker: Option<States>| { let req = self.clone(); async move { debug!("next_marker == {:?}", &next_marker); let response = match next_marker { Some(States::Init) => req.execute().await, Some(States::ContinuationNextTableName(continuation_next_table_name)) => { req.continuation_next_table_name(continuation_next_table_name) .execute() .await } None => return None, }; let response = match response { Ok(response) => response, Err(err) => return Some((Err(err), None)), }; let next_marker = response .continuation_next_table_name .clone() .map(States::ContinuationNextTableName); Some((Ok(response), next_marker)) } }) } }
//! This library implements core components of Nova. #![allow(non_snake_case)] #![allow(clippy::type_complexity)] #![feature(test)] #![deny(missing_docs)] mod commitments; pub mod errors; pub mod r1cs; pub mod traits; use std::marker::PhantomData; use commitments::{AppendToTranscriptTrait, CompressedCommitment}; use errors::NovaError; use merlin::Transcript; use r1cs::{R1CSGens, R1CSInstance, R1CSShape, R1CSWitness}; use traits::{ChallengeTrait, Group}; /// A SNARK that holds the proof of a step of an incremental computation pub struct StepSNARK<G: Group> { comm_T: CompressedCommitment<G::CompressedGroupElement>, _p: PhantomData<G>, } impl<G: Group> StepSNARK<G> { fn protocol_name() -> &'static [u8] { b"NovaStepSNARK" } /// Takes as input two relaxed R1CS instance-witness tuples `(U1, W1)` and `(U2, W2)` /// with the same structure `shape` and defined with respect to the same `gens`, /// and outputs a folded instance-witness tuple `(U, W)` of the same shape `shape`, /// with the guarantee that the folded witness `W` satisfies the folded instance `U` /// if and only if `W1` satisfies `U1` and `W2` satisfies `U2`. pub fn prove( gens: &R1CSGens<G>, S: &R1CSShape<G>, U1: &R1CSInstance<G>, W1: &R1CSWitness<G>, U2: &R1CSInstance<G>, W2: &R1CSWitness<G>, transcript: &mut Transcript, ) -> Result<(StepSNARK<G>, (R1CSInstance<G>, R1CSWitness<G>)), NovaError> { // append the protocol name to the transcript //transcript.append_protocol_name(StepSNARK::protocol_name()); transcript.append_message(b"protocol-name", StepSNARK::<G>::protocol_name()); // compute a commitment to the cross-term let (T, comm_T) = S.commit_T(gens, U1, W1, U2, W2)?; // append `comm_T` to the transcript and obtain a challenge comm_T.append_to_transcript(b"comm_T", transcript); // compute a challenge from the transcript let r = G::Scalar::challenge(b"r", transcript); // fold the instance using `r` and `comm_T` let U = U1.fold(U2, &comm_T, &r)?; // fold the witness using `r` and `T` let W = W1.fold(W2, &T, &r)?; // return the folded instance and witness Ok(( StepSNARK { comm_T, _p: Default::default(), }, (U, W), )) } /// Takes as input two relaxed R1CS instances `U1` and `U2` /// with the same shape and defined with respect to the same parameters, /// and outputs a folded instance `U` with the same shape, /// with the guarantee that the folded instance `U` /// if and only if `U1` and `U2` are satisfiable. pub fn verify( &self, U1: &R1CSInstance<G>, U2: &R1CSInstance<G>, transcript: &mut Transcript, ) -> Result<R1CSInstance<G>, NovaError> { // append the protocol name to the transcript transcript.append_message(b"protocol-name", StepSNARK::<G>::protocol_name()); // append `comm_T` to the transcript and obtain a challenge self.comm_T.append_to_transcript(b"comm_T", transcript); // compute a challenge from the transcript let r = G::Scalar::challenge(b"r", transcript); // fold the instance using `r` and `comm_T` let U = U1.fold(U2, &self.comm_T, &r)?; // return the folded instance Ok(U) } } /// A SNARK that holds the proof of the final step of an incremental computation pub struct FinalSNARK<G: Group> { W: R1CSWitness<G>, } impl<G: Group> FinalSNARK<G> { /// Produces a proof of a instance given its satisfying witness `W`. pub fn prove(W: &R1CSWitness<G>) -> Result<FinalSNARK<G>, NovaError> { Ok(FinalSNARK { W: W.clone() }) } /// Verifies the proof of a folded instance `U` given its shape `S` public parameters `gens` pub fn verify( &self, gens: &R1CSGens<G>, S: &R1CSShape<G>, U: &R1CSInstance<G>, ) -> Result<(), NovaError> { // check that the witness is a valid witness to the folded instance `U` S.is_sat(gens, U, &self.W) } } #[cfg(test)] mod tests { use super::*; use crate::traits::{CompressedGroup, Group, PrimeField}; use core::borrow::Borrow; use curve25519_dalek::traits::MultiscalarMul; use rand::{rngs::OsRng, CryptoRng, RngCore}; type S = curve25519_dalek::scalar::Scalar; type G = curve25519_dalek::ristretto::RistrettoPoint; type C = curve25519_dalek::ristretto::CompressedRistretto; impl Group for G { type Scalar = S; type CompressedGroupElement = C; fn vartime_multiscalar_mul<I, J>(scalars: I, points: J) -> Self where I: IntoIterator, I::Item: Borrow<Self::Scalar>, J: IntoIterator, J::Item: Borrow<Self>, Self: Clone, { Self::multiscalar_mul(scalars, points) } fn compress(&self) -> Self::CompressedGroupElement { self.compress() } fn from_uniform_bytes(bytes: &[u8]) -> Option<Self> { if bytes.len() != 64 { None } else { let mut arr = [0; 64]; arr.copy_from_slice(&bytes[0..64]); Some(Self::from_uniform_bytes(&arr)) } } } impl PrimeField for S { fn zero() -> Self { S::zero() } fn one() -> Self { S::one() } fn from_bytes_mod_order_wide(bytes: &[u8]) -> Option<Self> { if bytes.len() != 64 { None } else { let mut arr = [0; 64]; arr.copy_from_slice(&bytes[0..64]); Some(Self::from_bytes_mod_order_wide(&arr)) } } fn random(rng: &mut (impl RngCore + CryptoRng)) -> Self { S::random(rng) } } impl CompressedGroup for C { type GroupElement = G; fn decompress(&self) -> Option<Self::GroupElement> { self.decompress() } fn as_bytes(&self) -> &[u8] { self.as_bytes() } } impl ChallengeTrait for S { fn challenge(label: &'static [u8], transcript: &mut Transcript) -> Self { let mut buf = [0u8; 64]; transcript.challenge_bytes(label, &mut buf); S::from_bytes_mod_order_wide(&buf) } } #[test] fn test_tiny_r1cs() { let one = S::one(); let (num_cons, num_vars, num_inputs, A, B, C) = { let num_cons = 4; let num_vars = 4; let num_inputs = 1; // The R1CS for this problem consists of the following constraints: // `Z0 * Z0 - Z1 = 0` // `Z1 * Z0 - Z2 = 0` // `(Z2 + Z0) * 1 - Z3 = 0` // `(Z3 + 5) * 1 - I0 = 0` // Relaxed R1CS is a set of three sparse matrices (A B C), where there is a row for every // constraint and a column for every entry in z = (vars, u, inputs) // An R1CS instance is satisfiable iff: // Az \circ Bz = u \cdot Cz + E, where z = (vars, 1, inputs) let mut A: Vec<(usize, usize, S)> = Vec::new(); let mut B: Vec<(usize, usize, S)> = Vec::new(); let mut C: Vec<(usize, usize, S)> = Vec::new(); // constraint 0 entries in (A,B,C) A.push((0, 0, one)); B.push((0, 0, one)); C.push((0, 1, one)); // constraint 1 entries in (A,B,C) A.push((1, 1, one)); B.push((1, 0, one)); C.push((1, 2, one)); // constraint 2 entries in (A,B,C) A.push((2, 2, one)); A.push((2, 0, one)); B.push((2, num_vars, one)); C.push((2, 3, one)); // constraint 3 entries in (A,B,C) A.push((3, 3, one)); A.push((3, num_vars, one + one + one + one + one)); B.push((3, num_vars, one)); C.push((3, num_vars + 1, one)); (num_cons, num_vars, num_inputs, A, B, C) }; // create a shape object let S = { let res = R1CSShape::new(num_cons, num_vars, num_inputs, &A, &B, &C); assert!(res.is_ok()); res.unwrap() }; // generate generators let gens = R1CSGens::new(num_cons, num_vars); let rand_inst_witness_generator = |gens: &R1CSGens<G>| -> (R1CSInstance<G>, R1CSWitness<G>) { // compute a satisfying (vars, X) tuple let (vars, X) = { let mut csprng: OsRng = OsRng; let z0 = S::random(&mut csprng); let z1 = z0 * z0; // constraint 0 let z2 = z1 * z0; // constraint 1 let z3 = z2 + z0; // constraint 2 let i0 = z3 + one + one + one + one + one; // constraint 3 let vars = vec![z0, z1, z2, z3]; let X = vec![i0]; (vars, X) }; let W = { let E = vec![S::zero(); num_cons]; // default E let res = R1CSWitness::new(&S, &vars, &E); assert!(res.is_ok()); res.unwrap() }; let U = { let (comm_W, comm_E) = W.commit(&gens); let u = S::one(); //default u let res = R1CSInstance::new(&S, &comm_W, &comm_E, &X, &u); assert!(res.is_ok()); res.unwrap() }; // check that generated instance is satisfiable let is_sat = S.is_sat(&gens, &U, &W); assert!(is_sat.is_ok()); (U, W) }; let (U1, W1) = rand_inst_witness_generator(&gens); let (U2, W2) = rand_inst_witness_generator(&gens); // produce a step SNARK let mut prover_transcript = Transcript::new(b"StepSNARKExample"); let res = StepSNARK::prove(&gens, &S, &U1, &W1, &U2, &W2, &mut prover_transcript); assert!(res.is_ok()); let (step_snark, (_U, W)) = res.unwrap(); // verify the step SNARK let mut verifier_transcript = Transcript::new(b"StepSNARKExample"); let res = step_snark.verify(&U1, &U2, &mut verifier_transcript); assert!(res.is_ok()); let U = res.unwrap(); assert_eq!(U, _U); // produce a final SNARK let res = FinalSNARK::prove(&W); assert!(res.is_ok()); let final_snark = res.unwrap(); // verify the final SNARK let res = final_snark.verify(&gens, &S, &U); assert!(res.is_ok()); } }
use ginkgo::VM; fn main() { let mut vm = VM::new(); let a = vm.string(String::from("hi there\n")); println!("{}", vm.wrap(a)); }
use std::convert::TryFrom; use std::io::{self, BufRead}; use std::mem; fn update_cell_part1(src: &[Vec<u8>], i: usize, j: usize) -> u8 { let c = (i.saturating_sub(1)..=i + 1) .flat_map(|x| (j.saturating_sub(1)..=j + 1).map(move |y| (x, y))) .filter(|&t| t != (i, j)) .filter_map(|(x, y)| src.get(x)?.get(y)) .filter(|&c| *c == b'#') .count(); match (src[i][j], c) { (b'L', 0) => b'#', (b'#', (4..=8)) => b'L', _ => src[i][j], } } fn update_cell_part2(src: &[Vec<u8>], i: usize, j: usize) -> u8 { let c = (-1..=1) .flat_map(|x| (-1..=1).map(move |y| (x, y))) .filter(|&t| t != (0, 0)) .filter_map(|(x, y)| project(src, i, j, x, y)) .filter(|&c| c == b'#') .count(); match (src[i][j], c) { (b'L', 0) => b'#', (b'#', (5..=8)) => b'L', _ => src[i][j], } } fn project(src: &[Vec<u8>], mut i: usize, mut j: usize, x: i32, y: i32) -> Option<u8> { let mut current = b'.'; while current == b'.' { i = usize::try_from(i as i32 + x).ok()?; j = usize::try_from(j as i32 + y).ok()?; current = *src.get(i)?.get(j)?; } Some(current) } fn update_grid(src: &[Vec<u8>], dst: &mut [Vec<u8>], part: usize) { for (i, row) in dst.iter_mut().enumerate() { for (j, c) in row.iter_mut().enumerate() { if *c != b'.' { match part { 1 => *c = update_cell_part1(src, i, j), 2 => *c = update_cell_part2(src, i, j), _ => panic!(), } } } } } fn run_part(xs: &[Vec<u8>], part: usize) -> usize { let mut src = &mut xs.to_vec(); let mut dst = &mut xs.to_vec(); update_grid(src, dst, part); while src != dst { mem::swap(&mut src, &mut dst); update_grid(src, dst, part); } dst.iter().flatten().filter(|&x| *x == b'#').count() } fn main() { let vec: Vec<_> = io::stdin() .lock() .lines() .filter_map(|x| x.ok()) .map(|x| x.into_bytes()) .collect(); let result = run_part(&vec, 1); println!("Part 1: {}", result); let result = run_part(&vec, 2); println!("Part 2: {}", result); } // fn debug_grid(src: &[Vec<u8>]) { // for row in src.iter() { // println!("{}", String::from_utf8_lossy(row)) // } // println!() // }
use SafeWrapper; use ir::{Constant, PointerType, User}; use sys; /// A constant null pointer. pub struct ConstantPointerNull<'ctx>(Constant<'ctx>); impl_subtype!(ConstantPointerNull => Constant); impl<'ctx> ConstantPointerNull<'ctx> { /// Creates a constant null pointer. pub fn new(ty: &PointerType) -> Self { unsafe { let inner = sys::LLVMRustConstantPointerNullGet(ty.inner()); wrap_value!(inner => User => Constant => ConstantPointerNull) } } }
use super::base::*; use super::error::*; use super::strutil::Strutil; use crate::hack_report_less; use lazy_static::lazy_static; use regex::Regex; #[derive(Debug)] pub struct Lexer { pub tokens: Vec<Token>, pub cmd_type: Option<CommandType>, } impl Lexer { pub fn new() -> Lexer { Lexer { tokens: Vec::new(), cmd_type: None, } } pub fn set<'a>(&mut self, expr: &'a str) -> Result<(), Box<HackError>> { self.tokens.clear(); self.cmd_type = None; if Lexer::is_empty_line(expr) { hack_report_less!("Empty line"); } let expr = expr.trim(); if expr.starts_with("@") { self.cmd_type = Some(CommandType::ACommand); self.tokens.push(Token { repr: "@".into(), token_type: TOKENTYPE::AT, }); Lexer::add_tokens(&mut self.tokens, &expr[1..]) } else if expr.starts_with("(") && expr.ends_with(")") { self.cmd_type = Some(CommandType::LCommand); self.tokens.push(Token { repr: "(".into(), token_type: TOKENTYPE::LEFTBRACE, }); let e = Lexer::add_tokens(&mut self.tokens, &expr[1..expr.len() - 1]); self.tokens.push(Token { repr: ")".into(), token_type: TOKENTYPE::RIGHTBRACE, }); e } else { self.cmd_type = Some(CommandType::CCommand); let mut expr = expr.clone(); if Strutil::fall_within(expr, "=") { let a: Vec<&str> = expr.split('=').collect(); let dest = Some(a[0]); let e = Lexer::add_tokens(&mut self.tokens, dest.unwrap()); match e { Err(e_) => { return Err(e_); } Ok(_) => {} } expr = a[1]; self.tokens.push(Token { repr: "=".into(), token_type: TOKENTYPE::EQUAL, }); } if Strutil::fall_within(expr, ";") { let a: Vec<&str> = expr.split(';').collect(); let comp = Some(a[0]); let e = Lexer::add_tokens(&mut self.tokens, comp.unwrap()); match e { Err(e_) => { return Err(e_); } Ok(_) => {} } expr = a[1]; self.tokens.push(Token { repr: ";".into(), token_type: TOKENTYPE::SEMICOLON, }); } // JUMP Lexer::add_tokens(&mut self.tokens, &expr) } } pub fn add_tokens<'a>(v: &mut Vec<Token>, s: &'a str) -> Result<(), Box<HackError>> { let subs = s.split_whitespace(); for sub in subs { match Lexer::classify(sub) { Ok(t) => v.push(t), Err(e) => { return Err(e); } } } Ok(()) } pub fn is_empty_line(s: &str) -> bool { let iter = s.split_whitespace(); return iter.count() == 0; } pub fn classify(s: &str) -> Result<Token, Box<HackError>> { lazy_static! { static ref NUMBER: Regex = Regex::new(r"^\d+$").unwrap(); static ref SYMBOL: Regex = Regex::new(r"^[_[:alpha:]]+[_0-9A-Za-z]*$").unwrap(); } if NUMBER.is_match(s) { return Ok(Token { repr: s.into(), token_type: TOKENTYPE::NUMBER, }); } else if SYMBOL.is_match(s) { return Ok(Token { repr: s.into(), token_type: TOKENTYPE::SYMBOL, }); } else { return Ok(Token { repr: s.into(), token_type: TOKENTYPE::EXPRESSION, }); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_lexer() { let mut lexer = Lexer::new(); lexer.set("@R2"); println!("{:?}", lexer.tokens); assert_eq!( lexer.tokens[0], Token { repr: "@".into(), token_type: TOKENTYPE::AT } ); assert_eq!( lexer.tokens[1], Token { repr: "R2".into(), token_type: TOKENTYPE::SYMBOL } ); lexer.set("@234"); println!("{:?}", lexer.tokens); assert_eq!( lexer.tokens[0], Token { repr: "@".into(), token_type: TOKENTYPE::AT } ); assert_eq!( lexer.tokens[1], Token { repr: "234".into(), token_type: TOKENTYPE::NUMBER } ); } }
//! [![Build Status](https://travis-ci.org/cdumay/rust-cdumay_rest_client.svg?branch=master)](https://travis-ci.org/cdumay/rust-cdumay_rest_client) //! [![Latest version](https://img.shields.io/crates/v/cdumay_rest_client.svg)](https://crates.io/crates/cdumay_rest_client) //! [![Documentation](https://docs.rs/cdumay_rest_client/badge.svg)](https://docs.rs/cdumay_rest_client) //! ![License](https://img.shields.io/crates/l/cdumay_rest_client.svg) //! //! cdumay_rest_client is a basic REST library used to standardize result and serialize them using [serde](https://docs.serde.rs/serde/). //! //! ## Quickstart //! //! _Cargo.toml_: //! ```toml //! [dependencies] //! serde = "1.0" //! serde_derive = "1.0" //! serde_json = "1.0" //! cdumay_error = "0.1" //! cdumay_http_client = "0.1" //! cdumay_rest_client = "0.1" //! ``` //! //! _main.rs_: //! //! ```rust //! extern crate cdumay_error; //! extern crate cdumay_http_client; //! extern crate cdumay_rest_client; //! #[macro_use] //! extern crate serde_derive; //! extern crate serde_json; //! //! use cdumay_error::ErrorRepr; //! use cdumay_http_client::{ClientBuilder, HttpClient}; //! use cdumay_http_client::authentication::NoAuth; //! use cdumay_rest_client::RestClient; //! //! #[derive(Serialize, Deserialize, Clone, Debug)] //! struct Todo { //! id: usize, //! task: String, //! } //! //! fn main() { //! let cli = RestClient::<NoAuth>::new("http://127.0.0.1:5000").unwrap(); //! let result = cli.get::<Todo>("/todos/1".into(), None, None, None); //! //! match result { //! Ok(todo) => println!("{}", serde_json::to_string_pretty(&todo).unwrap()), //! Err(err) => println!("{}", serde_json::to_string_pretty(&ErrorRepr::from(err)).unwrap()), //! } //! } //! ``` //! _Output_: //! ```json //! { //! "id": 1, //! "task": "Build an API" //! } //! ``` //! ## Errors //! //! Errors can be displayed using [cdumay_error](https://docs.serde.rs/cdumay_error/): //! //! ```json //! { //! "code": 404, //! "extra": { //! "message": "Todo 7000 doesn't exist. You have requested this URI [/todos/7000] but did you mean /todos/<int:id> ?" //! }, //! "message": "Not Found", //! "msgid": "Err-18430" //! } //! ``` //! //! ## Project Links //! //! - Issues: https://github.com/cdumay/rust-cdumay_rest_client/issues //! - Documentation: https://docs.rs/cdumay_rest_client #![feature(try_trait)] extern crate cdumay_error; extern crate cdumay_http_client; extern crate cdumay_result; extern crate reqwest; extern crate serde; extern crate serde_json; extern crate serde_value; pub use client::RestClient; pub use errors::RestClientError; mod client; mod errors;
use std::collections::HashMap; use std::env::args; use std::result::Result; struct BagHolder { bags: HashMap<String, Bag>, } impl BagHolder { pub fn new() -> BagHolder { BagHolder { bags: HashMap<String, Bag>::new() } } } struct Bag { description: String, bags: Vec<Bag>, } impl Bag { pub fn new(description: String) -> Bag { Bag { description, bags: Vec<Bag>::new() } } } fn populate_bags(content: &String) { } fn part1(content: &String) -> usize { //customs_forms_anyone(content) 0 } fn part2(content: &String) -> usize { //customs_forms_everyone(content) 0 } #[cfg(test)] mod test { use super::*; const TEST_INPUT: &str = r#"light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags. "#; #[test] fn testcase1() { let content = String::from(TEST_INPUT); let part1_answer = part1(&content); assert_eq!(part1_answer, 11); } #[test] fn testcase2() { let content = String::from(TEST_INPUT); let part2_answer = part2(&content); assert_eq!(part2_answer, 6); } } fn main() -> Result<(), Box<dyn std::error::Error>> { let filename = args().nth(1).ok_or("I need a filename")?; let content = std::fs::read_to_string(&filename)?; let content = String::from(&content); let part1_answer = part1(&content); let content = String::from(&content); let part2_answer = part2(&content); println!("Hello, world!"); Ok(()) }
use core::fmt; use core::ptr; use std::str::{self, FromStr}; use super::WifiConfigError; const PASSWORD_MAX_LEN: usize = 64; /// A WiFi password. #[derive(Copy, Clone)] #[repr(transparent)] pub struct Password(pub(crate) [u8; PASSWORD_MAX_LEN]); impl Password { fn len(&self) -> usize { memchr::memchr(0, &self.0).unwrap_or(PASSWORD_MAX_LEN) } pub fn as_str(&self) -> &str { &unsafe { str::from_utf8_unchecked(&self.0[..self.len()]) } } pub fn from_bytes(bytes: &[u8]) -> Result<Password, WifiConfigError> { let ssid_len = bytes.len(); if ssid_len > PASSWORD_MAX_LEN { return Err(WifiConfigError::TooLong(PASSWORD_MAX_LEN, ssid_len)) } if let Err(utf8_error) = str::from_utf8(bytes) { return Err(WifiConfigError::Utf8Error(utf8_error)) } if let Some(pos) = memchr::memchr(0, bytes) { return Err(WifiConfigError::InteriorNul(pos)) } Ok(unsafe { Self::from_bytes_unchecked(bytes) }) } /// SAFTEY: The caller has to ensure that `bytes` does not contain a `NUL` byte and /// does not exceed 64 bytes. pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Password { let password_len = bytes.len(); let mut password = Self([0; PASSWORD_MAX_LEN]); ptr::copy_nonoverlapping(bytes.as_ptr(), password.0.as_mut_ptr(), password_len); password } } impl Default for Password { #[inline(always)] fn default() -> Self { Self([0; PASSWORD_MAX_LEN]) } } impl FromStr for Password { type Err = WifiConfigError; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::from_bytes(s.as_bytes()) } } impl fmt::Debug for Password { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Password") .field("password", &self.as_str()) .finish() } } impl fmt::Display for Password { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { #[cfg(debug)] return self.as_str().fmt(f); #[cfg(not(debug))] return "********".fmt(f); } }
mod ema; mod macd; mod macd_histogram; mod rsi; mod sma; mod value; mod stretched_rsi; mod smma; pub use ema::EMA; pub use macd::MACD; pub use macd_histogram::MACDHistogram; pub use rsi::RSI; pub use sma::SMA; pub use value::Value; pub use stretched_rsi::StretchedRSI; pub use smma::SMMA; use crate::economy::Monetary; pub trait Indicator { type Output; fn initialize(value: Monetary) -> Self; fn evaluate(&mut self, value: Monetary) -> Self::Output; } pub trait MovingAverage: Indicator {} macro_rules! peel { ( $name:ident, $($other:ident,)* ) => (tuple! { $($other,)* }) } macro_rules! tuple { () => (); ( $($name:ident,)+ ) => { impl<$($name: Indicator,)+> Indicator for ($($name,)+) { type Output = ($($name::Output,)+); fn initialize(value: Monetary) -> Self { ($($name::initialize(value),)+) } #[allow(non_snake_case)] fn evaluate(&mut self, value: Monetary) -> Self::Output { let ($($name,)+) = self; ($($name.evaluate(value),)+) } } peel! { $($name,)+ } }; } tuple! {T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,}
use codec::{Decode, Encode}; use rstd::cmp::{Ord, Ordering}; use rstd::prelude::Vec; /// Value or pair of value in vector #[derive(PartialEq)] #[cfg_attr(feature = "std", derive(Debug))] pub enum Median<T> { Value(T), Pair(T, T), } /// Get median from ordered values pub fn get_median<T: Ord + Copy>(mut values: Vec<T>) -> Option<Median<T>> { values.sort(); let middle = values.len() / 2; match values.len() { 0 | 1 => None, len if len % 2 == 0 => Some(Median::Pair(values[middle - 1], values[middle])), _len => Some(Median::Value(values[middle])), } } /// External (for blockchain) value #[derive(Encode, Decode, Clone, Eq, PartialEq, Default)] #[cfg_attr(feature = "std", derive(Debug))] pub struct ExternalValue<ValueType, Moment> { pub value: Option<ValueType>, /// Moment we last changed the value /// - None if value is empty pub last_changed: Option<Moment>, } impl<ValueType: Default + Eq + Ord + Clone, Moment: Default + Eq + Ord + Clone> Ord for ExternalValue<ValueType, Moment> { fn cmp(&self, other: &Self) -> Ordering { match self.value.cmp(&other.value) { Ordering::Equal => self.last_changed.cmp(&other.last_changed), ord => ord, } } } impl<ValueType: Default + Eq + Ord + Clone, Moment: Default + Eq + Ord + Clone> PartialOrd for ExternalValue<ValueType, Moment> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(&other)) } } impl<ValueType: Default + Eq + Ord + Clone, Moment: Default + Eq + Ord + Clone> ExternalValue<ValueType, Moment> { pub fn new(value: ValueType, now: Moment) -> Self { ExternalValue { value: Some(value), last_changed: Some(now), } } pub fn clean(&mut self) { self.value = None; self.last_changed = None; } pub fn update(&mut self, value: ValueType, now: Moment) { self.value = Some(value); self.last_changed = Some(now); } pub fn is_clean(&self) -> bool { self.last_changed.is_none() && self.value.is_none() } /// From pair of option to optional pair of cloned fields pub fn get(&self) -> Option<(ValueType, Moment)> { match (&self.value, &self.last_changed) { (Some(value), Some(last_changed)) => Some((value.clone(), last_changed.clone())), _ => None, } } } #[cfg(test)] mod tests { use super::{get_median, Median}; #[test] fn simple() { let array: Vec<u8> = (0..=10).collect(); let median = array[5]; assert_eq!(get_median(array), Some(Median::Value(median))); } }
mod point; mod points; mod corners; mod placement; mod placement_map; mod tile; use std::mem; use std::ptr; use std::sync::Once; use std::sync::ONCE_INIT; use core::intrinsics::unreachable; use game::board::pieces::tile::Tile; // This module is pure evil. Pure, hacky, evil. All ye who value safety turn // back now. I do not endorse or suggest the use of any of the methods // described here. // // Basically, it's faster to access that which is in the data segment than // that which is on the heap. But, if the value you want to make a global // variable is bigger than what the stack can hold, lazy_static! will be of no // use to you. See, lazy_static! requires that you return the value that the // global variable should be set to. This means you *have* to put the value on // the stack. So instead... this. // This type is something like 30 megabytes. Literally no stack on any OS is // that big by default, so we have to more or less improvise our own version // of lazy_static in order to get RAW SPEED. static mut PIECES: Option<[Tile; 21]> = None; static INIT: Once = ONCE_INIT; #[inline] fn initialize() { unsafe { INIT.call_once(|| { // Here's a problem. We have to assign PIECES to be Some without // actually putting anything of PIECES's size on the stack. To do // that, we have to somehow change PIECES from None to Some without // actually initializing any memory in that Some. How might we do // this? // // Well, if you've ever looked at the internal memory // representation of an Option<T>, you might note that the Some // representation just kinda sticks a 1 at the front of the data, // while the None representation is zeroed. So behold, the ultimate // in unsafe. unsafe { { // We cast a pointer to PIECES to be a mutable pointer to // the first byte of PIECES. let disgusting: *mut u8 = mem::transmute(&mut PIECES); // Then we set the first bit to be 1. This makes PIECES // a Some value without ever actually putting it on the // stack. Honestly I'm shocked this works. let first = ptr::read(disgusting); ptr::write(disgusting, first | 1); } let mut n = 0; for (piece, shape) in pieces_unsafe().iter_mut().zip(PIECE_SHAPES.iter()) { *piece = Tile::new(*shape, n); n += 1; } } }); } } #[inline] unsafe fn pieces_unsafe() -> &'static mut [Tile; 21] { // This is always called after PIECES has been initialized (and while it's // being initialized). Because of this, to avoid the overhead of the match, // we quietly pretend that there's a 0% chance of PIECES being None when // this function is called. match PIECES { Some(ref mut array) => array, _ => unreachable(), } } #[inline] fn pieces() -> &'static [Tile; 21] { // This is safe, since it initializes first. initialize(); unsafe { match PIECES { Some(ref array) => array, _ => unreachable(), } } } #[inline] pub fn piece(which: usize) -> &'static Tile { &pieces()[which] } #[inline] pub fn iter() -> ::std::slice::Iter<'static, Tile> { pieces().iter() } /* lazy_static! { static ref PIECES: Vec<Tile> = { let mut ret = Vec::with_capacity(21); for (n, &shape) in PIECE_SHAPES.iter().enumerate() { ret.push(Tile::new(shape, n)); } ret }; } */ // Pieces are by default in vertical, right-pointing orientation. // Oh yeah also, originally these looked something close to nice, but // `cargo fmt` destroyed them. So... whoops. static PIECE_SHAPES: [[u8; 49]; 21] = [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]];
#[derive(Debug, Copy, Clone)] struct Point (i32, i32); #[derive(Debug)] struct Rectangle { top_corner: Point, bottom_corner: Point, } impl Rectangle { fn width(&self) -> u32 { let denormalized = self.bottom_corner.0 - self.top_corner.0; let normalized = if denormalized < 0 { denormalized * -1 } else { denormalized }; normalized as u32 } fn height(&self) -> u32 { let denormalized = self.bottom_corner.1 - self.top_corner.1; let normalized = if denormalized < 0 { denormalized * -1 } else { denormalized }; normalized as u32 } fn area(&self) -> u32 { self.width() * self.height() } fn is_bigger(&self, other: &Rectangle) -> bool { self.area() > other.area() } fn square(top_corner: Point, side_length: u32) -> Rectangle { Rectangle{ top_corner: top_corner, bottom_corner: Point( top_corner.0 + side_length as i32, top_corner.1 + side_length as i32, ), } } } fn main() { let r = Rectangle { top_corner: Point(0, 0), bottom_corner: Point(10, 10), }; let r2 = Rectangle { top_corner: Point(0, 0), bottom_corner: Point(5, 5), }; let r3 = Rectangle { top_corner: Point(0, 0), bottom_corner: Point(30, 5), }; let sq = Rectangle::square(Point(0, 1), 64); println!("sq {:?}", sq); println!("Hello, world! {}", sq.area()); println!("he fits {}", r.is_bigger(&r2)); println!("he fits {}", r.is_bigger(&r3)); }
// Generated by the capnpc-rust plugin to the Cap'n Proto schema compiler. // DO NOT EDIT. // source: leaf.capnp pub mod weight { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_name(self) -> Result<text::Reader<'a>> { self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0) } pub fn has_name(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] pub fn get_tensor(self) -> Result<::leaf_capnp::tensor::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) } pub fn has_tensor(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_name(self) -> Result<text::Builder<'a>> { self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0) } #[inline] pub fn set_name(&mut self, value : text::Reader) { self.builder.get_pointer_field(0).set_text(value); } #[inline] pub fn init_name(self, size : u32) -> text::Builder<'a> { self.builder.get_pointer_field(0).init_text(size) } pub fn has_name(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] pub fn get_tensor(self) -> Result<::leaf_capnp::tensor::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) } #[inline] pub fn set_tensor<'b>(&mut self, value : ::leaf_capnp::tensor::Reader<'b>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_tensor(self, ) -> ::leaf_capnp::tensor::Builder<'a> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } pub fn has_tensor(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { pub fn get_tensor(&self) -> ::leaf_capnp::tensor::Pipeline<> { FromTypelessPipeline::new(self._typeless.get_pointer_field(1)) } } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 2 }; pub const TYPE_ID: u64 = 0x9958064d48c0bf4d; } } pub mod tensor { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_shape(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0)) } pub fn has_shape(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] pub fn get_data(self) -> Result<primitive_list::Reader<'a,f32>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) } pub fn has_data(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_shape(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0)) } #[inline] pub fn set_shape(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value) } #[inline] pub fn init_shape(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), size) } pub fn has_shape(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] pub fn get_data(self) -> Result<primitive_list::Builder<'a,f32>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) } #[inline] pub fn set_data(&mut self, value : primitive_list::Reader<'a,f32>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_data(self, size : u32) -> primitive_list::Builder<'a,f32> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), size) } pub fn has_data(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 2 }; pub const TYPE_ID: u64 = 0xc45ce77c74f40692; } } pub mod layer { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_name(self) -> Result<text::Reader<'a>> { self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0) } pub fn has_name(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] pub fn get_config(self) -> Result<::leaf_capnp::layer_config::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) } pub fn has_config(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } #[inline] pub fn get_weights_data(self) -> Result<struct_list::Reader<'a,::leaf_capnp::weight::Owned<>>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(2)) } pub fn has_weights_data(&self) -> bool { !self.reader.get_pointer_field(2).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_name(self) -> Result<text::Builder<'a>> { self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0) } #[inline] pub fn set_name(&mut self, value : text::Reader) { self.builder.get_pointer_field(0).set_text(value); } #[inline] pub fn init_name(self, size : u32) -> text::Builder<'a> { self.builder.get_pointer_field(0).init_text(size) } pub fn has_name(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] pub fn get_config(self) -> Result<::leaf_capnp::layer_config::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) } #[inline] pub fn set_config<'b>(&mut self, value : ::leaf_capnp::layer_config::Reader<'b>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_config(self, ) -> ::leaf_capnp::layer_config::Builder<'a> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } pub fn has_config(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn get_weights_data(self) -> Result<struct_list::Builder<'a,::leaf_capnp::weight::Owned<>>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(2)) } #[inline] pub fn set_weights_data(&mut self, value : struct_list::Reader<'a,::leaf_capnp::weight::Owned<>>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(2), value) } #[inline] pub fn init_weights_data(self, size : u32) -> struct_list::Builder<'a,::leaf_capnp::weight::Owned<>> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(2), size) } pub fn has_weights_data(&self) -> bool { !self.builder.get_pointer_field(2).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { pub fn get_config(&self) -> ::leaf_capnp::layer_config::Pipeline<> { FromTypelessPipeline::new(self._typeless.get_pointer_field(1)) } } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 3 }; pub const TYPE_ID: u64 = 0xbdbda6958923333f; } } pub mod layer_config { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_name(self) -> Result<text::Reader<'a>> { self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0) } pub fn has_name(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] pub fn get_layer_type(self) -> ::leaf_capnp::layer_config::layer_type::Reader<'a> { ::capnp::traits::FromStructReader::new(self.reader) } #[inline] pub fn get_outputs(self) -> Result<text_list::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(2)) } pub fn has_outputs(&self) -> bool { !self.reader.get_pointer_field(2).is_null() } #[inline] pub fn get_inputs(self) -> Result<text_list::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(3)) } pub fn has_inputs(&self) -> bool { !self.reader.get_pointer_field(3).is_null() } #[inline] pub fn get_params(self) -> Result<struct_list::Reader<'a,::leaf_capnp::weight_config::Owned<>>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(4)) } pub fn has_params(&self) -> bool { !self.reader.get_pointer_field(4).is_null() } #[inline] pub fn get_propagate_down(self) -> Result<primitive_list::Reader<'a,bool>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(5)) } pub fn has_propagate_down(&self) -> bool { !self.reader.get_pointer_field(5).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_name(self) -> Result<text::Builder<'a>> { self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0) } #[inline] pub fn set_name(&mut self, value : text::Reader) { self.builder.get_pointer_field(0).set_text(value); } #[inline] pub fn init_name(self, size : u32) -> text::Builder<'a> { self.builder.get_pointer_field(0).init_text(size) } pub fn has_name(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] pub fn get_layer_type(self) -> ::leaf_capnp::layer_config::layer_type::Builder<'a> { ::capnp::traits::FromStructBuilder::new(self.builder) } #[inline] pub fn init_layer_type(self, ) -> ::leaf_capnp::layer_config::layer_type::Builder<'a> { self.builder.set_data_field::<u16>(0, 0); self.builder.get_pointer_field(1).clear(); ::capnp::traits::FromStructBuilder::new(self.builder) } #[inline] pub fn get_outputs(self) -> Result<text_list::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(2)) } #[inline] pub fn set_outputs(&mut self, value : text_list::Reader<'a>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(2), value) } #[inline] pub fn init_outputs(self, size : u32) -> text_list::Builder<'a> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(2), size) } pub fn has_outputs(&self) -> bool { !self.builder.get_pointer_field(2).is_null() } #[inline] pub fn get_inputs(self) -> Result<text_list::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(3)) } #[inline] pub fn set_inputs(&mut self, value : text_list::Reader<'a>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(3), value) } #[inline] pub fn init_inputs(self, size : u32) -> text_list::Builder<'a> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(3), size) } pub fn has_inputs(&self) -> bool { !self.builder.get_pointer_field(3).is_null() } #[inline] pub fn get_params(self) -> Result<struct_list::Builder<'a,::leaf_capnp::weight_config::Owned<>>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(4)) } #[inline] pub fn set_params(&mut self, value : struct_list::Reader<'a,::leaf_capnp::weight_config::Owned<>>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(4), value) } #[inline] pub fn init_params(self, size : u32) -> struct_list::Builder<'a,::leaf_capnp::weight_config::Owned<>> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(4), size) } pub fn has_params(&self) -> bool { !self.builder.get_pointer_field(4).is_null() } #[inline] pub fn get_propagate_down(self) -> Result<primitive_list::Builder<'a,bool>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(5)) } #[inline] pub fn set_propagate_down(&mut self, value : primitive_list::Reader<'a,bool>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(5), value) } #[inline] pub fn init_propagate_down(self, size : u32) -> primitive_list::Builder<'a,bool> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(5), size) } pub fn has_propagate_down(&self) -> bool { !self.builder.get_pointer_field(5).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { pub fn get_layer_type(&self) -> ::leaf_capnp::layer_config::layer_type::Pipeline { FromTypelessPipeline::new(self._typeless.noop()) } } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 1, pointers : 6 }; pub const TYPE_ID: u64 = 0xcf9577520a6edcb7; } pub mod layer_type { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub use self::Which::{Convolution,Linear,LogSoftmax,Pooling,Sequential,Softmax,Relu,Sigmoid,NegativeLogLikelihood,Reshape}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } pub fn has_convolution(&self) -> bool { if self.reader.get_data_field::<u16>(0) != 0 { return false; } !self.reader.get_pointer_field(1).is_null() } pub fn has_linear(&self) -> bool { if self.reader.get_data_field::<u16>(0) != 1 { return false; } !self.reader.get_pointer_field(1).is_null() } pub fn has_pooling(&self) -> bool { if self.reader.get_data_field::<u16>(0) != 3 { return false; } !self.reader.get_pointer_field(1).is_null() } pub fn has_sequential(&self) -> bool { if self.reader.get_data_field::<u16>(0) != 4 { return false; } !self.reader.get_pointer_field(1).is_null() } pub fn has_negative_log_likelihood(&self) -> bool { if self.reader.get_data_field::<u16>(0) != 8 { return false; } !self.reader.get_pointer_field(1).is_null() } pub fn has_reshape(&self) -> bool { if self.reader.get_data_field::<u16>(0) != 9 { return false; } !self.reader.get_pointer_field(1).is_null() } #[inline] pub fn which(self) -> ::std::result::Result<WhichReader<'a,>, ::capnp::NotInSchema> { match self.reader.get_data_field::<u16>(0) { 0 => { return ::std::result::Result::Ok(Convolution( ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) )); } 1 => { return ::std::result::Result::Ok(Linear( ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) )); } 2 => { return ::std::result::Result::Ok(LogSoftmax( () )); } 3 => { return ::std::result::Result::Ok(Pooling( ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) )); } 4 => { return ::std::result::Result::Ok(Sequential( ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) )); } 5 => { return ::std::result::Result::Ok(Softmax( () )); } 6 => { return ::std::result::Result::Ok(Relu( () )); } 7 => { return ::std::result::Result::Ok(Sigmoid( () )); } 8 => { return ::std::result::Result::Ok(NegativeLogLikelihood( ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) )); } 9 => { return ::std::result::Result::Ok(Reshape( ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) )); } x => return ::std::result::Result::Err(::capnp::NotInSchema(x)) } } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn set_convolution<'b>(&mut self, value : ::leaf_capnp::convolution_config::Reader<'b>) -> Result<()> { self.builder.set_data_field::<u16>(0, 0); ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_convolution(self, ) -> ::leaf_capnp::convolution_config::Builder<'a> { self.builder.set_data_field::<u16>(0, 0); ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } pub fn has_convolution(&self) -> bool { if self.builder.get_data_field::<u16>(0) != 0 { return false; } !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn set_linear<'b>(&mut self, value : ::leaf_capnp::linear_config::Reader<'b>) -> Result<()> { self.builder.set_data_field::<u16>(0, 1); ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_linear(self, ) -> ::leaf_capnp::linear_config::Builder<'a> { self.builder.set_data_field::<u16>(0, 1); ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } pub fn has_linear(&self) -> bool { if self.builder.get_data_field::<u16>(0) != 1 { return false; } !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn set_log_softmax(&mut self, _value : ()) { self.builder.set_data_field::<u16>(0, 2); } #[inline] pub fn set_pooling<'b>(&mut self, value : ::leaf_capnp::pooling_config::Reader<'b>) -> Result<()> { self.builder.set_data_field::<u16>(0, 3); ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_pooling(self, ) -> ::leaf_capnp::pooling_config::Builder<'a> { self.builder.set_data_field::<u16>(0, 3); ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } pub fn has_pooling(&self) -> bool { if self.builder.get_data_field::<u16>(0) != 3 { return false; } !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn set_sequential<'b>(&mut self, value : ::leaf_capnp::sequential_config::Reader<'b>) -> Result<()> { self.builder.set_data_field::<u16>(0, 4); ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_sequential(self, ) -> ::leaf_capnp::sequential_config::Builder<'a> { self.builder.set_data_field::<u16>(0, 4); ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } pub fn has_sequential(&self) -> bool { if self.builder.get_data_field::<u16>(0) != 4 { return false; } !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn set_softmax(&mut self, _value : ()) { self.builder.set_data_field::<u16>(0, 5); } #[inline] pub fn set_relu(&mut self, _value : ()) { self.builder.set_data_field::<u16>(0, 6); } #[inline] pub fn set_sigmoid(&mut self, _value : ()) { self.builder.set_data_field::<u16>(0, 7); } #[inline] pub fn set_negative_log_likelihood<'b>(&mut self, value : ::leaf_capnp::negative_log_likelihood_config::Reader<'b>) -> Result<()> { self.builder.set_data_field::<u16>(0, 8); ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_negative_log_likelihood(self, ) -> ::leaf_capnp::negative_log_likelihood_config::Builder<'a> { self.builder.set_data_field::<u16>(0, 8); ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } pub fn has_negative_log_likelihood(&self) -> bool { if self.builder.get_data_field::<u16>(0) != 8 { return false; } !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn set_reshape<'b>(&mut self, value : ::leaf_capnp::reshape_config::Reader<'b>) -> Result<()> { self.builder.set_data_field::<u16>(0, 9); ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_reshape(self, ) -> ::leaf_capnp::reshape_config::Builder<'a> { self.builder.set_data_field::<u16>(0, 9); ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } pub fn has_reshape(&self) -> bool { if self.builder.get_data_field::<u16>(0) != 9 { return false; } !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn which(self) -> ::std::result::Result<WhichBuilder<'a,>, ::capnp::NotInSchema> { match self.builder.get_data_field::<u16>(0) { 0 => { return ::std::result::Result::Ok(Convolution( ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) )); } 1 => { return ::std::result::Result::Ok(Linear( ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) )); } 2 => { return ::std::result::Result::Ok(LogSoftmax( () )); } 3 => { return ::std::result::Result::Ok(Pooling( ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) )); } 4 => { return ::std::result::Result::Ok(Sequential( ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) )); } 5 => { return ::std::result::Result::Ok(Softmax( () )); } 6 => { return ::std::result::Result::Ok(Relu( () )); } 7 => { return ::std::result::Result::Ok(Sigmoid( () )); } 8 => { return ::std::result::Result::Ok(NegativeLogLikelihood( ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) )); } 9 => { return ::std::result::Result::Ok(Reshape( ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) )); } x => return ::std::result::Result::Err(::capnp::NotInSchema(x)) } } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 1, pointers : 6 }; pub const TYPE_ID: u64 = 0xae27ff0ec745ee6c; } pub enum Which<A0,A1,A2,A3,A4,A5> { Convolution(A0), Linear(A1), LogSoftmax(()), Pooling(A2), Sequential(A3), Softmax(()), Relu(()), Sigmoid(()), NegativeLogLikelihood(A4), Reshape(A5), } pub type WhichReader<'a,> = Which<Result<::leaf_capnp::convolution_config::Reader<'a>>,Result<::leaf_capnp::linear_config::Reader<'a>>,Result<::leaf_capnp::pooling_config::Reader<'a>>,Result<::leaf_capnp::sequential_config::Reader<'a>>,Result<::leaf_capnp::negative_log_likelihood_config::Reader<'a>>,Result<::leaf_capnp::reshape_config::Reader<'a>>>; pub type WhichBuilder<'a,> = Which<Result<::leaf_capnp::convolution_config::Builder<'a>>,Result<::leaf_capnp::linear_config::Builder<'a>>,Result<::leaf_capnp::pooling_config::Builder<'a>>,Result<::leaf_capnp::sequential_config::Builder<'a>>,Result<::leaf_capnp::negative_log_likelihood_config::Builder<'a>>,Result<::leaf_capnp::reshape_config::Builder<'a>>>; } } pub mod weight_config { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_name(self) -> Result<text::Reader<'a>> { self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0) } pub fn has_name(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_name(self) -> Result<text::Builder<'a>> { self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0) } #[inline] pub fn set_name(&mut self, value : text::Reader) { self.builder.get_pointer_field(0).set_text(value); } #[inline] pub fn init_name(self, size : u32) -> text::Builder<'a> { self.builder.get_pointer_field(0).init_text(size) } pub fn has_name(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 1 }; pub const TYPE_ID: u64 = 0x811453bfd610e05b; } } pub mod convolution_config { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_num_output(self) -> u64 { self.reader.get_data_field::<u64>(0) } #[inline] pub fn get_filter_shape(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0)) } pub fn has_filter_shape(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] pub fn get_stride(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) } pub fn has_stride(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } #[inline] pub fn get_padding(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(2)) } pub fn has_padding(&self) -> bool { !self.reader.get_pointer_field(2).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_num_output(self) -> u64 { self.builder.get_data_field::<u64>(0) } #[inline] pub fn set_num_output(&mut self, value : u64) { self.builder.set_data_field::<u64>(0, value); } #[inline] pub fn get_filter_shape(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0)) } #[inline] pub fn set_filter_shape(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value) } #[inline] pub fn init_filter_shape(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), size) } pub fn has_filter_shape(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] pub fn get_stride(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) } #[inline] pub fn set_stride(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_stride(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), size) } pub fn has_stride(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn get_padding(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(2)) } #[inline] pub fn set_padding(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(2), value) } #[inline] pub fn init_padding(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(2), size) } pub fn has_padding(&self) -> bool { !self.builder.get_pointer_field(2).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 1, pointers : 3 }; pub const TYPE_ID: u64 = 0x88558802da5e943e; } } pub mod linear_config { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_output_size(self) -> u64 { self.reader.get_data_field::<u64>(0) } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_output_size(self) -> u64 { self.builder.get_data_field::<u64>(0) } #[inline] pub fn set_output_size(&mut self, value : u64) { self.builder.set_data_field::<u64>(0, value); } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 1, pointers : 0 }; pub const TYPE_ID: u64 = 0xcaa7b7e8ad0dbdc2; } } pub mod pooling_config { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_mode(self) -> ::std::result::Result<::leaf_capnp::PoolingMode,::capnp::NotInSchema> { ::capnp::traits::FromU16::from_u16(self.reader.get_data_field::<u16>(0)) } #[inline] pub fn get_filter_shape(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0)) } pub fn has_filter_shape(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] pub fn get_stride(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) } pub fn has_stride(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } #[inline] pub fn get_padding(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(2)) } pub fn has_padding(&self) -> bool { !self.reader.get_pointer_field(2).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_mode(self) -> ::std::result::Result<::leaf_capnp::PoolingMode,::capnp::NotInSchema> { ::capnp::traits::FromU16::from_u16(self.builder.get_data_field::<u16>(0)) } #[inline] pub fn set_mode(&mut self, value : ::leaf_capnp::PoolingMode) { self.builder.set_data_field::<u16>(0, value as u16) } #[inline] pub fn get_filter_shape(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0)) } #[inline] pub fn set_filter_shape(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value) } #[inline] pub fn init_filter_shape(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), size) } pub fn has_filter_shape(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] pub fn get_stride(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) } #[inline] pub fn set_stride(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_stride(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), size) } pub fn has_stride(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn get_padding(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(2)) } #[inline] pub fn set_padding(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(2), value) } #[inline] pub fn init_padding(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(2), size) } pub fn has_padding(&self) -> bool { !self.builder.get_pointer_field(2).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 1, pointers : 3 }; pub const TYPE_ID: u64 = 0x9127853ffe85b249; } } #[repr(u16)] #[derive(Clone, Copy, PartialEq)] pub enum PoolingMode { Max = 0, Average = 1, } impl ::capnp::traits::FromU16 for PoolingMode { #[inline] fn from_u16(value : u16) -> ::std::result::Result<PoolingMode, ::capnp::NotInSchema> { match value { 0 => ::std::result::Result::Ok(PoolingMode::Max), 1 => ::std::result::Result::Ok(PoolingMode::Average), n => ::std::result::Result::Err(::capnp::NotInSchema(n)), } } } impl ::capnp::traits::ToU16 for PoolingMode { #[inline] fn to_u16(self) -> u16 { self as u16 } } impl ::capnp::traits::HasTypeId for PoolingMode { #[inline] fn type_id() -> u64 { 0x9d27c79eace4e424u64 } } pub mod sequential_config { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_layers(self) -> Result<struct_list::Reader<'a,::leaf_capnp::layer_config::Owned<>>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0)) } pub fn has_layers(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] pub fn get_inputs(self) -> Result<struct_list::Reader<'a,::leaf_capnp::shaped_input::Owned<>>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) } pub fn has_inputs(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } #[inline] pub fn get_force_backward(self) -> bool { self.reader.get_bool_field(0) } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_layers(self) -> Result<struct_list::Builder<'a,::leaf_capnp::layer_config::Owned<>>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0)) } #[inline] pub fn set_layers(&mut self, value : struct_list::Reader<'a,::leaf_capnp::layer_config::Owned<>>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value) } #[inline] pub fn init_layers(self, size : u32) -> struct_list::Builder<'a,::leaf_capnp::layer_config::Owned<>> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), size) } pub fn has_layers(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] pub fn get_inputs(self) -> Result<struct_list::Builder<'a,::leaf_capnp::shaped_input::Owned<>>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) } #[inline] pub fn set_inputs(&mut self, value : struct_list::Reader<'a,::leaf_capnp::shaped_input::Owned<>>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_inputs(self, size : u32) -> struct_list::Builder<'a,::leaf_capnp::shaped_input::Owned<>> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), size) } pub fn has_inputs(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } #[inline] pub fn get_force_backward(self) -> bool { self.builder.get_bool_field(0) } #[inline] pub fn set_force_backward(&mut self, value : bool) { self.builder.set_bool_field(0, value); } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 1, pointers : 2 }; pub const TYPE_ID: u64 = 0xd847cd2f4d7883da; } } pub mod shaped_input { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_name(self) -> Result<text::Reader<'a>> { self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0) } pub fn has_name(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] pub fn get_shape(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1)) } pub fn has_shape(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_name(self) -> Result<text::Builder<'a>> { self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0) } #[inline] pub fn set_name(&mut self, value : text::Reader) { self.builder.get_pointer_field(0).set_text(value); } #[inline] pub fn init_name(self, size : u32) -> text::Builder<'a> { self.builder.get_pointer_field(0).init_text(size) } pub fn has_name(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] pub fn get_shape(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1)) } #[inline] pub fn set_shape(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value) } #[inline] pub fn init_shape(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), size) } pub fn has_shape(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 2 }; pub const TYPE_ID: u64 = 0xdf092088cf64c972; } } pub mod negative_log_likelihood_config { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_num_classes(self) -> u64 { self.reader.get_data_field::<u64>(0) } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_num_classes(self) -> u64 { self.builder.get_data_field::<u64>(0) } #[inline] pub fn set_num_classes(&mut self, value : u64) { self.builder.set_data_field::<u64>(0, value); } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 1, pointers : 0 }; pub const TYPE_ID: u64 = 0x9f20dde1f742539b; } } pub mod reshape_config { #![allow(unused_imports)] use capnp::capability::{FromClientHook, FromTypelessPipeline}; use capnp::{text, data, Result}; use capnp::private::layout; use capnp::traits::{FromStructBuilder, FromStructReader}; use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list}; pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader : layout::StructReader<'a> } impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader : reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null())))) } } impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) } } impl <'a,> Reader<'a,> { pub fn borrow<'b>(&'b self) -> Reader<'b,> { Reader { .. *self } } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.reader.total_size() } #[inline] pub fn get_shape(self) -> Result<primitive_list::Reader<'a,u64>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0)) } pub fn has_shape(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } } pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> } impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { #[inline] fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE } } impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { #[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { Builder { builder : builder, } } } impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) } fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a,>> { ::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())))) } } impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> { fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a,>) -> Result<()> { pointer.set_struct(&value.reader) } } impl <'a,> Builder<'a,> { pub fn as_reader(self) -> Reader<'a,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn borrow<'b>(&'b mut self) -> Builder<'b,> { Builder { .. *self } } pub fn borrow_as_reader<'b>(&'b self) -> Reader<'b,> { ::capnp::traits::FromStructReader::new(self.builder.as_reader()) } pub fn total_size(&self) -> Result<::capnp::MessageSize> { self.builder.as_reader().total_size() } #[inline] pub fn get_shape(self) -> Result<primitive_list::Builder<'a,u64>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0)) } #[inline] pub fn set_shape(&mut self, value : primitive_list::Reader<'a,u64>) -> Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value) } #[inline] pub fn init_shape(self, size : u32) -> primitive_list::Builder<'a,u64> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), size) } pub fn has_shape(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } } pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline } impl FromTypelessPipeline for Pipeline { fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline { Pipeline { _typeless : typeless, } } } impl Pipeline { } mod _private { use capnp::private::layout; pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 1 }; pub const TYPE_ID: u64 = 0xfcf201d6cc054cfc; } }
#![windows_subsystem = "windows"] fn main() -> std::io::Result<()> { let launch_data = std::fs::read("launcher")?; let app_home_path = std::env::current_dir()?; let home = &format!("{}", app_home_path.parent().unwrap().display()); let launch_str = String::from_utf8_lossy(&launch_data); let commands: Vec<_> = launch_str.split(" ").map(|c| c.replace("%APP_HOME%", home)).collect(); let program = { if cfg!(windows) { "jdk/bin/javaw.exe" } else if cfg!(macos) { "jdk/Contents/Home/bin/java" } else if cfg!(unix) { "jdk/bin/java" } else { panic!("only windows, mac and unix is supported") } }; let res = std::process::Command::new(program).args(&commands).spawn()?.wait()?; std::process::exit(res.code().unwrap_or(-1)); }
#[doc = "Reader of register RCC_MP_MLAHBENCLRR"] pub type R = crate::R<u32, super::RCC_MP_MLAHBENCLRR>; #[doc = "Writer for register RCC_MP_MLAHBENCLRR"] pub type W = crate::W<u32, super::RCC_MP_MLAHBENCLRR>; #[doc = "Register RCC_MP_MLAHBENCLRR `reset()`'s with value 0x10"] impl crate::ResetValue for super::RCC_MP_MLAHBENCLRR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x10 } } #[doc = "RETRAMEN\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RETRAMEN_A { #[doc = "0: Writing has no effect, reading means\r\n that the memory is not allocated by the\r\n MPU"] B_0X0 = 0, #[doc = "1: Writing deallocates the memory to\r\n the MPU, reading means that the memory is\r\n allocated to the MPU."] B_0X1 = 1, } impl From<RETRAMEN_A> for bool { #[inline(always)] fn from(variant: RETRAMEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RETRAMEN`"] pub type RETRAMEN_R = crate::R<bool, RETRAMEN_A>; impl RETRAMEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RETRAMEN_A { match self.bits { false => RETRAMEN_A::B_0X0, true => RETRAMEN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == RETRAMEN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == RETRAMEN_A::B_0X1 } } #[doc = "Write proxy for field `RETRAMEN`"] pub struct RETRAMEN_W<'a> { w: &'a mut W, } impl<'a> RETRAMEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RETRAMEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the memory is not allocated by the MPU"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(RETRAMEN_A::B_0X0) } #[doc = "Writing deallocates the memory to the MPU, reading means that the memory is allocated to the MPU."] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(RETRAMEN_A::B_0X1) } #[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 } } impl R { #[doc = "Bit 4 - RETRAMEN"] #[inline(always)] pub fn retramen(&self) -> RETRAMEN_R { RETRAMEN_R::new(((self.bits >> 4) & 0x01) != 0) } } impl W { #[doc = "Bit 4 - RETRAMEN"] #[inline(always)] pub fn retramen(&mut self) -> RETRAMEN_W { RETRAMEN_W { w: self } } }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// SyntheticsTriggerCiTestsResponse : Object containing information about the tests triggered. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyntheticsTriggerCiTestsResponse { /// List of Synthetics locations. #[serde(rename = "locations", skip_serializing_if = "Option::is_none")] pub locations: Option<Vec<crate::models::SyntheticsTriggerCiTestLocation>>, /// Information about the tests runs. #[serde(rename = "results", skip_serializing_if = "Option::is_none")] pub results: Option<Vec<crate::models::SyntheticsTriggerCiTestRunResult>>, /// The public IDs of the Synthetics test triggered. #[serde(rename = "triggered_check_ids", skip_serializing_if = "Option::is_none")] pub triggered_check_ids: Option<Vec<String>>, } impl SyntheticsTriggerCiTestsResponse { /// Object containing information about the tests triggered. pub fn new() -> SyntheticsTriggerCiTestsResponse { SyntheticsTriggerCiTestsResponse { locations: None, results: None, triggered_check_ids: None, } } }