text
stringlengths
8
4.13M
#![cfg_attr(feature = "unstable", feature(unsize))] mod util; mod array; mod vector; mod array_vec; mod small_dst; mod small_vec; pub use array::{Array, ArrayIndex, Addressable}; pub use vector::Vector; pub use small_vec::{SmallVec, Spilled}; pub use array_vec::ArrayVec; pub use small_dst::SmallDST;
pub mod account_creation; pub mod payments; use reusable_fmt::fmt_reuse; // Template for a default Move script fmt_reuse! { TEMPLATE_SCRIPT_MAIN = r#" script {{ {imports} fun main({main_args}) {{ {main_body} }} }} "#; }
extern crate imap; use imap::IMAPStream; fn main() { let mut imapstream = box IMAPStream::new("imap.qq.com", 143); imapstream.connect(); imapstream.login("550532246@qq.com", "xxxxxxx"); imapstream.select("inbox"); }
#[doc = "Register `EMR2` reader"] pub type R = crate::R<EMR2_SPEC>; #[doc = "Register `EMR2` writer"] pub type W = crate::W<EMR2_SPEC>; #[doc = "Field `EM32` reader - CPU wakeup with event mask on event input"] pub type EM32_R = crate::BitReader<EM32_A>; #[doc = "CPU wakeup with event mask on event input\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EM32_A { #[doc = "0: Interrupt request line is masked"] Masked = 0, #[doc = "1: Interrupt request line is unmasked"] Unmasked = 1, } impl From<EM32_A> for bool { #[inline(always)] fn from(variant: EM32_A) -> Self { variant as u8 != 0 } } impl EM32_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EM32_A { match self.bits { false => EM32_A::Masked, true => EM32_A::Unmasked, } } #[doc = "Interrupt request line is masked"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == EM32_A::Masked } #[doc = "Interrupt request line is unmasked"] #[inline(always)] pub fn is_unmasked(&self) -> bool { *self == EM32_A::Unmasked } } #[doc = "Field `EM32` writer - CPU wakeup with event mask on event input"] pub type EM32_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EM32_A>; impl<'a, REG, const O: u8> EM32_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Interrupt request line is masked"] #[inline(always)] pub fn masked(self) -> &'a mut crate::W<REG> { self.variant(EM32_A::Masked) } #[doc = "Interrupt request line is unmasked"] #[inline(always)] pub fn unmasked(self) -> &'a mut crate::W<REG> { self.variant(EM32_A::Unmasked) } } #[doc = "Field `EM33` reader - CPU wakeup with event mask on event input"] pub use EM32_R as EM33_R; #[doc = "Field `EM33` writer - CPU wakeup with event mask on event input"] pub use EM32_W as EM33_W; impl R { #[doc = "Bit 0 - CPU wakeup with event mask on event input"] #[inline(always)] pub fn em32(&self) -> EM32_R { EM32_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - CPU wakeup with event mask on event input"] #[inline(always)] pub fn em33(&self) -> EM33_R { EM33_R::new(((self.bits >> 1) & 1) != 0) } } impl W { #[doc = "Bit 0 - CPU wakeup with event mask on event input"] #[inline(always)] #[must_use] pub fn em32(&mut self) -> EM32_W<EMR2_SPEC, 0> { EM32_W::new(self) } #[doc = "Bit 1 - CPU wakeup with event mask on event input"] #[inline(always)] #[must_use] pub fn em33(&mut self) -> EM33_W<EMR2_SPEC, 1> { EM33_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 = "EXTI CPU wakeup with event mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`emr2::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 [`emr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct EMR2_SPEC; impl crate::RegisterSpec for EMR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`emr2::R`](R) reader structure"] impl crate::Readable for EMR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`emr2::W`](W) writer structure"] impl crate::Writable for EMR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets EMR2 to value 0"] impl crate::Resettable for EMR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Reader of register GPIO_HI_IN"] pub type R = crate::R<u32, super::GPIO_HI_IN>; #[doc = "Reader of field `GPIO_HI_IN`"] pub type GPIO_HI_IN_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:5 - Input value on QSPI IO in order 0..5: SCLK, SSn, SD0, SD1, SD2, SD3"] #[inline(always)] pub fn gpio_hi_in(&self) -> GPIO_HI_IN_R { GPIO_HI_IN_R::new((self.bits & 0x3f) as u8) } }
use bevy::math::{Quat, Vec2, Vec3}; pub fn scale(y: f32, a: f32) -> f32 { y * a } pub fn flip(x: f32) -> f32 { 1.0 - x } pub fn clamp(x: f32) -> f32 { x.abs() } pub fn smooth_start<const N: i32>(x: f32 ) -> f32 { x.powi(N) } pub fn smooth_stop<const N: i32>(x: f32 ) -> f32 { flip(flip(x).powi(N)) } pub fn mix(y1: f32, y2: f32, blend: f32) -> f32 { scale(y1, blend) + scale(y2, flip(blend)) } pub fn smooth_step<const N: i32>(x: f32) -> f32 { mix(smooth_start::<N>(x), smooth_stop::<N>(x), x) } pub fn lerp(start: Vec2, end: Vec2, x: f32) -> f32 { start.lerp(end, x).y } pub fn bias<const N: i32>(x: f32, bias: f32) -> f32 { let k = (1.0-bias).powi(N); return (x * k) / (x * k - x + 1.0); } pub fn asymptotic_averaging(current: f32, target: f32, speed: f32) -> f32 { current + (target - current) * speed } pub fn asymptotic_averaging_3d(current: Vec3, target: Vec3, speed: f32) -> Vec3 { current + (target - current) * speed } pub fn asymptotic_averaging_rot(current: Quat, target: Quat, speed: f32) -> Quat { current + (target - current) * speed }
#[cfg(test)] mod tests { use crate::aes_ecb::detect_aes_ecb; use std::fs::File; use std::io::{BufRead, BufReader}; // Eighth cryptopals challenge - https://cryptopals.com/sets/1/challenges/8 #[test] fn challenge8() { let mut found: Option<String> = None; for line in BufReader::new(File::open("data/8.txt").unwrap()).lines() { let real_line = line.unwrap(); let data = base64::decode(&real_line.clone()).unwrap(); if detect_aes_ecb(&data) { found = Some(real_line.clone()); break; } } assert!(found .unwrap() .starts_with("d880619740a8a19b7840a8a31c810a3d08649")); } }
use std::cell::RefCell; use std::rc::Rc; use futures::{channel::mpsc, future::ready, stream::Stream, StreamExt}; use moxie::{load_once, once, state, Commit}; /// Root a state variable at the callsite, returning a `dispatch` function which may be used to send /// messages to be processed by the provided `reducer` and `operator`. /// /// For each message dispatched, the provided `reducer` will be invoked with a reference to the current /// state and the message. The state will then be updated with the return value from the `reducer`. /// /// The `operator` receives an `mpsc::UnboundedReceiver<Msg>` stream of messages which have _already_ /// been processed by the `reducer`, and returns a stream of messages which will begin the cycle over /// again (piped to dispatch). /// /// # Example /// /// ``` /// use futures::{executor::LocalPool, StreamExt, future::ready}; /// use moxie::runtime::RunLoop; /// use moxie_streams::mox_stream; /// /// #[derive(Clone)] /// enum Msg { /// Ping, /// Pong, /// } /// /// struct State { /// pings: usize, /// pongs: usize, /// } /// /// let mut rt = RunLoop::new(|| { /// mox_stream( /// State { pings: 0, pongs: 0 }, /// |state, msg| match *msg { /// Msg::Ping => State { /// pings: state.pings + 1, /// pongs: state.pongs, /// }, /// Msg::Pong => State { /// pings: state.pings, /// pongs: state.pongs + 1, /// }, /// }, /// || Box::new(|in_stream| { /// in_stream /// .filter(|msg| { /// ready(match **msg { /// Msg::Ping => true, /// _ => false, /// }) /// }) /// .map(|_| Msg::Pong) /// }), /// ) /// }); /// /// let mut exec = LocalPool::new(); /// rt.set_task_executor(exec.spawner()); /// /// exec.run_until_stalled(); /// /// let (first_commit, dispatch) = rt.run_once(); /// assert_eq!(first_commit.pings, 0); /// assert_eq!(first_commit.pongs, 0); /// /// dispatch(Msg::Pong); /// exec.run_until_stalled(); /// /// let (second_commit, _) = rt.run_once(); /// assert_eq!(second_commit.pings, 0); /// assert_eq!(second_commit.pongs, 1); /// /// dispatch(Msg::Ping); /// exec.run_until_stalled(); /// /// let (third_commit, _) = rt.run_once(); /// assert_eq!(third_commit.pings, 1); /// assert_eq!(third_commit.pongs, 2); /// ``` pub fn mox_stream<State: 'static, Msg: 'static, OutStream>( initial_state: State, reducer: impl Fn(&State, Rc<Msg>) -> State + 'static, get_operator: impl Fn() -> Box<dyn FnOnce(mpsc::UnboundedReceiver<Rc<Msg>>) -> OutStream>, ) -> (Commit<State>, impl Fn(Msg)) where OutStream: Stream<Item = Msg> + 'static, { let (current_state, accessor) = state(|| initial_state); let dispatch = once(|| { let (action_producer, action_consumer): ( mpsc::UnboundedSender<Msg>, mpsc::UnboundedReceiver<Msg>, ) = mpsc::unbounded(); let p = Rc::new(RefCell::new(action_producer)); let pc = p.clone(); let (mut operated_action_producer, operated_action_consumer): ( mpsc::UnboundedSender<Rc<Msg>>, mpsc::UnboundedReceiver<Rc<Msg>>, ) = mpsc::unbounded(); let _ = load_once(move || { action_consumer.for_each(move |msg| { let mrc = Rc::new(msg); accessor.update(|cur| Some(reducer(cur, mrc.clone()))); let _ = operated_action_producer.start_send(mrc); ready(()) }) }); let _ = load_once(move || { get_operator()(operated_action_consumer).for_each(move |msg| { let _ = pc.borrow_mut().start_send(msg); ready(()) }) }); move |msg| { let _ = p.borrow_mut().start_send(msg); } }); (current_state, dispatch) } #[macro_export] macro_rules! combine_operators { ( $( $x:expr ),* ) => { { let mut in_producers = vec![]; let (out_producer, out_consumer): ( futures::channel::mpsc::UnboundedSender<Msg>, futures::channel::mpsc::UnboundedReceiver<Msg>, ) = futures::channel::mpsc::unbounded(); let op = std::rc::Rc::new(std::cell::RefCell::new(out_producer)); $( let out = op.clone(); let (p, c): ( futures::channel::mpsc::UnboundedSender<Rc<Msg>>, futures::channel::mpsc::UnboundedReceiver<Rc<Msg>>, ) = futures::channel::mpsc::unbounded(); let _ = load_once(|| ($x)(c).for_each(move |msg| { let _ = out.borrow_mut().start_send(msg); futures::future::ready(()) })); in_producers.push(p); )* move |in_stream: futures::channel::mpsc::UnboundedReceiver<Rc<Msg>>| { let _ = moxie::load_once(move || in_stream.for_each(move |mrc| { in_producers.iter_mut().for_each(|p| { let _ = p.start_send(mrc.clone()); }); futures::future::ready(()) })); out_consumer } } }; } #[cfg(test)] mod tests { use super::*; use futures::executor::LocalPool; use moxie::runtime::RunLoop; #[test] fn state_update() { #[derive(Clone)] enum Msg { Increment, Decrement, } let mut rt = RunLoop::new(|| { mox_stream( 0, |state, msg| match *msg { Msg::Increment => state + 1, Msg::Decrement => state - 1, }, || Box::new(|in_stream| in_stream.filter(|_| ready(false)).map(|_| Msg::Decrement)), ) }); let mut exec = LocalPool::new(); rt.set_task_executor(exec.spawner()); exec.run_until_stalled(); let (first_commit, dispatch) = rt.run_once(); assert_eq!(*first_commit, 0); dispatch(Msg::Increment); exec.run_until_stalled(); let (second_commit, _) = rt.run_once(); assert_eq!(*second_commit, 1); dispatch(Msg::Decrement); exec.run_until_stalled(); let (third_commit, _) = rt.run_once(); assert_eq!(*third_commit, 0); } #[test] fn operator() { #[derive(Clone)] enum Msg { Ping, Pong, } struct State { pings: usize, pongs: usize, } let mut rt = RunLoop::new(|| { mox_stream( State { pings: 0, pongs: 0 }, |state, msg| match *msg { Msg::Ping => State { pings: state.pings + 1, pongs: state.pongs, }, Msg::Pong => State { pings: state.pings, pongs: state.pongs + 1, }, }, || { Box::new(|in_stream| { in_stream .filter(|msg| { ready(match **msg { Msg::Ping => true, _ => false, }) }) .map(|_| Msg::Pong) }) }, ) }); let mut exec = LocalPool::new(); rt.set_task_executor(exec.spawner()); exec.run_until_stalled(); let (first_commit, dispatch) = rt.run_once(); assert_eq!(first_commit.pings, 0); assert_eq!(first_commit.pongs, 0); dispatch(Msg::Pong); exec.run_until_stalled(); let (second_commit, _) = rt.run_once(); assert_eq!(second_commit.pings, 0); assert_eq!(second_commit.pongs, 1); dispatch(Msg::Ping); exec.run_until_stalled(); let (third_commit, _) = rt.run_once(); assert_eq!(third_commit.pings, 1); assert_eq!(third_commit.pongs, 2); } #[test] fn combine_operator() { #[derive(Clone)] enum Msg { Tic, Tac, Toe, } struct State { tic: usize, tac: usize, toe: usize, } let tic_operator = |in_stream: mpsc::UnboundedReceiver<Rc<Msg>>| { in_stream .filter(|mrc| match **mrc { Msg::Tic => ready(true), _ => ready(false), }) .map(|_| Msg::Tac) }; let tac_operator = |in_stream: mpsc::UnboundedReceiver<Rc<Msg>>| { in_stream .filter(|mrc| match **mrc { Msg::Tac => ready(true), _ => ready(false), }) .map(|_| Msg::Toe) }; let mut rt = RunLoop::new(|| { mox_stream( State { tic: 0, tac: 0, toe: 0, }, |state, msg| match *msg { Msg::Tic => State { tic: state.tic + 1, tac: state.tac, toe: state.toe, }, Msg::Tac => State { tic: state.tic, tac: state.tac + 1, toe: state.toe, }, Msg::Toe => State { tic: state.tic, tac: state.tac, toe: state.toe + 1, }, }, || Box::new(combine_operators!(tic_operator, tac_operator)), ) }); let mut exec = LocalPool::new(); rt.set_task_executor(exec.spawner()); exec.run_until_stalled(); let (first_commit, dispatch) = rt.run_once(); assert_eq!(first_commit.tic, 0); assert_eq!(first_commit.tac, 0); assert_eq!(first_commit.toe, 0); dispatch(Msg::Toe); exec.run_until_stalled(); let (second_commit, _) = rt.run_once(); assert_eq!(second_commit.tic, 0); assert_eq!(second_commit.tac, 0); assert_eq!(second_commit.toe, 1); dispatch(Msg::Tic); exec.run_until_stalled(); let (third_commit, _) = rt.run_once(); assert_eq!(third_commit.tic, 1); assert_eq!(third_commit.tac, 1); assert_eq!(third_commit.toe, 2); } }
/* * Slack Web API * * One way to interact with the Slack platform is its HTTP RPC-based Web API, a collection of methods requiring OAuth 2.0-based user, bot, or workspace tokens blessed with related OAuth scopes. * * The version of the OpenAPI document: 1.7.0 * * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ObjsExternalOrgMigrations { #[serde(rename = "current")] pub current: Vec<crate::models::ObjsExternalOrgMigrationsCurrent>, #[serde(rename = "date_updated")] pub date_updated: i32, } impl ObjsExternalOrgMigrations { pub fn new(current: Vec<crate::models::ObjsExternalOrgMigrationsCurrent>, date_updated: i32) -> ObjsExternalOrgMigrations { ObjsExternalOrgMigrations { current, date_updated, } } }
use crate::frame::tanh::*; extern "C" { fn fma_tanh_f32(ptr: *mut f32, count: usize); } #[derive(Copy, Clone, Debug)] pub struct TanhF32; impl TanhKer<f32> for TanhF32 { #[inline(always)] fn name() -> &'static str { "fma" } #[inline(always)] fn nr() -> usize { 8 } #[inline(always)] fn alignment_bytes() -> usize { 32 } #[inline(never)] fn run(buf: &mut [f32]) { unsafe { fma_tanh_f32(buf.as_mut_ptr(), buf.len()) } } } #[cfg(test)] mod test_simd { tanh_frame_tests!(is_x86_feature_detected!("fma"), crate::x86_64_fma::tanh::TanhF32); }
/* Copyright 2020 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use anyhow::{Context as _, Result}; use std::env; use std::path::Path; mod convert; fn main() -> Result<()> { let files = env::args().collect::<Vec<String>>(); for path in &files[1..] { let source = std::fs::read_to_string(path).with_context(|| format!("failed to read `{}`", path))?; let mut full_script = String::new(); full_script.push_str(&convert::harness()); full_script.push_str(&convert::convert(path, &source)?); std::fs::write( Path::new(path).with_extension("js").file_name().unwrap(), &full_script, )?; } Ok(()) }
// The MD4 Message-Digest Algorithm // <https://tools.ietf.org/html/rfc1320> use core::convert::TryFrom; const INITIAL_STATE: [u32; 4] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476]; pub fn md4<T: AsRef<[u8]>>(data: T) -> [u8; Md4::DIGEST_LEN] { Md4::oneshot(data) } #[derive(Clone)] pub struct Md4 { buffer: [u8; Self::BLOCK_LEN], state: [u32; 4], len: u64, // in bytes. offset: usize, } impl Md4 { pub const BLOCK_LEN: usize = 64; pub const DIGEST_LEN: usize = 16; const BLOCK_LEN_BITS: u64 = Self::BLOCK_LEN as u64 * 8; const MLEN_SIZE: usize = core::mem::size_of::<u64>(); const MLEN_SIZE_BITS: u64 = Self::MLEN_SIZE as u64 * 8; const MAX_PAD_LEN: usize = Self::BLOCK_LEN + Self::MLEN_SIZE as usize; pub fn new() -> Self { Self { buffer: [0u8; 64], state: INITIAL_STATE, len: 0, offset: 0, } } pub fn update(&mut self, data: &[u8]) { let mut i = 0usize; while i < data.len() { if self.offset < Self::BLOCK_LEN { self.buffer[self.offset] = data[i]; self.offset += 1; i += 1; } if self.offset == Self::BLOCK_LEN { transform(&mut self.state, &self.buffer); self.offset = 0; self.len += Self::BLOCK_LEN as u64; } } } pub fn finalize(mut self) -> [u8; Self::DIGEST_LEN] { let mlen = self.len + self.offset as u64; // in bytes let mlen_bits = mlen * 8; // in bits // pad len, in bits let plen_bits = Self::BLOCK_LEN_BITS - (mlen_bits + Self::MLEN_SIZE_BITS + 1) % Self::BLOCK_LEN_BITS + 1; // pad len, in bytes let plen = plen_bits / 8; debug_assert_eq!(plen_bits % 8, 0); debug_assert!(plen > 1); debug_assert_eq!( (mlen + plen + Self::MLEN_SIZE as u64) % Self::BLOCK_LEN as u64, 0 ); // NOTE: MAX_PAD_LEN 是一个很小的数字,所以这里可以安全的 unwrap. let plen = usize::try_from(plen).unwrap(); let mut padding: [u8; Self::MAX_PAD_LEN] = [0u8; Self::MAX_PAD_LEN]; padding[0] = 0x80; let mlen_octets: [u8; Self::MLEN_SIZE] = mlen_bits.to_le_bytes(); padding[plen..plen + Self::MLEN_SIZE].copy_from_slice(&mlen_octets); let data = &padding[..plen + Self::MLEN_SIZE]; self.update(data); // NOTE: 数据填充完毕后,此时已经处理的消息应该是 BLOCK_LEN 的倍数,因此,offset 此时已被清零。 debug_assert_eq!(self.offset, 0); let mut output = [0u8; Self::DIGEST_LEN]; output[0..4].copy_from_slice(&self.state[0].to_le_bytes()); output[4..8].copy_from_slice(&self.state[1].to_le_bytes()); output[8..12].copy_from_slice(&self.state[2].to_le_bytes()); output[12..16].copy_from_slice(&self.state[3].to_le_bytes()); output } pub fn oneshot<T: AsRef<[u8]>>(data: T) -> [u8; Self::DIGEST_LEN] { let mut m = Self::new(); m.update(data.as_ref()); m.finalize() } } macro_rules! F { ($x:expr, $y:expr, $z:expr) => { (($x) & ($y)) | (!($x) & ($z)) }; } macro_rules! G { ($x:expr, $y:expr, $z:expr) => { (($x) & ($y)) | (($x) & ($z)) | (($y) & ($z)) }; } macro_rules! H { ($x:expr, $y:expr, $z:expr) => { ($x) ^ ($y) ^ ($z) }; } macro_rules! FF { ($a:expr, $b:expr, $c:expr, $d:expr, $k:expr, $s:expr) => { $a.wrapping_add(F!($b, $c, $d)) .wrapping_add($k) .rotate_left($s) }; } macro_rules! GG { ($a:expr, $b:expr, $c:expr, $d:expr, $k:expr, $s:expr) => { $a.wrapping_add(G!($b, $c, $d)) .wrapping_add($k) .wrapping_add(0x5A827999) .rotate_left($s) }; } macro_rules! HH { ($a:expr, $b:expr, $c:expr, $d:expr, $k:expr, $s:expr) => { $a.wrapping_add(H!($b, $c, $d)) .wrapping_add($k) .wrapping_add(0x6ED9EBA1) .rotate_left($s) }; } #[inline] fn transform(state: &mut [u32; 4], block: &[u8]) { debug_assert_eq!(state.len(), 4); debug_assert_eq!(block.len(), Md4::BLOCK_LEN); let mut a = state[0]; let mut b = state[1]; let mut c = state[2]; let mut d = state[3]; // load block to data let mut data = [0u32; 16]; for i in 0usize..16 { let idx = i * 4; data[i] = u32::from_le_bytes([ block[idx + 0], block[idx + 1], block[idx + 2], block[idx + 3], ]); } // round 1 for &i in &[0usize, 4, 8, 12] { a = FF!(a, b, c, d, data[i], 3); d = FF!(d, a, b, c, data[i + 1], 7); c = FF!(c, d, a, b, data[i + 2], 11); b = FF!(b, c, d, a, data[i + 3], 19); } // round 2 for i in 0..4 { a = GG!(a, b, c, d, data[i], 3); d = GG!(d, a, b, c, data[i + 4], 5); c = GG!(c, d, a, b, data[i + 8], 9); b = GG!(b, c, d, a, data[i + 12], 13); } // round 3 for &i in &[0usize, 2, 1, 3] { a = HH!(a, b, c, d, data[i], 3); d = HH!(d, a, b, c, data[i + 8], 9); c = HH!(c, d, a, b, data[i + 4], 11); b = HH!(b, c, d, a, data[i + 12], 15); } state[0] = state[0].wrapping_add(a); state[1] = state[1].wrapping_add(b); state[2] = state[2].wrapping_add(c); state[3] = state[3].wrapping_add(d); } #[test] fn test_md4() { // A.5 Test suite // <https://tools.ietf.org/html/rfc1320#appendix-A.5> assert_eq!( &md4(""), &hex::decode("31d6cfe0d16ae931b73c59d7e0c089c0").unwrap()[..] ); assert_eq!( &md4("a"), &hex::decode("bde52cb31de33e46245e05fbdbd6fb24").unwrap()[..] ); assert_eq!( &md4("abc"), &hex::decode("a448017aaf21d8525fc10ae87aa6729d").unwrap()[..] ); assert_eq!( &md4("message digest"), &hex::decode("d9130a8164549fe818874806e1c7014b").unwrap()[..] ); assert_eq!( &md4("abcdefghijklmnopqrstuvwxyz"), &hex::decode("d79e1c308aa5bbcdeea8ed63df412da9").unwrap()[..] ); assert_eq!( &md4("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), &hex::decode("043f8582f241db351ce627e153e7f0e4").unwrap()[..] ); assert_eq!( &md4("12345678901234567890123456789012345678901234567890123456789012345678901234567890"), &hex::decode("e33b4ddc9c38f2199c3e7b164fcc0536").unwrap()[..] ); }
use crate::{FeedId, Runtime}; use codec::{Decode, Encode}; use pallet_feeds::feed_processor::{FeedMetadata, FeedObjectMapping, FeedProcessor}; use pallet_grandpa_finality_verifier::chain::Chain; use scale_info::TypeInfo; use sp_api::HeaderT; use sp_core::Hasher; use sp_runtime::traits::BlakeTwo256; use sp_runtime::{generic, DispatchError}; use sp_std::prelude::*; /// Polkadot-like chain. struct PolkadotLike; impl Chain for PolkadotLike { type BlockNumber = u32; type Hash = <BlakeTwo256 as Hasher>::Out; type Header = generic::Header<u32, BlakeTwo256>; type Hasher = BlakeTwo256; } /// Type used to represent a FeedId or ChainId struct GrandpaValidator<C>(C); impl<C: Chain> FeedProcessor<FeedId> for GrandpaValidator<C> { fn init(&self, feed_id: FeedId, data: &[u8]) -> sp_runtime::DispatchResult { pallet_grandpa_finality_verifier::initialize::<Runtime, C>(feed_id, data) } fn put(&self, feed_id: FeedId, object: &[u8]) -> Result<Option<FeedMetadata>, DispatchError> { Ok(Some( pallet_grandpa_finality_verifier::validate_finalized_block::<Runtime, C>( feed_id, object, )? .encode(), )) } fn object_mappings(&self, _feed_id: FeedId, object: &[u8]) -> Vec<FeedObjectMapping> { extract_substrate_object_mapping::<C>(object) } fn delete(&self, feed_id: FeedId) -> sp_runtime::DispatchResult { pallet_grandpa_finality_verifier::purge::<Runtime>(feed_id) } } struct ParachainImporter<C>(C); impl<C: Chain> FeedProcessor<FeedId> for ParachainImporter<C> { fn put(&self, _feed_id: FeedId, object: &[u8]) -> Result<Option<FeedMetadata>, DispatchError> { let block = C::decode_block::<Runtime>(object)?; Ok(Some( (block.block.header.hash(), *block.block.header.number()).encode(), )) } fn object_mappings(&self, _feed_id: FeedId, object: &[u8]) -> Vec<FeedObjectMapping> { extract_substrate_object_mapping::<C>(object) } } fn extract_substrate_object_mapping<C: Chain>(object: &[u8]) -> Vec<FeedObjectMapping> { let block = match C::decode_block::<Runtime>(object) { Ok(block) => block, // we just return empty if we failed to decode as this is not called in runtime Err(_) => return vec![], }; // we send two mappings pointed to the same object // block height and block hash // this would be easier for sync client to crawl through the descendents by block height // if you already have a block hash, you can fetch the same block with it as well vec![ FeedObjectMapping::Custom { key: block.block.header.number().encode(), offset: 0, }, FeedObjectMapping::Custom { key: block.block.header.hash().as_ref().to_vec(), offset: 0, }, ] } /// FeedProcessorId represents the available FeedProcessor impls #[derive(Default, Debug, Clone, Copy, Encode, Decode, TypeInfo, Eq, PartialEq)] pub enum FeedProcessorKind { /// Content addressable Feed processor, #[default] ContentAddressable, /// Polkadot like relay chain Feed processor that validates grandpa justifications and indexes the entire block PolkadotLike, /// Parachain Feed processor that just indexes the entire block ParachainLike, } pub(crate) fn feed_processor( feed_processor_kind: FeedProcessorKind, ) -> Box<dyn FeedProcessor<FeedId>> { match feed_processor_kind { FeedProcessorKind::PolkadotLike => Box::new(GrandpaValidator(PolkadotLike)), FeedProcessorKind::ContentAddressable => Box::new(()), FeedProcessorKind::ParachainLike => Box::new(ParachainImporter(PolkadotLike)), } }
extern crate hal; extern crate once_cell; use crate::application::Window; use crate::graphics::gfxal::back::Backend; use crate::maths; use once_cell::sync::OnceCell; use std::sync::Mutex; use hal::{ adapter::PhysicalDevice, device::Device, pool::CommandPool, queue::QueueFamily, window::{PresentationSurface, Surface}, }; use std::mem::ManuallyDrop; /// the state of the graphics backend /// this is somewhat equivalent to a context and contains everything that /// is needed for a renderer that does that isn't directly related to the rendering part. /// *There should only ever be one of these* //TODO: impl drop #[allow(missing_docs)] pub struct GfxState { /// current frame of the application pub frame: u64, /// the number of simultaniously computed frames pub frames_in_flight: usize, pub selected_adapter: hal::adapter::Adapter<Backend>, pub adapters: Vec<hal::adapter::Adapter<Backend>>, pub surface: <Backend as hal::Backend>::Surface, pub memory_types: Vec<hal::adapter::MemoryType>, pub queue_group: hal::queue::QueueGroup<Backend>, pub device: <Backend as hal::Backend>::Device, pub command_pools: Vec<<Backend as hal::Backend>::CommandPool>, pub command_buffers: Vec<<Backend as hal::Backend>::CommandBuffer>, pub submission_complete_semaphores: Vec<<Backend as hal::Backend>::Semaphore>, pub submission_complete_fences: Vec<<Backend as hal::Backend>::Fence>, pub viewport: hal::pso::Viewport, pub render_pass: ManuallyDrop<<Backend as hal::Backend>::RenderPass>, pub extent: hal::image::Extent, pub format: hal::format::Format, pub frame_idx: usize, pub surface_image: <<Backend as hal::Backend>::Surface as hal::window::PresentationSurface< Backend, >>::SwapchainImage, pub framebuffer: <Backend as hal::Backend>::Framebuffer, pub clear_color: crate::maths::Color, pub window: std::sync::Arc<std::sync::Mutex<Window>>, } /// the graphics context, there should only ever be one of these, /// it contains everything needed to draw stuff to the screen. It is behind a `Mutex` /// which means that there can only ever be one of these unwrapped on a single thread. pub static GRAPHICS_CONTEXT: OnceCell<Mutex<GfxState>> = OnceCell::new(); /// this gives access to the graphics context within the crate. It is behind a `Mutex` /// which means that there can only ever be one of these unwrapped on a single thread. /// This will not work in the client. macro_rules! crate_get_graphics_context { () => { crate::graphics::gfxal::gfxstate::GRAPHICS_CONTEXT .get() .expect("failed to get graphics context") .try_lock() .unwrap() }; } /// gives the client access to the graphics context, this should never have to be /// used however is useful for debugging purposes, this will not work if you use it /// within the chai crate. It is also behind a `Mutex` /// which means that there can only ever be one of these unwrapped on a single thread. #[macro_export] macro_rules! get_graphics_context { () => { chai::graphics::gfxal::gfxstate::GRAPHICS_CONTEXT .get() .expect("failed to get graphics context") .try_lock() .unwrap() }; } impl GfxState { /// creates the graphics state #[profiled] pub fn init( mut adapters: Vec<hal::adapter::Adapter<Backend>>, mut surface: <Backend as hal::Backend>::Surface, adapter_index: usize, window: std::sync::Arc<std::sync::Mutex<Window>>, size: maths::Size, ) { use hal::pso::DescriptorPool; use std::borrow::Borrow; let mut adapter = adapters.remove(adapter_index); let memory_types = adapter.physical_device.memory_properties().memory_types; let family = adapter .queue_families .iter() .find(|family| { surface.supports_queue_family(family) && family.queue_type().supports_graphics() }) .unwrap(); let mut gpu = unsafe { adapter .physical_device .open(&[(family, &[1.0])], hal::Features::empty()) .unwrap() }; let queue_group = gpu.queue_groups.pop().unwrap(); let device = gpu.device; let caps = surface.capabilities(&mut adapter.physical_device); let formats = surface.supported_formats(&adapter.physical_device); println!("formats: {:?}", formats); let format = formats.map_or(hal::format::Format::Rgba8Srgb, |formats| { formats .iter() .find(|format| format.base_format().1 == hal::format::ChannelType::Srgb) .map(|format| *format) .unwrap_or(formats[0]) }); let swap_config = hal::window::SwapchainConfig::from_caps(&caps, format, size.into()); // println!("{:?}", swap_config); let extent = swap_config.extent; unsafe { surface .configure_swapchain(&device, swap_config) .expect("failed to configure swapchain"); }; let render_pass = { let attachment = hal::pass::Attachment { format: Some(format), samples: 1, ops: hal::pass::AttachmentOps::new( hal::pass::AttachmentLoadOp::Clear, hal::pass::AttachmentStoreOp::Store, ), stencil_ops: hal::pass::AttachmentOps::DONT_CARE, layouts: hal::image::Layout::Undefined..hal::image::Layout::Present, }; let subpass = hal::pass::SubpassDesc { colors: &[(0, hal::image::Layout::ColorAttachmentOptimal)], depth_stencil: None, inputs: &[], resolves: &[], preserves: &[], }; ManuallyDrop::new( unsafe { device.create_render_pass(&[attachment], &[subpass], &[]) } .expect("failed to create render pass"), ) }; let frames_in_flight = 3; let mut submission_complete_semaphores = Vec::with_capacity(frames_in_flight); let mut submission_complete_fences = Vec::with_capacity(frames_in_flight); let mut command_pools = Vec::with_capacity(frames_in_flight); let mut command_buffers = Vec::with_capacity(frames_in_flight); let command_pool = unsafe { device.create_command_pool( queue_group.family, hal::pool::CommandPoolCreateFlags::empty(), ) } .expect("failed to create command pool"); command_pools.push(command_pool); for _ in 1..frames_in_flight { unsafe { command_pools.push( device .create_command_pool( queue_group.family, hal::pool::CommandPoolCreateFlags::empty(), ) .expect("failed to create command pool for frame in flight"), ); } } for i in 0..frames_in_flight { submission_complete_semaphores.push( device .create_semaphore() .expect("failed to create semaphore"), ); submission_complete_fences .push(device.create_fence(true).expect("failed to create fence")); command_buffers .push(unsafe { command_pools[i].allocate_one(hal::command::Level::Primary) }); } let viewport = hal::pso::Viewport { rect: hal::pso::Rect { x: 0, y: 0, w: extent.width as _, h: extent.height as _, }, depth: 0.0..1.0, }; let extent = hal::image::Extent { width: size.width as hal::image::Size, height: size.height as hal::image::Size, depth: 1.0 as hal::image::Size, }; let (surface_image, framebuffer) = unsafe { let surface_image = match surface.acquire_image(!0) { Ok((image, _)) => image, Err(_) => { panic!("failed to create surface image"); } }; let framebuffer = device .create_framebuffer( &render_pass, std::iter::once(surface_image.borrow()), extent, ) .unwrap(); (surface_image, framebuffer) }; GRAPHICS_CONTEXT.get_or_init(move || { Mutex::new(GfxState { frame: 0, frames_in_flight, selected_adapter: adapter, adapters, surface, memory_types, queue_group, device, command_pools, command_buffers, viewport, render_pass, submission_complete_semaphores, submission_complete_fences, format, extent, frame_idx: 0, surface_image, framebuffer, clear_color: crate::maths::Color::new_from_rgb(0, 0, 0), window, }) }); } /// sets the clear color of the graphics state. This is applied in `begin_scene` #[profiled] pub fn set_clear_color(&mut self, color: crate::maths::Color) { self.clear_color = color; } /// List available gpus, this can be used to let the user choose what gpu to use. /// These are normally hardware gpu's but can be software implementations #[profiled] pub fn list_gpus(&self) -> Vec<&hal::adapter::Adapter<Backend>> { use std::iter::FromIterator; let mut nvec = Vec::from_iter(self.adapters.iter().clone()); nvec.push(&self.selected_adapter); nvec } /// filters supported gpus, you prob don't need to use this, /// you can get the same information easier from `list_gpus` #[profiled] pub fn filter_gpus( adapters: Vec<hal::adapter::Adapter<Backend>>, surface: &<Backend as hal::Backend>::Surface, ) -> Vec<hal::adapter::Adapter<Backend>> { use std::iter::FromIterator; Vec::from_iter(adapters.into_iter().filter(|a| { a.queue_families .iter() .any(|qf| qf.queue_type().supports_graphics() && surface.supports_queue_family(qf)) })) } /// creates the framebuffer and image surface needed for rendering #[profiled] #[rustfmt::skip] // for some reason fmt mangles parts of this fn pub fn create_frame_and_surface(&mut self) -> ( <Backend as hal::Backend>::Framebuffer, <<Backend as hal::Backend>::Surface as hal::window::PresentationSurface<Backend>>::SwapchainImage ) { use std::borrow::Borrow; unsafe { let img = match self.surface.acquire_image(!0) { Ok((image, _)) => image, Err(_) => { self.recreate_swapchain(); return self.create_frame_and_surface(); } }; let fb = self .device .create_framebuffer( &self.render_pass, std::iter::once(img.borrow()), self.extent, ) .unwrap(); (fb, img) } } /// recreate the swapchain (usually caused by resizing the window) pub(crate) fn recreate_swapchain(&mut self) { let caps = self .surface .capabilities(&self.selected_adapter.physical_device); let sizing = self.window.try_lock().unwrap().get_size(); let swap_config = hal::window::SwapchainConfig::from_caps(&caps, self.format, sizing.into()); log_info!(format!("{:?}", swap_config)); let extent = swap_config.extent.to_extent(); unsafe { self.surface .configure_swapchain(&self.device, swap_config) .expect("Can't create swapchain"); } self.viewport.rect.w = extent.width as _; self.viewport.rect.h = extent.height as _; } /// begins the scene, this clears the screen and preps it for accepting commands. #[profiled] pub fn begin_scene(&mut self) { use hal::command::CommandBuffer; let idx = self.frame_idx; let viewport = self.viewport.clone(); let cmd_buffers = &mut self.command_buffers; unsafe { cmd_buffers[idx].begin_primary(hal::command::CommandBufferFlags::ONE_TIME_SUBMIT); cmd_buffers[idx].set_viewports(0, &[viewport.clone()]); cmd_buffers[idx].set_scissors(0, &[viewport.rect]); cmd_buffers[self.frame_idx].begin_render_pass( &self.render_pass, &self.framebuffer, self.viewport.clone().rect, &[hal::command::ClearValue { color: hal::command::ClearColor { float32: [ self.clear_color.r, self.clear_color.g, self.clear_color.b, self.clear_color.a, ], }, }], hal::command::SubpassContents::Inline, ); } } /// ends the scene (best docs in the world) pub fn end_scene(&mut self) { use hal::command::CommandBuffer; let (new_framebuffer, new_surface_image) = { self.create_frame_and_surface() }; let cmd_buffer = &mut self.command_buffers[self.frame_idx]; unsafe { use hal::queue::{CommandQueue, Submission}; self.frame += 1; self.frame_idx = self.frame as usize % self.frames_in_flight; cmd_buffer.end_render_pass(); cmd_buffer.finish(); let submission = Submission { command_buffers: std::iter::once(&*cmd_buffer), wait_semaphores: None, signal_semaphores: std::iter::once( &self.submission_complete_semaphores[self.frame_idx], ), }; self.queue_group.queues[0].submit( submission, Some(&self.submission_complete_fences[self.frame_idx]), ); let result = self.queue_group.queues[0].present_surface( &mut self.surface, std::mem::replace(&mut self.surface_image, new_surface_image), Some(&self.submission_complete_semaphores[self.frame_idx]), ); self.device .destroy_framebuffer(std::mem::replace(&mut self.framebuffer, new_framebuffer)); if result.is_err() { self.recreate_swapchain(); } // self.queue_group.queues[0].wait_idle(); } } }
use nom::number::complete::{le_u8, le_f32}; use serde_derive::{Serialize}; use super::parserHeader::*; #[derive(Debug, PartialEq, Serialize)] pub struct LapData { pub m_lastLapTime: f32, pub m_currentLapTime: f32, pub m_bestLapTime: f32, pub m_sector1Time: f32, pub m_sector2Time: f32, pub m_lapDistance: f32, pub m_totalDistance: f32, pub m_safetyCarDelta: f32, pub m_carPosition: u8, pub m_currentLapNum: u8, pub m_pitStatus: u8, pub m_sector: u8, pub m_currentLapInvalid: u8, pub m_penalties: u8, pub m_gridPosition: u8, pub m_driverStatus: u8, pub m_resultStatus: u8 } named!(pub parse_lap_data<&[u8], LapData>, do_parse!( m_lastLapTime: le_f32 >> m_currentLapTime: le_f32 >> m_bestLapTime: le_f32 >> m_sector1Time: le_f32 >> m_sector2Time: le_f32 >> m_lapDistance: le_f32 >> m_totalDistance: le_f32 >> m_safetyCarDelta: le_f32 >> m_carPosition: le_u8 >> m_currentLapNum: le_u8 >> m_pitStatus: le_u8 >> m_sector: le_u8 >> m_currentLapInvalid: le_u8 >> m_penalties: le_u8 >> m_gridPosition: le_u8 >> m_driverStatus: le_u8 >> m_resultStatus: le_u8 >> (LapData { m_lastLapTime: m_lastLapTime, m_currentLapTime: m_currentLapTime, m_bestLapTime: m_bestLapTime, m_sector1Time: m_sector1Time, m_sector2Time: m_sector2Time, m_lapDistance: m_lapDistance, m_totalDistance: m_totalDistance, m_safetyCarDelta: m_safetyCarDelta, m_carPosition: m_carPosition, m_currentLapNum: m_currentLapNum, m_pitStatus: m_pitStatus, m_sector: m_sector, m_currentLapInvalid: m_currentLapInvalid, m_penalties: m_penalties, m_gridPosition: m_gridPosition, m_driverStatus: m_driverStatus, m_resultStatus: m_resultStatus }) ) ); named!(pub parse_lap_datas<&[u8], Vec<LapData>>, count!(parse_lap_data, 20) ); #[derive(Debug, PartialEq, Serialize)] pub struct PacketLapData { pub m_header: PacketHeader, pub m_lapData: Vec<LapData>, } named!(pub parse_lap_data_packet<&[u8], PacketLapData>, do_parse!( m_header: parse_header >> m_lapData: parse_lap_datas >> (PacketLapData { m_header: m_header, m_lapData: m_lapData }) ) );
#![allow(dead_code)] #![allow(non_camel_case_types)] /// A very small, restricted subset of uinput. Not too much work was done to refine this since /// there exists a uinput crate. /// That crate currently has an issue compiling (05/27) mod key; mod uinput_sys; pub use self::key::Key; use self::uinput_sys as ffi; use std::io::Write; use std::fs::{OpenOptions, File}; use std::os::unix::io::AsRawFd; mod ioctl { const UINPUT_IOCTL_BASE: u8 = 'U' as u8; ioctl!(none ui_dev_create with UINPUT_IOCTL_BASE, 1); ioctl!(none ui_dev_destroy with UINPUT_IOCTL_BASE, 2); ioctl!(write_ptr set_ev_bit with UINPUT_IOCTL_BASE, 100; ::libc::c_int); ioctl!(write_ptr set_key_bit with UINPUT_IOCTL_BASE, 101; ::libc::c_int); ioctl!(write_ptr set_rel_bit with UINPUT_IOCTL_BASE, 102; ::libc::c_int); ioctl!(write_ptr set_abs_bit with UINPUT_IOCTL_BASE, 103; ::libc::c_int); } unsafe fn any_as_u8_slice<T: Sized>(p: &T) -> &[u8] { ::std::slice::from_raw_parts( (p as *const T) as *const u8, ::std::mem::size_of::<T>(), ) } pub struct UInput { ffi: ffi::uinput_user_dev, ev: ffi::input_event, uinput_device: File, } impl UInput { /// Create a uinput handle. pub fn new() -> UInput { let mut name = [0; 80]; name[0] = 97; // 'a' let ffi_dev = ffi::uinput_user_dev { name: name, id: ffi::input_id { bustype: 0x03, // BUS_USB vendor: 1, product: 1, version: 1 }, ff_effects_max: 0, absmax: [0; 64], absmin: [0; 64], absfuzz: [0; 64], absflat: [0; 64], }; let ev = ffi::input_event { time: ffi::timeval { tv_sec: 0, tv_usec: 0, }, kind: 0, code: 0, value: 0, }; // Attempt to open uinput let mut uinput_device = OpenOptions::new() .read(true) .write(true) .open("/dev/uinput") // or /dev/input/uinput .expect("Failed to open uinput"); let fd = uinput_device.as_raw_fd(); // Register all relevant events unsafe { ioctl::set_ev_bit(fd, (EventType::EV_KEY as u8) as *const ::libc::c_int).expect("ioctl failed."); ioctl::set_key_bit(fd, 0x110 as *const _).expect("ioctl failed."); // BTN_LEFT ioctl::set_key_bit(fd, 0x111 as *const _).expect("ioctl failed."); // BTN_RIGHT /* ioctl::set_key_bit(fd, 0x112 as *const _).expect("ioctl failed."); // BTN_MIDDLE ioctl::set_key_bit(fd, 0x115 as *const _).expect("ioctl failed."); // BTN_FORWARD ioctl::set_key_bit(fd, 0x116 as *const _).expect("ioctl failed."); // BTN_BACK */ for i in 1..150u8 { ioctl::set_key_bit(fd, i as *const _).expect("ioctl failed."); // Most of the keyboard keys. } ioctl::set_ev_bit(fd, (EventType::EV_REL as u8) as *const ::libc::c_int).expect("ioctl failed."); ioctl::set_rel_bit(fd, 0 as *const _).expect("ioctl failed."); // REL_X ioctl::set_rel_bit(fd, 1 as *const _).expect("ioctl failed."); // REL_Y /* ioctl::set_ev_bit(fd, (EventType::EV_ABS as u8) as *const ::libc::c_int).expect("ioctl failed."); ioctl::set_abs_bit(fd, 0 as *const _).expect("ioctl failed."); // ABS_X ioctl::set_abs_bit(fd, 1 as *const _).expect("ioctl failed."); // ABS_Y */ let raw_dev = any_as_u8_slice(&ffi_dev); uinput_device.write_all(raw_dev).expect("Write failed."); ioctl::ui_dev_create(fd).expect("uidev create failed."); } UInput { ffi: ffi_dev, ev: ev, uinput_device: uinput_device, } } pub fn key_press(&mut self, key: Key) { self.ev.kind = EventType::EV_KEY as u16; let val: u8 = key.into(); self.ev.code = val as u16; self.ev.value = 1; self.write(); } pub fn key_release(&mut self, key: Key) { self.ev.kind = EventType::EV_KEY as u16; let val: u8 = key.into(); self.ev.code = val as u16; self.ev.value = 0; self.write(); } pub fn key_click(&mut self, key: Key) { self.key_press(key); self.key_release(key); } pub fn btn_left_press(&mut self) { self.ev.kind = EventType::EV_KEY as u16; self.ev.code = 0x110 as u16; self.ev.value = 1; self.write(); } pub fn btn_left_release(&mut self) { self.ev.kind = EventType::EV_KEY as u16; self.ev.code = 0x110 as u16; self.ev.value = 0; self.write(); } pub fn btn_right_press(&mut self) { self.ev.kind = EventType::EV_KEY as u16; self.ev.code = 0x111 as u16; self.ev.value = 1; self.write(); } pub fn btn_right_release(&mut self) { self.ev.kind = EventType::EV_KEY as u16; self.ev.code = 0x111 as u16; self.ev.value = 0; self.write(); } pub fn sync(&mut self) { self.ev.kind = EventType::EV_SYN as u16; self.ev.code = 0; self.ev.value = 0; self.write(); } pub fn rel_x(&mut self, val: i32) { self.ev.kind = EventType::EV_REL as u16; self.ev.code = 0; self.ev.value = val; self.write(); } pub fn rel_y(&mut self, val: i32) { self.ev.kind = EventType::EV_REL as u16; self.ev.code = 1; self.ev.value = val; self.write(); } pub fn abs_x(&mut self, val: i32) { self.ev.kind = EventType::EV_ABS as u16; self.ev.code = 0; self.ev.value = val; self.write(); } pub fn abs_y(&mut self, val: i32) { self.ev.kind = EventType::EV_ABS as u16; self.ev.code = 1; self.ev.value = val; self.write(); } fn write(&mut self) { unsafe { let raw_ev = any_as_u8_slice(&self.ev); self.uinput_device.write_all(raw_ev).expect("Write failed."); } } } impl Drop for UInput { fn drop(&mut self) { let fd = self.uinput_device.as_raw_fd(); unsafe { ioctl::ui_dev_destroy(fd).expect("uidev destroy failed."); } } } pub enum EventType { EV_SYN = 0x00, EV_KEY = 0x01, EV_REL = 0x02, EV_ABS = 0x03, /* EV_MSC = 0x04, EV_SW = 0x05, EV_LED = 0x11, EV_SND = 0x12, EV_REP = 0x14, EV_FF = 0x15, EV_PWR = 0x16, EV_FF_STATUS = 0x17, EV_MAX = 0x1f, EV_CNT = 0x20, */ }
//! Bidirectional hashmaps! //! This crate aims to provide a data structure that can take store a 1:1 relation between two //! different types, and provide constant time lookup within this relation. //! //! Unlike a regular hashmap, which provides lookups from "keys" to "values", the two directional //! hashmap provides lookups from "left keys" to "right keys" and from "right keys" to "left keys". //! The difference between a "value" in a hashmap and a "right key" in a `BiMap` is that the right //! key must be hashable and comparable, and that duplicate right keys cannot exist within the //! bimap, even if they have different left keys mapping to them. #[cfg(test)] #[macro_use] extern crate quickcheck; #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub mod bitfield; mod bucket; mod builder; mod iterator; use bitfield::{BitField, DefaultBitField}; use bucket::Bucket; pub use builder::BiMapBuilder; pub use iterator::{IntoIter, Iter}; use std::borrow::Borrow; use std::collections::hash_map::RandomState; use std::fmt::{self, Debug}; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter::{self, Extend, FromIterator}; use std::mem; pub(crate) const DEFAULT_HASH_MAP_SIZE: usize = 32; const RESIZE_GROWTH_FACTOR: usize = 2; // left as a fraction to avoid floating point multiplication and division where it isn't needed pub(crate) const MAX_LOAD_FACTOR: f32 = 1.1; /// The two way hashmap itself. See the crate level documentation for more information. Uses /// hopscotch hashing internally. /// /// L and R are the left and right types being mapped to eachother. LH and RH are the hash builders /// used to hash the left keys and right keys. B is the bitfield used to store neighbourhoods. #[derive(Clone)] pub struct BiMap<L, R, LH = RandomState, RH = RandomState, B = DefaultBitField> { /// The number of pairs inside the map len: usize, /// All of the left keys, and the locations of their pairs within the right_data array. left_data: Box<[Bucket<L, usize, B>]>, /// All of the right keys, and the locations of their pairs within the left_data array. right_data: Box<[Bucket<R, usize, B>]>, /// Used to generate hash values for the left keys left_hasher: LH, /// Used to generate hash values for the right keys right_hasher: RH, } impl<L, R> Default for BiMap<L, R> { fn default() -> Self { BiMapBuilder::new().finish() } } impl<L, R> BiMap<L, R> { /// Creates a new empty BiMap. /// /// ``` /// # use isomorphism::BiMap; /// let map: BiMap<u64, char> = BiMap::new(); /// ``` pub fn new() -> Self { Default::default() } } impl<L, R, LH, RH, B> BiMap<L, R, LH, RH, B> { /// Returns a lower bound on the number of elements that this hashmap can hold without needing /// to be resized. /// /// ``` /// # use isomorphism::BiMap; /// let map: BiMap<String, String> = BiMap::new(); /// let capacity = map.capacity(); /// assert!(capacity >= 0); /// ``` pub fn capacity(&self) -> usize { (self.left_data.len() as f32 / MAX_LOAD_FACTOR).floor() as usize } /// Returns the number of pairs inside this hashmap. Each remove will decrement this count. /// Each insert will increment this count, but may then also decrement it by one or two if the /// keys being inserted already existed and were associated with other pairs. /// /// ``` /// # use isomorphism::BiMap; /// let mut map = BiMap::new(); /// assert_eq!(0, map.len()); /// /// map.insert("Hello", "World"); /// map.insert("Hashmaps", "Are cool"); /// assert_eq!(2, map.len()); /// /// // this removes the ("Hello", "World") pair and the ("Hashmaps", "Are cool") pair, leaving /// // only the ("Hello", "Are cool") pair behind. /// map.insert("Hello", "Are cool"); /// assert_eq!(1, map.len()); /// ``` pub fn len(&self) -> usize { self.len } /// Returns true if the bimap contains no pairs. /// /// ``` /// # use isomorphism::BiMap; /// let mut map = BiMap::new(); /// assert!(map.is_empty()); /// /// map.insert("Hello", "World"); /// assert!(!map.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.len == 0 } /// An iterator visiting all key-value pairs in an arbitrary order. The iterator element is /// type (&'a L, &'a R). /// /// ``` /// # use isomorphism::BiMap; /// let mut map = BiMap::new(); /// map.insert("Hello", "World"); /// map.insert("Hashmaps", "Are cool"); /// /// for (&left, &right) in map.iter() { /// println!("{} {}", left, right); /// } /// ``` pub fn iter(&self) -> Iter<L, R, B> { self.into_iter() } } impl<L, R, LH, RH, B> BiMap<L, R, LH, RH, B> where L: Hash + Eq, R: Hash + Eq, LH: BuildHasher, RH: BuildHasher, B: BitField, { /// Finds the ideal position of a key within the hashmap. fn find_ideal_index<K: Hash, H: BuildHasher>(key: &K, hasher: &H, len: usize) -> usize { let mut hasher = hasher.build_hasher(); key.hash(&mut hasher); hasher.finish() as usize % len } /// Find the bitfield associated with an ideal hash index in a hashmap array, and mark a given /// index as full. fn mark_as_full<K>(ideal_index: usize, actual_index: usize, data: &mut [Bucket<K, usize, B>]) { let offset = (data.len() + actual_index - ideal_index) % data.len(); data[ideal_index].neighbourhood = data[ideal_index].neighbourhood | B::one_at(offset); } /// Finds the bitflield associated with an ideal hash index in a hashmap array, and mark a /// given index as empty. fn mark_as_empty<K>(ideal_index: usize, actual_index: usize, data: &mut [Bucket<K, usize, B>]) { let offset = (data.len() + actual_index - ideal_index) % data.len(); data[ideal_index].neighbourhood = data[ideal_index].neighbourhood & B::zero_at(offset); } /// Inserts a given key into its data bucket. As this may do reshuffling, it requires a /// reference to the value data buckets also. Returns, if it was possible to insert the value, /// the index to which it was inserted. If it was not possible to do the insert, returns the /// key that was going to be inserted. If this function returns successfully, it is guaranteed /// that the key is located at the index specified, but its matching value is not set to /// anything meaningful. This is the callers responsibility. fn insert_one_sided<K: Hash, V, H: BuildHasher>( key: K, key_data: &mut [Bucket<K, usize, B>], value_data: &mut [Bucket<V, usize, B>], hasher: &H, ) -> Result<usize, K> { let len = key_data.len(); let ideal_index = Self::find_ideal_index(&key, hasher, len); if key_data[ideal_index].neighbourhood.full() { return Err(key); } let nearest = key_data[ideal_index..] .iter() .chain(key_data[..ideal_index].iter()) .enumerate() .find(|&(_, bucket)| bucket.data.is_none()) .map(|(offset, _)| offset); if let Some(offset) = nearest { // is this free space within the neighbourhood? if offset < B::size() { // insert and we're done let index = (offset + ideal_index) % len; Self::mark_as_full(ideal_index, index, key_data); key_data[index].data = Some((key, usize::max_value(), ideal_index)); Ok(index) } else { // need to make room -> find a space, boot the old thing out to make room, insert, // repeat let max_offset = (ideal_index + B::size()) % len; let nearest = (0..) .map(|i| (len + max_offset - i) % len) .take(B::size() - 1) .skip(1) .find(|&i| { let &(_, _, ideal) = key_data[i].data.as_ref().unwrap(); // check if the bucket we're planning to displace is closer to the blank // space than we are, and make sure that it is close enough for us to move // into its spot (more complicated due to wrap around) if ideal > ideal_index { ideal - ideal_index < B::size() } else if ideal < ideal_index { ideal < max_offset && max_offset < ideal } else { false } }); if let Some(index) = nearest { // we've found a spot to insert into let (new_key, new_value, new_ideal) = key_data[index].data.take().unwrap(); Self::mark_as_empty(new_ideal, index, key_data); key_data[index].data = Some((key, usize::max_value(), ideal_index)); Self::mark_as_full(ideal_index, index, key_data); match Self::insert_one_sided(new_key, key_data, value_data, hasher) { Ok(new_key_index) => { // the replacement worked { let &mut (_, ref mut paired_key_index, _) = value_data[new_value].data.as_mut().unwrap(); *paired_key_index = new_key_index; let &mut (_, ref mut paired_value_index, _) = key_data[new_key_index].data.as_mut().unwrap(); *paired_value_index = new_value; } Self::mark_as_full(new_ideal, new_key_index, key_data); // finish our insert and return Ok(index) } Err(new_key) => { // the replacement failed - undo our insert Self::mark_as_full(new_ideal, index, key_data); Self::mark_as_empty(ideal_index, index, key_data); let (key, _, _) = key_data[index].data.take().unwrap(); key_data[index].data = Some((new_key, new_value, new_ideal)); Err(key) } } } else { // no spot can be inserted into Err(key) } } } else { // there is no free space Err(key) } } /// Inserts an (L, R) pair into the hashmap. Returned is a (R, L) tuple of options. The /// `Option<R>` is the value that was previously associated with the inserted L (or lack /// thereof), and vice versa for the `Option<L>`. /// /// ``` /// # use isomorphism::BiMap; /// let mut map = BiMap::new(); /// /// // neither "Hello" nor 5 were previously mapped to anything, so nothing is returned. /// assert_eq!((None, None), map.insert("Hello", 5)); /// /// // "Hello" was previously mapped to 5, so remapping it to 7 means that the 5 got evicted /// // from the hashmap and is therefore returned. 7 was not previously mapped to anything, /// // though. /// assert_eq!((Some(5), None), map.insert("Hello", 7)); /// /// // Note now that inserting "Hello" with a new right value means that 5 no longer exists in /// // the hashmap. /// assert_eq!(None, map.get_right(&5)); /// ``` pub fn insert(&mut self, left: L, right: R) -> (Option<R>, Option<L>) { let output = { let &mut BiMap { ref mut len, ref mut left_data, ref mut right_data, ref left_hasher, ref right_hasher, } = self; match Self::remove(&left, left_data, right_data, left_hasher, right_hasher, len) { Some((old_left, old_right)) => { if old_right == right { (Some(old_right), Some(old_left)) } else { ( Some(old_right), Self::remove( &right, right_data, left_data, right_hasher, left_hasher, len, ) .map(|(_key, value)| value), ) } } None => ( None, Self::remove( &right, right_data, left_data, right_hasher, left_hasher, len, ) .map(|(_key, value)| value), ), } }; // attempt to insert, hold onto the keys if it fails let failure: Option<(L, R)> = if MAX_LOAD_FACTOR * self.len as f32 >= self.left_data.len() as f32 { Some((left, right)) } else { let &mut BiMap { ref mut left_data, ref mut right_data, ref left_hasher, ref right_hasher, .. } = self; match Self::insert_one_sided(left, left_data, right_data, left_hasher) { Ok(left_index) => { match Self::insert_one_sided(right, right_data, left_data, right_hasher) { Ok(right_index) => { let &mut (_, ref mut paired_right_index, _) = left_data[left_index].data.as_mut().unwrap(); *paired_right_index = right_index; let &mut (_, ref mut paired_left_index, _) = right_data[right_index].data.as_mut().unwrap(); *paired_left_index = left_index; None } Err(right) => { let (left, _, left_ideal) = left_data[left_index].data.take().unwrap(); Self::mark_as_empty(left_ideal, left_index, left_data); Some((left, right)) } } } Err(left) => Some((left, right)), } }; if failure.is_none() { self.len += 1; } if let Some((left, right)) = failure { // resize, as we were unable to insert self.len = 0; let capacity = self.left_data.len() * RESIZE_GROWTH_FACTOR; let old_left_data = mem::replace(&mut self.left_data, Bucket::empty_vec(capacity)); let old_right_data = mem::replace(&mut self.right_data, Bucket::empty_vec(capacity)); iter::once((left, right)) .chain(IntoIter::new(old_left_data, old_right_data)) .for_each(|(left, right)| { self.insert(left, right); }); } output } /// Looks up a key in the key_data section of the hashap, and if it exists returns it from the /// value_data section of the hashap. Returns the value that is associated with the key, if it /// exists. fn get<'a, Q: ?Sized, K, V, KH>( key: &Q, key_data: &[Bucket<K, usize, B>], value_data: &'a [Bucket<V, usize, B>], key_hasher: &KH, ) -> Option<&'a V> where Q: Hash + Eq, K: Hash + Eq + Borrow<Q>, KH: BuildHasher, { let len = key_data.len(); let ideal = Self::find_ideal_index(&key, key_hasher, len); let neighbourhood = key_data[ideal].neighbourhood; neighbourhood .iter() .filter_map(|offset| key_data[(ideal + offset) % len].data.as_ref()) .filter(|&&(ref candidate_key, ..)| candidate_key.borrow() == key) .filter_map(|&(_, pair_index, _)| value_data[pair_index].data.as_ref()) .map(|&(ref value, ..)| value) .next() } /// Removes a key from the key_data section of the hashmap, and removes the value from the /// value_data section of the hashmap. Returns the value that is associated with the key, if it /// exists. fn remove<Q: ?Sized, K, V, KH, VH>( key: &Q, key_data: &mut [Bucket<K, usize, B>], value_data: &mut [Bucket<V, usize, B>], key_hasher: &KH, value_hasher: &VH, map_len: &mut usize, ) -> Option<(K, V)> where Q: Hash + Eq, K: Hash + Eq + Borrow<Q>, V: Hash, KH: BuildHasher, VH: BuildHasher, { let len = key_data.len(); let index = Self::find_ideal_index(&key, key_hasher, len); let neighbourhood = key_data[index].neighbourhood; if let Some(offset) = neighbourhood .iter() .find(|offset| match key_data[(index + offset) % len].data { Some((ref candidate_key, ..)) => candidate_key.borrow() == key, _ => false, }) { key_data[index].neighbourhood = neighbourhood & B::zero_at(offset); let (key, value_index, _) = key_data[(index + offset) % len].data.take().unwrap(); let (value, ..) = value_data[value_index].data.take().unwrap(); let ideal_value_index = Self::find_ideal_index(&value, value_hasher, len); let value_offset = (value_index + len - ideal_value_index) % len; value_data[ideal_value_index].neighbourhood = value_data[ideal_value_index].neighbourhood & B::zero_at(value_offset); *map_len -= 1; Some((key, value)) } else { None } } /// Gets a key from the left of the hashmap. Returns the value from the right of the hashmap /// that associates with this key, if it exists. /// /// ``` /// # use isomorphism::BiMap; /// let mut map = BiMap::new(); /// assert_eq!(None, map.get_left("Hello")); /// /// map.insert("Hello", 5); /// assert_eq!(Some(&5), map.get_left("Hello")); /// ``` pub fn get_left<'a, Q: ?Sized>(&'a self, left: &Q) -> Option<&'a R> where L: Borrow<Q>, Q: Hash + Eq, { let &BiMap { ref left_data, ref right_data, ref left_hasher, .. } = self; Self::get(left, left_data, right_data, left_hasher) } /// Gets a key from the right of the hashmap. Returns the value from the left of the hashmap /// that associates with this key, if it exists. /// /// ``` /// # use isomorphism::BiMap; /// let mut map = BiMap::new(); /// assert_eq!(None, map.get_right(&5)); /// /// map.insert("Hello", 5); /// assert_eq!(Some(&"Hello"), map.get_right(&5)); /// ``` pub fn get_right<'a, Q: ?Sized>(&'a self, right: &Q) -> Option<&'a L> where R: Borrow<Q>, Q: Hash + Eq, { let &BiMap { ref right_data, ref left_data, ref right_hasher, .. } = self; Self::get(right, right_data, left_data, right_hasher) } /// Removes a key from the left of the hashmap. Returns the value from the right of the hashmap /// that was associated with this key, if it existed. Will remove both the left and right sides /// of the pair, if it exists, meaning that `get_right` will no longer work for the value /// associated with the key that is removed. /// /// ``` /// # use isomorphism::BiMap; /// let mut map = BiMap::new(); /// map.insert("Hello", 5); /// /// assert_eq!(Some(&5), map.get_left("Hello")); /// assert_eq!(Some(&"Hello"), map.get_right(&5)); /// /// let old = map.remove_left("Hello"); /// assert_eq!(Some(5), old); /// /// assert_eq!(None, map.get_left("Hello")); /// assert_eq!(None, map.get_right(&5)); /// ``` pub fn remove_left<Q: ?Sized>(&mut self, left: &Q) -> Option<R> where L: Borrow<Q>, Q: Hash + Eq, { let &mut BiMap { ref mut len, ref mut left_data, ref mut right_data, ref left_hasher, ref right_hasher, } = self; Self::remove(left, left_data, right_data, left_hasher, right_hasher, len) .map(|(_key, value)| value) } /// Removes a key from the right of the hashmap. Returns the value from the left of the hashmap /// that was associated with this key, if it existed. Will remove both the left and right sides /// of the pair, if it exists, meaning that `get_left` will no longer work for the value /// associated with the key that is removed. /// /// ``` /// # use isomorphism::BiMap; /// let mut map = BiMap::new(); /// map.insert("Hello", 5); /// /// assert_eq!(Some(&5), map.get_left("Hello")); /// assert_eq!(Some(&"Hello"), map.get_right(&5)); /// /// let old = map.remove_right(&5); /// assert_eq!(Some("Hello"), old); /// /// assert_eq!(None, map.get_left("Hello")); /// assert_eq!(None, map.get_right(&5)); /// ``` pub fn remove_right<Q: ?Sized>(&mut self, right: &Q) -> Option<L> where R: Borrow<Q>, Q: Hash + Eq, { let &mut BiMap { ref mut len, ref mut left_data, ref mut right_data, ref left_hasher, ref right_hasher, } = self; Self::remove(right, right_data, left_data, right_hasher, left_hasher, len) .map(|(_key, value)| value) } } impl<L, R, LH, RH, B> PartialEq for BiMap<L, R, LH, RH, B> where L: Hash + Eq, R: Hash + Eq, LH: BuildHasher, RH: BuildHasher, B: BitField, { fn eq(&self, other: &Self) -> bool { self.len() == other.len() && self.iter().all(|(left, right)| { other.get_left(left).map_or(false, |r| *right == *r) && other.get_right(right).map_or(false, |l| *left == *l) }) } } impl<L, R, LH, RH, B> Eq for BiMap<L, R, LH, RH, B> where L: Hash + Eq, R: Hash + Eq, LH: BuildHasher, RH: BuildHasher, B: BitField, { } impl<L, R, LH, RH, B> Debug for BiMap<L, R, LH, RH, B> where L: Debug, R: Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map().entries(self.iter()).finish() } } impl<'a, L, R, LH, RH, B> IntoIterator for &'a BiMap<L, R, LH, RH, B> { type Item = (&'a L, &'a R); type IntoIter = Iter<'a, L, R, B>; fn into_iter(self) -> Self::IntoIter { let &BiMap { ref left_data, ref right_data, .. } = self; Iter::new(left_data.iter(), right_data) } } impl<L, R, LH, RH, B> IntoIterator for BiMap<L, R, LH, RH, B> { type Item = (L, R); type IntoIter = IntoIter<L, R, B>; fn into_iter(self) -> Self::IntoIter { let BiMap { left_data, right_data, .. } = self; IntoIter::new(left_data, right_data) } } impl<L, R, LH, RH, B> FromIterator<(L, R)> for BiMap<L, R, LH, RH, B> where L: Hash + Eq, R: Hash + Eq, LH: BuildHasher + Default, RH: BuildHasher + Default, B: BitField, { fn from_iter<T: IntoIterator<Item = (L, R)>>(iter: T) -> Self { let mut output = BiMapBuilder::new() .left_hasher(Default::default()) .right_hasher(Default::default()) .bitfield::<B>() .finish(); output.extend(iter); output } } impl<L, R, LH, RH, B> Extend<(L, R)> for BiMap<L, R, LH, RH, B> where L: Hash + Eq, R: Hash + Eq, LH: BuildHasher, RH: BuildHasher, B: BitField, { fn extend<T: IntoIterator<Item = (L, R)>>(&mut self, iter: T) { for (left, right) in iter { self.insert(left, right); } } } #[cfg(feature = "serde")] impl<L, R, LH, RH, B> Serialize for BiMap<L, R, LH, RH, B> where L: Serialize, R: Serialize, { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { use serde::ser::SerializeSeq; let mut seq = serializer.serialize_seq(Some(self.len))?; for (ref left, ref right) in self.iter() { seq.serialize_element(&(left, right))?; } seq.end() } } #[cfg(feature = "serde")] impl<'de, L, R, LH, RH, B> Deserialize<'de> for BiMap<L, R, LH, RH, B> where L: Hash + Eq + Deserialize<'de>, R: Hash + Eq + Deserialize<'de>, LH: BuildHasher + Default, RH: BuildHasher + Default, B: BitField, { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { use std::fmt; use std::marker::PhantomData; use serde::de::{MapAccess, Visitor}; struct MapVisitor<L, R, LH, RH, B> { marker: PhantomData<BiMap<L, R, LH, RH, B>>, } impl<'de, L, R, LH, RH, B> Visitor<'de> for MapVisitor<L, R, LH, RH, B> where L: Hash + Eq + Deserialize<'de>, R: Hash + Eq + Deserialize<'de>, LH: BuildHasher + Default, RH: BuildHasher + Default, B: BitField, { type Value = BiMap<L, R, LH, RH, B>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a map") } fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let builder = BiMapBuilder::new() .left_hasher(Default::default()) .right_hasher(Default::default()) .bitfield::<B>(); let mut output = if let Some(size) = map.size_hint() { builder.capacity(size).finish() } else { builder.finish() }; while let Some((left, right)) = map.next_entry()? { output.insert(left, right); } Ok(output) } } let visitor = MapVisitor { marker: PhantomData, }; deserializer.deserialize_map(visitor) } } #[cfg(test)] mod test { use crate::BiMap; #[test] fn test_iteration_empty() { let map: BiMap<(), ()> = BiMap::new(); assert_eq!((&map).into_iter().next(), None); assert_eq!(map.into_iter().next(), None); } }
use std::time::Duration; use std::time::Instant; /// /// A container to host a value-instant pair. /// pub(crate) struct TimedData<T> { pub(crate) item: T, pub(crate) time_stored: Instant, } impl<T> TimedData<T> { pub(crate) fn new(item: T) -> TimedData<T> { TimedData { item, time_stored: Instant::now(), } } pub(crate) fn still_valid(&self, time_to_live: Duration) -> bool { // NOTE(zac): // A token is still valid if it has not been alive for longer than the // specified time_to_live. let time_lived_thus_far = Instant::now() - self.time_stored; time_to_live > time_lived_thus_far } } #[cfg(test)] mod tests { use super::*; use std::time::Duration; use std::thread::sleep; #[test] fn should_be_considered_valid_if_within_duration() { let time_to_live = Duration::from_secs(10); let timed_data = TimedData::new(5); assert!(timed_data.still_valid(time_to_live)); } #[test] fn should_not_be_considered_valid_if_after_duration() { let time_to_live = Duration::from_millis(5); let timed_data = TimedData::new(5); sleep(time_to_live); assert!(!timed_data.still_valid(time_to_live)); } }
extern crate docstrings; use docstrings::parse_md_docblock; fn main() { println!("{:#?}", parse_md_docblock(DOC_STR).unwrap()); } const DOC_STR: &'static str = "\ Lorem ipsum A longer description lorem ipsum dolor sit amet. # Parameters - `param1`: Foo - `param2`: Bar ";
extern crate gcc; use std::env; pub fn main() { let target = env::var("TARGET").unwrap(); let os = if target.contains("linux") { "LINUX" } else if target.contains("darwin") { "DARWIN" } else { "UNKNOWN" }; gcc::Config::new() .file("src/const.c") .file("src/sizes.c") .define(os, None) .compile("libnixtest.a"); }
use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Utc}; use std::{borrow::Cow, sync::Arc}; use storm::{Error, Result}; use tiberius::Uuid; pub trait FromSql<'a>: Sized { type Column: tiberius::FromSql<'a>; fn from_sql(col: Option<Self::Column>) -> Result<Self>; } impl<'a, T> FromSql<'a> for Option<T> where T: FromSql<'a>, { type Column = T::Column; fn from_sql(col: Option<Self::Column>) -> Result<Self> { Ok(match col { Some(v) => Some(T::from_sql(Some(v))?), None => None, }) } } macro_rules! from_sql { ($s:ty, $col:ty) => { impl<'a> FromSql<'a> for $s { type Column = $col; fn from_sql(col: Option<Self::Column>) -> Result<Self> { match col { Some(v) => Ok(v), None => Err(storm::Error::ColumnNull), } } } }; } from_sql!(&'a str, &'a str); from_sql!(DateTime<FixedOffset>, DateTime<FixedOffset>); from_sql!(DateTime<Utc>, DateTime<Utc>); from_sql!(NaiveDate, NaiveDate); from_sql!(NaiveDateTime, NaiveDateTime); from_sql!(NaiveTime, NaiveTime); from_sql!(Uuid, Uuid); from_sql!(bool, bool); from_sql!(f32, f32); from_sql!(f64, f64); from_sql!(i16, i16); from_sql!(i32, i32); from_sql!(i64, i64); from_sql!(u8, u8); from_sql!(&'a [u8], &'a [u8]); #[cfg(feature = "dec19x5")] impl<'a> FromSql<'a> for dec19x5crate::Decimal { type Column = dec19x5crate::Decimal; fn from_sql(col: Option<Self::Column>) -> Result<Self> { match col { Some(v) => Ok(v), None => Err(storm::Error::ColumnNull), } } } impl<'a> FromSql<'a> for String { type Column = &'a str; fn from_sql(col: Option<Self::Column>) -> Result<Self> { match col { Some(v) => Ok(v.to_owned()), None => Err(storm::Error::ColumnNull), } } } impl<'a> FromSql<'a> for Vec<u8> { type Column = &'a [u8]; fn from_sql(col: Option<Self::Column>) -> Result<Self> { match col { Some(v) => Ok(v.to_owned()), None => Err(storm::Error::ColumnNull), } } } impl<'a, T: FromSql<'a>> FromSql<'a> for Arc<T> { type Column = T::Column; fn from_sql(col: Option<Self::Column>) -> Result<Self> { T::from_sql(col).map(Arc::new) } } impl<'a, T: FromSql<'a>> FromSql<'a> for Box<T> { type Column = T::Column; fn from_sql(col: Option<Self::Column>) -> Result<Self> { T::from_sql(col).map(Box::new) } } impl<'a, T: Clone + FromSql<'a>> FromSql<'a> for Cow<'a, T> { type Column = T::Column; fn from_sql(col: Option<Self::Column>) -> Result<Self> { T::from_sql(col).map(Cow::Owned) } } impl<'a> FromSql<'a> for Box<[u8]> { type Column = &'a [u8]; fn from_sql(col: Option<Self::Column>) -> Result<Self> { match col { Some(col) => Ok(col.to_vec().into_boxed_slice()), None => Err(Error::ColumnNull), } } } impl<'a> FromSql<'a> for Box<str> { type Column = &'a str; fn from_sql(col: Option<Self::Column>) -> Result<Self> { match col { Some(col) => Ok(col.to_string().into_boxed_str()), None => Err(Error::ColumnNull), } } } impl<'a, 'b> FromSql<'a> for Cow<'b, [u8]> { type Column = &'a [u8]; fn from_sql(col: Option<Self::Column>) -> Result<Self> { match col { Some(col) => Ok(Cow::Owned(col.to_vec())), None => Err(Error::ColumnNull), } } } impl<'a, 'b> FromSql<'a> for Cow<'b, str> { type Column = &'a str; fn from_sql(col: Option<Self::Column>) -> Result<Self> { match col { Some(col) => Ok(Cow::Owned(col.to_string())), None => Err(Error::ColumnNull), } } } /// Internal used for macros #[doc(hidden)] pub fn _macro_load_field<'a, T: FromSql<'a>>(row: &'a tiberius::Row, index: usize) -> Result<T> { row.try_get(index) .map_err(storm::Error::Mssql) .and_then(FromSql::from_sql) }
use iron::status; use iron::prelude::*; pub fn friendly_greeting(_: &mut Request) -> IronResult<Response> { return Ok(Response::with((status::Ok, "Hello World!"))); }
use std::sync::Arc; use async_trait::async_trait; pub use bonsaidb_core::circulate::Relay; use bonsaidb_core::{ circulate, pubsub::{self, database_topic, PubSub}, schema::Schema, Error, }; #[async_trait] impl<DB> PubSub for super::Database<DB> where DB: Schema, { type Subscriber = Subscriber; async fn create_subscriber(&self) -> Result<Self::Subscriber, bonsaidb_core::Error> { Ok(Subscriber { database_name: self.data.name.to_string(), subscriber: self.data.storage.relay().create_subscriber().await, }) } async fn publish<S: Into<String> + Send, P: serde::Serialize + Sync>( &self, topic: S, payload: &P, ) -> Result<(), bonsaidb_core::Error> { self.data .storage .relay() .publish(database_topic(&self.data.name, &topic.into()), payload) .await?; Ok(()) } async fn publish_to_all<P: serde::Serialize + Sync>( &self, topics: Vec<String>, payload: &P, ) -> Result<(), bonsaidb_core::Error> { self.data .storage .relay() .publish_to_all( topics .iter() .map(|topic| database_topic(&self.data.name, topic)) .collect(), payload, ) .await?; Ok(()) } } /// A subscriber for `PubSub` messages. pub struct Subscriber { database_name: String, subscriber: circulate::Subscriber, } #[async_trait] impl pubsub::Subscriber for Subscriber { async fn subscribe_to<S: Into<String> + Send>(&self, topic: S) -> Result<(), Error> { self.subscriber .subscribe_to(database_topic(&self.database_name, &topic.into())) .await; Ok(()) } async fn unsubscribe_from(&self, topic: &str) -> Result<(), Error> { let topic = format!("{}\u{0}{}", self.database_name, topic); self.subscriber.unsubscribe_from(&topic).await; Ok(()) } fn receiver(&self) -> &'_ flume::Receiver<Arc<circulate::Message>> { self.subscriber.receiver() } }
use wasm_bindgen::prelude::*; use super::{BufferGeometry, Material, Object3D}; #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = Object3D)] pub type Group; #[wasm_bindgen(constructor)] pub fn new() -> Group; } #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = Object3D)] pub type Line; } #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = Object3D)] pub type LineSegments; #[wasm_bindgen(constructor)] pub fn new(geometry: &BufferGeometry, material: &Material) -> LineSegments; #[wasm_bindgen(method, setter, js_name = "geometry")] pub fn set_geometry(this: &LineSegments, geometry: &BufferGeometry); } #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = Object3D)] pub type Mesh; #[wasm_bindgen(constructor)] pub fn new(geometry: &BufferGeometry, material: &Material) -> Mesh; #[wasm_bindgen(method, getter)] pub fn material(this: &Mesh) -> Material; #[wasm_bindgen(method, getter)] pub fn geometry(this: &Mesh) -> BufferGeometry; #[wasm_bindgen(method, setter, js_name = "geometry")] pub fn set_geometry(this: &Mesh, geometry: &BufferGeometry); }
use regex::Regex; use std::fs::File; use std::io::{BufRead, BufReader}; use struct_lib::Token; // Int match part fn int_match(text: &mut String) -> Token::Token { // <dec int> ::= <number>{<number>} // <number> ::= 0|1|2|3|4|5|6|7|8|9 // Regex for constant integers let int_re = Regex::new(r"(^[0-9][0-9]*)\b").unwrap(); let int_cap = int_re.captures(&text); let int; let mut token = Token::new(); let mut int_str: String; match int_cap { Some(int_cap) => { int = int_cap.get(1).unwrap(); // let int_start = int.start(); let int_end = int.end(); int_str = int.as_str().to_string(); token._type = "CONSTANT".to_string(); token._value = int_str.clone(); // println!("Int Match: {}", int_str); text.replace_range(..int_end, ""); // println!("Int Start: {}", int_start); // println!("Int End: {}", int_end); }, None => println!("int None"), }; token } // Word match part fn word_match(text: &mut String) -> Token::Token { // <word> :: = <alpha_underscore>{<alpha>|"_"|<number>} // <alpha_underscore> ::= <alpha>|"_" // <alpha> ::= a-zA-Z{a-zA-Z} // Regex for keyword, variable name + symbols let word_re = Regex::new(r"([a-zA-Z_][a-zA-Z_0-9]*)\b").unwrap(); let word_cap = word_re.captures(&text); let word; let mut token = Token::new(); let mut word_str: String; match word_cap { Some(word_cap) => { word = word_cap.get(1).unwrap(); // let word_start = word.start(); let word_end = word.end(); token._value = word.as_str().to_string(); word_str = keyword_match(word.as_str()).to_string(); token._type = word_str.clone(); // println!("WordMatch: {}", word_str); text.replace_range(..word_end, ""); // end = word_end; // println!("Word Start: {}", word_start); // println!("Word End: {}", word_end); }, None => println!("word None"), }; token } // Symbol match part fn symbol_match(text: &mut String) -> Token::Token { // <symbol> ::= "("|")"|"{"|"}"|";" let syb_re = Regex::new(r"(^[\(\)\{\};])").unwrap(); let syb_cap = syb_re.captures(&text); let syb; let mut token = Token::new(); let mut syb_str: String; match syb_cap { Some(syb_cap) => { syb = syb_cap.get(1).unwrap(); // let syb_start = syb.start(); let syb_end = syb.end(); token._value = syb.as_str().to_string(); syb_str = keysyb_match(syb.as_str()).to_string(); token._type = syb_str.clone(); // println!("Syb Match: {}", syb_str); text.replace_range(..syb_end, ""); // println!("Syb Start: {}", syb_start); // println!("Syb End: {}", syb_end); }, None => println!("Syb None"), }; token } fn keyword_match(word: &str) -> &str { match word { "int" => "INT_KEYWORD", "return" => "RETURN_KEYWORD", _ => "IDENTIFIER", } } fn keysyb_match(word: &str) -> &str { match word { "(" => "OPEN_PAREN", ")" => "CLOSE_PAREN", "{" => "OPEN_BRACE", "}" => "CLOSE_BRACE", ";" => "SEMICOLON", _ => panic!("Unrecognize symbol"), } } fn main() { let filename_vec = vec!["missing_paren.c", "missing_retval.c", "no_brace.c", "no_semicolon.c", "no_space.c", "wrong_case.c"]; // let filename_vec = vec!["multi_digit.c", "newlines.c", "no_newlines.c", "return_0.c", "return_2.c", "spaces.c"]; for filename in filename_vec { let filename = "../../test/stage_1/invalid/".to_owned() + filename; // println!("{:?}", filename); let file = File::open(&filename).expect("Failed to open the file"); let reader = BufReader::new(file); println!("----------------"); println!("File: {}", &filename); let mut token_vec = Vec::new(); for line in reader.lines(){ let mut text = line.unwrap().trim().to_string(); println!("\nNew Line: \n\"{}\"\n", text); let mut first: char; let mut token: Token::Token; while text.len()!=0 { // println!("{:?}", &text); first = text.chars().nth(0).unwrap(); if first.is_ascii_digit() { token = int_match(&mut text); println!("Int token: {}, {}", &token._type, &token._value); token_vec.push(token); } else if first.is_ascii_alphabetic() { token = word_match(&mut text); println!("Word token: {}, {}", &token._type, &token._value); token_vec.push(token); } else if first.is_ascii_punctuation() { token = symbol_match(&mut text); println!("Syb token: {}, {}", &token._type, &token._value); token_vec.push(token); } else { panic!("Invalid char: {}", first); } text = text.trim_start().to_string(); } } println!("\n"); println!("Token vec "); for i in 0..token_vec.len() { println!("type: {}", &token_vec[i]._type); println!("value: {}", &token_vec[i]._value); } println!("--------\n"); } }
pub mod tax_parameters; pub use tax_parameters::TaxParameters;
use crate::{ alloc::Allocator, containers::{Array, String}, }; pub trait Serializer { type Ok; type Err; type ArraySerializer: ArraySerializer<Ok = Self::Ok, Err = Self::Err>; type MapSerializer: MapSerializer<Ok = Self::Ok, Err = Self::Err>; fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Err>; fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Err>; fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Err>; fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Err>; fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Err>; fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Err>; fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Err>; fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Err>; fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Err>; fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Err>; fn serialize_array(self, len: Option<usize>) -> Result<Self::ArraySerializer, Self::Err>; fn serialize_map(self, len: Option<usize>) -> Result<Self::MapSerializer, Self::Err>; fn serialize_f32(self, value: f32) -> Result<Self::Ok, Self::Err>; fn serialize_f64(self, value: f64) -> Result<Self::Ok, Self::Err>; fn serialize_null(self) -> Result<Self::Ok, Self::Err>; fn serialize_bool(self, value: bool) -> Result<Self::Ok, Self::Err>; } pub trait ArraySerializer { type Ok; type Err; fn serialize_element<T: Serialize>(&mut self, elmt: T) -> Result<Self::Ok, Self::Err>; fn end(self) -> Result<Self::Ok, Self::Err>; } pub trait MapSerializer { type Ok; type Err; fn serialize_entry<K: Serialize, V: Serialize>( &mut self, k: K, v: V, ) -> Result<Self::Ok, Self::Err>; fn end(self) -> Result<Self::Ok, Self::Err>; } pub trait Serialize { fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Err>; } pub enum VisitorType { UnsignedInteger, SignedInteger, FloatingPoint, Boolean, String, Bytes, Null, Array, Map, } pub trait VisitorError { fn unexpected_type(t: VisitorType) -> Self; } pub trait Visitor<'de>: Sized { type Value; type Err: VisitorError; fn accept_u8(self, value: u8) -> Result<Self::Value, Self::Err> { self.accept_u16(value as u16) } fn accept_u16(self, value: u16) -> Result<Self::Value, Self::Err> { self.accept_u32(value as u32) } fn accept_u32(self, value: u32) -> Result<Self::Value, Self::Err> { self.accept_u64(value as u64) } fn accept_u64(self, _value: u64) -> Result<Self::Value, Self::Err> { Err(VisitorError::unexpected_type(VisitorType::UnsignedInteger)) } fn accept_i8(self, value: i8) -> Result<Self::Value, Self::Err> { self.accept_i16(value as i16) } fn accept_i16(self, value: i16) -> Result<Self::Value, Self::Err> { self.accept_i32(value as i32) } fn accept_i32(self, value: i32) -> Result<Self::Value, Self::Err> { self.accept_i64(value as i64) } fn accept_i64(self, _value: i64) -> Result<Self::Value, Self::Err> { Err(VisitorError::unexpected_type(VisitorType::SignedInteger)) } fn accept_f32(self, value: f32) -> Result<Self::Value, Self::Err> { self.accept_f64(value as f64) } fn accept_f64(self, _value: f64) -> Result<Self::Value, Self::Err> { Err(VisitorError::unexpected_type(VisitorType::FloatingPoint)) } fn accept_bool(self, _value: bool) -> Result<Self::Value, Self::Err> { Err(VisitorError::unexpected_type(VisitorType::Boolean)) } fn accept_str(self, _value: &str) -> Result<Self::Value, Self::Err> { Err(VisitorError::unexpected_type(VisitorType::String)) } fn accept_borrowed_str(self, value: &'de str) -> Result<Self::Value, Self::Err> { self.accept_str(value) } fn accept_string<A: Allocator>(self, value: String<A>) -> Result<Self::Value, Self::Err> { self.accept_str(&value) } fn accept_bytes(self, _value: &[u8]) -> Result<Self::Value, Self::Err> { Err(VisitorError::unexpected_type(VisitorType::Bytes)) } fn accept_borrowed_bytes(self, value: &'de [u8]) -> Result<Self::Value, Self::Err> { self.accept_bytes(value) } fn accept_bytes_array<A: Allocator>(self, value: Array<u8, A>) -> Result<Self::Value, Self::Err> { self.accept_bytes(&value) } fn accept_null(self) -> Result<Self::Value, Self::Err> { Err(VisitorError::unexpected_type(VisitorType::Null)) } fn accept_array<A>(self, _accessor: A) -> Result<Self::Value, Self::Err> where A: ArrayAccessor<'de>, { Err(VisitorError::unexpected_type(VisitorType::Array)) } fn accept_map<A>(self, _accessor: A) -> Result<Self::Value, Self::Err> where A: MapAccessor<'de>, { Err(VisitorError::unexpected_type(VisitorType::Map)) } } pub trait ArrayAccessor<'de> { type Err; fn size_hint(&self) -> Option<usize>; fn next_element<T>(&mut self) -> Result<Option<T>, Self::Err> where T: Deserialize<'de>; } pub trait MapAccessor<'de> { type Err; fn size_hint(&self) -> Option<usize>; fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Err> where K: Deserialize<'de>, V: Deserialize<'de>; } pub trait Deserializer<'de> { type Err; fn deserialize_u8<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_u16<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_u32<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_u64<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_i8<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_i16<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_i32<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_i64<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_f32<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_f64<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_bool<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_str<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_string<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_bytes<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_bytes_array<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_null<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_array<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; fn deserialize_map<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Err>; } pub trait Deserialize<'de>: Sized { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Err>; }
use super::*; prelude_macros::implement_accessors! { Vec2, Vec3, Vec4, // Uint2, // Uint3, // Uint4, } #[test] fn test_accessors() { let _ = 1.0.vec3().x; 1.0.vec3().xy(); 1.0.vec3().zyx(); }
//! Config module contains the top-level config for the app. use std::env; use sentry_integration::SentryConfig; use config_crate::{Config as RawConfig, ConfigError, Environment, File}; use stq_http; use stq_logging::GrayLogConfig; /// Basic settings - HTTP binding address and database DSN #[derive(Debug, Deserialize, Clone)] pub struct Config { pub server: Server, pub client: Client, pub graylog: Option<GrayLogConfig>, pub sentry: Option<SentryConfig>, } /// Common server settings #[derive(Debug, Deserialize, Clone)] pub struct Server { pub host: String, pub port: i32, pub database: String, pub redis: Option<String>, pub thread_count: usize, pub cache_ttl_sec: u64, } /// Http client settings #[derive(Debug, Deserialize, Clone)] pub struct Client { pub http_client_retries: usize, pub http_client_buffer_size: usize, pub dns_worker_thread_count: usize, pub http_timeout_ms: u64, } /// Creates new app config struct /// #Examples /// ``` /// use delivery_lib::config::*; /// /// let config = Config::new(); /// ``` impl Config { pub fn new() -> Result<Self, ConfigError> { let mut s = RawConfig::new(); s.merge(File::with_name("config/base"))?; // Note that this file is _optional_ let env = env::var("RUN_MODE").unwrap_or_else(|_| "development".into()); s.merge(File::with_name(&format!("config/{}", env)).required(false))?; // Add in settings from the environment (with a prefix of STQ_USERS) s.merge(Environment::with_prefix("STQ_DELIV"))?; s.try_into() } pub fn to_http_config(&self) -> stq_http::client::Config { stq_http::client::Config { http_client_buffer_size: self.client.http_client_buffer_size, http_client_retries: self.client.http_client_retries, timeout_duration_ms: self.client.http_timeout_ms, } } }
use inspector::ResultInspector; fn main() { let ok: Result<_, ()> = Ok(42); ok.inspect(|x| println!("ok value is {}", x)).unwrap(); }
use std::process; use std::process::{Command, Stdio}; fn main() { let command = Command::new("cargo") .arg("fmt") .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .output() .expect("failed to execute cargo fmt"); process::exit(command.status.code().unwrap_or(0)); }
//! Kube is an umbrella-crate for interacting with [Kubernetes](http://kubernetes.io) in Rust. //! //! # Overview //! //! Kube contains a Kubernetes client, a controller runtime, a custom resource derive, and various tooling //! required for building applications or controllers that interact with Kubernetes. //! //! The main modules are: //! //! - [`client`](crate::client) with the Kubernetes [`Client`](crate::Client) and its layers //! - [`config`](crate::config) for cluster [`Config`](crate::Config) //! - [`api`](crate::api) with the generic Kubernetes [`Api`](crate::Api) //! - [`derive`](kube_derive) with the [`CustomResource`](crate::CustomResource) derive for building controllers types //! - [`runtime`](crate::runtime) with a [`Controller`](crate::runtime::Controller) / [`watcher`](crate::runtime::watcher()) / [`reflector`](crate::runtime::reflector::reflector) / [`Store`](crate::runtime::reflector::Store) //! - [`core`](crate::core) with generics from `apimachinery` //! //! You can use each of these as you need with the help of the [exported features](https://github.com/kube-rs/kube/blob/main/kube/Cargo.toml#L18). //! //! # Using the Client //! ```no_run //! use futures::{StreamExt, TryStreamExt}; //! use kube::{Client, api::{Api, ResourceExt, ListParams, PostParams}}; //! use k8s_openapi::api::core::v1::Pod; //! //! #[tokio::main] //! async fn main() -> Result<(), Box<dyn std::error::Error>> { //! // Infer the runtime environment and try to create a Kubernetes Client //! let client = Client::try_default().await?; //! //! // Read pods in the configured namespace into the typed interface from k8s-openapi //! let pods: Api<Pod> = Api::default_namespaced(client); //! for p in pods.list(&ListParams::default()).await? { //! println!("found pod {}", p.name_any()); //! } //! Ok(()) //! } //! ``` //! //! For details, see: //! //! - [`Client`](crate::client) for the extensible Kubernetes client //! - [`Api`](crate::Api) for the generic api methods available on Kubernetes resources //! - [k8s-openapi](https://docs.rs/k8s-openapi/*/k8s_openapi/) for documentation about the generated Kubernetes types //! //! # Using the Runtime with the Derive macro //! //! ```no_run //! use schemars::JsonSchema; //! use serde::{Deserialize, Serialize}; //! use serde_json::json; //! use futures::{StreamExt, TryStreamExt}; //! use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition; //! use kube::{ //! api::{Api, DeleteParams, PatchParams, Patch, ResourceExt}, //! core::CustomResourceExt, //! Client, CustomResource, //! runtime::{watcher, WatchStreamExt, wait::{conditions, await_condition}}, //! }; //! //! // Our custom resource //! #[derive(CustomResource, Deserialize, Serialize, Clone, Debug, JsonSchema)] //! #[kube(group = "clux.dev", version = "v1", kind = "Foo", namespaced)] //! pub struct FooSpec { //! info: String, //! #[schemars(length(min = 3))] //! name: String, //! replicas: i32, //! } //! //! #[tokio::main] //! async fn main() -> Result<(), Box<dyn std::error::Error>> { //! let client = Client::try_default().await?; //! let crds: Api<CustomResourceDefinition> = Api::all(client.clone()); //! //! // Apply the CRD so users can create Foo instances in Kubernetes //! crds.patch("foos.clux.dev", //! &PatchParams::apply("my_manager"), //! &Patch::Apply(Foo::crd()) //! ).await?; //! //! // Wait for the CRD to be ready //! tokio::time::timeout( //! std::time::Duration::from_secs(10), //! await_condition(crds, "foos.clux.dev", conditions::is_crd_established()) //! ).await?; //! //! // Watch for changes to foos in the configured namespace //! let foos: Api<Foo> = Api::default_namespaced(client.clone()); //! let wc = watcher::Config::default(); //! let mut apply_stream = watcher(foos, wc).applied_objects().boxed(); //! while let Some(f) = apply_stream.try_next().await? { //! println!("saw apply to {}", f.name_any()); //! } //! Ok(()) //! } //! ``` //! //! For details, see: //! //! - [`CustomResource`](crate::CustomResource) for documentation how to configure custom resources //! - [`runtime::watcher`](crate::runtime::watcher()) for how to long-running watches work and why you want to use this over [`Api::watch`](crate::Api::watch) //! - [`runtime`](crate::runtime) for abstractions that help with more complicated Kubernetes application //! //! # Examples //! A large list of complete, runnable examples with explainations are available in the [examples folder](https://github.com/kube-rs/kube/tree/main/examples). #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(missing_docs)] #![forbid(unsafe_code)] macro_rules! cfg_client { ($($item:item)*) => { $( #[cfg_attr(docsrs, doc(cfg(feature = "client")))] #[cfg(feature = "client")] $item )* } } macro_rules! cfg_config { ($($item:item)*) => { $( #[cfg_attr(docsrs, doc(cfg(feature = "config")))] #[cfg(feature = "config")] $item )* } } macro_rules! cfg_error { ($($item:item)*) => { $( #[cfg_attr(docsrs, doc(cfg(any(feature = "config", feature = "client"))))] #[cfg(any(feature = "config", feature = "client"))] $item )* } } cfg_client! { pub use kube_client::api; pub use kube_client::discovery; pub use kube_client::client; #[doc(inline)] pub use api::Api; #[doc(inline)] pub use client::Client; #[doc(inline)] pub use discovery::Discovery; } cfg_config! { pub use kube_client::config; #[doc(inline)] pub use config::Config; } cfg_error! { pub use kube_client::error; #[doc(inline)] pub use error::Error; /// Convient alias for `Result<T, Error>` pub type Result<T, E = Error> = std::result::Result<T, E>; } /// Re-exports from [`kube-derive`](kube_derive) #[cfg(feature = "derive")] #[cfg_attr(docsrs, doc(cfg(feature = "derive")))] pub use kube_derive::CustomResource; /// Re-exports from `kube-runtime` #[cfg(feature = "runtime")] #[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] #[doc(inline)] pub use kube_runtime as runtime; pub use crate::core::{CustomResourceExt, Resource, ResourceExt}; /// Re-exports from `kube_core` #[doc(inline)] pub use kube_core as core; // Tests that require a cluster and the complete feature set // Can be run with `cargo test -p kube --lib --features=runtime,derive -- --ignored` #[cfg(test)] #[cfg(all(feature = "derive", feature = "client"))] mod test { use crate::{ api::{DeleteParams, Patch, PatchParams}, Api, Client, CustomResourceExt, Resource, ResourceExt, }; use kube_derive::CustomResource; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(CustomResource, Deserialize, Serialize, Clone, Debug, JsonSchema)] #[kube(group = "clux.dev", version = "v1", kind = "Foo", namespaced)] #[kube(status = "FooStatus")] #[kube(scale = r#"{"specReplicasPath":".spec.replicas", "statusReplicasPath":".status.replicas"}"#)] #[kube(crates(kube_core = "crate::core"))] // for dev-dep test structure pub struct FooSpec { name: String, info: Option<String>, replicas: isize, } #[derive(Deserialize, Serialize, Clone, Debug, Default, JsonSchema)] pub struct FooStatus { is_bad: bool, replicas: isize, } #[tokio::test] #[ignore = "needs kubeconfig"] async fn custom_resource_generates_correct_core_structs() { use crate::core::{ApiResource, DynamicObject, GroupVersionKind}; let client = Client::try_default().await.unwrap(); let gvk = GroupVersionKind::gvk("clux.dev", "v1", "Foo"); let api_resource = ApiResource::from_gvk(&gvk); let a1: Api<DynamicObject> = Api::namespaced_with(client.clone(), "myns", &api_resource); let a2: Api<Foo> = Api::namespaced(client, "myns"); // make sure they return the same url_path through their impls assert_eq!(a1.resource_url(), a2.resource_url()); } use k8s_openapi::{ api::core::v1::ConfigMap, apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition, }; #[tokio::test] #[ignore = "needs cluster (creates + patches foo crd)"] #[cfg(all(feature = "derive", feature = "runtime"))] async fn derived_resource_queriable_and_has_subresources() -> Result<(), Box<dyn std::error::Error>> { use crate::runtime::wait::{await_condition, conditions}; use serde_json::json; let client = Client::try_default().await?; let ssapply = PatchParams::apply("kube").force(); let crds: Api<CustomResourceDefinition> = Api::all(client.clone()); // Server-side apply CRD and wait for it to get ready crds.patch("foos.clux.dev", &ssapply, &Patch::Apply(Foo::crd())) .await?; let establish = await_condition(crds.clone(), "foos.clux.dev", conditions::is_crd_established()); let _ = tokio::time::timeout(std::time::Duration::from_secs(10), establish).await?; // Use it let foos: Api<Foo> = Api::default_namespaced(client.clone()); // Apply from generated struct { let foo = Foo::new("baz", FooSpec { name: "baz".into(), info: Some("old baz".into()), replicas: 1, }); let o = foos.patch("baz", &ssapply, &Patch::Apply(&foo)).await?; assert_eq!(o.spec.name, "baz"); let oref = o.object_ref(&()); assert_eq!(oref.name.unwrap(), "baz"); assert_eq!(oref.uid, o.uid()); } // Apply from partial json! { let patch = json!({ "apiVersion": "clux.dev/v1", "kind": "Foo", "spec": { "name": "foo", "replicas": 2 } }); let o = foos.patch("baz", &ssapply, &Patch::Apply(patch)).await?; assert_eq!(o.spec.replicas, 2, "patching spec updated spec.replicas"); } // check subresource { let scale = foos.get_scale("baz").await?; assert_eq!(scale.spec.unwrap().replicas, Some(2)); let status = foos.get_status("baz").await?; assert!(status.status.is_none(), "nothing has set status"); } // set status subresource { let fs = serde_json::json!({"status": FooStatus { is_bad: false, replicas: 1 }}); let o = foos .patch_status("baz", &Default::default(), &Patch::Merge(&fs)) .await?; assert!(o.status.is_some(), "status set after patch_status"); } // set scale subresource { let fs = serde_json::json!({"spec": { "replicas": 3 }}); let o = foos .patch_scale("baz", &Default::default(), &Patch::Merge(&fs)) .await?; assert_eq!(o.status.unwrap().replicas, 1, "scale replicas got patched"); let linked_replicas = o.spec.unwrap().replicas.unwrap(); assert_eq!(linked_replicas, 3, "patch_scale updates linked spec.replicas"); } // cleanup foos.delete_collection(&DeleteParams::default(), &Default::default()) .await?; crds.delete("foos.clux.dev", &DeleteParams::default()).await?; Ok(()) } #[tokio::test] #[ignore = "needs cluster (lists pods)"] async fn custom_serialized_objects_are_queryable_and_iterable() -> Result<(), Box<dyn std::error::Error>> { use crate::core::{ object::{HasSpec, HasStatus, NotUsed, Object}, ApiResource, }; use k8s_openapi::api::core::v1::Pod; #[derive(Clone, Deserialize, Debug)] struct PodSpecSimple { containers: Vec<ContainerSimple>, } #[derive(Clone, Deserialize, Debug)] struct ContainerSimple { #[allow(dead_code)] image: String, } type PodSimple = Object<PodSpecSimple, NotUsed>; // use known type information from pod (can also use discovery for this) let ar = ApiResource::erase::<Pod>(&()); let client = Client::try_default().await?; let api: Api<PodSimple> = Api::default_namespaced_with(client, &ar); let mut list = api.list(&Default::default()).await?; // check we can mutably iterate over ObjectList for pod in &mut list { pod.spec_mut().containers = vec![]; *pod.status_mut() = None; pod.annotations_mut() .entry("kube-seen".to_string()) .or_insert_with(|| "yes".to_string()); pod.labels_mut() .entry("kube.rs".to_string()) .or_insert_with(|| "hello".to_string()); pod.finalizers_mut().push("kube-finalizer".to_string()); pod.managed_fields_mut().clear(); // NB: we are **not** pushing these back upstream - (Api::apply or Api::replace needed for it) } // check we can iterate over ObjectList normally - and check the mutations worked for pod in list { assert!(pod.annotations().get("kube-seen").is_some()); assert!(pod.labels().get("kube.rs").is_some()); assert!(pod.finalizers().contains(&"kube-finalizer".to_string())); assert!(pod.spec().containers.is_empty()); assert!(pod.managed_fields().is_empty()); } Ok(()) } #[tokio::test] #[ignore = "needs cluster (fetches api resources, and lists all)"] #[cfg(feature = "derive")] async fn derived_resources_discoverable() -> Result<(), Box<dyn std::error::Error>> { use crate::{ core::{DynamicObject, GroupVersion, GroupVersionKind}, discovery::{self, verbs, ApiGroup, Discovery, Scope}, runtime::wait::{await_condition, conditions, Condition}, }; #[derive(CustomResource, Deserialize, Serialize, Clone, Debug, JsonSchema)] #[kube(group = "kube.rs", version = "v1", kind = "TestCr", namespaced)] #[kube(crates(kube_core = "crate::core"))] // for dev-dep test structure struct TestCrSpec {} let client = Client::try_default().await?; // install crd is installed let crds: Api<CustomResourceDefinition> = Api::all(client.clone()); let ssapply = PatchParams::apply("kube").force(); crds.patch("testcrs.kube.rs", &ssapply, &Patch::Apply(TestCr::crd())) .await?; let establish = await_condition(crds.clone(), "testcrs.kube.rs", conditions::is_crd_established()); let crd = tokio::time::timeout(std::time::Duration::from_secs(10), establish).await??; assert!(conditions::is_crd_established().matches_object(crd.as_ref())); tokio::time::sleep(std::time::Duration::from_secs(2)).await; // Established condition is actually not enough for api discovery :( // create partial information for it to discover let gvk = GroupVersionKind::gvk("kube.rs", "v1", "TestCr"); let gv = GroupVersion::gv("kube.rs", "v1"); // discover by both (recommended kind on groupversion) and (pinned gvk) and they should equal let apigroup = discovery::oneshot::pinned_group(&client, &gv).await?; let (ar1, caps1) = apigroup.recommended_kind("TestCr").unwrap(); let (ar2, caps2) = discovery::pinned_kind(&client, &gvk).await?; assert_eq!(caps1.operations.len(), caps2.operations.len(), "unequal caps"); assert_eq!(ar1, ar2, "unequal apiresource"); assert_eq!(DynamicObject::api_version(&ar2), "kube.rs/v1", "unequal dynver"); // run (almost) full discovery let discovery = Discovery::new(client.clone()) // skip something in discovery (clux.dev crd being mutated in other tests) .exclude(&["rbac.authorization.k8s.io", "clux.dev"]) .run() .await?; // check our custom resource first by resolving within groups assert!(discovery.has_group("kube.rs"), "missing group kube.rs"); let (ar, _caps) = discovery.resolve_gvk(&gvk).unwrap(); assert_eq!(ar.group, gvk.group, "unexpected discovered group"); assert_eq!(ar.version, gvk.version, "unexcepted discovered ver"); assert_eq!(ar.kind, gvk.kind, "unexpected discovered kind"); // check all non-excluded groups that are iterable let mut groups = discovery.groups_alphabetical().into_iter(); let firstgroup = groups.next().unwrap(); assert_eq!(firstgroup.name(), ApiGroup::CORE_GROUP, "core not first"); for group in groups { for (ar, caps) in group.recommended_resources() { if !caps.supports_operation(verbs::LIST) { continue; } let api: Api<DynamicObject> = if caps.scope == Scope::Namespaced { Api::default_namespaced_with(client.clone(), &ar) } else { Api::all_with(client.clone(), &ar) }; api.list(&Default::default()).await?; } } // cleanup crds.delete("testcrs.kube.rs", &DeleteParams::default()).await?; Ok(()) } #[tokio::test] #[ignore = "needs cluster (will create await a pod)"] #[cfg(feature = "runtime")] async fn pod_can_await_conditions() -> Result<(), Box<dyn std::error::Error>> { use crate::{ api::{DeleteParams, PostParams}, runtime::wait::{await_condition, conditions, delete::delete_and_finalize, Condition}, Api, Client, }; use k8s_openapi::api::core::v1::Pod; use std::time::Duration; use tokio::time::timeout; let client = Client::try_default().await?; let pods: Api<Pod> = Api::default_namespaced(client); // create busybox pod that's alive for at most 20s let data: Pod = serde_json::from_value(serde_json::json!({ "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "busybox-kube4", "labels": { "app": "kube-rs-test" }, }, "spec": { "terminationGracePeriodSeconds": 1, "restartPolicy": "Never", "containers": [{ "name": "busybox", "image": "busybox:1.34.1", "command": ["sh", "-c", "sleep 20"], }], } }))?; let pp = PostParams::default(); assert_eq!( data.name_unchecked(), pods.create(&pp, &data).await?.name_unchecked() ); // Watch it phase for a few seconds let is_running = await_condition(pods.clone(), "busybox-kube4", conditions::is_pod_running()); let _ = timeout(Duration::from_secs(15), is_running).await?; // Verify we can get it let pod = pods.get("busybox-kube4").await?; assert_eq!(pod.spec.as_ref().unwrap().containers[0].name, "busybox"); // Wait for a more complicated condition: ContainersReady AND Initialized // TODO: remove these once we can write these functions generically fn is_each_container_ready() -> impl Condition<Pod> { |obj: Option<&Pod>| { if let Some(o) = obj { if let Some(s) = &o.status { if let Some(conds) = &s.conditions { if let Some(pcond) = conds.iter().find(|c| c.type_ == "ContainersReady") { return pcond.status == "True"; } } } } false } } let is_fully_ready = await_condition( pods.clone(), "busybox-kube4", conditions::is_pod_running().and(is_each_container_ready()), ); let _ = timeout(Duration::from_secs(10), is_fully_ready).await?; // Delete it - and wait for deletion to complete let dp = DeleteParams::default(); delete_and_finalize(pods.clone(), "busybox-kube4", &dp).await?; // verify it is properly gone assert!(pods.get("busybox-kube4").await.is_err()); Ok(()) } #[tokio::test] #[ignore = "needs cluster (lists cms)"] async fn api_get_opt_handles_404() -> Result<(), Box<dyn std::error::Error>> { let client = Client::try_default().await?; let api = Api::<ConfigMap>::default_namespaced(client); assert_eq!( api.get_opt("this-cm-does-not-exist-ajklisdhfqkljwhreq").await?, None ); Ok(()) } }
use std::fs::File; use std::io::{BufReader, BufWriter}; use bitflags::bitflags; use serde::{Deserialize, Serialize}; use crate::joypad::{Button, JoyPort}; use crate::savable::Savable; pub use addr_modes::AddrMode; pub use instructions::OPTABLE; mod addr_modes; mod instructions; /// Memory page of the cpu stack const STACK_PAGE: u16 = 0x0100; /// Reset value of the stack pointer const STACK_RESET: u8 = 0xFD; /// Reset value of the status register const STATUS_RESET: u8 = Flags::U.bits() | Flags::I.bits(); /// Non-maskable interrupt vector const NMI_VECTOR: u16 = 0xFFFA; /// Reset vector const RESET_VECTOR: u16 = 0xFFFC; /// Interrupt request vector const IRQ_VECTOR: u16 = 0xFFFE; pub trait CpuInterface: Interface + Savable {} /// Cpu's interface to the rest of the components pub trait Interface { /// Reads a byte from `addr` fn read(&mut self, addr: u16) -> u8; /// Writes a byte to `addr` fn write(&mut self, addr: u16, data: u8); /// Polls the state of NMI flag of Ppu /// /// `true`: Ppu is requesting NMI. `false`: Ppu is not requesting NMI fn poll_nmi(&mut self) -> bool { false } /// Polls the state of IRQ flag of Apu /// /// `true`: Apu is requesting IRQ. `false`: Apu is not requesting IRQ fn poll_irq(&mut self) -> bool { false } /// Performs one clock tick on the bus fn tick(&mut self, _cycles: u64) {} /// Updates a controller's state /// /// Used with SDL2 keyboard events fn update_joypad(&mut self, _button: Button, _pressed: bool, _port: JoyPort) {} /// Returns the number of frame rendered by the Ppu fn frame_count(&self) -> u128 { 0 } /// Resets the bus and its components fn reset(&mut self) {} /// Gets audio samples from the Apu fn samples(&mut self) -> Vec<f32> { vec![] } /// Returns how many samples are ready to be played fn sample_count(&self) -> usize { 0 } } bitflags! { /// Cpu Flags #[derive(Serialize, Deserialize)] struct Flags: u8 { /// Negative const N = 0b10000000; /// Overflow const V = 0b01000000; /// Unused const U = 0b00100000; /// Break flag const B = 0b00010000; /// Decimal flag (disabled on the NES) const D = 0b00001000; /// Disable interrupt const I = 0b00000100; /// Zero const Z = 0b00000010; /// Carry const C = 0b00000001; } } /// 2A03 Cpu pub struct Cpu<'a> { /// Accumulator a: u8, /// Index X x: u8, /// Index Y y: u8, /// Stack pointer s: u8, /// Status register p: Flags, /// Program counter pc: u16, /// Memory bus bus: Box<dyn CpuInterface + 'a>, /// Current instruction duration in cycles ins_cycles: u64, /// Cycles elapsed cycles: u64, } impl Savable for Cpu<'_> { fn save(&self, output: &mut BufWriter<File>) -> bincode::Result<()> { self.bus.save(output)?; bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.a)?; bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.x)?; bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.y)?; bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.s)?; bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.p)?; bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.pc)?; bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.ins_cycles)?; bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.cycles)?; Ok(()) } fn load(&mut self, input: &mut BufReader<File>) -> bincode::Result<()> { self.bus.load(input)?; self.a = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?; self.x = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?; self.y = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?; self.s = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?; self.p = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?; self.pc = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?; self.ins_cycles = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?; self.cycles = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?; Ok(()) } } impl<'a> Cpu<'a> { pub fn new<I>(bus: I) -> Self where I: CpuInterface + 'a, { Self { a: 0, x: 0, y: 0, s: STACK_RESET, p: Flags::from_bits_truncate(STATUS_RESET), pc: 0, bus: Box::new(bus), ins_cycles: 0, cycles: 0, } } pub fn pc(&self) -> u16 { self.pc } pub fn a(&self) -> u8 { self.a } pub fn x(&self) -> u8 { self.x } pub fn y(&self) -> u8 { self.y } pub fn s(&self) -> u8 { self.s } pub fn p(&self) -> u8 { self.p.bits() } /// Cpu cycles passed pub fn cycles(&self) -> u64 { self.cycles } /// Ppu frames rendered pub fn frame_count(&self) -> u128 { self.bus.frame_count() } /// Resets the NES pub fn reset(&mut self) { self.bus.reset(); self.a = 0; self.x = 0; self.y = 0; self.s = STACK_RESET; self.p = Flags::from_bits_truncate(STATUS_RESET); // Set pc to value at reset vector self.pc = self.mem_read_word(RESET_VECTOR); self.ins_cycles = 0; // Reset takes 7 cycles self.bus.tick(7); self.cycles = 7; } /// Gets audio samples from the Apu pub fn samples(&mut self) -> Vec<f32> { self.bus.samples() } /// Returns how many samples are ready to be played pub fn sample_count(&self) -> usize { self.bus.sample_count() } /// Non-maskable interrupt fn nmi(&mut self) { // Push the program counter self.push_word(self.pc); // Push the status register without the Break flag self.push_byte((self.p & !Flags::B).bits()); // Set disable interrupt self.p.insert(Flags::I); // Set pc to value at NMI vector self.pc = self.mem_read_word(NMI_VECTOR); // NMI takes 7 cycles self.cycles += 7; self.ins_cycles = 7; } /// Interrupt request fn irq(&mut self) { // Don't execute if disable interrupt is set if !self.p.contains(Flags::I) { // Push the program counter self.push_word(self.pc); // Push the status register without the Break flag self.push_byte((self.p & !Flags::B).bits()); // Set disable interrupt self.p.insert(Flags::I); // Set pc to value at IRQ vector self.pc = self.mem_read_word(IRQ_VECTOR); // IRQ takes 7 cycles self.cycles += 7; self.ins_cycles = 7; } else { self.ins_cycles = 0; } } /// Executes an instruction and runs a callback function in a loop /// /// Used with the trace debug module #[allow(dead_code)] pub fn run_with_callback<F>(&mut self, mut callback: F) where F: FnMut(&mut Self), { loop { callback(self); self.execute(); } } /// Executes a full instruction /// /// Returns how many cycles were executed #[allow(dead_code)] pub fn execute(&mut self) -> u64 { let mut nmi_cycles = 0; // If Ppu has requested a NMI, do it if self.bus.poll_nmi() { self.nmi(); // Clock the bus for the NMI cycles duration (7) self.bus.tick(self.ins_cycles); nmi_cycles = self.ins_cycles; } // Get next instruction opcode let opcode = self.read_byte(); // Get the instruction from the instruction table let ins = *OPTABLE.get(&opcode).unwrap(); // Set the current instruction cycle duration self.ins_cycles = ins.cycles; // Call the instruction function (ins.cpu_fn)(self, ins.mode); // Clock the bus for the instruction's cycles duration self.bus.tick(self.ins_cycles); let mut irq_cycles = 0; // If Apu has requested an interrupt, do it if self.bus.poll_irq() { self.irq(); self.bus.tick(self.ins_cycles); irq_cycles = self.ins_cycles; } // Count cycles self.cycles = self .cycles .wrapping_add(nmi_cycles + irq_cycles + self.ins_cycles); nmi_cycles + irq_cycles + self.ins_cycles } /// Clocks the Cpu once /// /// This function is not cycle accurate. I execute the instruction in one cycle and then do nothing for the remaining cycles pub fn clock(&mut self) { // If current instruction is done and a NMI is requested, do it if self.ins_cycles == 0 && self.bus.poll_nmi() { self.nmi(); } // If current instruction is done and a IRQ is requested, do it if self.ins_cycles == 0 && self.bus.poll_irq() { self.irq(); } // If current instruction is done, do the next one if self.ins_cycles == 0 { // Read opcode let opcode = self.read_byte(); // Get the instruction from the instruction table let ins = *OPTABLE.get(&opcode).unwrap(); self.ins_cycles = ins.cycles; (ins.cpu_fn)(self, ins.mode); } // Tick once self.bus.tick(1); // Count cycles self.cycles = self.cycles.wrapping_add(1); // Once instruction cycle has passed self.ins_cycles -= 1; } /// Updates a controller's state /// /// Used with SDL2 keyboard events pub fn update_joypad(&mut self, button: Button, pressed: bool, port: JoyPort) { self.bus.update_joypad(button, pressed, port); } /// Reads a byte at addr pub fn mem_read(&mut self, addr: u16) -> u8 { self.bus.read(addr) } /// Reads a word (2 bytes) at addr /// /// This Cpu is little endian pub fn mem_read_word(&mut self, addr: u16) -> u16 { // Read low byte first let lo = self.mem_read(addr); // Then high byte let hi = self.mem_read(addr.wrapping_add(1)); // Combine them u16::from_le_bytes([lo, hi]) } /// Writes a byte to addr pub fn mem_write(&mut self, addr: u16, data: u8) { self.bus.write(addr, data); } /// Reads a byte at program counter, then increments it fn read_byte(&mut self) -> u8 { let b = self.mem_read(self.pc); self.increment_pc(); b } /// Reads a word (2 bytes) at program counter, then increments it fn read_word(&mut self) -> u16 { // Read low byte first let lo = self.read_byte(); // Then high byte let hi = self.read_byte(); // Combine them u16::from_le_bytes([lo, hi]) } /// Pushes a byte on the stack fn push_byte(&mut self, data: u8) { // Write byte at stack pointer location self.mem_write(STACK_PAGE + self.s() as u16, data); // Decrement stack pointer self.s = self.s().wrapping_sub(1); } /// Pushes a word (2 bytes) on the stack fn push_word(&mut self, data: u16) { // Get high byte from data let hi = (data >> 8) as u8; // Get low byte from data let lo = data as u8; // Push the high byte first because it will be popped off in reverse order (low, then high) self.push_byte(hi); self.push_byte(lo); } /// Pops a byte off the stack fn pop_byte(&mut self) -> u8 { // Increment stack pointer self.s = self.s().wrapping_add(1); // Read byte at stack pointer location self.mem_read(STACK_PAGE + self.s() as u16) } /// Pops a word (2 bytes) off the stack fn pop_word(&mut self) -> u16 { // Little endian, so pop low let lo = self.pop_byte(); // Then high let hi = self.pop_byte(); // Combine them u16::from_le_bytes([lo, hi]) } /// Returns the address of the operand based on the addressing mode fn operand_addr(&mut self, mode: AddrMode) -> u16 { match mode { // None or implied don't have operand AddrMode::None | AddrMode::Imp => panic!("Not supported"), // Immediate or relative: the operand is the byte right after the opcode AddrMode::Imm | AddrMode::Rel => self.pc, // Zero page: the byte after the opcode is the operand address in page 0x00 AddrMode::Zp0 => self.read_byte() as u16, // Zero page with X: the byte after the opcode plus the value in register X is the operand address in page 0x00 AddrMode::Zpx => { let base = self.read_byte(); base.wrapping_add(self.x()) as u16 } // Zero page with Y: the byte after the opcode plus the value in register Y is the operand address in page 0x00 AddrMode::Zpy => { let base = self.read_byte(); base.wrapping_add(self.y()) as u16 } // Absolute: the two bytes right after the opcode makes the operand address // Indirect: I cheat a bit here, the actual address is the operand. I use it as the operand later. Indirect is only used with JMP AddrMode::Abs | AddrMode::Ind => self.read_word(), // Absolute with X: the two bytes right after the opcode plus the value in register X makes the operand address AddrMode::Abx => { let base = self.read_word(); let addr = base.wrapping_add(self.x() as u16); // If a page is crossed (e.g. when the first byte is at 0x04FF and the second at 0x0500) it takes an extra cycle if Self::page_crossed(base, addr) { self.ins_cycles += 1; } addr } // Absolute with X for write instructions: the two bytes right after the opcode plus the value in register X makes the operand address AddrMode::AbxW => { let base = self.read_word(); base.wrapping_add(self.x() as u16) } // Absolute with Y: the two bytes right after the opcode plus the value in register Y makes the operand address AddrMode::Aby => { let base = self.read_word(); let addr = base.wrapping_add(self.y() as u16); // If a page is crossed (e.g. when the first byte is at 0x04FF and the second at 0x0500) it takes an extra cycle if Self::page_crossed(base, addr) { self.ins_cycles += 1; } addr } // Absolute with Y for write instructions: the two bytes right after the opcode plus the value in register Y makes the operand address AddrMode::AbyW => { let base = self.read_word(); base.wrapping_add(self.y() as u16) } // Indirect with X: the two bytes right after the opcode plus the value in register X make a pointer in page 0x00. The value at this // location is the address of the operand AddrMode::Izx => { // Construct pointer let base = self.read_byte(); let ptr = base.wrapping_add(self.x()); // Read values let lo = self.mem_read(ptr as u16); let hi = self.mem_read(ptr.wrapping_add(1) as u16); u16::from_le_bytes([lo, hi]) } // Indirect with Y: the two bytes right after the opcode make a pointer in page 0x00. The value at this // location plus the value in register Y is the address of the operand. Note that the pointer never // leaves page 0x00. 0x00FF wraps to 0x0000 AddrMode::Izy => { // Construct pointer let ptr = self.read_byte(); // Read values let lo = self.mem_read(ptr as u16); let hi = self.mem_read(ptr.wrapping_add(1) as u16); // Add value in register Y to the result let addr = u16::from_le_bytes([lo, hi]).wrapping_add(self.y() as u16); // If a page is crossed (e.g. when the first byte is at 0x04FF and the second at 0x0500) it takes an extra cycle if Self::page_crossed(u16::from_le_bytes([lo, hi]), addr) { self.ins_cycles += 1; } addr } // Indirect with Y: the two bytes right after the opcode make a pointer in page 0x00. The value at this // location plus the value in register Y is the address of the operand. Note that the pointer never // leaves page 0x00. 0x00FF wraps to 0x0000 AddrMode::IzyW => { // Construct pointer let ptr = self.read_byte(); // Read values let lo = self.mem_read(ptr as u16); let hi = self.mem_read(ptr.wrapping_add(1) as u16); // Add value in register Y to the result u16::from_le_bytes([lo, hi]).wrapping_add(self.y() as u16) } } } /// Fetches the operand at the address based on the addressing mode fn fetch_operand(&mut self, addr: u16, mode: AddrMode) -> u8 { match mode { // Should not be called with these modes AddrMode::None | AddrMode::Imp | AddrMode::Ind => panic!("Not supported"), // The operand is next to the opcode for these 2 AddrMode::Imm | AddrMode::Rel => self.read_byte(), // All the others reads at the provided address. Should be the address returned from `operand_addr` _ => self.mem_read(addr), } } /// Branched if the condition is met fn branch(&mut self, cond: bool) { // Get the operand (offset). Can be positive or negative let offset = self.read_byte() as i8; // If the condition is true, branch if cond { // Branching take one more cycle self.ins_cycles += 1; // Calculate new address let new_addr = self.pc.wrapping_add(offset as u16); // If a page is crossed, add one more cycle if Self::page_crossed(self.pc, new_addr) { self.ins_cycles += 1; } // Set program counter to new address self.pc = new_addr; } } /// Increments the program counter fn increment_pc(&mut self) { self.pc = self.pc.wrapping_add(1); } /// Sets flags Zero and Negative based on value fn set_z_n(&mut self, v: u8) { // If value equals 0 self.p.set(Flags::Z, v == 0); // If value bit 7 is set self.p.set(Flags::N, v & 0x80 != 0); } /// Sets the accumulator to v fn set_a(&mut self, v: u8) { self.a = v; // Update flags Z and N self.set_z_n(v); } /// Sets the X register to v fn set_x(&mut self, v: u8) { self.x = v; // Update flags Z and N self.set_z_n(v); } /// Sets the X register to v fn set_y(&mut self, v: u8) { self.y = v; // Update flags Z and N self.set_z_n(v); } /// Sets the status register to v fn set_p(&mut self, v: u8) { // Always set U flag and never the B flag self.p.bits = (v | Flags::U.bits()) & !Flags::B.bits(); } /// Returns if a page was crossed or not fn page_crossed(old: u16, new: u16) -> bool { old & 0xFF00 != new & 0xFF00 } /// Wrap an address so it doesn't change page fn wrap(old: u16, new: u16) -> u16 { (old & 0xFF00) | (new & 0x00FF) } // List of all the 2A03 instructions /// Load accumulator fn lda(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_a(v); } /// Load X register fn ldx(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_x(v); } /// Load Y register fn ldy(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_y(v); } /// Store accumulator fn sta(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); self.mem_write(addr, self.a()); } /// Store X register fn stx(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); self.mem_write(addr, self.x()); } /// Store Y register fn sty(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); self.mem_write(addr, self.y()); } /// Transfer accumulator to X register fn tax(&mut self, _mode: AddrMode) { self.set_x(self.a()); } /// Transfer accumulator to Y register fn tay(&mut self, _mode: AddrMode) { self.set_y(self.a()); } /// Transfer stack pointer to X register fn tsx(&mut self, _mode: AddrMode) { self.set_x(self.s()); } /// Transfer X register to accumulator fn txa(&mut self, _mode: AddrMode) { self.set_a(self.x()); } /// Transfer X register to stack pointer fn txs(&mut self, _mode: AddrMode) { self.s = self.x(); } /// Transfer Y register to accumulator fn tya(&mut self, _mode: AddrMode) { self.set_a(self.y()); } /// Clear carry fn clc(&mut self, _mode: AddrMode) { self.p.remove(Flags::C); } /// Clear decimal fn cld(&mut self, _mode: AddrMode) { self.p.remove(Flags::D); } /// Clear interrupt fn cli(&mut self, _mode: AddrMode) { self.p.remove(Flags::I); } /// Clear overflow fn clv(&mut self, _mode: AddrMode) { self.p.remove(Flags::V); } /// Set carry fn sec(&mut self, _mode: AddrMode) { self.p.insert(Flags::C); } /// Set decimal fn sed(&mut self, _mode: AddrMode) { self.p.insert(Flags::D); } /// Set interrupt fn sei(&mut self, _mode: AddrMode) { self.p.insert(Flags::I); } /// Increment memory fn inc(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode).wrapping_add(1); self.set_z_n(v); self.mem_write(addr, v); } /// Increment X register fn inx(&mut self, _mode: AddrMode) { self.set_x(self.x().wrapping_add(1)); } /// Increment Y register fn iny(&mut self, _mode: AddrMode) { self.set_y(self.y().wrapping_add(1)); } /// Decrement memory fn dec(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode).wrapping_sub(1); self.set_z_n(v); self.mem_write(addr, v); } /// Decrement X register fn dex(&mut self, _mode: AddrMode) { self.set_x(self.x().wrapping_sub(1)); } /// Decrement Y register fn dey(&mut self, _mode: AddrMode) { self.set_y(self.y().wrapping_sub(1)); } /// Compare fn cmp(&mut self, v1: u8, v2: u8) { let result = v1.wrapping_sub(v2); self.p.set(Flags::C, v1 >= v2); self.set_z_n(result); } /// Compare with accumulator fn cpa(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.cmp(self.a(), v); } /// Compare with X register fn cpx(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.cmp(self.x(), v); } /// Compare with Y register fn cpy(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.cmp(self.y(), v); } /// Branch if carry set fn bcs(&mut self, _mode: AddrMode) { self.branch(self.p.contains(Flags::C)); } /// Branch if carry clear fn bcc(&mut self, _mode: AddrMode) { self.branch(!self.p.contains(Flags::C)); } /// Branch if equal fn beq(&mut self, _mode: AddrMode) { self.branch(self.p.contains(Flags::Z)); } /// Branch if not equal fn bne(&mut self, _mode: AddrMode) { self.branch(!self.p.contains(Flags::Z)); } /// Branch if minus fn bmi(&mut self, _mode: AddrMode) { self.branch(self.p.contains(Flags::N)); } /// Branch if positive fn bpl(&mut self, _mode: AddrMode) { self.branch(!self.p.contains(Flags::N)); } /// Branch if overflow set fn bvs(&mut self, _mode: AddrMode) { self.branch(self.p.contains(Flags::V)); } /// Branch if overflow clear fn bvc(&mut self, _mode: AddrMode) { self.branch(!self.p.contains(Flags::V)); } /// Jump absolute fn jmp_abs(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); self.pc = addr; } /// Jump indirect fn jmp_ind(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let lo = self.mem_read(addr); let hi = self.mem_read(Self::wrap(addr, addr.wrapping_add(1))); self.pc = u16::from_le_bytes([lo, hi]); } /// Break fn brk(&mut self, _mode: AddrMode) { if !self.p.contains(Flags::I) { self.increment_pc(); self.push_word(self.pc); self.push_byte((self.p | Flags::B).bits()); self.p.insert(Flags::I); self.pc = self.mem_read_word(IRQ_VECTOR); } } /// Push accumulator fn pha(&mut self, _mode: AddrMode) { self.push_byte(self.a()); } /// Push status fn php(&mut self, _mode: AddrMode) { self.push_byte((self.p | Flags::B).bits()); } /// Pull accumulator fn pla(&mut self, _mode: AddrMode) { let v = self.pop_byte(); self.set_a(v); } /// Pull status fn plp(&mut self, _mode: AddrMode) { let v = self.pop_byte(); self.set_p(v); } /// Jump to subroutine fn jsr(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); self.push_word(self.pc.wrapping_sub(1)); self.pc = addr; } /// Return from subroutine fn rts(&mut self, _mode: AddrMode) { let addr = self.pop_word(); self.pc = addr.wrapping_add(1); } /// Return from interrupt fn rti(&mut self, _mode: AddrMode) { let v = self.pop_byte(); let addr = self.pop_word(); self.set_p(v); self.pc = addr; } /// No-op fn nop(&mut self, mode: AddrMode) { match mode { AddrMode::Imp => {} _ => { let addr = self.operand_addr(mode); self.fetch_operand(addr, mode); } } } /// Bit test fn bit(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.p.set(Flags::Z, self.a() & v == 0); self.p.set(Flags::V, v & 0x40 != 0); self.p.set(Flags::N, v & 0x80 != 0); } /// Bitwise AND fn and(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_a(self.a() & v); } /// Exclusive OR fn eor(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_a(self.a() ^ v); } /// Bitwise OR fn ora(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_a(self.a() | v); } /// Arithmetic shift left fn asl(&mut self, v: u8) -> u8 { self.p.set(Flags::C, v & 0x80 != 0); let result = v << 1; self.set_z_n(result); result } /// Arithmetic shift left on accumulator fn asl_acc(&mut self, _mode: AddrMode) { let v = self.asl(self.a()); self.set_a(v); } /// Arithmetic shift left on memory fn asl_mem(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let result = self.asl(v); self.mem_write(addr, result); } /// Logical shift right fn lsr(&mut self, v: u8) -> u8 { self.p.set(Flags::C, v & 0x01 != 0); let result = v >> 1; self.set_z_n(result); result } /// Logical shift right on accumulator fn lsr_acc(&mut self, _mode: AddrMode) { let v = self.lsr(self.a()); self.set_a(v); } /// Logical shift right on memory fn lsr_mem(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let result = self.lsr(v); self.mem_write(addr, result); } /// Rotate left fn rol(&mut self, v: u8) -> u8 { let c = self.p.contains(Flags::C) as u8; self.p.set(Flags::C, v & 0x80 != 0); let result = (v << 1) | c; self.set_z_n(result); result } /// Rotate left on accumulator fn rol_acc(&mut self, _mode: AddrMode) { let v = self.rol(self.a()); self.set_a(v); } /// Rotate left on memory fn rol_mem(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let result = self.rol(v); self.mem_write(addr, result); } /// Rotate right fn ror(&mut self, v: u8) -> u8 { let c = self.p.contains(Flags::C) as u8; self.p.set(Flags::C, v & 0x01 != 0); let result = (c << 7) | (v >> 1); self.set_z_n(result); result } /// Rotate right on accumulator fn ror_acc(&mut self, _mode: AddrMode) { let v = self.ror(self.a()); self.set_a(v); } /// Rotate right on memory fn ror_mem(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let result = self.ror(v); self.mem_write(addr, result); } /// Performs addition with on accumulator value fn add(&mut self, v: u8) { let c = self.p.contains(Flags::C); let sum = self.a() as u16 + v as u16 + c as u16; let result = sum as u8; self.p .set(Flags::V, (v ^ result) & (result ^ self.a()) & 0x80 != 0); self.p.set(Flags::C, sum > 0xFF); self.set_a(result); } /// Performs substraction on accumulator with value /// /// Substraction is adding with all the bits flipped fn sub(&mut self, v: u8) { self.add(!v); } /// Add with carry fn adc(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.add(v); } /// Sub with carry fn sbc(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.sub(v); } // ----------- Illegal opcodes ----------- /// Illegal operation which halts the cpu fn kil(&mut self, _mode: AddrMode) { panic!("KIL opcode called"); } /// ASL & ORA fn slo(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let result = self.asl(v); self.set_a(self.a() | result); self.mem_write(addr, result); } /// ROL & AND fn rla(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let result = self.rol(v); self.set_a(self.a() & result); self.mem_write(addr, result); } /// LSR & EOR fn sre(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let result = self.lsr(v); self.set_a(self.a() ^ result); self.mem_write(addr, result); } /// ROR & ADC fn rra(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let result = self.ror(v); self.add(result); self.mem_write(addr, result); } /// STA & STX fn sax(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); self.mem_write(addr, self.a() & self.x()); } /// STA & STX & (High byte + 1) fn ahx(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let hi = ((addr >> 8) as u8).wrapping_add(1); self.mem_write(addr, hi & self.a() & self.x()); } /// LDA & LDX fn lax(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_x(v); self.set_a(v); } /// DEC & CMP fn dcp(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode).wrapping_sub(1); self.cmp(self.a(), v); self.mem_write(addr, v); } /// INC & SBC fn isb(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode).wrapping_add(1); self.sub(v); self.mem_write(addr, v); } /// AND with Carry flag fn anc(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_a(self.a() & v); self.p.set(Flags::C, self.p.contains(Flags::N)); } /// AND with Carry flag & LSR fn alr(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_a(self.a() & v); self.p.set(Flags::C, self.a() & 0x01 != 0); self.set_a(self.a() >> 1); } fn arr(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); let c = (self.p.contains(Flags::C) as u8) << 7; self.set_a(((self.a() & v) >> 1) | c); self.p.set(Flags::C, self.a() & 0x40 != 0); let c = self.p.contains(Flags::C) as u8; self.p.set(Flags::V, (c ^ ((self.a() >> 5) & 0x01)) != 0); } fn xxa(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_a(self.x() & v); } fn tas(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); self.s = self.x() & self.a(); let hi = ((addr >> 8) as u8).wrapping_add(1); self.mem_write(addr, self.s() & hi); } fn shy(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let hi = ((addr >> 8) as u8).wrapping_add(1); let lo = addr as u8; let v = self.y() & hi; self.mem_write(u16::from_le_bytes([lo, self.y() & hi]), v); } fn shx(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let hi = ((addr >> 8) as u8).wrapping_add(1); let lo = addr as u8; let v = self.x() & hi; self.mem_write(u16::from_le_bytes([lo, self.x() & hi]), v); } fn las(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.set_a(v & self.s()); self.set_x(self.a()); self.s = self.a(); } fn axs(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.p.set(Flags::C, (self.a() & self.x()) >= v); self.set_x(v); } } #[cfg(test)] mod tests { use super::*; use crate::bus::TestBus; fn get_test_cpu(program: Vec<u8>, ram: Vec<u8>) -> Cpu<'static> { let mut bus = TestBus::new(program); for (addr, data) in ram.iter().enumerate() { bus.set_ram(addr as u16, *data); } let mut cpu = Cpu::new(bus); cpu.pc = 0x2000; cpu } fn get_test_cpu_from_bus(bus: TestBus) -> Cpu<'static> { let mut cpu = Cpu::new(bus); cpu.pc = 0x2000; cpu } #[test] fn test_a9() { let mut cpu = get_test_cpu(vec![0xA9, 0x05], vec![0]); cpu.execute(); assert_eq!(cpu.a, 0x05); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA9, 0x00], vec![0]); cpu.execute(); assert_eq!(cpu.a, 0x00); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA9, 0x80], vec![0]); cpu.execute(); assert_eq!(cpu.a, 0x80); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); } #[test] fn test_a5() { let mut cpu = get_test_cpu(vec![0xA5, 0x02], vec![0x00, 0x00, 0x23]); cpu.execute(); assert_eq!(cpu.a, 0x23); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA5, 0x00], vec![0x00]); cpu.execute(); assert_eq!(cpu.a, 0x00); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA5, 0x00], vec![0x85]); cpu.execute(); assert_eq!(cpu.a, 0x85); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_b5() { let mut bus = TestBus::new(vec![0xB5, 0x00]); bus.set_ram(0xFF, 0x50); let mut cpu = get_test_cpu_from_bus(bus); cpu.x = 0xFF; cpu.execute(); assert_eq!(cpu.a, 0x50); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xB5, 0x01], vec![0x50]); cpu.x = 0xFF; cpu.execute(); assert_eq!(cpu.a, 0x50); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.ins_cycles, 4); } #[test] fn test_ad() { let mut bus = TestBus::new(vec![0xAD, 0x05, 0x02]); bus.set_ram(0x0205, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.execute(); assert_eq!(cpu.a, 0xFE); assert_eq!(cpu.ins_cycles, 4); } #[test] fn test_bd() { let mut bus = TestBus::new(vec![0xBD, 0x05, 0x02]); bus.set_ram(0x020A, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.x = 5; cpu.execute(); assert_eq!(cpu.a, 0xFE); assert_eq!(cpu.ins_cycles, 4); let mut bus = TestBus::new(vec![0xBD, 0xFF, 0x05]); bus.set_ram(0x0604, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.x = 5; cpu.execute(); assert_eq!(cpu.a, 0xFE); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_b9() { let mut bus = TestBus::new(vec![0xB9, 0x05, 0x02]); bus.set_ram(0x020A, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.y = 5; cpu.execute(); assert_eq!(cpu.a, 0xFE); assert_eq!(cpu.ins_cycles, 4); let mut bus = TestBus::new(vec![0xB9, 0xFF, 0x05]); bus.set_ram(0x0604, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.y = 5; cpu.execute(); assert_eq!(cpu.a, 0xFE); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_a1() { let mut bus = TestBus::new(vec![0xA1, 0x05]); bus.set_ram(0x0A, 0x00); bus.set_ram(0x0B, 0x02); bus.set_ram(0x0200, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.x = 5; cpu.execute(); assert_eq!(cpu.a, 0xFE); assert_eq!(cpu.ins_cycles, 6); } #[test] fn test_b1() { let mut bus = TestBus::new(vec![0xB1, 0x05]); bus.set_ram(0x05, 0x00); bus.set_ram(0x06, 0x02); bus.set_ram(0x0205, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.y = 5; cpu.execute(); assert_eq!(cpu.a, 0xFE); assert_eq!(cpu.ins_cycles, 5); let mut bus = TestBus::new(vec![0xB1, 0x05]); bus.set_ram(0x05, 0xFF); bus.set_ram(0x06, 0x02); bus.set_ram(0x0300, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.y = 1; cpu.execute(); assert_eq!(cpu.a, 0xFE); assert_eq!(cpu.ins_cycles, 6); } #[test] fn test_a2() { let mut cpu = get_test_cpu(vec![0xA2, 0x05], vec![0]); cpu.execute(); assert_eq!(cpu.x, 0x05); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA2, 0x00], vec![0]); cpu.execute(); assert_eq!(cpu.x, 0x00); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA2, 0x80], vec![0]); cpu.execute(); assert_eq!(cpu.x, 0x80); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); } #[test] fn test_a6() { let mut cpu = get_test_cpu(vec![0xA6, 0x02], vec![0x00, 0x00, 0x23]); cpu.execute(); assert_eq!(cpu.x, 0x23); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA6, 0x00], vec![0x00]); cpu.execute(); assert_eq!(cpu.x, 0x00); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA6, 0x00], vec![0x85]); cpu.execute(); assert_eq!(cpu.x, 0x85); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_b6() { let mut bus = TestBus::new(vec![0xB6, 0x00]); bus.set_ram(0xFF, 0x50); let mut cpu = get_test_cpu_from_bus(bus); cpu.y = 0xFF; cpu.execute(); assert_eq!(cpu.x, 0x50); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xB6, 0x01], vec![0x50]); cpu.y = 0xFF; cpu.execute(); assert_eq!(cpu.x, 0x50); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.ins_cycles, 4); } #[test] fn test_ae() { let mut bus = TestBus::new(vec![0xAE, 0x05, 0x02]); bus.set_ram(0x0205, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.execute(); assert_eq!(cpu.x, 0xFE); assert_eq!(cpu.ins_cycles, 4); } #[test] fn test_be() { let mut bus = TestBus::new(vec![0xBE, 0x05, 0x02]); bus.set_ram(0x020A, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.y = 5; cpu.execute(); assert_eq!(cpu.x, 0xFE); assert_eq!(cpu.ins_cycles, 4); let mut bus = TestBus::new(vec![0xBE, 0xFF, 0x05]); bus.set_ram(0x0604, 0xFE); let mut cpu = get_test_cpu_from_bus(bus); cpu.y = 5; cpu.execute(); assert_eq!(cpu.x, 0xFE); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_a0() { let mut cpu = get_test_cpu(vec![0xA0, 0x05], vec![0]); cpu.execute(); assert_eq!(cpu.y, 0x05); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA0, 0x00], vec![0]); cpu.execute(); assert_eq!(cpu.y, 0x00); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); let mut cpu = get_test_cpu(vec![0xA0, 0x80], vec![0]); cpu.execute(); assert_eq!(cpu.y, 0x80); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); } #[test] fn test_85() { let mut cpu = get_test_cpu(vec![0x85, 0x03], vec![]); cpu.a = 0xDE; cpu.execute(); assert_eq!(cpu.mem_read(0x03), 0xDE); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_9d() { let mut cpu = get_test_cpu(vec![0x9D, 0x03, 0x04], vec![]); cpu.a = 0xDE; cpu.x = 0x0A; cpu.execute(); assert_eq!(cpu.mem_read(0x040D), 0xDE); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_86() { let mut cpu = get_test_cpu(vec![0x86, 0x03], vec![]); cpu.x = 0xDE; cpu.execute(); assert_eq!(cpu.mem_read(0x03), 0xDE); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_84() { let mut cpu = get_test_cpu(vec![0x84, 0x03], vec![]); cpu.y = 0xDE; cpu.execute(); assert_eq!(cpu.mem_read(0x03), 0xDE); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_aa() { let mut cpu = get_test_cpu(vec![0xAA], vec![]); cpu.a = 0x20; cpu.execute(); assert_eq!(cpu.x, cpu.a); assert_eq!(cpu.x, 0x20); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_a8() { let mut cpu = get_test_cpu(vec![0xA8], vec![]); cpu.a = 0x20; cpu.execute(); assert_eq!(cpu.y, cpu.a); assert_eq!(cpu.y, 0x20); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_ba() { let mut cpu = get_test_cpu(vec![0xBA], vec![]); cpu.s = 0x20; cpu.execute(); assert_eq!(cpu.x, cpu.s); assert_eq!(cpu.x, 0x20); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_8a() { let mut cpu = get_test_cpu(vec![0x8A], vec![]); cpu.x = 0x20; cpu.execute(); assert_eq!(cpu.a, cpu.x); assert_eq!(cpu.a, 0x20); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_9a() { let mut cpu = get_test_cpu(vec![0x9A], vec![]); cpu.x = 0x20; cpu.execute(); assert_eq!(cpu.s, cpu.x); assert_eq!(cpu.s, 0x20); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_98() { let mut cpu = get_test_cpu(vec![0x98], vec![]); cpu.y = 0x20; cpu.execute(); assert_eq!(cpu.a, cpu.y); assert_eq!(cpu.a, 0x20); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_18() { let mut cpu = get_test_cpu(vec![0x18], vec![]); cpu.p.insert(Flags::C); cpu.execute(); assert!(!cpu.p.contains(Flags::C)); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_d8() { let mut cpu = get_test_cpu(vec![0xD8], vec![]); cpu.p.insert(Flags::D); cpu.execute(); assert!(!cpu.p.contains(Flags::D)); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_58() { let mut cpu = get_test_cpu(vec![0x58], vec![]); cpu.p.insert(Flags::I); cpu.execute(); assert!(!cpu.p.contains(Flags::I)); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_b8() { let mut cpu = get_test_cpu(vec![0xB8], vec![]); cpu.p.insert(Flags::V); cpu.execute(); assert!(!cpu.p.contains(Flags::V)); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_38() { let mut cpu = get_test_cpu(vec![0x38], vec![]); cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_f8() { let mut cpu = get_test_cpu(vec![0xF8], vec![]); cpu.execute(); assert!(cpu.p.contains(Flags::D)); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_78() { let mut cpu = get_test_cpu(vec![0x78], vec![]); cpu.execute(); assert!(cpu.p.contains(Flags::I)); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_e6() { let mut cpu = get_test_cpu(vec![0xE6, 0x01], vec![0x00, 0xFE]); cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.mem_read(0x01), 0xFF); assert_eq!(cpu.ins_cycles, 5); let mut cpu = get_test_cpu(vec![0xE6, 0x01], vec![0x00, 0xFF]); cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); assert_eq!(cpu.mem_read(0x01), 0x00); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_e8() { let mut cpu = get_test_cpu(vec![0xE8], vec![]); cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.x, 0x01); assert_eq!(cpu.ins_cycles, 2); let mut cpu = get_test_cpu(vec![0xE8], vec![]); cpu.x = 0xFF; cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); assert_eq!(cpu.x, 0x00); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_c8() { let mut cpu = get_test_cpu(vec![0xC8], vec![]); cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.y, 0x01); assert_eq!(cpu.ins_cycles, 2); let mut cpu = get_test_cpu(vec![0xC8], vec![]); cpu.y = 0xFF; cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); assert_eq!(cpu.y, 0x00); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_c6() { let mut cpu = get_test_cpu(vec![0xC6, 0x01], vec![0x00, 0x00]); cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.mem_read(0x01), 0xFF); assert_eq!(cpu.ins_cycles, 5); let mut cpu = get_test_cpu(vec![0xC6, 0x01], vec![0x00, 0x01]); cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); assert_eq!(cpu.mem_read(0x01), 0x00); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_ca() { let mut cpu = get_test_cpu(vec![0xCA], vec![]); cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.x, 0xFF); assert_eq!(cpu.ins_cycles, 2); let mut cpu = get_test_cpu(vec![0xCA], vec![]); cpu.x = 0x01; cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); assert_eq!(cpu.x, 0x00); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_88() { let mut cpu = get_test_cpu(vec![0x88], vec![]); cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.y, 0xFF); assert_eq!(cpu.ins_cycles, 2); let mut cpu = get_test_cpu(vec![0x88], vec![]); cpu.y = 0x01; cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::Z)); assert_eq!(cpu.y, 0x00); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_c9() { let mut cpu = get_test_cpu(vec![0xC9, 0x05], vec![]); cpu.a = 0x05; cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert!(cpu.p.contains(Flags::Z)); assert!(!cpu.p.contains(Flags::N)); let mut cpu = get_test_cpu(vec![0xC9, 0x0A], vec![]); cpu.a = 0x05; cpu.execute(); assert!(!cpu.p.contains(Flags::C)); assert!(!cpu.p.contains(Flags::Z)); assert!(cpu.p.contains(Flags::N)); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_e4() { let mut bus = TestBus::new(vec![0xE4, 0x05]); bus.set_ram(0x05, 0x0A); let mut cpu = get_test_cpu_from_bus(bus); cpu.x = 0x05; cpu.execute(); assert!(!cpu.p.contains(Flags::C)); assert!(!cpu.p.contains(Flags::Z)); assert!(cpu.p.contains(Flags::N)); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_cc() { let mut bus = TestBus::new(vec![0xCC, 0x05, 0x03]); bus.set_ram(0x0305, 0x0A); let mut cpu = get_test_cpu_from_bus(bus); cpu.y = 0x05; cpu.execute(); assert!(!cpu.p.contains(Flags::C)); assert!(!cpu.p.contains(Flags::Z)); assert!(cpu.p.contains(Flags::N)); assert_eq!(cpu.ins_cycles, 4); } #[test] fn test_90() { let mut cpu = get_test_cpu(vec![0x90, 0x05], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002 + 0x05); assert_eq!(cpu.ins_cycles, 3); let mut cpu = get_test_cpu(vec![0x90, !0x05 + 1], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002 - 0x05); assert_eq!(cpu.ins_cycles, 4); let mut cpu = get_test_cpu(vec![0x90, !0x05 + 1], vec![]); cpu.p.insert(Flags::C); cpu.execute(); assert_eq!(cpu.pc, 0x2002); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_b0() { let mut cpu = get_test_cpu(vec![0xB0, 0x05], vec![]); cpu.p.insert(Flags::C); cpu.execute(); assert_eq!(cpu.pc, 0x2002 + 0x05); assert_eq!(cpu.ins_cycles, 3); let mut cpu = get_test_cpu(vec![0xB0, !0x05 + 1], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_f0() { let mut cpu = get_test_cpu(vec![0xF0, 0x05], vec![]); cpu.p.insert(Flags::Z); cpu.execute(); assert_eq!(cpu.pc, 0x2002 + 0x05); assert_eq!(cpu.ins_cycles, 3); let mut cpu = get_test_cpu(vec![0xF0, !0x05 + 1], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_d0() { let mut cpu = get_test_cpu(vec![0xD0, 0x05], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002 + 0x05); assert_eq!(cpu.ins_cycles, 3); let mut cpu = get_test_cpu(vec![0xD0, !0x05 + 1], vec![]); cpu.p.insert(Flags::Z); cpu.execute(); assert_eq!(cpu.pc, 0x2002); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_30() { let mut cpu = get_test_cpu(vec![0x30, 0x05], vec![]); cpu.p.insert(Flags::N); cpu.execute(); assert_eq!(cpu.pc, 0x2002 + 0x05); assert_eq!(cpu.ins_cycles, 3); let mut cpu = get_test_cpu(vec![0x30, !0x05 + 1], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_10() { let mut cpu = get_test_cpu(vec![0x10, 0x05], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002 + 0x05); assert_eq!(cpu.ins_cycles, 3); let mut cpu = get_test_cpu(vec![0x10, !0x05 + 1], vec![]); cpu.p.insert(Flags::N); cpu.execute(); assert_eq!(cpu.pc, 0x2002); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_50() { let mut cpu = get_test_cpu(vec![0x50, 0x05], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002 + 0x05); assert_eq!(cpu.ins_cycles, 3); let mut cpu = get_test_cpu(vec![0x50, !0x05 + 1], vec![]); cpu.p.insert(Flags::V); cpu.execute(); assert_eq!(cpu.pc, 0x2002); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_70() { let mut cpu = get_test_cpu(vec![0x70, 0x05], vec![]); cpu.p.insert(Flags::V); cpu.execute(); assert_eq!(cpu.pc, 0x2002 + 0x05); assert_eq!(cpu.ins_cycles, 3); let mut cpu = get_test_cpu(vec![0x70, !0x05 + 1], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2002); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_4c() { let mut cpu = get_test_cpu(vec![0x4C, 0x34, 0x02], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x0234); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_6c() { let mut bus = TestBus::new(vec![0x6C, 0x05, 0x03]); bus.set_ram(0x0305, 0x0A); bus.set_ram(0x0306, 0x06); let mut cpu = get_test_cpu_from_bus(bus); cpu.execute(); assert_eq!(cpu.pc, 0x060A); // wrap bug test let mut bus = TestBus::new(vec![0x6C, 0xFF, 0x10]); bus.set_ram(0x10FF, 0x0A); bus.set_ram(0x1000, 0x06); let mut cpu = get_test_cpu_from_bus(bus); cpu.execute(); assert_eq!(cpu.pc, 0x060A); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_48() { let mut cpu = get_test_cpu(vec![0x48], vec![]); cpu.a = 0x93; cpu.execute(); assert_eq!( cpu.mem_read(STACK_PAGE + cpu.s.wrapping_add(1) as u16), 0x93 ); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_08() { let mut cpu = get_test_cpu(vec![0x08], vec![]); cpu.p.insert(Flags::N); cpu.p.insert(Flags::V); cpu.p.insert(Flags::C); cpu.execute(); assert_eq!( cpu.mem_read(STACK_PAGE + cpu.s.wrapping_add(1) as u16), (Flags::N | Flags::V | Flags::U | Flags::B | Flags::C | Flags::I).bits() ); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_68() { let mut bus = TestBus::new(vec![0x68]); bus.set_ram(STACK_PAGE + 0xA5, 0x0A); let mut cpu = get_test_cpu_from_bus(bus); cpu.s = 0xA4; cpu.execute(); assert_eq!(cpu.a, 0x0A); assert_eq!(cpu.ins_cycles, 4); let mut cpu = get_test_cpu(vec![0x68], vec![]); cpu.execute(); assert_eq!(cpu.a, 0x00); assert!(cpu.p.contains(Flags::Z)); assert_eq!(cpu.ins_cycles, 4); } #[test] fn test_28() { let mut bus = TestBus::new(vec![0x28]); bus.set_ram(STACK_PAGE + 0xA5, (Flags::N | Flags::B | Flags::I).bits()); let mut cpu = get_test_cpu_from_bus(bus); cpu.s = 0xA4; cpu.execute(); assert_eq!(cpu.p, Flags::N | Flags::U | Flags::I); assert_eq!(cpu.ins_cycles, 4); } #[test] fn test_20() { let mut cpu = get_test_cpu(vec![0x20, 0x63, 0x05], vec![]); cpu.execute(); assert_eq!(cpu.mem_read_word(STACK_PAGE + cpu.s as u16 + 1), 0x2002); assert_eq!(cpu.pc, 0x0563); assert_eq!(cpu.ins_cycles, 6); } #[test] fn test_60() { let mut bus = TestBus::new(vec![0x60]); bus.set_ram(STACK_PAGE + 0xFE, 0xEF); bus.set_ram(STACK_PAGE + 0xFF, 0xBE); let mut cpu = get_test_cpu_from_bus(bus); cpu.execute(); assert_eq!(cpu.pc, 0xBEEF + 1); assert_eq!(cpu.ins_cycles, 6); } #[test] fn test_40() { let mut bus = TestBus::new(vec![0x40]); bus.set_ram(STACK_PAGE + 0xFE, (Flags::V | Flags::C).bits()); bus.set_ram(STACK_PAGE + 0xFF, 0xEF); bus.set_ram(STACK_PAGE, 0xBE); let mut cpu = get_test_cpu_from_bus(bus); cpu.execute(); assert_eq!(cpu.pc, 0xBEEF); assert_eq!(cpu.p, Flags::V | Flags::U | Flags::C); assert_eq!(cpu.ins_cycles, 6); } #[test] fn test_ea() { let mut cpu = get_test_cpu(vec![0xEA], vec![]); cpu.execute(); assert_eq!(cpu.pc, 0x2001); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_24() { let mut bus = TestBus::new(vec![0x24, 0xFE]); bus.set_ram(0xFE, 0b0010_0110); let mut cpu = get_test_cpu_from_bus(bus); cpu.a = 0b1101_1001; cpu.execute(); assert!(cpu.p.contains(Flags::Z)); assert_eq!(cpu.ins_cycles, 3); let mut bus = TestBus::new(vec![0x24, 0xFE]); bus.set_ram(0xFE, 0b1100_0110); let mut cpu = get_test_cpu_from_bus(bus); cpu.a = 0b1101_1001; cpu.execute(); assert!(!cpu.p.contains(Flags::Z)); assert!(cpu.p.contains(Flags::V)); assert!(cpu.p.contains(Flags::N)); assert_eq!(cpu.ins_cycles, 3); } #[test] fn test_29() { let mut cpu = get_test_cpu(vec![0x29, 0x8E], vec![]); cpu.a = 0x3C; cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.a, 0x3C & 0x8E); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_49() { let mut cpu = get_test_cpu(vec![0x49, 0x8E], vec![]); cpu.a = 0x3C; cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.a, 0x3C ^ 0x8E); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_09() { let mut cpu = get_test_cpu(vec![0x09, 0x8E], vec![]); cpu.a = 0x3C; cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.a, 0x3C | 0x8E); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_0a() { let mut cpu = get_test_cpu(vec![0x0A], vec![]); cpu.a = 0xC1; cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert_eq!(cpu.a, 0xC1 << 1); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_06() { let mut cpu = get_test_cpu(vec![0x06, 0x00], vec![0x67]); cpu.execute(); assert!(!cpu.p.contains(Flags::C)); assert_eq!(cpu.mem_read(0x00), 0x67 << 1); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_4a() { let mut cpu = get_test_cpu(vec![0x4A], vec![]); cpu.a = 0xC0; cpu.execute(); assert!(!cpu.p.contains(Flags::C)); assert_eq!(cpu.a, 0xC1 >> 1); assert_eq!(cpu.ins_cycles, 2); } #[test] fn test_46() { let mut cpu = get_test_cpu(vec![0x46, 0x00], vec![0x67]); cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert_eq!(cpu.mem_read(0x00), 0x67 >> 1); assert_eq!(cpu.ins_cycles, 5); } #[test] fn test_2a() { let mut cpu = get_test_cpu(vec![0x2A], vec![]); cpu.a = 0b0100_0010; cpu.p.insert(Flags::C); cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z | Flags::C)); assert_eq!(cpu.a, 0b1000_0101); } #[test] fn test_2e() { let mut bus = TestBus::new(vec![0x2E, 0xFE, 0x10]); bus.set_ram(0x10FE, 0b1001_0110); let mut cpu = get_test_cpu_from_bus(bus); cpu.p.insert(Flags::C); cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.mem_read(0x10FE), 0b0010_1101); let mut bus = TestBus::new(vec![0x2E, 0xFE, 0x10]); bus.set_ram(0x10FE, 0b0001_0110); let mut cpu = get_test_cpu_from_bus(bus); cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert!(!cpu.p.contains(Flags::C)); assert_eq!(cpu.mem_read(0x10FE), 0b0010_1100); } #[test] fn test_6a() { let mut cpu = get_test_cpu(vec![0x6A], vec![]); cpu.a = 0b0100_0011; cpu.p.insert(Flags::C); cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::C)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.a, 0b1010_0001); } #[test] fn test_6e() { let mut bus = TestBus::new(vec![0x6E, 0xFE, 0x10]); bus.set_ram(0x10FE, 0b1001_0110); let mut cpu = get_test_cpu_from_bus(bus); cpu.p.insert(Flags::C); cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::C)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.mem_read(0x10FE), 0b1100_1011); let mut bus = TestBus::new(vec![0x6E, 0xFE, 0x10]); bus.set_ram(0x10FE, 0b0001_0110); let mut cpu = get_test_cpu_from_bus(bus); cpu.execute(); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert!(!cpu.p.contains(Flags::C)); assert_eq!(cpu.mem_read(0x10FE), 0b0000_1011); } #[test] fn test_69() { let mut cpu = get_test_cpu(vec![0x69, 0x45], vec![]); cpu.a = 0xBA; cpu.p.insert(Flags::C); cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert!(cpu.p.contains(Flags::Z)); assert!(!cpu.p.contains(Flags::V)); assert!(!cpu.p.contains(Flags::N)); assert_eq!(cpu.a, 0x00); let mut cpu = get_test_cpu(vec![0x69, 0xB5], vec![]); cpu.a = 0xBA; cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert!(cpu.p.contains(Flags::V)); assert!(!cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert_eq!(cpu.a, 0x6F); } #[test] fn test_e9() { let mut cpu = get_test_cpu(vec![0xE9, 0x45], vec![]); cpu.a = 0xBA; cpu.p.insert(Flags::C); cpu.execute(); assert!(!cpu.p.contains(Flags::Z)); assert!(!cpu.p.contains(Flags::N)); assert!(cpu.p.contains(Flags::C)); assert!(cpu.p.contains(Flags::V)); assert_eq!(cpu.a, 0xBA - 0x45); let mut cpu = get_test_cpu(vec![0xE9, 0x38], vec![]); cpu.a = 0xF7; cpu.p.insert(Flags::C); cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert!(!cpu.p.contains(Flags::V)); assert_eq!(cpu.a, 0xF7 - 0x38); let mut cpu = get_test_cpu(vec![0xE9, 0x02], vec![]); cpu.a = 0xFF; cpu.p.insert(Flags::C); cpu.execute(); assert!(cpu.p.contains(Flags::C)); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::Z)); assert!(!cpu.p.contains(Flags::V)); assert_eq!(cpu.a, 0xFF - 0x02); let mut cpu = get_test_cpu(vec![0xE9, 0x02], vec![]); cpu.a = 0x00; cpu.p.insert(Flags::C); cpu.execute(); assert!(cpu.p.contains(Flags::N)); assert!(!cpu.p.contains(Flags::C)); assert!(!cpu.p.contains(Flags::Z)); assert!(!cpu.p.contains(Flags::V)); assert_eq!(cpu.a, 0x00u8.wrapping_sub(0x02)); } }
#[derive(Clone)] pub struct Board { rows: Vec<Vec<i32>>, rows_done: [i32; 5], cols_done: [i32; 5], winner: bool, } pub struct Bingo { moves: Vec<i32>, boards: Vec<Board>, } #[aoc_generator(day4)] pub fn input_generator(input: &str) -> Bingo { let mut input = input.split("\n\n"); let moves = input .next() .unwrap() .split(",") .map(|m| m.parse().unwrap()) .collect(); let boards: Vec<Board> = input .map(|b| Board { rows: b .lines() .map(|l| { l.trim() .split_whitespace() .map(|n| n.parse().unwrap()) .collect() }) .collect(), rows_done: [0; 5], cols_done: [0; 5], winner: false, }) .collect(); Bingo { moves, boards } } #[aoc(day4, part1)] pub fn solve_part1(bingo: &Bingo) -> i32 { let moves = bingo.moves.clone(); let mut boards = bingo.boards.clone(); for n in 0..moves.len() { for b in 0..boards.len() { for r in 0..boards[b].rows.len() { for c in 0..boards[b].rows[0].len() { if boards[b].rows[r][c] == moves[n] { boards[b].rows[r][c] = -1; boards[b].rows_done[r] += 1; boards[b].cols_done[c] += 1; } if boards[b].rows_done[r] == 5 || boards[b].cols_done[c] == 5 { return moves[n] * boards[b] .rows .clone() .into_iter() .flatten() .filter(|c| *c != -1i32) .sum::<i32>(); } } } } } return 0; } #[aoc(day4, part2)] pub fn solve_part2(bingo: &Bingo) -> i32 { let moves = bingo.moves.clone(); let mut boards = bingo.boards.clone(); let mut score: i32 = 0; for n in 0..moves.len() { for b in 0..boards.len() { if boards[b].winner { continue; } for r in 0..boards[b].rows.len() { for c in 0..boards[b].rows[0].len() { if boards[b].rows[r][c] == moves[n] { boards[b].rows[r][c] = -1; boards[b].rows_done[r] += 1; boards[b].cols_done[c] += 1; if boards[b].rows_done[r] == 5 || boards[b].cols_done[c] == 5 { boards[b].winner = true; score = moves[n] * boards[b] .rows .clone() .into_iter() .flatten() .filter(|c| *c != -1i32) .sum::<i32>(); } } } } } } return score; } #[cfg(test)] mod tests { use super::*; const INPUT: &str = r#"7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 22 13 17 11 0 8 2 23 4 24 21 9 14 16 7 6 10 3 18 5 1 12 20 15 19 3 15 0 2 22 9 18 13 17 5 19 8 7 25 23 20 11 10 24 4 14 21 16 12 6 14 21 17 24 4 10 16 15 9 19 18 8 23 26 20 22 11 13 6 5 2 0 12 3 7"#; #[test] fn example1() { assert_eq!(solve_part1(&input_generator(INPUT)), 4512); } #[test] fn example2() { assert_eq!(solve_part2(&input_generator(INPUT)), 1924); } }
use std::collections::HashMap; use std::io; use std::str::FromStr; use chrono::{NaiveDateTime, Timelike}; use lazy_static::lazy_static; use regex::Regex; use crate::base::Part; pub fn part1(r: &mut dyn io::Read) -> Result<String, String> { solve(r, Part::One) } pub fn part2(r: &mut dyn io::Read) -> Result<String, String> { solve(r, Part::Two) } fn solve(r: &mut dyn io::Read, part: Part) -> Result<String, String> { let mut input = String::new(); r.read_to_string(&mut input).map_err(|e| e.to_string())?; let mut sorted_events = parse_input(&input); sorted_events.sort(); match part { Part::One => Ok(strategy_1(&sorted_events).to_string()), Part::Two => Ok(strategy_2(&sorted_events).to_string()), } } fn parse_input(input: &str) -> Vec<Event> { input .lines() .map(Event::from_str) .map(Result::unwrap) .collect() } fn strategy_1(sorted_events: &[Event]) -> u64 { let guard_events = gather_guard_events(sorted_events); let (id, (_total_sleep, most_sleeping_minute, _most_times_asleep)) = guard_events .iter() .map(|(id, events)| (id, calculate_sleeping(events))) .max_by_key(|&(_id, (total_sleep, _most_sleeping_minute, _most_times_asleep))| total_sleep) .unwrap(); id * u64::from(most_sleeping_minute) } fn strategy_2(sorted_events: &[Event]) -> u64 { let guard_events = gather_guard_events(sorted_events); let (id, (_total_sleep, most_sleeping_minute, _most_times_asleep)) = guard_events .iter() .map(|(id, events)| (id, calculate_sleeping(events))) .max_by_key( |&(_id, (_total_sleep, _most_sleeping_minute, most_times_asleep))| most_times_asleep, ) .unwrap(); id * u64::from(most_sleeping_minute) } fn gather_guard_events(events: &[Event]) -> HashMap<u64, Vec<Vec<(u32, EventType)>>> { let first_event = events[0]; let first_event_minute = first_event.datetime.minute(); let first_event_type = first_event.event_type; let mut current_guard = if let EventType::BeginsShift(id) = first_event_type { id } else { panic!("First event is not a begins shift event"); }; let mut current_events = vec![(first_event_minute, first_event_type)]; let mut map = HashMap::new(); for &event in &events[1..] { let event_minute = event.datetime.minute(); let event_type = event.event_type; if let EventType::BeginsShift(id) = event_type { map.entry(current_guard) .or_insert_with(Vec::new) .push(current_events); current_guard = id; current_events = Vec::new(); } else { current_events.push((event_minute, event_type)); } } map.entry(current_guard) .or_insert_with(Vec::new) .push(current_events); map } fn calculate_sleeping(events: &[Vec<(u32, EventType)>]) -> (u32, u32, u32) { let mut combined = events .into_iter() .cloned() .flatten() .filter(|(_event_minute, event_type)| { if let EventType::BeginsShift(_) = event_type { false } else { true } }) .collect::<Vec<(u32, EventType)>>(); combined.sort(); let mut last_event_minute = 0; let mut total_sleep = 0; let mut times_asleep = 0; let mut most_sleeping_minute = 0; let mut most_times_asleep = 0; for &(event_minute, event_type) in &combined { total_sleep += (event_minute - last_event_minute) * times_asleep; match event_type { EventType::BeginsShift(_) => unreachable!(), EventType::FallsAsleep => times_asleep += 1, EventType::WakesUp => times_asleep -= 1, }; if times_asleep > most_times_asleep { most_sleeping_minute = event_minute; most_times_asleep = times_asleep; } last_event_minute = event_minute; } (total_sleep, most_sleeping_minute, most_times_asleep) } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] struct Event { datetime: NaiveDateTime, event_type: EventType, } impl FromStr for Event { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { lazy_static! { static ref EVENT_RE: Regex = Regex::new(r"\[(?P<datetime>\d{4}\-\d{2}\-\d{2} \d{2}:\d{2})\] (?P<event_type>.+)") .unwrap(); } let captures = EVENT_RE.captures(s).unwrap(); let datetime = NaiveDateTime::parse_from_str(&captures["datetime"], "%Y-%m-%d %H:%M").unwrap(); let event_type = EventType::from_str(&captures["event_type"]).unwrap(); Ok(Event { datetime, event_type, }) } } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] enum EventType { BeginsShift(u64), FallsAsleep, WakesUp, } impl FromStr for EventType { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { lazy_static! { static ref BEGIN_RE: Regex = Regex::new(r"Guard #(?P<id>\d+) begins shift").unwrap(); } if let Some(caps) = BEGIN_RE.captures(s) { let id = u64::from_str(&caps["id"]).unwrap(); Ok(EventType::BeginsShift(id)) } else { match s { "falls asleep" => Ok(EventType::FallsAsleep), "wakes up" => Ok(EventType::WakesUp), _ => Err(format!("invalid event: \"{}\"", s)), } } } } #[cfg(test)] mod tests { use super::*; use crate::test; use chrono::NaiveDate; mod parsing { use super::*; mod event { use super::*; #[test] fn begins_shift() { let input = "[1518-11-01 00:00] Guard #10 begins shift"; let expected_datetime = NaiveDate::from_ymd(1518, 11, 1).and_hms(0, 0, 0); let expected_event_type = EventType::BeginsShift(10); let expected = Event { datetime: expected_datetime, event_type: expected_event_type, }; assert_eq!(expected, Event::from_str(input).unwrap()); } #[test] fn falls_asleep() { let input = "[1518-11-01 00:42] falls asleep"; let expected_datetime = NaiveDate::from_ymd(1518, 11, 1).and_hms(0, 42, 0); let expected_event_type = EventType::FallsAsleep; let expected = Event { datetime: expected_datetime, event_type: expected_event_type, }; assert_eq!(expected, Event::from_str(input).unwrap()); } #[test] fn wakes_up() { let input = "[1518-11-01 00:58] wakes up"; let expected_datetime = NaiveDate::from_ymd(1518, 11, 1).and_hms(0, 58, 0); let expected_event_type = EventType::WakesUp; let expected = Event { datetime: expected_datetime, event_type: expected_event_type, }; assert_eq!(expected, Event::from_str(input).unwrap()); } } mod event_type { use super::*; #[test] fn begins_shift_single_digit() { let input = "Guard #4 begins shift"; let expected = EventType::BeginsShift(4); assert_eq!(expected, EventType::from_str(input).unwrap()); } #[test] fn begins_shift_multiple_digits() { let input = "Guard #1234 begins shift"; let expected = EventType::BeginsShift(1234); assert_eq!(expected, EventType::from_str(input).unwrap()); } #[test] fn begin_shift_invalid_id() { let input = "Guard #asd begins shift"; assert!(EventType::from_str(input).is_err()); } #[test] fn falls_asleep() { let input = "falls asleep"; let expected = EventType::FallsAsleep; assert_eq!(expected, EventType::from_str(input).unwrap()); } #[test] fn wakes_up() { let input = "wakes up"; let expected = EventType::WakesUp; assert_eq!(expected, EventType::from_str(input).unwrap()); } } } mod part1 { use super::*; test!(example, file "testdata/day04/ex", "240", part1); test!(actual, file "../../../inputs/2018/04", "125444", part1); } mod part2 { use super::*; test!(example, file "testdata/day04/ex", "4455", part2); test!(actual, file "../../../inputs/2018/04", "18325", part2); } }
use crate::{ instruction::{Instruction, Opcode}, interconnect::Interconnect, io::IO, mmu::Mmu, }; use log::info; use std::fmt::{self, Display}; mod flags; pub use self::flags::ConditionalFlags; mod register; pub use self::register::Register; mod error; use self::error::EmulateError; type Result<T> = std::result::Result<T, EmulateError>; // Instruction Implementations mod implementations; pub struct I8080 { a: u8, b: u8, c: u8, d: u8, e: u8, h: u8, l: u8, sp: u16, pc: u16, flags: ConditionalFlags, rc: [bool; 8], interrupts_enabled: bool, } impl I8080 { pub fn new() -> I8080 { I8080 { a: 0, b: 0, c: 0, d: 0, e: 0, h: 0, l: 0, sp: 0, pc: 0, flags: ConditionalFlags::new(), rc: [false; 8], interrupts_enabled: true, } } pub fn emulate_instruction<T: Mmu, U: IO>( &mut self, instruction: Instruction, interconnect: &mut Interconnect<T, U>, is_interrupt: bool, ) -> Result<()> { use self::Opcode::*; let mmu = &mut interconnect.mmu; let io = &mut interconnect.io; let old_pc = self.pc; match is_interrupt { true => self.interrupts_enabled = false, false => self.pc += instruction.len(), } self.reset_rc(); let r = match instruction.opcode() { NOP => Ok(()), // Data transfer Instructions LXI(r) => self.lxi(r, instruction.data()), LDAX(r) => self.ldax(r, mmu), LDA => self.lda(instruction.data(), mmu), STA => self.sta(instruction.data(), mmu), MOV(d, s) => self.mov(d, s, mmu), MVI(r) => self.mvi(r, instruction.data(), mmu), XCHG => self.xchg(), PUSH(r) => self.push(r, mmu), POP(r) => self.pop(r, mmu), // Arithmetic Instructions INX(r) => self.inx(r), DCX(r) => self.dcx(r), INR(r) => self.inr(r, mmu), DCR(r) => self.dcr(r, mmu), ADD(r) => self.add(r, mmu), ADI => self.adi(instruction.data()), DAD(r) => self.dad(r), SUB(r) => self.sub(r, mmu), SUI => self.sui(instruction.data()), RRC => self.rrc(), // Logical Instructions CPI => self.cpi(instruction.data()), ANI => self.ani(instruction.data()), ANA(r) => self.ana(r, mmu), XRA(r) => self.xra(r, mmu), // IO Instructions OUT => self.out(instruction.data(), io), IN => self.input(instruction.data(), io), // Branch Instructions JMP => self.jmp(instruction.data()), JZ => self.jz(instruction.data()), JNZ => self.jnz(instruction.data()), JNC => self.jnc(instruction.data()), CALL => self.call(instruction.data(), mmu), RET => self.ret(mmu), // Special Instructions EI => self.ei(), _op => return Err(EmulateError::UnimplementedInstruction { instruction }), }; if let Ok(()) = r { info!("{}: {}; {}", old_pc, instruction, self); } r } fn set_8bit_register(&mut self, register: Register, value: u8) { self.register_changed(register); match register { Register::A => self.a = value, Register::B => self.b = value, Register::C => self.c = value, Register::D => self.d = value, Register::E => self.e = value, Register::H => self.h = value, Register::L => self.l = value, Register::M => { self.l = value; self.h = 0 } Register::SP => self.sp = value as u16, }; } pub fn get_8bit_register(&self, register: Register) -> Result<u8> { match register { Register::A => Ok(self.a), Register::B => Ok(self.b), Register::C => Ok(self.c), Register::D => Ok(self.d), Register::E => Ok(self.e), Register::H => Ok(self.h), Register::L => Ok(self.l), _r => return Err(EmulateError::RegisterNot8Bit { register }), } } pub fn m(&self) -> u16 { let high = self.get_8bit_register(Register::H).unwrap() as u16; let low = self.get_8bit_register(Register::L).unwrap() as u16; high << 8 | low } fn set_m(&mut self, addr: u16) { let (high, low) = split_bytes(addr); self.set_8bit_register(Register::H, high); self.set_8bit_register(Register::L, low); } fn set_sp(&mut self, value: u16) { self.register_changed(Register::SP); self.sp = value; } pub fn sp(&self) -> u16 { self.sp } pub fn pc(&self) -> u16 { self.pc } pub fn flags(&self) -> ConditionalFlags { self.flags } pub fn interrupts_enabled(&self) -> bool { self.interrupts_enabled } fn push_u16<T: Mmu>(&mut self, value: u16, mmu: &mut T) -> Result<()> { let (high, low) = split_bytes(value); self.push_u8(high, mmu)?; self.push_u8(low, mmu)?; Ok(()) } fn push_u8<T: Mmu>(&mut self, value: u8, mmu: &mut T) -> Result<()> { let loc = self.sp - 1; //if loc < 0x2000 { // return Err(EmulateError::StackOverflow); //}; mmu.write_byte(loc, value); self.sp -= 1; self.register_changed(Register::SP); Ok(()) } fn pop_u8<T: Mmu>(&mut self, mmu: &T) -> Result<u8> { let value = mmu.read_byte(self.sp); self.sp += 1; self.register_changed(Register::SP); Ok(value) } fn pop_u16<T: Mmu>(&mut self, mmu: &T) -> Result<u16> { let low = self.pop_u8(mmu)?; let high = self.pop_u8(mmu)?; Ok(concat_bytes(high, low)) } fn register_changed(&mut self, reg: Register) { match reg { Register::A => self.rc[0] = true, Register::B => self.rc[1] = true, Register::C => self.rc[2] = true, Register::D => self.rc[3] = true, Register::E => self.rc[4] = true, Register::H => self.rc[5] = true, Register::L => self.rc[6] = true, Register::M => { self.rc[5] = true; self.rc[6] = true } Register::SP => self.rc[7] = true, } } fn reset_rc(&mut self) { for i in self.rc.iter_mut() { *i = false; } } } pub(crate) fn split_bytes(bytes: u16) -> (u8, u8) { let low_byte = (bytes & 0x00ff) as u8; let high_byte = (bytes & 0xff00) >> 8; let high_byte = high_byte as u8; (high_byte, low_byte) } pub(crate) fn concat_bytes(high: u8, low: u8) -> u16 { (high as u16) << 8 | (low as u16) } trait TwosComplement<RHS = Self> { type Output; fn complement_sub(self, subtrahend: RHS) -> Self::Output; } impl TwosComplement for u8 { type Output = (u8, bool); fn complement_sub(self, subtrahend: Self) -> Self::Output { let complement = !subtrahend + 1; let (value, carry) = self.overflowing_add(complement); (value, !carry) } } impl Display for I8080 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use colored::*; let a = match self.rc[0] { true => format!("{:02x}", self.a).blue(), false => format!("{:02x}", self.a).white(), }; let b = match self.rc[1] { true => format!("{:02x}", self.b).blue(), false => format!("{:02x}", self.b).white(), }; let c = match self.rc[2] { true => format!("{:02x}", self.c).blue(), false => format!("{:02x}", self.c).white(), }; let d = match self.rc[3] { true => format!("{:02x}", self.d).blue(), false => format!("{:02x}", self.d).white(), }; let e = match self.rc[4] { true => format!("{:02x}", self.e).blue(), false => format!("{:02x}", self.e).white(), }; let h = match self.rc[5] { true => format!("{:02x}", self.h).blue(), false => format!("{:02x}", self.h).white(), }; let l = match self.rc[6] { true => format!("{:02x}", self.l).blue(), false => format!("{:02x}", self.l).white(), }; let s = match self.rc[7] { true => format!("{:02x}", self.sp).blue(), false => format!("{:02x}", self.sp).white(), }; write!( f, "CPU: a={}|b={}|c={}|d={}|e={}|h={}|l={}|sp={}", a, b, c, d, e, h, l, s, ) } } #[cfg(test)] mod tests { use super::{concat_bytes, split_bytes}; #[test] fn can_split_bytes() { let (high, low) = split_bytes(0xea14); assert_eq!(high, 0xea); assert_eq!(low, 0x14); } #[test] fn can_concat_bytes() { let low = 0x14; let high = 0xea; assert_eq!(concat_bytes(high, low), 0xea14); } }
#[doc = "Register `CCCSR` reader"] pub type R = crate::R<CCCSR_SPEC>; #[doc = "Register `CCCSR` writer"] pub type W = crate::W<CCCSR_SPEC>; #[doc = "Field `EN` reader - enable"] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - enable"] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CS` reader - Code selection"] pub type CS_R = crate::BitReader; #[doc = "Field `CS` writer - Code selection"] pub type CS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `READY` reader - Compensation cell ready flag"] pub type READY_R = crate::BitReader; #[doc = "Field `READY` writer - Compensation cell ready flag"] pub type READY_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSLV` reader - High-speed at low-voltage"] pub type HSLV_R = crate::BitReader; #[doc = "Field `HSLV` writer - High-speed at low-voltage"] pub type HSLV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - enable"] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Code selection"] #[inline(always)] pub fn cs(&self) -> CS_R { CS_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 8 - Compensation cell ready flag"] #[inline(always)] pub fn ready(&self) -> READY_R { READY_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 16 - High-speed at low-voltage"] #[inline(always)] pub fn hslv(&self) -> HSLV_R { HSLV_R::new(((self.bits >> 16) & 1) != 0) } } impl W { #[doc = "Bit 0 - enable"] #[inline(always)] #[must_use] pub fn en(&mut self) -> EN_W<CCCSR_SPEC, 0> { EN_W::new(self) } #[doc = "Bit 1 - Code selection"] #[inline(always)] #[must_use] pub fn cs(&mut self) -> CS_W<CCCSR_SPEC, 1> { CS_W::new(self) } #[doc = "Bit 8 - Compensation cell ready flag"] #[inline(always)] #[must_use] pub fn ready(&mut self) -> READY_W<CCCSR_SPEC, 8> { READY_W::new(self) } #[doc = "Bit 16 - High-speed at low-voltage"] #[inline(always)] #[must_use] pub fn hslv(&mut self) -> HSLV_W<CCCSR_SPEC, 16> { HSLV_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 = "compensation cell control/status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cccsr::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 [`cccsr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CCCSR_SPEC; impl crate::RegisterSpec for CCCSR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cccsr::R`](R) reader structure"] impl crate::Readable for CCCSR_SPEC {} #[doc = "`write(|w| ..)` method takes [`cccsr::W`](W) writer structure"] impl crate::Writable for CCCSR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CCCSR to value 0"] impl crate::Resettable for CCCSR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use super::{ error::{ ErrorMsg, MsgType::{self, *}, }, token::{self, ByteValue, Token, Value}, }; use codespan_reporting::{ diagnostic::{Diagnostic, Label}, files::SimpleFiles, term, }; use std::{ fmt, iter::Peekable, num, result, str::{self, CharIndices}, }; #[cfg(feature = "std")] use std::{borrow::Cow, string}; #[cfg(not(feature = "std"))] use alloc::{ borrow::Cow, string::{self, String, ToString}, vec::Vec, }; use lexical_core as lexical; #[cfg(target_arch = "wasm32")] use serde::Serialize; /// Alias for `Result` with an error of type `cddl::LexerError` pub type Result<T> = result::Result<T, Error>; /// Lexer position #[cfg_attr(target_arch = "wasm32", derive(Serialize))] #[derive(Debug, Copy, Clone)] pub struct Position { /// Line number pub line: usize, /// Column number pub column: usize, /// Token begin and end index range pub range: (usize, usize), /// Lexer index pub index: usize, } impl Default for Position { fn default() -> Self { Position { line: 1, column: 1, range: (0, 0), index: 0, } } } /// Lexer error #[derive(Debug)] pub struct Error { /// Error type pub error_type: LexerErrorType, input: String, position: Position, } /// Various error types emitted by the lexer #[derive(Debug)] pub enum LexerErrorType { /// CDDL lexing syntax error LEXER(MsgType), /// UTF-8 parsing error UTF8(string::FromUtf8Error), /// Byte string not properly encoded as base 16 BASE16(String), /// Byte string not properly encoded as base 64 BASE64(String), /// Error parsing integer PARSEINT(num::ParseIntError), /// Error parsing float PARSEFLOAT(lexical::Error), /// Error parsing hexfloat PARSEHEXF(hexf_parse::ParseHexfError), } #[cfg(feature = "std")] impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut files = SimpleFiles::new(); let file_id = files.add("input", self.input.as_str()); let config = term::Config::default(); let mut buffer = Vec::new(); let mut writer = term::termcolor::NoColor::new(&mut buffer); match &self.error_type { LexerErrorType::LEXER(le) => { let diagnostic = Diagnostic::error() .with_message("lexer error") .with_labels(vec![Label::primary( file_id, self.position.range.0..self.position.range.1, ) .with_message(ErrorMsg::from(*le).to_string())]); term::emit(&mut writer, &config, &files, &diagnostic).map_err(|_| fmt::Error)?; write!(f, "{}", String::from_utf8(buffer).map_err(|_| fmt::Error)?) } LexerErrorType::UTF8(utf8e) => { let diagnostic = Diagnostic::error() .with_message("lexer error") .with_labels(vec![Label::primary( file_id, self.position.range.0..self.position.range.1, ) .with_message(utf8e.to_string())]); term::emit(&mut writer, &config, &files, &diagnostic).map_err(|_| fmt::Error)?; write!(f, "{}", String::from_utf8(buffer).map_err(|_| fmt::Error)?) } LexerErrorType::BASE16(b16e) => { let diagnostic = Diagnostic::error() .with_message("lexer error") .with_labels(vec![Label::primary( file_id, self.position.range.0..self.position.range.1, ) .with_message(b16e.to_string())]); term::emit(&mut writer, &config, &files, &diagnostic).map_err(|_| fmt::Error)?; write!(f, "{}", String::from_utf8(buffer).map_err(|_| fmt::Error)?) } LexerErrorType::BASE64(b64e) => { let diagnostic = Diagnostic::error() .with_message("lexer error") .with_labels(vec![Label::primary( file_id, self.position.range.0..self.position.range.1, ) .with_message(b64e.to_string())]); term::emit(&mut writer, &config, &files, &diagnostic).map_err(|_| fmt::Error)?; write!(f, "{}", String::from_utf8(buffer).map_err(|_| fmt::Error)?) } LexerErrorType::PARSEINT(pie) => { let diagnostic = Diagnostic::error() .with_message("lexer error") .with_labels(vec![Label::primary( file_id, self.position.range.0..self.position.range.1, ) .with_message(pie.to_string())]); term::emit(&mut writer, &config, &files, &diagnostic).map_err(|_| fmt::Error)?; write!(f, "{}", String::from_utf8(buffer).map_err(|_| fmt::Error)?) } LexerErrorType::PARSEFLOAT(pfe) => { let diagnostic = Diagnostic::error() .with_message("lexer error") .with_labels(vec![Label::primary( file_id, self.position.range.0..self.position.range.1, ) .with_message(format!("{:#?}", pfe))]); term::emit(&mut writer, &config, &files, &diagnostic).map_err(|_| fmt::Error)?; write!(f, "{}", String::from_utf8(buffer).map_err(|_| fmt::Error)?) } LexerErrorType::PARSEHEXF(phf) => { let diagnostic = Diagnostic::error() .with_message("lexer error") .with_labels(vec![Label::primary( file_id, self.position.range.0..self.position.range.1, ) .with_message(format!("{:#?}", phf))]); term::emit(&mut writer, &config, &files, &diagnostic).map_err(|_| fmt::Error)?; write!(f, "{}", String::from_utf8(buffer).map_err(|_| fmt::Error)?) } } } } impl From<(&str, Position, MsgType)> for Error { fn from(e: (&str, Position, MsgType)) -> Self { Error { error_type: LexerErrorType::LEXER(e.2), input: e.0.to_string(), position: e.1, } } } impl From<(&str, Position, string::FromUtf8Error)> for Error { fn from(e: (&str, Position, string::FromUtf8Error)) -> Self { Error { error_type: LexerErrorType::UTF8(e.2), input: e.0.to_string(), position: e.1, } } } impl From<(&str, Position, base16::DecodeError)> for Error { fn from(e: (&str, Position, base16::DecodeError)) -> Self { Error { error_type: LexerErrorType::BASE16(e.2.to_string()), input: e.0.to_string(), position: e.1, } } } impl From<(&str, Position, data_encoding::DecodeError)> for Error { fn from(e: (&str, Position, data_encoding::DecodeError)) -> Self { Error { error_type: LexerErrorType::BASE64(e.2.to_string()), input: e.0.to_string(), position: e.1, } } } impl From<(&str, Position, num::ParseIntError)> for Error { fn from(e: (&str, Position, num::ParseIntError)) -> Self { Error { error_type: LexerErrorType::PARSEINT(e.2), input: e.0.to_string(), position: e.1, } } } impl From<(&str, Position, lexical::Error)> for Error { fn from(e: (&str, Position, lexical::Error)) -> Self { Error { error_type: LexerErrorType::PARSEFLOAT(e.2), input: e.0.to_string(), position: e.1, } } } impl From<(&str, Position, hexf_parse::ParseHexfError)> for Error { fn from(e: (&str, Position, hexf_parse::ParseHexfError)) -> Self { Error { error_type: LexerErrorType::PARSEHEXF(e.2), input: e.0.to_string(), position: e.1, } } } /// Lexer which holds a byte slice and iterator over the byte slice #[derive(Debug)] pub struct Lexer<'a> { /// CDDL input string pub str_input: &'a str, // TODO: Remove duplicate iterator in favor of multipeek input: Peekable<CharIndices<'a>>, multipeek: itertools::MultiPeek<CharIndices<'a>>, /// Lexer position in input pub position: Position, } /// Iterator over a lexer pub struct LexerIter<'a> { l: Lexer<'a>, } /// Iterated lexer token item pub type Item<'a> = std::result::Result<(Position, Token<'a>), Error>; impl<'a> Iterator for LexerIter<'a> { type Item = Item<'a>; fn next(&mut self) -> Option<Self::Item> { let next_token = self.l.next_token(); Some(next_token) } } /// Creates a `Lexer` from a string slice /// /// # Arguments /// /// `str_input` - String slice with input pub fn lexer_from_str(str_input: &str) -> Lexer { Lexer::new(str_input) } impl<'a> Lexer<'a> { /// Creates a new `Lexer` from a given `&str` input pub fn new(str_input: &'a str) -> Lexer<'a> { Lexer { str_input, input: str_input.char_indices().peekable(), multipeek: itertools::multipeek(str_input.char_indices()), position: Position { line: 1, column: 1, range: (0, 0), index: 0, }, } } /// Creates a Lexer from a byte slice pub fn from_slice(input: &[u8]) -> Lexer { let str_input = std::str::from_utf8(input).unwrap(); Lexer::new(str_input) } /// Returns an iterator over a lexer pub fn iter(self) -> LexerIter<'a> { LexerIter { l: self } } fn read_char(&mut self) -> Result<(usize, char)> { self.multipeek.next(); self .input .next() .map(|c| { if c.1 == '\n' { self.position.line += 1; self.position.column = 1; } else { self.position.column += 1; } if !c.1.is_ascii_whitespace() { self.position.index = c.0; } c }) .ok_or_else(|| (self.str_input, self.position, UnableToAdvanceToken).into()) } /// Advances the index of the str iterator over the input and returns a /// `Token` pub fn next_token(&mut self) -> Result<(Position, Token<'a>)> { self.skip_whitespace()?; let token_offset = self.position.index; if let Ok(c) = self.read_char() { match c { (_, '\n') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::NEWLINE)) } (_, '=') => match self.peek_char() { Some(&c) if c.1 == '>' => { let _ = self.read_char()?; self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::ARROWMAP)) } _ => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::ASSIGN)) } }, (_, '+') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::ONEORMORE)) } (_, '?') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::OPTIONAL)) } (_, '*') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::ASTERISK)) } (_, '(') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::LPAREN)) } (_, ')') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::RPAREN)) } (_, '[') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::LBRACKET)) } (_, ']') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::RBRACKET)) } (_, '<') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::LANGLEBRACKET)) } (idx, '"') => { let tv = self.read_text_value(idx)?; self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::VALUE(Value::TEXT(tv.into())))) } (_, '{') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::LBRACE)) } (_, '}') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::RBRACE)) } (_, ',') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::COMMA)) } (idx, ';') => { let comment = self.read_comment(idx)?; self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::COMMENT(comment))) } (_, ':') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::COLON)) } (_, '^') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::CUT)) } (_, '&') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::GTOCHOICE)) } (_, '>') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::RANGLEBRACKET)) } (_, '~') => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::UNWRAP)) } (_, '/') => match self.peek_char() { Some(&c) if c.1 == '/' => { let _ = self.read_char()?; match self.peek_char() { Some(&c) if c.1 == '=' => { let _ = self.read_char()?; self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::GCHOICEALT)) } _ => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::GCHOICE)) } } } Some(&c) if c.1 == '=' => { let _ = self.read_char()?; self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::TCHOICEALT)) } _ => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::TCHOICE)) } }, (_, '#') => match self.peek_char() { Some(&c) if is_digit(c.1) => { let (idx, _) = self.read_char()?; let t = self.read_number(idx)?.1; match self.peek_char() { Some(&c) if c.1 == '.' => { let _ = self.read_char()?; let (idx, _) = self.read_char()?; self.position.range = (token_offset, self.position.index + 1); #[cfg(not(target_arch = "wasm32"))] { Ok(( self.position, Token::TAG(Some(t as u8), Some(self.read_number(idx)?.1)), )) } #[cfg(target_arch = "wasm32")] { Ok(( self.position, Token::TAG(Some(t as u8), Some(self.read_number(idx)?.1 as usize)), )) } } _ => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::TAG(Some(t as u8), None))) } } } _ => { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::TAG(None, None))) } }, (_, '\'') => { let (idx, _) = self.read_char()?; let bsv = self.read_byte_string(idx)?; self.position.range = (token_offset, self.position.index + 1); Ok(( self.position, Token::VALUE(Value::BYTE(ByteValue::UTF8(bsv.as_bytes().into()))), )) } (idx, '.') => { if let Some(&c) = self.peek_char() { if c.1 == '.' { // Rangeop let _ = self.read_char()?; if let Some(&c) = self.peek_char() { if c.1 == '.' { let _ = self.read_char()?; self.position.range = (token_offset, self.position.index + 1); return Ok((self.position, Token::RANGEOP(false))); } } self.position.range = (token_offset, self.position.index + 1); return Ok((self.position, Token::RANGEOP(true))); } else if is_ealpha(c.1) { // Controlop let ctrlop = token::lookup_control_from_str(self.read_identifier(idx)?).ok_or_else(|| { self.position.range = (token_offset, self.position.index + 1); Error::from((self.str_input, self.position, InvalidControlOperator)) })?; self.position.range = (token_offset, self.position.index + 1); return Ok((self.position, Token::ControlOperator(ctrlop))); } } self.position.range = (token_offset, self.position.index + 1); Err((self.str_input, self.position, InvalidCharacter).into()) } (idx, ch) => { if is_ealpha(ch) { // base 16 (hex) encoded byte string if ch == 'h' { if let Some(&c) = self.peek_char() { if c.1 == '\'' { let _ = self.read_char()?; let (idx, _) = self.read_char()?; // Ensure that the byte string has been properly encoded. let b = self.read_prefixed_byte_string(idx)?; let mut buf = [0u8; 1024]; return base16::decode_slice(&b[..], &mut buf) .map_err(|e| (self.str_input, self.position, e).into()) .map(|_| { self.position.range = (token_offset, self.position.index + 1); (self.position, Token::VALUE(Value::BYTE(ByteValue::B16(b)))) }); } } } // base 64 encoded byte string if ch == 'b' { if let Some(&c) = self.peek_char() { if c.1 == '6' { let _ = self.read_char()?; if let Some(&c) = self.peek_char() { if c.1 == '4' { let _ = self.read_char()?; if let Some(&c) = self.peek_char() { if c.1 == '\'' { let _ = self.read_char()?; let (idx, _) = self.read_char()?; // Ensure that the byte string has been properly // encoded let bs = self.read_prefixed_byte_string(idx)?; let mut buf = vec![0; data_encoding::BASE64.decode_len(bs.len()).unwrap()]; return data_encoding::BASE64URL .decode_mut(&bs, &mut buf) .map_err(|e| (self.str_input, self.position, e.error).into()) .map(|_| { self.position.range = (token_offset, self.position.index + 1); (self.position, Token::VALUE(Value::BYTE(ByteValue::B64(bs)))) }); } } } } } } } let ident = token::lookup_ident(self.read_identifier(idx)?); self.position.range = (token_offset, self.position.index + 1); return Ok((self.position, ident)); } else if is_digit(ch) || ch == '-' { let number = self.read_int_or_float(idx)?; self.position.range = (token_offset, self.position.index + 1); return Ok((self.position, number)); } self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::ILLEGAL(&self.str_input[idx..=idx]))) } } } else { self.position.range = (token_offset, self.position.index + 1); Ok((self.position, Token::EOF)) } } fn read_identifier(&mut self, idx: usize) -> Result<&'a str> { let mut end_idx = idx; while let Some(&c) = self.peek_char() { if is_ealpha(c.1) || is_digit(c.1) || c.1 == '.' || c.1 == '-' { match c.1 { // Check for range '.' => { end_idx = self.read_char()?.0; if let Some(&c) = self.peek_char() { if c.1 == '\u{0020}' { return Ok(&self.str_input[idx..end_idx]); } } } _ => end_idx = self.read_char()?.0, } } else { break; } } Ok(&self.str_input[idx..=end_idx]) } fn read_text_value(&mut self, idx: usize) -> Result<&'a str> { while let Some(&(_, ch)) = self.peek_char() { match ch { // SCHAR '\x20'..='\x21' | '\x23'..='\x5b' | '\x5d'..='\x7e' | '\u{0080}'..='\u{10FFFD}' => { let _ = self.read_char()?; } // SESC '\\' => { let _ = self.read_char(); if let Some(&(_, ch)) = self.peek_char() { match ch { '\x20'..='\x7e' | '\u{0080}'..='\u{10FFFD}' => { let _ = self.read_char()?; } _ => return Err((self.str_input, self.position, InvalidEscapeCharacter).into()), } } } // Closing " '\x22' => { return Ok(&self.str_input[idx + 1..self.read_char()?.0]); } _ => { return Err( ( self.str_input, self.position, InvalidTextStringLiteralCharacter, ) .into(), ) } } } Err((self.str_input, self.position, EmptyTextStringLiteral).into()) } fn read_byte_string(&mut self, idx: usize) -> Result<&'a str> { while let Some(&(_, ch)) = self.peek_char() { match ch { // BCHAR '\x20'..='\x26' | '\x28'..='\x5b' | '\x5d'..='\x7e' | '\u{0080}'..='\u{10FFFD}' => { let _ = self.read_char(); } // SESC '\\' => { let _ = self.read_char(); if let Some(&(_, ch)) = self.peek_char() { match ch { '\x20'..='\x7e' | '\u{0080}'..='\u{10FFFD}' => { let _ = self.read_char()?; } _ => return Err((self.str_input, self.position, InvalidEscapeCharacter).into()), } } } // Closing ' '\x27' => return Ok(&self.str_input[idx..self.read_char()?.0]), _ => { if ch.is_ascii_whitespace() { let _ = self.read_char()?; } else { return Err( ( self.str_input, self.position, InvalidByteStringLiteralCharacter, ) .into(), ); } } } } Err((self.str_input, self.position, EmptyByteStringLiteral).into()) } fn read_prefixed_byte_string(&mut self, idx: usize) -> Result<Cow<'a, [u8]>> { let mut has_whitespace = false; while let Some(&(_, ch)) = self.peek_char() { match ch { // BCHAR '\x20'..='\x26' | '\x28'..='\x5b' | '\x5d'..='\x7e' | '\u{0080}'..='\u{10FFFD}' => { let _ = self.read_char(); } // SESC '\\' => { let _ = self.read_char(); if let Some(&(_, ch)) = self.peek_char() { match ch { '\x20'..='\x7e' | '\u{0080}'..='\u{10FFFD}' => { let _ = self.read_char()?; } _ => return Err((self.str_input, self.position, InvalidEscapeCharacter).into()), } } } // Closing ' '\x27' => { // Whitespace is ignored for prefixed byte strings and requires allocation if has_whitespace { return Ok( self.str_input[idx..self.read_char()?.0] .to_string() .replace(' ', "") .into_bytes() .into(), ); } return Ok(self.str_input[idx..self.read_char()?.0].as_bytes().into()); } // CRLF _ => { // TODO: if user forgets closing "'", but another "'" is found later // in the string, the error emitted here can be confusing if ch.is_ascii_whitespace() { has_whitespace = true; let _ = self.read_char()?; } else { return Err( ( self.str_input, self.position, InvalidByteStringLiteralCharacter, ) .into(), ); } } } } Err((self.str_input, self.position, EmptyByteStringLiteral).into()) } fn read_comment(&mut self, idx: usize) -> Result<&'a str> { let mut comment_char = (idx, char::default()); while let Some(&(_, ch)) = self.peek_char() { if ch != '\x0a' && ch != '\x0d' { comment_char = self.read_char()?; } else { return Ok(&self.str_input[idx + 1..self.read_char()?.0]); } } Ok(&self.str_input[idx + 1..=comment_char.0]) } fn skip_whitespace(&mut self) -> Result<()> { while let Some(&(idx, ch)) = self.peek_char() { if ch == '\n' { self.position.index = idx; return Ok(()); } if ch.is_whitespace() { let _ = self.read_char()?; } else { self.position.index = idx; break; } } Ok(()) } fn read_int_or_float(&mut self, mut idx: usize) -> Result<Token<'a>> { let mut is_signed = false; let mut signed_idx = 0; if self.str_input.as_bytes()[idx] == b'-' { is_signed = true; signed_idx = idx; idx = self.read_char()?.0; } let (mut end_idx, i) = self.read_number(idx)?; if let Some(&c) = self.multipeek.peek() { let mut hexfloat = false; if i == 0 && c.0 - idx == 1 && c.1 == 'x' { let _ = self.read_char()?; if self.multipeek.peek().is_none() { return Err((self.str_input, self.position, InvalidHexFloat).into()); } let (idx, _) = self.read_char()?; let _ = self.read_hexdigit(idx)?; hexfloat = true; } if c.1 == '.' || c.1 == 'x' { if c.1 == 'x' { let _ = self.read_char()?; } if let Some(&c) = self.multipeek.peek() { if hexfloat && is_hexdigit(c.1) { let _ = self.read_char()?; let _ = self.read_hexdigit(c.0)?; if self.read_char()?.1 != 'p' { return Err((self.str_input, self.position, InvalidHexFloat).into()); } let (exponent_idx, _) = self.read_char()?; end_idx = self.read_exponent(exponent_idx)?.0; if is_signed { return Ok(Token::VALUE(Value::FLOAT( hexf_parse::parse_hexf64(&self.str_input[signed_idx..=end_idx], false) .map_err(|e| Error::from((self.str_input, self.position, e)))?, ))); } return Ok(Token::VALUE(Value::FLOAT( hexf_parse::parse_hexf64(&self.str_input[idx..=end_idx], false) .map_err(|e| Error::from((self.str_input, self.position, e)))?, ))); } if is_digit(c.1) { let _ = self.read_char()?; end_idx = self.read_number(c.0)?.0; if let Some(&(_, 'e')) = self.peek_char() { let _ = self.read_char()?; let (exponent_idx, _) = self.read_char()?; end_idx = self.read_exponent(exponent_idx)?.0; } if is_signed { return Ok(Token::VALUE(Value::FLOAT( lexical::parse::<f64>(self.str_input[signed_idx..=end_idx].as_bytes()) .map_err(|e| Error::from((self.str_input, self.position, e)))?, ))); } return Ok(Token::VALUE(Value::FLOAT( lexical::parse::<f64>(self.str_input[idx..=end_idx].as_bytes()) .map_err(|e| Error::from((self.str_input, self.position, e)))?, ))); } } } } let mut is_exponent = false; if let Some(&(_, 'e')) = self.peek_char() { let _ = self.read_char()?; let (exponent_idx, _) = self.read_char()?; end_idx = self.read_exponent(exponent_idx)?.0; is_exponent = true; } if is_signed { if is_exponent { return Ok(Token::VALUE(Value::INT( lexical::parse::<f64>(self.str_input[signed_idx..=end_idx].as_bytes()) .map_err(|e| Error::from((self.str_input, self.position, e)))? as isize, ))); } else { return Ok(Token::VALUE(Value::INT( self.str_input[signed_idx..=end_idx] .parse() .map_err(|e| Error::from((self.str_input, self.position, e)))?, ))); } } if is_exponent { return Ok(Token::VALUE(Value::UINT( lexical::parse::<f64>(self.str_input[idx..=end_idx].as_bytes()) .map_err(|e| Error::from((self.str_input, self.position, e)))? as usize, ))); } #[cfg(not(target_arch = "wasm32"))] { Ok(Token::VALUE(Value::UINT(i))) } #[cfg(target_arch = "wasm32")] { Ok(Token::VALUE(Value::UINT(i as usize))) } } #[cfg(not(target_arch = "wasm32"))] fn read_number(&mut self, idx: usize) -> Result<(usize, usize)> { let mut end_index = idx; while let Some(&c) = self.peek_char() { if is_digit(c.1) { let (ei, _) = self.read_char()?; end_index = ei; } else { break; } } Ok(( end_index, self.str_input[idx..=end_index] .parse() .map_err(|e| Error::from((self.str_input, self.position, e)))?, )) } #[cfg(target_arch = "wasm32")] fn read_number(&mut self, idx: usize) -> Result<(usize, u64)> { let mut end_index = idx; while let Some(&c) = self.peek_char() { if is_digit(c.1) { let (ei, _) = self.read_char()?; end_index = ei; } else { break; } } Ok(( end_index, self.str_input[idx..=end_index] .parse() .map_err(|e| Error::from((self.str_input, self.position, e)))?, )) } fn read_exponent(&mut self, idx: usize) -> Result<(usize, &str)> { let mut end_index = idx; if let Some(&c) = self.peek_char() { if c.1 != '-' && c.1 != '+' && !is_digit(c.1) { return Err((self.str_input, self.position, InvalidExponent).into()); } } while let Some(&c) = self.peek_char() { if is_digit(c.1) { let (ei, _) = self.read_char()?; end_index = ei; } else { break; } } Ok((end_index, &self.str_input[idx..=end_index])) } fn read_hexdigit(&mut self, idx: usize) -> Result<(usize, &str)> { let mut end_index = idx; while let Some(&c) = self.peek_char() { if is_hexdigit(c.1) { let (ei, _) = self.read_char()?; end_index = ei; } else { break; } } Ok((end_index, &self.str_input[idx..=end_index])) } fn peek_char(&mut self) -> Option<&(usize, char)> { self.input.peek() } } fn is_ealpha(ch: char) -> bool { ch.is_alphabetic() || ch == '@' || ch == '_' || ch == '$' } fn is_digit(ch: char) -> bool { ch.is_ascii_digit() } fn is_hexdigit(ch: char) -> bool { ch.is_ascii_hexdigit() } #[cfg(test)] mod tests { use super::{ super::token::{ControlOperator, SocketPlug, Token::*}, *, }; use pretty_assertions::assert_eq; #[cfg(not(feature = "std"))] use super::super::alloc::string::ToString; use indoc::indoc; #[test] fn verify_next_token() -> Result<()> { let input = indoc!( r#" ; this is a comment ; this is another comment mynumber = 10.5 mytag = #6.1234(tstr) myfirstrule = "myotherrule" mybytestring = 'hello there' mybase16rule = h'68656c6c6f20776f726c64' mybase64rule = b64'aGVsbG8gd29ybGQ=' mysecondrule = mynumber .. 100.5 myintrule = -10 mysignedfloat = -10.5 myintrange = -10..10 mycontrol = mynumber .gt 0 @terminal-color = basecolors / othercolors ; an inline comment messages = message<"reboot", "now"> address = { delivery } delivery = ( street: tstr, ? number ^ => uint, city // po-box: uint, city // per-pickup: true ) city = ( name: tstr zip-code: uint 1*3 $$tcp-option, ) ; test"# ); let expected_tok = [ (COMMENT(" this is a comment"), "; this is a comment"), ( COMMENT(" this is another comment"), "; this is another comment", ), (NEWLINE, ""), (IDENT("mynumber", None), "mynumber"), (ASSIGN, "="), (VALUE(Value::FLOAT(10.5)), "10.5"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("mytag", None), "mytag"), (ASSIGN, "="), (TAG(Some(6), Some(1234)), "#6.1234"), (LPAREN, "("), (TSTR, "tstr"), (RPAREN, ")"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("myfirstrule", None), "myfirstrule"), (ASSIGN, "="), (VALUE(Value::TEXT("myotherrule".into())), "\"myotherrule\""), (NEWLINE, ""), (NEWLINE, ""), (IDENT("mybytestring", None), "mybytestring"), (ASSIGN, "="), ( VALUE(Value::BYTE(ByteValue::UTF8(b"hello there".as_ref().into()))), "'hello there'", ), (NEWLINE, ""), (NEWLINE, ""), (IDENT("mybase16rule", None), "mybase16rule"), (ASSIGN, "="), ( VALUE(Value::BYTE(ByteValue::B16( b"68656c6c6f20776f726c64".as_ref().into(), ))), "h'68656c6c6f20776f726c64'", ), (NEWLINE, ""), (NEWLINE, ""), (IDENT("mybase64rule", None), "mybase64rule"), (ASSIGN, "="), ( VALUE(Value::BYTE(ByteValue::B64( b"aGVsbG8gd29ybGQ=".as_ref().into(), ))), "b64'aGVsbG8gd29ybGQ='", ), (NEWLINE, ""), (NEWLINE, ""), (IDENT("mysecondrule", None), "mysecondrule"), (ASSIGN, "="), (IDENT("mynumber", None), "mynumber"), (RANGEOP(true), ".."), (VALUE(Value::FLOAT(100.5)), "100.5"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("myintrule", None), "myintrule"), (ASSIGN, "="), (VALUE(Value::INT(-10)), "-10"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("mysignedfloat", None), "mysignedfloat"), (ASSIGN, "="), (VALUE(Value::FLOAT(-10.5)), "-10.5"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("myintrange", None), "myintrange"), (ASSIGN, "="), (VALUE(Value::INT(-10)), "-10"), (RANGEOP(true), ".."), (VALUE(Value::UINT(10)), "10"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("mycontrol", None), "mycontrol"), (ASSIGN, "="), (IDENT("mynumber", None), "mynumber"), (ControlOperator(ControlOperator::GT), ".gt"), (VALUE(Value::UINT(0)), "0"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("@terminal-color", None), "@terminal-color"), (ASSIGN, "="), (IDENT("basecolors", None), "basecolors"), (TCHOICE, "/"), (IDENT("othercolors", None), "othercolors"), (COMMENT(" an inline comment"), "; an inline comment"), (NEWLINE, ""), (IDENT("messages", None), "messages"), (ASSIGN, "="), (IDENT("message", None), "message"), (LANGLEBRACKET, "<"), (VALUE(Value::TEXT("reboot".into())), "\"reboot\""), (COMMA, ","), (VALUE(Value::TEXT("now".into())), "\"now\""), (RANGLEBRACKET, ">"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("address", None), "address"), (ASSIGN, "="), (LBRACE, "{"), (IDENT("delivery", None), "delivery"), (RBRACE, "}"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("delivery", None), "delivery"), (ASSIGN, "="), (LPAREN, "("), (NEWLINE, ""), (IDENT("street", None), "street"), (COLON, ":"), (TSTR, "tstr"), (COMMA, ","), (OPTIONAL, "?"), (NUMBER, "number"), (CUT, "^"), (ARROWMAP, "=>"), (UINT, "uint"), (COMMA, ","), (IDENT("city", None), "city"), (GCHOICE, "//"), (NEWLINE, ""), (IDENT("po-box", None), "po-box"), (COLON, ":"), (UINT, "uint"), (COMMA, ","), (IDENT("city", None), "city"), (GCHOICE, "//"), (NEWLINE, ""), (IDENT("per-pickup", None), "per-pickup"), (COLON, ":"), (TRUE, "true"), (NEWLINE, ""), (RPAREN, ")"), (NEWLINE, ""), (NEWLINE, ""), (IDENT("city", None), "city"), (ASSIGN, "="), (LPAREN, "("), (NEWLINE, ""), (IDENT("name", None), "name"), (COLON, ":"), (TSTR, "tstr"), (NEWLINE, ""), (IDENT("zip-code", None), "zip-code"), (COLON, ":"), (UINT, "uint"), (NEWLINE, ""), (VALUE(Value::UINT(1)), "1"), (ASTERISK, "*"), (VALUE(Value::UINT(3)), "3"), (IDENT("tcp-option", Some(SocketPlug::GROUP)), "$$tcp-option"), (COMMA, ","), (NEWLINE, ""), (RPAREN, ")"), (COMMENT(" test"), "; test"), ]; let mut l = Lexer::new(input); for (expected_tok, literal) in expected_tok.iter() { let tok = l.next_token()?; assert_eq!((&tok.1, &*tok.1.to_string()), (expected_tok, *literal)) } Ok(()) } #[test] fn verify_controlop() -> Result<()> { let input = r#".size"#; let expected_tok = Token::ControlOperator(ControlOperator::SIZE); let mut l = Lexer::new(input); assert_eq!(expected_tok.to_string(), l.next_token()?.1.to_string()); Ok(()) } #[test] fn verify_range() -> Result<()> { let input = r#"-10.5..10.5"#; let mut l = Lexer::new(input); let expected_tokens = [ (VALUE(Value::FLOAT(-10.5)), "-10.5"), (RANGEOP(true), ".."), (VALUE(Value::FLOAT(10.5)), "10.5"), ]; for (expected_tok, literal) in expected_tokens.iter() { let tok = l.next_token()?; assert_eq!((expected_tok, *literal), (&tok.1, &*tok.1.to_string())) } Ok(()) } #[test] fn verify_multiline_byte_string() -> Result<()> { let input = r#"'test test'"#; let mut l = Lexer::new(input); let tok = l.next_token()?; assert_eq!( ( &VALUE(Value::BYTE(ByteValue::UTF8(Cow::Borrowed( b"test\n test" )))), "'test\n test'" ), (&tok.1, &*tok.1.to_string()) ); Ok(()) } #[test] fn verify_hexfloat() -> Result<()> { let input = r#"0x1.999999999999ap-4"#; let mut l = Lexer::new(input); let tok = l.next_token()?; assert_eq!( (&VALUE(Value::FLOAT(0.1)), "0.1"), (&tok.1, &*tok.1.to_string()) ); Ok(()) } #[test] fn verify_exponent() -> Result<()> { let input = r#"-100.7e-1"#; let mut l = Lexer::new(input); let tok = l.next_token()?; assert_eq!( (&VALUE(Value::FLOAT(-10.07)), "-10.07"), (&tok.1, &*tok.1.to_string()) ); Ok(()) } #[test] fn verify_lexer_diagnostic() -> Result<()> { let input = r#"myrule = number .asdf 10"#; let mut l = Lexer::new(input); l.next_token()?; l.next_token()?; l.next_token()?; match l.next_token() { Ok(_) => Ok(()), Err(e) => { #[cfg(feature = "std")] println!("{}", e); assert_eq!( e.to_string(), indoc!( r#" error: lexer error ┌─ input:1:17 │ 1 │ myrule = number .asdf 10 │ ^^^^^ invalid control operator "# ) ); Ok(()) } } } }
#[doc = "Reader of register IC_CLR_INTR"] pub type R = crate::R<u32, super::IC_CLR_INTR>; #[doc = "Reader of field `CLR_INTR`"] pub type CLR_INTR_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Read this register to clear the combined interrupt, all individual interrupts, and the IC_TX_ABRT_SOURCE register. This bit does not clear hardware clearable interrupts but software clearable interrupts. Refer to Bit 9 of the IC_TX_ABRT_SOURCE register for an exception to clearing IC_TX_ABRT_SOURCE.\\n\\n Reset value: 0x0"] #[inline(always)] pub fn clr_intr(&self) -> CLR_INTR_R { CLR_INTR_R::new((self.bits & 0x01) != 0) } }
use crate::messages::ChainId; use codec::{Decode, Encode}; use frame_support::weights::Weight; use frame_support::Parameter; use scale_info::TypeInfo; use sp_domains::DomainId; use sp_runtime::traits::Member; use sp_runtime::{sp_std, DispatchError, DispatchResult}; use sp_std::vec::Vec; /// Represents a particular endpoint in a given Execution environment. pub type EndpointId = u64; /// Endpoint as defined in the formal spec. /// Endpoint is an application that can send and receive messages from other chains. #[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] pub enum Endpoint { /// Id of the endpoint on a specific chain. Id(EndpointId), } /// Endpoint request or response payload. pub type EndpointPayload = Vec<u8>; /// Request sent by src_endpoint to dst_endpoint. #[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] pub struct EndpointRequest { pub src_endpoint: Endpoint, pub dst_endpoint: Endpoint, pub payload: EndpointPayload, } /// Response for the message request. pub type EndpointResponse = Result<EndpointPayload, DispatchError>; /// Sender provides abstraction on sending messages to other chains. pub trait Sender<AccountId> { /// Unique Id of the message between dst_chain and src_chain. type MessageId: Parameter + Member + Copy + Default; /// Sends a message to dst_chain_id. fn send_message( sender: &AccountId, dst_chain_id: ChainId, req: EndpointRequest, ) -> Result<Self::MessageId, DispatchError>; /// Only used in benchmark to prepare for a upcoming `send_message` call to /// ensure it will succeed. #[cfg(feature = "runtime-benchmarks")] fn unchecked_open_channel(dst_chain_id: ChainId) -> Result<(), DispatchError>; } /// Handler to /// - handle message request from other chains. /// - handle requested message responses from other chains. pub trait EndpointHandler<MessageId> { /// Triggered by pallet-messenger when a new inbox message is received and bound for this handler. fn message( &self, src_chain_id: ChainId, message_id: MessageId, req: EndpointRequest, ) -> EndpointResponse; /// Return the maximal possible consume weight of `message` fn message_weight(&self) -> Weight; /// Triggered by pallet-messenger when a response for a request is received from dst_chain_id. fn message_response( &self, dst_chain_id: ChainId, message_id: MessageId, req: EndpointRequest, resp: EndpointResponse, ) -> DispatchResult; /// Return the maximal possible consume weight of `message_response` fn message_response_weight(&self) -> Weight; } #[cfg(feature = "runtime-benchmarks")] pub struct BenchmarkEndpointHandler; #[cfg(feature = "runtime-benchmarks")] impl<MessageId> EndpointHandler<MessageId> for BenchmarkEndpointHandler { fn message( &self, _src_chain_id: ChainId, _message_id: MessageId, _req: EndpointRequest, ) -> EndpointResponse { Ok(Vec::new()) } fn message_weight(&self) -> Weight { Weight::zero() } fn message_response( &self, _dst_chain_id: ChainId, _message_id: MessageId, _req: EndpointRequest, _resp: EndpointResponse, ) -> DispatchResult { Ok(()) } fn message_response_weight(&self) -> Weight { Weight::zero() } } /// Trait that can provide info for a given Domain. pub trait DomainInfo<Number, Hash, StateRoot> { /// Returns the best known number of a given Domain. fn domain_best_number(domain_id: DomainId) -> Option<Number>; /// Returns the known state root of a specific block. fn domain_state_root(domain_id: DomainId, number: Number, hash: Hash) -> Option<StateRoot>; } impl<Number, Hash, StateRoot> DomainInfo<Number, Hash, StateRoot> for () { fn domain_best_number(_domain_id: DomainId) -> Option<Number> { None } fn domain_state_root(_domain_id: DomainId, _number: Number, _hash: Hash) -> Option<StateRoot> { None } }
use std::path::Path; use std::io::stdin; use inkwell as llvm; use inkwell::targets::{Target, TargetTriple, TargetMachine, RelocMode, CodeModel, InitializationConfig}; use inkwell::OptimizationLevel; use std::process::Command; use diesel_lib::parser::{ lexer::tokens, Parser }; mod compiler; use clap::{App, Arg}; fn main() { let args = App::new("Diesel Compiler") .about("Compiles Diesel Files") .arg(Arg::with_name("output") .short("o") .long("output") .value_name("FILE") .help("Sets the output file") .required(true) .takes_value(true) ) .arg(Arg::with_name("emit-ir") .long("emit-ir") .help("Emit LLVM IR") ) .arg(Arg::with_name("emit-asm") .long("emit-asm") .help("Emit assembly") ) .arg(Arg::with_name("input") .required(true) .value_name("INPUT") .help("Input source files") .required(true) .multiple(true) .index(1) ) .get_matches(); let context = llvm::context::Context::create(); Target::initialize_aarch64(&InitializationConfig::default()); let triple = TargetMachine::get_default_triple(); let target = Target::from_triple(&triple).unwrap(); let target_machine = target.create_target_machine( &triple, "", "", OptimizationLevel::None, RelocMode::Default, CodeModel::Default ).unwrap(); let mut obj_files = Vec::new(); for src in args.values_of("input").unwrap() { let input = Path::new(src); let output = input.with_extension("o"); compiler::compile_module(&context, &target_machine, input, &output); obj_files.push(output); } let output = args.value_of("output").unwrap(); let mut args = vec!["-o", output]; let mut obj_strs = obj_files.iter().map(|s| s.to_str().unwrap()).collect::<Vec<&str>>(); args.append(&mut obj_strs); Command::new("clang") .args(args) .spawn() .expect("Failed to link"); }
use cgmath::prelude::*; use cgmath::Point3; #[derive(Clone, Copy, Debug)] pub struct BoundingBox { pub min: Point3<f32>, pub max: Point3<f32>, } impl BoundingBox { pub fn neg_infinity_bounds() -> Self { Self { min: [std::f32::INFINITY; 3].into(), max: [std::f32::NEG_INFINITY; 3].into(), } } pub fn pos_infinity_bounds() -> Self { Self { min: [std::f32::NEG_INFINITY; 3].into(), max: [std::f32::INFINITY; 3].into(), } } pub fn surface_area(&self) -> f32 { let w = self.max.x - self.min.x; let h = self.max.y - self.min.y; let d = self.max.z - self.min.z; 2.0 * (w + h + d) } pub fn transform(&self, xfm: impl Transform<Point3<f32>>) -> Self { let vertices = [ Point3::new(self.min.x, self.min.y, self.min.z), Point3::new(self.min.x, self.min.y, self.max.z), Point3::new(self.min.x, self.max.y, self.min.z), Point3::new(self.min.x, self.max.y, self.max.z), Point3::new(self.max.x, self.min.y, self.min.z), Point3::new(self.max.x, self.min.y, self.max.z), Point3::new(self.max.x, self.max.y, self.min.z), Point3::new(self.max.x, self.max.y, self.max.z), ]; let mut bbox = BoundingBox::neg_infinity_bounds(); for vertex in &vertices { bbox.extend(&Self::from_point(xfm.transform_point(*vertex))); } bbox } pub fn from_point(point: Point3<f32>) -> Self { Self { min: point, max: point, } } pub fn extend(&mut self, other: &BoundingBox) { self.min.x = self.min.x.min(other.min.x); self.min.y = self.min.y.min(other.min.y); self.min.z = self.min.z.min(other.min.z); self.max.x = self.max.x.max(other.max.x); self.max.y = self.max.y.max(other.max.y); self.max.z = self.max.z.max(other.max.z); } pub fn intersect(&mut self, other: &BoundingBox) { self.min.x = self.min.x.max(other.min.x); self.min.y = self.min.y.max(other.min.y); self.min.z = self.min.z.max(other.min.z); self.max.x = self.max.x.min(other.max.x); self.max.y = self.max.y.min(other.max.y); self.max.z = self.max.z.min(other.max.z); } pub fn intersection(boxes: impl IntoIterator<Item = Self>) -> Self { let max = Point3::new(std::f32::INFINITY, std::f32::INFINITY, std::f32::INFINITY); let min = max * -1.0; // this ensures that any min/max operation updates the bbox let mut extents = Self { max, min }; for bbox in boxes.into_iter() { extents.min.x = extents.min.x.max(bbox.min.x); extents.min.y = extents.min.y.max(bbox.min.y); extents.min.z = extents.min.z.max(bbox.min.z); extents.max.x = extents.max.x.min(bbox.max.x); extents.max.y = extents.max.y.min(bbox.max.y); extents.max.z = extents.max.z.min(bbox.max.z); } extents } pub fn from_extents(boxes: impl IntoIterator<Item = Self>) -> Self { let mut extents = Self::neg_infinity_bounds(); for bbox in boxes.into_iter() { extents.min.x = extents.min.x.min(bbox.min.x); extents.max.x = extents.max.x.max(bbox.max.x); extents.min.y = extents.min.y.min(bbox.min.y); extents.max.y = extents.max.y.max(bbox.max.y); extents.min.z = extents.min.z.min(bbox.min.z); extents.max.z = extents.max.z.max(bbox.max.z); } extents } }
#[rustversion::nightly] const NIGHTLY: bool = true; #[rustversion::not(nightly)] const NIGHTLY: bool = false; fn main() { // Set cfg flags depending on release channel if NIGHTLY { println!("cargo:rustc-cfg=nightly"); } }
use crate::{error::ApllodbResult, validation_helper::short_name::ShortName}; use serde::{Deserialize, Serialize}; /// Database name. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub struct DatabaseName(ShortName); impl DatabaseName { /// Constructor. /// /// # Failures /// - [NameTooLong](crate::SqlState::NameTooLong) when: /// - `name` length is longer than 64 (counted as UTF-8 character). pub fn new(name: impl ToString) -> ApllodbResult<Self> { let sn = ShortName::new(name)?; Ok(Self(sn)) } /// database name pub fn as_str(&self) -> &str { self.0.as_str() } }
//! provides init and shutdown functions allowing for entering //! and gracefully exiting alternate screen where program can //! happily perform its shenanigans. //! init function sets up panic hook that will call shutdown() //! preventing messing up the terminal if the program were to panic! //! //! # Usage //! ```no_run //! use smokey::utils::termprep; //! termprep::init(); //! // main tui app loop //! termprep::shutdown(); //! ``` use std::io::stdout; use std::panic; use crossterm::{ cursor, execute, style::Print, terminal::{ disable_raw_mode, enable_raw_mode, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, }, }; /// enters alt screen and sets up panic hook that prevents /// messing up the user terminal if this program were to panic pub fn init() { init_terminal(); set_panic_hook(); } /// performs all nesccesarry actions to leave alt screen /// and return to terminal state before the program was run pub fn shutdown() { cleanup_terminal(); } /// enters alt screen and all that good stuff fn init_terminal() { let mut sout = stdout(); execute!(sout, EnterAlternateScreen).expect("enter alt screen"); execute!(sout, cursor::MoveTo(0, 0)).expect("write to alt screen failed"); execute!(sout, Clear(ClearType::All)).expect("Unable to clear screen."); enable_raw_mode().expect("Unable to enter raw mode."); } /// leaves the alt screen and leaves terminal as it was before /// launching the program fn cleanup_terminal() { let mut sout = stdout(); execute!(sout, Clear(ClearType::All)).expect("Unable to clear screen."); execute!(sout, LeaveAlternateScreen).expect("Unable to leave alternate screen."); disable_raw_mode().expect("Unable to disable raw mode"); } // would drop work? fn panic_hook(panic_info: &panic::PanicInfo) { cleanup_terminal(); let msg = match panic_info.payload().downcast_ref::<String>() { Some(s) => format!("p! {}", s), None => match panic_info.payload().downcast_ref::<&str>() { Some(s) => format!("oof! {}", s), None => String::from("weird panic hook"), }, }; let location = panic_info.location().unwrap(); let mut sout = stdout(); execute!(sout, Print(format!("{}\n{}\n", msg, location))).unwrap(); } /// In case of panic restores terminal before program terminates fn set_panic_hook() { panic::set_hook(Box::new(|info| panic_hook(info))); }
use std::{env, fs}; use ngc::parse::parse; fn main() { let filename = env::args().nth(1).expect("file name required"); let input = fs::read_to_string(&filename).unwrap(); match parse(&filename, &input) { Err(e) => eprintln!("Parse error: {}", e), Ok(prog) => println!("{}", prog), } }
mod twitch_notif; pub use twitch_notif::TwitchNotifEmbed;
extern crate env_logger; extern crate embed_lang; use embed_lang::vm::api; use embed_lang::vm::api::{VMType, Function}; use embed_lang::vm::gc::Traverseable; use embed_lang::vm::vm::{RootedThread, Thread, VMInt, Value, Root, RootStr}; use embed_lang::Compiler; use embed_lang::import::Import; fn load_script(vm: &Thread, filename: &str, input: &str) -> ::embed_lang::Result<()> { Compiler::new() .load_script(vm, filename, input) } fn run_expr(vm: &Thread, s: &str) -> Value { Compiler::new() .run_expr(vm, "<top>", s).unwrap_or_else(|err| panic!("{}", err)) } fn make_vm() -> RootedThread { let vm = ::embed_lang::new_vm(); let import = vm.get_macros().get("import"); import.as_ref() .and_then(|import| import.downcast_ref::<Import>()) .expect("Import macro") .add_path(".."); vm } #[test] fn call_function() { let _ = ::env_logger::init(); let add10 = r" let add10 : Int -> Int = \x -> x #Int+ 10 in add10 "; let mul = r" let mul : Float -> Float -> Float = \x y -> x #Float* y in mul "; let mut vm = make_vm(); load_script(&mut vm, "add10", &add10).unwrap_or_else(|err| panic!("{}", err)); load_script(&mut vm, "mul", &mul).unwrap_or_else(|err| panic!("{}", err)); { let mut f: Function<fn(VMInt) -> VMInt> = vm.get_global("add10") .unwrap(); let result = f.call(2).unwrap(); assert_eq!(result, 12); } let mut f: Function<fn(f64, f64) -> f64> = vm.get_global("mul").unwrap(); let result = f.call(4., 5.).unwrap(); assert_eq!(result, 20.); } #[test] fn pass_userdata() { let _ = ::env_logger::init(); let s = r" let id : Test -> Test = \x -> x in id "; let mut vm = make_vm(); fn test(test: *mut Test) -> bool { let test = unsafe { &mut *test }; let x = test.x == 123; test.x *= 2; x } let test: fn(_) -> _ = test; impl VMType for Test { type Type = Test; } impl Traverseable for Test { } struct Test { x: VMInt, } vm.register_type::<Test>("Test", vec![]) .unwrap_or_else(|_| panic!("Could not add type")); vm.define_global("test", test).unwrap_or_else(|err| panic!("{}", err)); load_script(&mut vm, "id", &s).unwrap_or_else(|err| panic!("{}", err)); let mut test = Test { x: 123 }; { let mut f: Function<fn(*mut Test) -> *mut Test> = vm.get_global("id").unwrap(); let result = f.call(&mut test).unwrap(); let p: *mut _ = &mut test; assert!(result == p); } let mut f: Function<fn(*mut Test) -> bool> = vm.get_global("test").unwrap(); let result = f.call(&mut test).unwrap(); assert!(result); assert_eq!(test.x, 123 * 2); } #[test] fn root_data() { let _ = ::env_logger::init(); struct Test(VMInt); impl Traverseable for Test { } impl VMType for Test { type Type = Test; } let expr = r#" \x -> test x 1 "#; let vm = make_vm(); fn test(r: Root<Test>, i: VMInt) -> VMInt { r.0 + i } vm.register_type::<Test>("Test", vec![]) .unwrap_or_else(|_| panic!("Could not add type")); vm.define_global("test", { let test: fn(_, _) -> _ = test; test }) .unwrap(); load_script(&vm, "script_fn", expr).unwrap_or_else(|err| panic!("{}", err)); let mut script_fn: Function<fn(api::Userdata<Test>) -> VMInt> = vm.get_global("script_fn").unwrap(); let result = script_fn.call(api::Userdata(Test(123))) .unwrap(); assert_eq!(result, 124); } #[test] fn root_string() { let _ = ::env_logger::init(); let expr = r#" test "hello" "#; let mut vm = make_vm(); fn test(s: RootStr) -> String { let mut result = String::from(&s[..]); result.push_str(" world"); result } vm.define_global("test", { let test: fn(_) -> _ = test; test }) .unwrap(); let result = run_expr(&mut vm, expr); match result { Value::String(s) => assert_eq!(&s[..], "hello world"), x => panic!("Expected string {:?}", x), } }
#![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { let mut contents = match String::from_utf8(data.to_vec()) { Ok(v) => v, Err(e) => panic!("Invalid UTF-8 sequence: {}", e), }; let replacee: String = "x".to_string(); let replacer: String = "z".to_string(); //println!("{}", contents); let old_str = contents.clone(); contents = contents.replace(&replacee, &replacer); if contents.eq(&old_str) { println!("Booh!, no \"{}\" found", &replacee); //std::process::exit(0); } println!("{}", contents); });
use proc_macro2::TokenStream; use quote::format_ident; use syn::{ parse_quote, ExprPath, ItemConst, ItemFn, ItemImpl, ItemMod, ItemStatic, LitByteStr, LitStr, }; use super::context::Context; use crate::parse::process::Process; impl Process { fn gen_wrapper_fn(&self) -> ItemFn { let ident = &self.ident; parse_quote! { pub(super) extern "C" fn wrapper () { let proc_self; unsafe { proc_self = VALUE.as_ref().unwrap(); } let ctx = Context::new(proc_self); super:: #ident(ctx) } } } pub fn gen_create_fn(&self) -> ItemImpl { let create_ident = format_ident!("create_{}", self.ident); let deadline: ExprPath = self.deadline.into(); let priority = self.base_priority; let stack_size = self.stack_size.as_u64() as u32; let time_capacity: TokenStream = self.time_capacity.clone().into(); let period: TokenStream = self.period.clone().into(); parse_quote! { impl<'a> super:: StartContext<'a, Hypervisor> { pub fn #create_ident<'b>(&'b mut self) -> Result<&'b Process::<Hypervisor>, Error>{ use core::str::FromStr; let attr = ProcessAttribute { period: #period, time_capacity: #time_capacity, entry_point: wrapper, stack_size: #stack_size, base_priority: #priority, deadline: #deadline, name: NAME, }; let process = self.ctx.create_process(attr)?; // This is safe because during cold/warm start only one thread works unsafe { VALUE = Some( process ); Ok(VALUE.as_ref().unwrap()) } } } } } pub fn gen_static_value(&self) -> ItemStatic { parse_quote! { pub(super) static mut VALUE : Option<Process::<Hypervisor>> = None; } } pub fn gen_static_name(&self) -> syn::Result<ItemConst> { const LEN: usize = 32; let name = self.name.to_string(); let len = name.bytes().len(); if len > LEN { return Err(syn::Error::new_spanned( self.name.clone(), format!("max name length is {LEN} bytes"), )); } let name = &format!("{name}{:\0<1$}", "", LEN - len); let lit_name: LitStr = parse_quote!(#name); let name = LitByteStr::new(name.as_bytes(), lit_name.span()); Ok(parse_quote! { pub(super) const NAME: Name = Name::new( * #name ); }) } pub fn gen_process_mod(&self) -> syn::Result<ItemMod> { let ident = &self.ident; let wrapper = self.gen_wrapper_fn(); let static_name = self.gen_static_name()?; let static_value = self.gen_static_value(); let create_fn = self.gen_create_fn(); let context_ident = Context::from_process(self).get_context_ident(); Ok(parse_quote! { mod #ident { use a653rs::prelude::*; use super::Hypervisor; pub(super) type Context<'a> = super:: #context_ident <'a, Hypervisor> ; #wrapper #create_fn #static_name #static_value } }) } }
#![no_std] #![no_main] extern crate panic_semihosting; pub use cortex_m::{asm::bkpt, iprint, iprintln, peripheral::ITM}; pub use cortex_m_rt::entry; pub use f3::hal::{prelude, serial::Serial, stm32f30x::usart1, time::MonoTimer}; use f3::hal::{ prelude::*, stm32f30x::{self, USART1}, }; use f3::{ led::Led, }; use f3::hal::delay::Delay; fn init() -> (f3::hal::delay::Delay, &'static mut usart1::RegisterBlock, MonoTimer, ITM, Led) { let dp = stm32f30x::Peripherals::take().unwrap(); let cp = cortex_m::Peripherals::take().unwrap(); dp.GPIOA.odr.write(|w| unsafe { w.bits(1)}); let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain(); // clock configuration using the default settings (all clocks run at 8 MHz) let clocks = rcc.cfgr.freeze(&mut flash.acr); let mut gpioa = dp.GPIOA.split(&mut rcc.ahb); let tx = gpioa.pa9.into_af7(&mut gpioa.moder, &mut gpioa.afrh); let rx = gpioa.pa10.into_af7(&mut gpioa.moder, &mut gpioa.afrh); Serial::usart1(dp.USART1, (tx, rx), 9_600.bps(), clocks, &mut rcc.apb2); // If you are having trouble sending/receiving data to/from the // HC-05 bluetooth module, try this configuration instead: // Serial::usart1(dp.USART1, (tx, rx), 9600.bps(), clocks, &mut rcc.apb2); let mut gpioe = dp.GPIOE.split(&mut rcc.ahb); let led = gpioe.pe9 .into_push_pull_output( &mut gpioe.moder, &mut gpioe.otyper); // TODO: trye this access before checking previous line "dp.GPIOA.odr.write(|w| unsafe { w.bits(1)});" let external_button = gpioe.pe7.into_pull_down_input( &mut gpioe.moder, &mut gpioe.pupdr); let delay = Delay::new(cp.SYST, clocks); unsafe { ( delay, &mut *(USART1::ptr() as *mut _), MonoTimer::new(cp.DWT, clocks), cp.ITM, led.into() ) } } enum ButtonState { PressedNew, PressedOld, RiseNew, RiseOld } struct UserButton { last_state: bool, } impl UserButton { fn new() -> Self { return UserButton {last_state:false}; } fn handle_user_button(&mut self) -> ButtonState { let result: ButtonState; if unsafe { (*stm32f30x::GPIOA::ptr()).idr.read().bits() & 1 != 0 } { if self.last_state == true { result = ButtonState::PressedOld; } else { result = ButtonState::PressedNew; } self.last_state = true; } else { if self.last_state == false { result = ButtonState::RiseOld } else { result = ButtonState::RiseNew; } self.last_state = false; } return result; } } struct PE7Button { last_state: bool, } impl PE7Button { fn new() -> Self { return Self {last_state:false}; } fn handle_user_button(&mut self) -> ButtonState { let result: ButtonState; if unsafe { (*stm32f30x::GPIOE::ptr()).idr.read().idr7().bit_is_set()} { if self.last_state == true { result = ButtonState::PressedOld; } else { result = ButtonState::PressedNew; } self.last_state = true; } else { if self.last_state == false { result = ButtonState::RiseOld } else { result = ButtonState::RiseNew; } self.last_state = false; } return result; } } #[entry] fn main() -> ! { // initialize user leds let (mut delay, usart1, mono_timer, itm, mut led) = init(); // Send a single character //usart1.tdr.write(|w| w.tdr().bits(u16::from(b'X'))); let mut led_on = true; let mut user_button = UserButton::new(); let mut pe7_button = PE7Button::new(); led.on(); loop { match pe7_button.handle_user_button() { ButtonState::RiseNew => { usart1.tdr.write(|w| w.tdr().bits(u16::from(b'X'))); if led_on { led.off(); } else { led.on(); } led_on = !led_on; }, _ => { match user_button.handle_user_button() { ButtonState::RiseNew => { usart1.tdr.write(|w| w.tdr().bits(u16::from(b'X'))); if led_on { led.off(); } else { led.on(); } led_on = !led_on; }, _ => { // ignoring } } } } delay.delay_ms(40_u16) } }
mod command_counter; mod config; mod invite; mod server_config; pub use self::{ command_counter::CommandCounterEmbed, config::ConfigEmbed, invite::InviteEmbed, server_config::ServerConfigEmbed, };
use std::marker::PhantomData; use crate::{Context, MethodErr, IfaceBuilder,stdimpl}; use crate::ifacedesc::Registry; use std::collections::{BTreeMap, HashSet}; use std::any::Any; const INTROSPECTABLE: usize = 0; const PROPERTIES: usize = 1; #[derive(Debug, Copy, Clone, Eq, Ord, Hash, PartialEq, PartialOrd)] pub struct IfaceToken<T: Send + 'static>(usize, PhantomData<&'static T>); #[derive(Debug)] struct Object { ifaces: HashSet<usize>, data: Box<dyn Any + Send + 'static> } #[derive(Debug)] pub struct Crossroads { map: BTreeMap<dbus::Path<'static>, Object>, registry: Registry, add_standard_ifaces: bool, } impl Crossroads { pub fn new() -> Crossroads { let mut cr = Crossroads { map: Default::default(), registry: Default::default(), add_standard_ifaces: true, }; let t0 = stdimpl::introspectable(&mut cr); let t1 = stdimpl::properties(&mut cr); debug_assert_eq!(t0.0, INTROSPECTABLE); debug_assert_eq!(t1.0, PROPERTIES); cr } pub fn set_add_standard_ifaces(&mut self, enable: bool) { self.add_standard_ifaces = enable; } pub fn register<T, N, F>(&mut self, name: N, f: F) -> IfaceToken<T> where T: Send + 'static, N: Into<dbus::strings::Interface<'static>>, F: FnOnce(&mut IfaceBuilder<T>) { let iface = IfaceBuilder::build(Some(name.into()), f); let x = self.registry.push(iface); IfaceToken(x, PhantomData) } pub fn data_mut<D: Any + Send + 'static>(&mut self, name: &dbus::Path<'static>) -> Option<&mut D> { let obj = self.map.get_mut(name)?; obj.data.downcast_mut() } pub fn insert<'z, D, I, N>(&mut self, name: N, ifaces: I, data: D) where D: Any + Send + 'static, N: Into<dbus::Path<'static>>, I: IntoIterator<Item = &'z IfaceToken<D>> { let ifaces = ifaces.into_iter().map(|x| x.0); let mut ifaces: HashSet<usize> = std::iter::FromIterator::from_iter(ifaces); if self.add_standard_ifaces { ifaces.insert(INTROSPECTABLE); if ifaces.iter().any(|u| self.registry().has_props(*u)) { ifaces.insert(PROPERTIES); } } self.map.insert(name.into(), Object { ifaces, data: Box::new(data)}); } pub (crate) fn find_iface_token(&self, path: &dbus::Path<'static>, interface: Option<&dbus::strings::Interface<'static>>) -> Result<usize, MethodErr> { let obj = self.map.get(path).ok_or_else(|| MethodErr::no_path(path))?; self.registry.find_token(interface, &obj.ifaces) } pub (crate) fn registry(&mut self) -> &mut Registry { &mut self.registry } pub (crate) fn registry_and_ifaces(&self, path: &dbus::Path<'static>) -> (&Registry, &HashSet<usize>) { let obj = self.map.get(path).unwrap(); (&self.registry, &obj.ifaces) } pub (crate) fn get_children(&self, path: &dbus::Path<'static>) -> Vec<&str> { use std::ops::Bound; let mut range = self.map.range((Bound::Excluded(path), Bound::Unbounded)); let p2 = path.as_bytes(); let mut r = vec!(); while let Some((c, _)) = range.next() { if !c.as_bytes().starts_with(p2) { break; } let csub: &str = &c[p2.len()..]; if csub.len() == 0 || csub.as_bytes()[0] != b'/' { continue; } r.push(&csub[1..]); }; r } pub fn handle_message<S: dbus::channel::Sender>(&mut self, message: dbus::Message, conn: &S) -> Result<(), ()> { let mut ctx = Context::new(message).ok_or(())?; let (itoken, mut cb) = ctx.check(|ctx| { let itoken = self.find_iface_token(ctx.path(), ctx.interface())?; let cb = self.registry.take_method(itoken, ctx.method())?; Ok((itoken, cb)) })?; // No failure paths before method is given back! let methodname = ctx.method().clone(); let ctx = cb(ctx, self); self.registry.give_method(itoken, &methodname, cb); if let Some(mut ctx) = ctx { ctx.flush_messages(conn) } else { Ok(()) } } pub fn introspectable<T: Send + 'static>(&self) -> IfaceToken<T> { IfaceToken(INTROSPECTABLE, PhantomData) } pub fn properties<T: Send + 'static>(&self) -> IfaceToken<T> { IfaceToken(PROPERTIES, PhantomData) } }
use super::*; use crate::{ components::{self, Resource}, indices::{EntityId, UserId, WorldPosition}, intents::{ check_dropoff_intent, check_melee_intent, check_mine_intent, check_move_intent, CachePathIntent, DropoffIntent, MeleeIntent, MineIntent, MoveIntent, MutPathCacheIntent, PathCacheIntentAction, }, pathfinding, profile, storage::views::FromWorld, }; use crate::{prelude::World, terrain::TileTerrainType}; use std::convert::{TryFrom, TryInto}; use tracing::{debug, error, trace, warn}; pub fn melee_attack(vm: &mut Vm<ScriptExecutionData>, target: i64) -> Result<(), ExecutionError> { profile!("melee-attack"); let aux = vm.get_aux(); trace!("melee_attack"); let target: u64 = target.try_into().map_err(|_| { warn!("melee_attack called without a valid target"); ExecutionError::invalid_argument("melee_attack called without valid a target".to_owned()) })?; let target: EntityId = EntityId::from(target); let storage = aux.storage(); let entity_id = aux.entity_id; let user_id = aux.user_id.expect("user_id to be set"); let intent = MeleeIntent { attacker: entity_id, defender: target, }; let res = check_melee_intent(&intent, user_id, FromWorld::from_world(storage)); if let OperationResult::Ok = res { vm.get_aux_mut().intents.melee_attack_intent = Some(intent); } vm.stack_push(res)?; Ok(()) } pub fn unload( vm: &mut Vm<ScriptExecutionData>, amount: i64, ty: Resource, target: i64, ) -> Result<(), ExecutionError> { profile!("unload"); let aux = vm.get_aux(); trace!("unload"); let amount = TryFrom::try_from(amount).map_err(|e| { ExecutionError::invalid_argument(format!("unload called with invalid amount: {}", e)) })?; let target: u64 = target.try_into().map_err(|_| { warn!("melee_attack called without a valid target"); ExecutionError::invalid_argument("melee_attack called without valid a target".to_owned()) })?; let target: EntityId = EntityId::from(target); trace!( "unload: amount: {} type: {:?} target: {:?}, {}", amount, ty, target, aux ); let storage = aux.storage(); let entity_id = aux.entity_id; let user_id = aux.user_id.expect("user_id to be set"); let dropoff_intent = DropoffIntent { bot: entity_id, amount, ty, structure: target, }; let checkresult = check_dropoff_intent(&dropoff_intent, user_id, FromWorld::from_world(storage)); if let OperationResult::Ok = checkresult { vm.get_aux_mut().intents.dropoff_intent = Some(dropoff_intent); } vm.stack_push(checkresult)?; Ok(()) } pub fn mine_resource(vm: &mut Vm<ScriptExecutionData>, target: i64) -> Result<(), ExecutionError> { profile!("mine_resource"); let aux = vm.get_aux(); let target: u64 = target.try_into().map_err(|_| { warn!("melee_attack called without a valid target"); ExecutionError::invalid_argument("melee_attack called without valid a target".to_owned()) })?; let target: EntityId = EntityId::from(target); let s = tracing::trace_span!( "mine_resource", entity_id = aux.entity_id.to_string().as_str() ); let _e = s.enter(); trace!("target: {:?}, {}", target, aux); let storage = aux.storage(); let user_id = aux.user_id.expect("user_id to be set"); let intent = MineIntent { bot: aux.entity_id, resource: target, }; let checkresult = check_mine_intent(&intent, user_id, FromWorld::from_world(storage)); vm.stack_push(checkresult)?; trace!("result: {:?}", checkresult); if let OperationResult::Ok = checkresult { vm.get_aux_mut().intents.mine_intent = Some(intent); } Ok(()) } pub fn approach_entity( vm: &mut Vm<ScriptExecutionData>, target: i64, ) -> Result<(), ExecutionError> { profile!("approach_entity"); let aux = vm.get_aux(); let target: u64 = target.try_into().map_err(|_| { warn!("melee_attack called without a valid target"); ExecutionError::invalid_argument("melee_attack called without valid a target".to_owned()) })?; let target: EntityId = EntityId::from(target); trace!("approach_entity: target: {:?}", target); let entity = aux.entity_id; let storage = aux.storage(); let user_id = aux.user_id.expect("user_id to be set"); let targetpos = match storage .view::<EntityId, components::PositionComponent>() .reborrow() .get(target) { Some(x) => x, None => { warn!("entity {:?} does not have position component!", target); vm.stack_push(OperationResult::InvalidInput)?; return Ok(()); } }; let checkresult = match move_to_pos(entity, targetpos.0, user_id, storage) { Ok(Some((move_intent, pop_cache_intent, update_cache_intent))) => { let intents = &mut vm.get_aux_mut().intents; intents.move_intent = Some(move_intent); if let Some(pop_cache_intent) = pop_cache_intent { intents.mut_path_cache_intent = Some(pop_cache_intent); } if let Some(update_cache_intent) = update_cache_intent { intents.update_path_cache_intent = Some(update_cache_intent); } OperationResult::Ok } Ok(None) => { trace!("Bot {:?} approach_entity: nothing to do", entity); OperationResult::Ok } Err(e) => e, }; vm.stack_push(checkresult)?; Ok(()) } pub fn move_bot_to_position( vm: &mut Vm<ScriptExecutionData>, point: &FieldTable, ) -> Result<(), ExecutionError> { profile!("move_bot_to_position"); let aux = vm.get_aux(); trace!("move_bot_to_position"); let entity = aux.entity_id; let storage = aux.storage(); let user_id = aux.user_id.expect("user_id to be set"); let point: WorldPosition = parse_world_pos(point)?; let checkresult = match move_to_pos(entity, point, user_id, storage) { Ok(Some((move_intent, pop_cache_intent, update_cache_intent))) => { let intents = &mut vm.get_aux_mut().intents; intents.move_intent = Some(move_intent); if let Some(pop_cache_intent) = pop_cache_intent { intents.mut_path_cache_intent = Some(pop_cache_intent); } if let Some(update_cache_intent) = update_cache_intent { intents.update_path_cache_intent = Some(update_cache_intent); } OperationResult::Ok } Ok(None) => { trace!("{:?} move_to_pos nothing to do", entity); OperationResult::Ok } Err(e) => e, }; vm.stack_push(checkresult)?; Ok(()) } type MoveToPosIntent = ( MoveIntent, Option<MutPathCacheIntent>, Option<CachePathIntent>, ); fn move_to_pos( bot: EntityId, to: WorldPosition, user_id: UserId, storage: &World, ) -> Result<Option<MoveToPosIntent>, OperationResult> { use crate::prelude::*; profile!("move_to_pos"); let botpos = storage .view::<EntityId, components::PositionComponent>() .reborrow() .get(bot) .ok_or_else(|| { warn!("entity does not have position component!"); OperationResult::InvalidInput })?; // attempt to use the cached path // which requires non-empty cache with a valid next step match storage .view::<EntityId, PathCacheComponent>() .reborrow() .get(bot) { Some(cache) if cache.target == to => { if let Some(position) = cache.path.last().cloned() { let intent = MoveIntent { bot, position: WorldPosition { room: botpos.0.room, pos: position.0, }, }; if let OperationResult::Ok = check_move_intent(&intent, user_id, FromWorld::from_world(storage)) { trace!("Bot {:?} path cache hit", bot); let result = ( intent, Some(MutPathCacheIntent { bot, action: PathCacheIntentAction::Pop, }), None, ); return Ok(Some(result)); } } } _ => {} } trace!("Bot path cache miss"); let conf = UnwrapView::<ConfigKey, GameConfig>::from_world(storage); let max_pathfinding_iter = conf.path_finding_limit; let mut path = Vec::with_capacity(max_pathfinding_iter as usize); let mut next_room = None; if let Err(e) = pathfinding::find_path( botpos.0, to, 1, FromWorld::from_world(storage), max_pathfinding_iter, &mut path, &mut next_room, ) { trace!("pathfinding failed {:?}", e); return Err(OperationResult::InvalidTarget); } match path.pop() { Some(position) => { let intent = MoveIntent { bot, position: WorldPosition { room: botpos.0.room, pos: position.0, }, }; let checkresult = check_move_intent(&intent, user_id, FromWorld::from_world(storage)); match checkresult { OperationResult::Ok => { let cache_intent = if !path.is_empty() { // skip >= 0 let skip = path.len().max(PATH_CACHE_LEN) - PATH_CACHE_LEN; let cache_intent = CachePathIntent { bot, cache: PathCacheComponent { target: to, path: path.into_iter().skip(skip).take(PATH_CACHE_LEN).collect(), }, }; Some(cache_intent) } else { None }; Ok(Some((intent, None, cache_intent))) } _ => Err(checkresult), } } None => { trace!("Entity is trying to move to its own position"); match next_room { Some(to_room) => { let is_bridge = storage .view::<WorldPosition, TerrainComponent>() .get(botpos.0) .map(|TerrainComponent(t)| *t == TileTerrainType::Bridge) .unwrap_or_else(|| { error!("Bot is not standing on terrain {:?}", botpos); false }); if !is_bridge { return Err(OperationResult::InvalidTarget); } let target_pos = match pathfinding::get_valid_transits( botpos.0, to_room, FromWorld::from_world(storage), ) { Ok(candidates) => candidates[0], Err(pathfinding::TransitError::NotFound) => { return Err(OperationResult::PathNotFound) } Err(e) => { error!("Transit failed {:?}", e); return Err(OperationResult::OperationFailed); } }; let intent = MoveIntent { bot, position: target_pos, }; Ok(Some(( intent, Some(MutPathCacheIntent { bot, action: PathCacheIntentAction::Del, }), None, ))) } None => { debug!("Entity is trying to move to its own position, but no next room was returned"); Ok(None) } } } } } #[cfg(test)] mod tests { use super::*; use crate::map_generation::room::iter_edge; use crate::prelude::*; use crate::query; use crate::terrain::TileTerrainType; #[test] fn can_move_to_another_room() { let mut storage = World::new(); let bot_id = storage.insert_entity(); let room_radius = 3; let room_center = Axial::new(room_radius, room_radius); let mut from = WorldPosition { room: Axial::new(0, 0), pos: Axial::default(), }; let to = WorldPosition { room: Axial::new(0, 2), pos: Axial::new(2, 1), }; let next_room = Axial::new(0, 1); from.pos = iter_edge( room_center, room_radius as u32, &RoomConnection { direction: next_room, offset_end: 1, offset_start: 1, }, ) .unwrap() .next() .unwrap(); let user_id = UserId::default(); query!( mutate storage { EntityId, Bot, .insert(bot_id); EntityId, PositionComponent, .insert(bot_id, PositionComponent(from)); EntityId, OwnedEntity, .insert(bot_id, OwnedEntity{owner_id:user_id}); ConfigKey, RoomProperties, .update(Some(RoomProperties{radius:room_radius as u32, center: room_center})); WorldPosition, EntityComponent, .extend_rooms([Room(from.room),Room(Axial::new(0,1)), Room(to.room)].iter().cloned()) .expect("Failed to add rooms"); WorldPosition, TerrainComponent, .extend_rooms([Room(from.room),Room(Axial::new(0,1)), Room(to.room)].iter().cloned()) .expect("Failed to add rooms"); WorldPosition, TerrainComponent, .iter_rooms_mut().for_each(|(_, room)|room.resize(3)); WorldPosition, TerrainComponent, .extend_from_slice(&mut [ ( from, TerrainComponent(TileTerrainType::Bridge) ), ( WorldPosition{room: Axial::new(0,1), pos: Axial::new(5,0)} , TerrainComponent(TileTerrainType::Bridge) ), ]) .expect("Failed to insert terrain"); }); let mut init_connections = |room| { // init connections... let mut connections = RoomConnections::default(); let neighbour = next_room; connections.0[Axial::neighbour_index(neighbour).expect("Bad neighbour")] = Some(RoomConnection { direction: neighbour, offset_end: 0, offset_start: 0, }); query!( mutate storage { Axial, RoomConnections, .insert(from.room, connections ) .expect("Failed to add room connections"); } ); let mut connections = RoomConnections::default(); let neighbour = next_room; connections.0[Axial::neighbour_index(neighbour).expect("Bad neighbour")] = Some(RoomConnection { direction: neighbour, offset_end: 0, offset_start: 0, }); query!( mutate storage { Axial, RoomConnections, .insert( room, connections ) .expect("Failed to add room connections"); } ); }; init_connections(next_room); init_connections(to.room); let (MoveIntent { bot, position }, ..) = move_to_pos(bot_id, to, user_id, &storage) .expect("Expected move to succeed") .expect("Expected a move intent"); assert_eq!(bot, bot_id); assert_eq!(position.room, next_room); } }
// Copyright (c) 2020 Jesse Weaver. // // This file is part of secretgarden. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use anyhow::{anyhow, Context, Result as AHResult}; use base64; use clap::Clap; use dirs_next; use std::env; use std::fs; mod secret_store; mod secret_types; mod ssh_agent_decryptor; mod types; use crate::secret_store::{ContainedSecretStore, SecretStore}; use crate::secret_types::opaque::{generate_opaque, run_set_opaque, OpaqueOpts, SetOpaqueOpts}; use crate::secret_types::password::{generate_password, PasswordOpts}; use crate::secret_types::ssh_key::{generate_ssh_key, transform_ssh_key, SshKeyOpts}; use crate::secret_types::x509::{run_x509, X509Opts}; use crate::ssh_agent_decryptor::SshAgentSecretContainerFile; use crate::types::OptionsType; #[derive(Clap)] #[clap(version = env!("CARGO_PKG_VERSION"))] struct Opts { #[clap(subcommand)] subcmd: SubCommand, } #[derive(Clap)] enum SubCommand { #[clap(version = env!("CARGO_PKG_VERSION"), about = "Get an opaque value", long_about = "Get an opaque value.\n\nOpaque values cannot be generated and must be set with `set-opaque`.\n\n")] Opaque(OpaqueOpts), #[clap(version = env!("CARGO_PKG_VERSION"), about = "Get or generate a password", long_about = "Get or generate a password.")] Password(PasswordOpts), #[clap(version = env!("CARGO_PKG_VERSION"), about = "Set an opaque value", long_about = "Set an opaque value.")] SetOpaque(SetOpaqueOpts), #[clap(version = env!("CARGO_PKG_VERSION"), about = "Get or generate an SSH key", long_about = "Get or generate an SSH key. Will output the private key by default.")] SshKey(SshKeyOpts), #[clap(version = env!("CARGO_PKG_VERSION"), about = "Get or generate an X.509 certificate", long_about = "Get or generate an X.509 certificate. Will output the certificate and private key by default.")] X509(X509Opts), #[clap(version = env!("CARGO_PKG_VERSION"), about = "Install the Ansible plugin to your home directory", long_about = "Install the Ansible plugin to your home directory.")] InstallAnsiblePlugin, } fn run_secret_type_with_transform<'a, OptsT: OptionsType<'a>>( store: &mut impl SecretStore, secret_type: &str, generator: impl Fn(&OptsT) -> AHResult<String>, transformer: impl Fn(String, &OptsT) -> AHResult<String>, opts: &OptsT, ) -> AHResult<()> { let mut value = store.get_or_generate(generator, secret_type, &opts)?; if opts.common_opts().base64 { value = base64::encode(value.chars().map(|c| c as u8).collect::<Vec<u8>>()); } println!("{}", transformer(value, opts)?); Ok(()) } fn run_secret_type<'a, OptsT: OptionsType<'a>>( store: &mut impl SecretStore, secret_type: &str, generator: impl Fn(&OptsT) -> AHResult<String>, opts: &OptsT, ) -> AHResult<()> { run_secret_type_with_transform(store, secret_type, generator, |x, _| Ok(x), opts) } fn run_install_ansible_plugin() -> AHResult<()> { let home_dir_path = dirs_next::home_dir().ok_or(anyhow!( "Could not determine your home directory; is $HOME set?" ))?; let ansible_lookup_plugin_directory = format!( "{}/.ansible/plugins/lookup", home_dir_path.to_str().unwrap(), ); let ansible_lookup_plugin_path = format!("{}/secretgarden.py", ansible_lookup_plugin_directory,); fs::create_dir_all(ansible_lookup_plugin_directory) .context("Failed to create directory {} for Ansible lookup plugin")?; fs::write( &ansible_lookup_plugin_path, include_bytes!("ansible_lookup_plugin.py").to_vec(), ) .context(format!( "Failed to write Ansible plugin to {}", &ansible_lookup_plugin_path )) } fn main() -> AHResult<()> { sodiumoxide::init().map_err(|_| anyhow!("Failed to initialize sodiumoxide"))?; let opts = Opts::parse(); let ssh_auth_sock_path = env::var("SSH_AUTH_SOCK") .map_err(|_| anyhow!("SSH_AUTH_SOCK not set; ssh-agent not running?"))?; let mut store = ContainedSecretStore::new(SshAgentSecretContainerFile::new(ssh_auth_sock_path)); match opts.subcmd { SubCommand::Opaque(o) => run_secret_type(&mut store, "opaque", generate_opaque, &o), SubCommand::Password(o) => run_secret_type(&mut store, "password", generate_password, &o), SubCommand::SetOpaque(o) => run_set_opaque(&mut store, o), SubCommand::SshKey(o) => run_secret_type_with_transform( &mut store, "ssh-key", generate_ssh_key, transform_ssh_key, &o, ), SubCommand::X509(o) => run_x509(&mut store, &o), SubCommand::InstallAnsiblePlugin => run_install_ansible_plugin(), } }
use std::result::Result as StdResult; use futures::try_ready; use resol_vbus::BlobBuffer; use tokio::net::TcpStream; use tokio::prelude::*; use crate::error::{Error, Result}; type ReceiveCommandValidatorResult<T> = (&'static str, Option<Result<T>>); type ReceiveCommandValidatorFutureBox<T> = Box<dyn Future<Item = ReceiveCommandValidatorResult<T>, Error = Error> + Send>; type ReceiveCommandSendReplyResult<S, T> = (S, Option<Result<T>>); type ReceiveCommandSendReplyFutureBox<S, T> = Box<dyn Future<Item = ReceiveCommandSendReplyResult<S, T>, Error = Error> + Send>; /// Handles the server-side of the [VBus-over-TCP][1] handshake. /// /// [1]: http://danielwippermann.github.io/resol-vbus/vbus-over-tcp.html /// /// # Examples /// /// This example simulates a RESOL DL2 by accepting TCP connections on port /// 7053, requiring the client to provide a password and then switch the /// connection into raw VBus data mode. /// /// ```no_run /// use tokio::prelude::*; /// use tokio::net::TcpListener; /// use tokio_resol_vbus::TcpServerHandshake; /// /// let addr = "127.0.0.1:7053".parse().expect("Unable to parse address"); /// let listener = TcpListener::bind(&addr).expect("Unable to bind listener"); /// /// let server = listener /// .incoming() /// .map_err(|err| eprintln!("{}", err)) /// .for_each(|socket| { /// let conn = TcpServerHandshake::start(socket) /// .and_then(|hs| hs.receive_pass_command_and_verify_password(|password| { /// if password == "vbus" { /// Ok(Some(password)) /// } else { /// Ok(None) /// } /// })) /// .and_then(|(hs, _)| hs.receive_data_command()) /// .and_then(|socket| { /// // do something with the socket /// # Ok(()) /// }) /// .map_err(|err| eprintln!("Server error: {}", err)); /// tokio::spawn(conn) /// }); /// /// tokio::run(server); /// ``` #[derive(Debug)] pub struct TcpServerHandshake { socket: TcpStream, buf: BlobBuffer, } impl TcpServerHandshake { /// Start the VBus-over-TCP handshake as the client side connecting to a server. pub fn start(socket: TcpStream) -> impl Future<Item = Self, Error = Error> { let hs = TcpServerHandshake { socket, buf: BlobBuffer::new(), }; hs.send_reply("+HELLO\r\n") } /// Consume `self` and return the underlying `TcpStream`. pub fn into_inner(self) -> TcpStream { self.socket } /// Send a reply to the client. fn send_reply(self, reply: &'static str) -> impl Future<Item = Self, Error = Error> { let mut hs = Some(self); let bytes = reply.as_bytes(); let mut idx = 0; future::poll_fn(move || { loop { let hs = hs.as_mut().unwrap(); if idx < bytes.len() { let len = try_ready!(hs.socket.poll_write(&bytes[idx..])); if len == 0 { return Err(Error::new("Reached EOF")); } idx += len; } else { break; } } Ok(Async::Ready(hs.take().unwrap())) }) } fn poll_receive_line(&mut self) -> Poll<String, Error> { loop { if let Some(idx) = self.buf.iter().position(|b| *b == 10) { let string = std::str::from_utf8(&self.buf)?.to_string(); self.buf.consume(idx + 1); return Ok(Async::Ready(string)); } let mut tmp_buf = [0u8; 256]; let len = try_ready!(self.socket.poll_read(&mut tmp_buf)); if len == 0 { return Err(Error::new("Reached EOF")); } self.buf.extend_from_slice(&tmp_buf[0..len]); } } /// Receive a command and verify it and its provided arguments. The /// command reception is repeated as long as the verification fails. /// /// The preferred way to receive commands documented in the VBus-over-TCP /// specification is through the `receive_xxx_command` and /// `receive_xxx_command_and_verify_yyy` methods which use the /// `receive_command` method internally. /// /// This method takes a validator function that is called with the /// received command and its optional arguments. The validator /// returns a `Future` that can resolve into an /// `std::result::Result<T, &'static str>`. It can either be: /// - `Ok(value)` if the validation succeeded. The `value` is used /// to resolve the `receive_command` `Future`. /// - `Err(reply)` if the validation failed. The `reply` is send /// back to the client and the command reception is repeated. pub fn receive_command<V, R, T>( self, validator: V, ) -> impl Future<Item = (Self, T), Error = Error> where V: Fn(String, Option<String>) -> R, R: Future<Item = StdResult<T, &'static str>, Error = Error> + Send + 'static, T: Send + 'static, { let mut self_option = Some(self); let mut future0: Option<ReceiveCommandValidatorFutureBox<T>> = None; let mut future1: Option<ReceiveCommandSendReplyFutureBox<Self, T>> = None; let mut phase = 0; future::poll_fn(move || loop { match phase { // Phase 0: // - `self` is stored in `self_option` // - create `receive_xxx_command` future 0 => { let line = try_ready!(self_option.as_mut().unwrap().poll_receive_line()); let line = line.trim(); let (command, args) = if let Some(idx) = line.chars().position(|c| c.is_whitespace()) { let command = (&line[0..idx]).to_uppercase(); let args = (&line[idx..].trim()).to_string(); (command, Some(args)) } else { (line.to_string(), None) }; let future: ReceiveCommandValidatorFutureBox<T> = if command == "QUIT" { let result = ("+OK\r\n", Some(Err(Error::new("Received QUIT command")))); Box::new(future::ok(result)) } else { let future = validator(command, args); Box::new(future.and_then(|result| { let result = match result { Ok(value) => ("+OK\r\n", Some(Ok(value))), Err(reply) => (reply, None), }; Ok(result) })) }; future0 = Some(future); phase = 1; } 1 => { let (reply, result) = try_ready!(future0.as_mut().unwrap().poll()); let hs = self_option.take().unwrap(); let future = hs.send_reply(reply).and_then(|hs| Ok((hs, result))); future1 = Some(Box::new(future)); phase = 2; } 2 => { let (hs, result) = try_ready!(future1.as_mut().unwrap().poll()); future1 = None; if let Some(result) = result { phase = 3; match result { Ok(value) => break Ok(Async::Ready((hs, value))), Err(err) => break Err(err), } } else { phase = 0; } } // Phase 3: // - this future is already resolved // - panic! 3 => panic!("Called poll() on resolved future"), _ => unreachable!(), } }) } /// Wait for a `CONNECT <via_tag>` command. The via tag argument is returned. pub fn receive_connect_command(self) -> impl Future<Item = (Self, String), Error = Error> { self.receive_connect_command_and_verify_via_tag(|via_tag| Ok(Some(via_tag))) } /// Wait for a `CONNECT <via_tag>` command. pub fn receive_connect_command_and_verify_via_tag<V, F, R>( self, validator: V, ) -> impl Future<Item = (Self, String), Error = Error> where V: Fn(String) -> F, F: IntoFuture<Item = Option<String>, Error = Error, Future = R> + Send, R: Future<Item = Option<String>, Error = Error> + Send + 'static, { self.receive_command(move |command, args| { let result = if command != "CONNECT" { Err("-ERROR Expected CONNECT command\r\n") } else if let Some(via_tag) = args { Ok(via_tag) } else { Err("-ERROR Expected argument\r\n") }; let future: Box< dyn Future<Item = StdResult<String, &'static str>, Error = Error> + Send, > = match result { Ok(via_tag) => { Box::new(validator(via_tag).into_future().map(|result| match result { Some(via_tag) => Ok(via_tag), None => Err("-ERROR Invalid via tag\r\n"), })) } Err(reply) => Box::new(future::ok(Err(reply))), }; future }) } /// Wait for a `PASS <password>` command. pub fn receive_pass_command(self) -> impl Future<Item = (Self, String), Error = Error> { self.receive_pass_command_and_verify_password(|password| Ok(Some(password))) } /// Wait for a `PASS <password>` command and validate the provided password. pub fn receive_pass_command_and_verify_password<V, F, R>( self, validator: V, ) -> impl Future<Item = (Self, String), Error = Error> where V: Fn(String) -> F, F: IntoFuture<Item = Option<String>, Error = Error, Future = R> + Send, R: Future<Item = Option<String>, Error = Error> + Send + 'static, { self.receive_command(move |command, args| { let result = if command != "PASS" { Err("-ERROR Expected PASS command\r\n") } else if let Some(password) = args { Ok(password) } else { Err("-ERROR Expected argument\r\n") }; let future: Box< dyn Future<Item = StdResult<String, &'static str>, Error = Error> + Send, > = match result { Ok(password) => Box::new(validator(password).into_future().map( |result| match result { Some(password) => Ok(password), None => Err("-ERROR Invalid password\r\n"), }, )), Err(reply) => Box::new(future::ok(Err(reply))), }; future }) } /// Wait for a `CHANNEL <channel>` command. pub fn receive_channel_command(self) -> impl Future<Item = (Self, u8), Error = Error> { self.receive_channel_command_and_verify_channel(|channel| Ok(Some(channel))) } /// Wait for `CHANNEL <channel>` command and validate the provided channel pub fn receive_channel_command_and_verify_channel<V, F, R>( self, validator: V, ) -> impl Future<Item = (Self, u8), Error = Error> where V: Fn(u8) -> F, F: IntoFuture<Item = Option<u8>, Error = Error, Future = R> + Send + 'static, R: Future<Item = Option<u8>, Error = Error> + Send + 'static, { self.receive_command(move |command, args| { let result = if command != "CHANNEL" { Err("-ERROR Expected CHANNEL command\r\n") } else if let Some(args) = args { if let Ok(channel) = args.parse::<u8>() { Ok(channel) } else { Err("-ERROR Expected 8 bit number argument\r\n") } } else { Err("-ERROR Expected argument\r\n") }; let future: Box<dyn Future<Item = StdResult<u8, &'static str>, Error = Error> + Send> = match result { Ok(channel) => { Box::new(validator(channel).into_future().map(|result| match result { Some(channel) => Ok(channel), None => Err("-ERROR Invalid channel\r\n"), })) } Err(reply) => Box::new(future::ok(Err(reply))), }; future }) } /// Wait for a `DATA` command. pub fn receive_data_command(self) -> impl Future<Item = TcpStream, Error = Error> { self.receive_command(|command, args| { let result = if command != "DATA" { Err("-ERROR Expected DATA command\r\n") } else if args.is_some() { Err("-ERROR Did not expect arguments\r\n") } else { Ok(()) }; future::ok(result) }) .map(|(hs, _)| hs.into_inner()) } } #[cfg(test)] mod tests { use std::net::Shutdown; use tokio::net::TcpListener; use crate::{error::Result, tcp_client_handshake::TcpClientHandshake}; use super::*; fn wait_for_close(mut socket: TcpStream) -> impl Future<Item = (), Error = Error> { future::poll_fn(move || { let mut buf = [0; 256]; let len = try_ready!(socket.poll_read(&mut buf)); if len != 0 { Err(Error::new(format!( "Read {} bytes: {:?}", len, std::str::from_utf8(&buf[0..len]) ))) } else { Ok(Async::Ready(())) } }) } #[test] fn test() -> Result<()> { let addr = "127.0.0.1:7053".parse()?; let mut listener = TcpListener::bind(&addr)?; let addr = listener.local_addr()?; let handler = future::lazy(move || { let server = future::poll_fn(move || { let (socket, _addr) = try_ready!(listener.poll_accept()); Ok(Async::Ready(socket)) }) .map_err(|err: std::io::Error| { panic!("{}", err); }) .and_then(|socket| TcpServerHandshake::start(socket)) .and_then(|hs| hs.receive_connect_command()) .and_then(|(hs, args)| { assert_eq!("via_tag", args); hs.receive_pass_command_and_verify_password(|password| { if password == "password" { Ok(Some(password)) } else { Ok(None) } }) }) .and_then(|(hs, args)| { assert_eq!("password", args); hs.receive_channel_command_and_verify_channel(|channel| { if channel == 123 { Ok(Some(channel)) } else { Ok(None) } }) }) .and_then(|(hs, channel)| { assert_eq!(123, channel); hs.receive_data_command() }) .and_then(|socket| { socket .shutdown(Shutdown::Write) .expect("Unable to shutdown server"); wait_for_close(socket) }) .map_err(|err| { panic!("Server error: {}", err); }); let client = TcpStream::connect(&addr) .map_err(|err| Error::new(err)) .and_then(|socket| TcpClientHandshake::start(socket)) .and_then(|hs| hs.send_connect_command("via_tag")) .and_then(|hs| hs.send_pass_command("password")) .and_then(|hs| hs.send_channel_command(123)) .and_then(|hs| hs.send_data_command()) .and_then(|socket| { socket .shutdown(Shutdown::Write) .expect("Unable to shutdown client"); wait_for_close(socket) }) .map_err(|err| { panic!("Client error: {}", err); }); tokio::spawn(server); tokio::spawn(client); Ok(()) }); println!("Starting runtime..."); tokio::run(handler); println!("Runtime ended"); Ok(()) } }
static BASE64_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789+/"; pub fn encode(v: &[u8]) -> Vec<u8> { let len = v.len(); let mut split: Vec<u8> = Vec::new(); for i in 0..(len * 4 / 3 + ((len % 3 != 0) as usize)) { let index = i / 4 * 3; match i % 4 { 0 => split.push(v[index] >> 2), 1 => if index+1 < len { split.push(((v[index] & 3) << 4) + (v[index + 1] >> 4)) } else { split.push((v[index] & 3) << 4) }, 2 => { if index+2 < len { split.push(((v[index + 1] & 15) << 2) + (v[index + 2] >> 6)) } else { split.push((v[index + 1] & 15) << 2) }}, 3 => { split.push(v[index + 2] & 63)}, _ => panic!("Impossible!") } } let mut encoded: Vec<u8> = split.iter().map(|x| BASE64_CHARS[*x as usize]).collect(); let elen = encoded.len(); if elen % 4 != 0 { let len = encoded.len(); encoded.resize(len + 4 - elen % 4, b'='); } encoded } pub fn decode(v: &[u8]) -> Vec<u8> { let trans: Vec<u8> = v.iter() .take_while(|&x| { *x != b'=' }) .filter_map(|x| BASE64_CHARS.iter().position(|c| c == x).map(|x| x as u8)) .collect(); let mut res: Vec<u8> = Vec::new(); for i in 0..trans.len() { match i % 4 { 0 => res.push(trans[i] << 2), 1 => { *res.last_mut().unwrap() = *res.last().unwrap() + (trans[i] >> 4); res.push(trans[i] << 4) }, 2 => { *res.last_mut().unwrap() = *res.last().unwrap() + (trans[i] >> 2); res.push(trans[i] << 6) }, 3 => *res.last_mut().unwrap() = *res.last().unwrap() + trans[i], _ => panic!("Impossible") } } if v.iter().last() == Some(&b'=') { res.pop(); } res }
/* * Binary indexed tree test (Rust) * * Copyright (c) 2019 Project Nayuki. (MIT License) * https://www.nayuki.io/page/binary-indexed-tree * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - The Software is provided "as is", without warranty of any kind, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. In no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the Software or the use or other dealings in the * Software. */ extern crate rand; use rand::Rng; use rand::distributions::IndependentSample; use rand::distributions::range::Range; mod binaryindexedtree; use binaryindexedtree::BinaryIndexedTree; fn main() { test_size_constructor(); test_all_ones(); test_array_constructor_randomly(); test_add_and_set_randomly(); println!("Test passed"); } fn test_size_constructor() { let sizelimit: usize = 10_000; let checks = 10; type T = i8; let rng = &mut rand::thread_rng(); for len in 0 .. sizelimit { let bt = BinaryIndexedTree::<T>::new_size(len); assert_eq!(len, bt.len()); assert_eq!(0, bt.get_total()); let indexdist = Range::new(0, len.max(1)); let indexonedist = Range::new(0, len + 1); for _ in 0 .. checks { if len > 0 { assert_eq!(0, bt.get(indexdist.ind_sample(rng))); } assert_eq!(0, bt.get_prefix_sum(indexonedist.ind_sample(rng))); let mut start = indexonedist.ind_sample(rng); let mut end = indexonedist.ind_sample(rng); if start > end { std::mem::swap(&mut start, &mut end); } assert_eq!(0, bt.get_range_sum(start, end)); } } } fn test_all_ones() { let sizelimit: usize = 10_000; let checks = 10; type T = u16; let rng = &mut rand::thread_rng(); let modedist = Range::new(0, 4); for len in 1 .. sizelimit { let mut bt; let mode = modedist.ind_sample(rng); if mode == 0 { bt = BinaryIndexedTree::<T>::new_array(&vec![1; len]); } else { bt = BinaryIndexedTree::<T>::new_size(len); let p: f64 = match mode { 1 => 0.0, 2 => 1.0, 3 => rng.gen::<f64>(), _ => unreachable!(), }; for i in 0 .. len { if rng.gen::<f64>() < p { bt.add(i, 1); } else { bt.set(i, 1); } } } assert_eq!(len, bt.len()); assert_eq!(len as T, bt.get_total()); let indexdist = Range::new(0, len.max(1)); let indexonedist = Range::new(0, len + 1); for _ in 0 .. checks { assert_eq!(1, bt.get(indexdist.ind_sample(rng))); let k = indexonedist.ind_sample(rng); assert_eq!(k as T, bt.get_prefix_sum(k)); let mut start = indexonedist.ind_sample(rng); let mut end = indexonedist.ind_sample(rng); if start > end { std::mem::swap(&mut start, &mut end); } assert_eq!((end - start) as T, bt.get_range_sum(start, end)); } } } fn test_array_constructor_randomly() { let trials = 10_000; let sizelimit: usize = 10_000; let checks = 100; type T = i64; let rng = &mut rand::thread_rng(); let lendist = Range::new(0, sizelimit); for _ in 0 .. trials { let len = lendist.ind_sample(rng); let mut vals: Vec<T> = vec![]; let mut cums: Vec<T> = vec![0]; let valdist = Range::new(-1000, 1001); for _ in 0 .. len { let x = valdist.ind_sample(rng); vals.push(x); let y = *cums.last().unwrap(); cums.push(y + x); } let bt = BinaryIndexedTree::<T>::new_array(&vals); assert_eq!(len, bt.len()); assert_eq!(cums[len], bt.get_total()); let indexdist = Range::new(0, len.max(1)); let indexonedist = Range::new(0, len + 1); for _ in 0 .. checks { if len > 0 { let k = indexdist.ind_sample(rng); assert_eq!(vals[k], bt.get(k)); } let k = indexonedist.ind_sample(rng); assert_eq!(cums[k], bt.get_prefix_sum(k)); let mut start = indexonedist.ind_sample(rng); let mut end = indexonedist.ind_sample(rng); if start > end { std::mem::swap(&mut start, &mut end); } assert_eq!(cums[end] - cums[start], bt.get_range_sum(start, end)); } } } fn test_add_and_set_randomly() { let trials = 10_000; let sizelimit: usize = 10_000; let operations = 10_000; let checks = 100; type E = u64; type T = std::num::Wrapping<E>; let rng = &mut rand::thread_rng(); let lendist = Range::new(1, sizelimit); for _ in 0 .. trials { let len = lendist.ind_sample(rng); let mut vals: Vec<T>; let mut bt: BinaryIndexedTree<T> = if rng.gen::<bool>() { vals = vec![std::num::Wrapping(0); len]; BinaryIndexedTree::<T>::new_size(len) } else { vals = (0 .. len).map(|_| std::num::Wrapping(rng.gen::<E>())).collect(); BinaryIndexedTree::<T>::new_array(&vals) }; let indexdist = Range::new(0, len.max(1)); for _ in 0 .. operations { let k = indexdist.ind_sample(rng); let x: T = std::num::Wrapping(rng.gen()); if rng.gen::<bool>() { vals[k] += x; bt.add(k, x); } else { vals[k] = x; bt.set(k, x); } } let mut cums = vec![std::num::Wrapping(0)]; for x in vals.iter() { let y = *cums.last().unwrap(); cums.push(y + x); } let indexonedist = Range::new(0, len + 1); for _ in 0 .. checks { let k = indexdist.ind_sample(rng); assert_eq!(vals[k], bt.get(k)); let k = indexonedist.ind_sample(rng); assert_eq!(cums[k], bt.get_prefix_sum(k)); let mut start = indexonedist.ind_sample(rng); let mut end = indexonedist.ind_sample(rng); if start > end { std::mem::swap(&mut start, &mut end); } assert_eq!(cums[end] - cums[start], bt.get_range_sum(start, end)); } } }
/*! ```rudra-poc [target] crate = "signal-simple" version = "0.1.1" [[target.peer]] crate = "crossbeam-utils" version = "0.8.0" [report] issue_url = "https://github.com/kitsuneninetails/signal-rust/issues/2" issue_date = 2020-11-15 rustsec_url = "https://github.com/RustSec/advisory-db/pull/694" rustsec_id = "RUSTSEC-2020-0126" [[bugs]] analyzer = "SendSyncVariance" bug_class = "SendSyncVariance" bug_count = 2 rudra_report_locations = ["src/channel.rs:58:1: 58:42", "src/channel.rs:59:1: 59:42"] ``` !*/ #![forbid(unsafe_code)] use signal_simple::channel::SyncChannel; use crossbeam_utils::thread; use std::cell::Cell; // A simple tagged union used to demonstrate problems with data races in Cell. #[derive(Debug, Clone, Copy)] enum RefOrInt { Ref(&'static u64), Int(u64), } static SOME_INT: u64 = 123; fn main() { let cell = Cell::new(RefOrInt::Ref(&SOME_INT)); let channel = SyncChannel::new(); channel.send(&cell); thread::scope(|s| { s.spawn(|_| { let smuggled_cell = channel.recv().unwrap(); loop { // Repeatedly write Ref(&addr) and Int(0xdeadbeef) into the cell. smuggled_cell.set(RefOrInt::Ref(&SOME_INT)); smuggled_cell.set(RefOrInt::Int(0xdeadbeef)); } }); loop { if let RefOrInt::Ref(addr) = cell.get() { // Hope that between the time we pattern match the object as a // `Ref`, it gets written to by the other thread. if addr as *const u64 == &SOME_INT as *const u64 { continue; } println!("Pointer is now: {:p}", addr); println!("Dereferencing addr will now segfault: {}", *addr); } } }); }
use std::collections::HashMap; use std::path::Path; use std::process::Command; use std::time::SystemTime; // import helper functions from loader module use crate::loader::{get_var_trimmed, read_bracketed_var}; #[derive(Debug, Clone, Eq, PartialEq)] pub(crate) struct FinalRule { target: String, // Every rule in the final list only has one target (or target pattern) it provides prereqs: Vec<String>, recipes: Vec<String>, } #[allow(dead_code)] impl FinalRule { // constructor pub(crate) fn new(target: String, prereqs: Vec<String>, recipes: Vec<String>) -> Self { Self { target, prereqs, recipes, } } // read only member access pub(crate) fn target(&self) -> &str { &self.target } pub(crate) fn prereqs(&self) -> &Vec<String> { &self.prereqs } pub(crate) fn recipes(&self) -> &Vec<String> { &self.recipes } // mutable member access pub(crate) fn target_mut(&mut self) -> &mut str { &mut self.target } pub(crate) fn prereqs_mut(&mut self) -> &mut Vec<String> { &mut self.prereqs } pub(crate) fn recipes_mut(&mut self) -> &mut Vec<String> { &mut self.recipes } } #[derive(Debug, Clone, Eq, PartialEq)] pub struct MakeFile { var_map: HashMap<String, String>, finalised_rules: Vec<FinalRule>, include_list: Vec<String>, } impl MakeFile { /// The crate internal constructor for a Makefile pub(crate) fn new( var_map: HashMap<String, String>, finalised_rules: Vec<FinalRule>, include_list: Vec<String>, ) -> Self { MakeFile { var_map, finalised_rules, include_list, } } /// Substitutes variables for their actual value fn substitute_var( &self, it: &mut dyn Iterator<Item = char>, target: &str, deps: &[String], ) -> String { match it.next().expect("Unexpected end of variable, quitting!") { '@' => target.to_owned(), '?' => deps.iter().fold(String::new(), |res, dep| res + " " + dep), '<' => deps.iter().next().unwrap_or(&String::new()).clone(), '$' => String::from("$"), // handle bracketed variables '(' => get_var_trimmed( &self.var_map, read_bracketed_var(it, ")", |it| self.substitute_var(it, target, deps)), ), '{' => get_var_trimmed( &self.var_map, read_bracketed_var(it, "}", |it| self.substitute_var(it, target, deps)), ), x => panic!("${} ???", x), } } /// Performs the build specified by the makefile. fn build(&self, target: &FinalRule, silent: bool) -> SystemTime { let mut newest_dep: SystemTime = SystemTime::UNIX_EPOCH; for prereq in &target.prereqs { if let Some(rule) = self.finalised_rules.iter().find(|r| r.target == *prereq) { newest_dep = std::cmp::max(self.build(rule, silent), newest_dep); } else if !Path::new(prereq).exists() { panic!("No rule to build target \"{}\", stopping.", prereq); } else { newest_dep = std::cmp::max( std::fs::metadata(prereq).unwrap().modified().unwrap(), newest_dep, ); } } let modified = std::fs::metadata(&target.target) .ok() .map(|meta| meta.modified().ok()) .flatten(); if Path::new(&target.target).exists() && &newest_dep < modified.as_ref().unwrap() { return modified.unwrap(); } for recipe in &target.recipes { let mut recipe_san = String::new(); let mut it = recipe.chars().peekable(); while let Some(c) = it.next() { match c { '$' => { recipe_san.push_str(&self.substitute_var( &mut it, &target.target, &target.prereqs, )); } x => { recipe_san.push(x); } } } let mut recipe = recipe_san.trim(); let recipe_silent; if recipe.starts_with('@') { recipe = recipe[1..].trim(); recipe_silent = true; } else { recipe_silent = false; } if !silent && !recipe_silent { println!("{}", recipe); } let status = Command::new("sh") .arg("-c") .arg(recipe) .status() .expect("Failed to execute process"); if !status.success() { panic!("Program exited with nonzero status, stopping."); } } SystemTime::now() } /// Builds the default target pub fn build_default(&self, silent: bool) { let default_target = self.var_map.get(".DEFAULT_GOAL"); // Naming is consistent let mut rule = None; if let Some(default_target) = default_target { rule = self .finalised_rules .iter() .find(|rule| rule.target == *default_target); } if rule == None { rule = self.finalised_rules.first(); } if let Some(rule) = rule { self.build(rule, silent); } else { panic!("No targets available, quitting!"); } } /// Builds a makefile target pub fn build_target(&self, target: impl AsRef<str>, silent: bool) { let rule = self .finalised_rules .iter() .find(|rule| rule.target == target.as_ref()); if let Some(rule) = rule { self.build(rule, silent); } else { panic!("No rule to make target {}, quitting!", target.as_ref()); } } }
extern crate agg; use agg::Pixel; fn draw_black_frame(pix: &mut agg::Pixfmt<agg::Rgb8>) { let w = pix.width(); let h = pix.height(); println!("w,h: {} {}", w,h); let black = agg::Rgb8::black(); for i in 0 .. h { pix.copy_pixel(0, i, black); pix.copy_pixel(w-1, i, black); } for &k in [0,h-1].iter() { for i in 0 .. w { pix.copy_pixel(i, k, black); } } } #[test] fn t02_pixel_formats() { //let rbuf = agg::RenderingBuffer::new(320, 220, 3); let mut pix = agg::Pixfmt::<agg::Rgb8>::new(320,220); pix.clear(); draw_black_frame(&mut pix); for i in 0 .. pix.height()/2 { let c = agg::Rgb8::new(127,200,98); pix.copy_pixel(i, i, c); } pix.to_file("tests/tmp/agg_test_02.png").unwrap(); assert_eq!(agg::ppm::img_diff("tests/tmp/agg_test_02.png", "images/agg_test_02.png").unwrap(), true); }
fn main() { let mut input = String::from_utf8(std::fs::read("input/day10").unwrap()) .unwrap() .split_terminator("\n") .map(|n| n.parse().unwrap()) .collect::<Vec<u64>>(); input.push(0); input.sort(); input.push(input.last().unwrap() + 3); let mut ones = 0usize; let mut threes = 0; input.windows(2).for_each(|n| match n[1] - n[0] { 1 => ones += 1, 3 => threes += 1, _ => (), }); let answer = ones * threes; println!("{}", answer); }
mod common; use actix_web::{test, web, App}; use drogue_cloud_authentication_service::{endpoints, service, WebData}; use drogue_cloud_service_api::auth::device::authn::{AuthenticationRequest, Credential}; use drogue_cloud_test_common::{client, db}; use serde_json::{json, Value}; use serial_test::serial; fn device1_json() -> Value { json!({"pass":{ "application": { "metadata": { "name": "app1", "uid": "4e185ea6-7c26-11eb-a319-d45d6455d210", "creationTimestamp": "2020-01-01T00:00:00Z", "resourceVersion": "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "generation": 0, }, }, "device": { "metadata": { "application": "app1", "name": "device1", "uid": "4e185ea6-7c26-11eb-a319-d45d6455d211", "creationTimestamp": "2020-01-01T00:00:00Z", "resourceVersion": "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "generation": 0, }, } }}) } fn device3_json() -> Value { json!({"pass":{ "application": { "metadata": { "name": "app1", "uid": "4e185ea6-7c26-11eb-a319-d45d6455d210", "creationTimestamp": "2020-01-01T00:00:00Z", "resourceVersion": "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "generation": 0, }, }, "device": { "metadata": { "application": "app1", "name": "device3", "uid": "4e185ea6-7c26-11eb-a319-d45d6455d212", "creationTimestamp": "2020-01-01T00:00:00Z", "resourceVersion": "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "generation": 0, }, } }}) } /// Authorize a device using a password. #[actix_rt::test] #[serial] async fn test_auth_passes_password() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "device1".into(), credential: Credential::Password("foo".into()), r#as: None, } => device1_json()); } /// Authorize a device using a password. #[actix_rt::test] #[serial] async fn test_auth_passes_password_alias() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "foo".into(), credential: Credential::Password("bar".into()), r#as: None, } => device3_json()); } /// Authorize a device using a username/password combination for a password-only credential /// that has a username matching the device ID. #[actix_rt::test] #[serial] async fn test_auth_passes_password_with_device_username() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "device1".into(), credential: Credential::UsernamePassword{username: "device1".into(), password: "foo".into()}, r#as: None, } => device1_json()); } /// Authorize a device using a username/password combination for a password-only credential /// that has a username matching the device ID. #[actix_rt::test] #[serial] async fn test_auth_fails_password_with_non_matching_device_username() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "device1".into(), credential: Credential::UsernamePassword{username: "device2".into(), password: "foo".into()}, r#as: None, } => json!("fail")); } #[actix_rt::test] #[serial] async fn test_auth_fails_wrong_password() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "device1".into(), credential: Credential::Password("foo1".into()), r#as: None, } => json!("fail")); } #[actix_rt::test] #[serial] async fn test_auth_fails_missing_tenant() { test_auth!(AuthenticationRequest{ application: "app2".into(), device: "device1".into(), credential: Credential::Password("foo".into()), r#as: None, } => json!("fail")); } #[actix_rt::test] #[serial] async fn test_auth_fails_missing_device() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "device2".into(), credential: Credential::Password("foo".into()), r#as: None, } => json!("fail")); } #[actix_rt::test] #[serial] async fn test_auth_passes_username_password() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "device3".into(), credential: Credential::UsernamePassword{username: "foo".into(), password: "bar".into()}, r#as: None, } => device3_json()); } /// The password only variant must fail, as the username is not the device id. #[actix_rt::test] #[serial] async fn test_auth_fails_password_only() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "device3".into(), credential: Credential::Password("bar".into()), r#as: None, } => json!("fail")); } /// The password only variant must success, as the username is equal to the device id. #[actix_rt::test] #[serial] async fn test_auth_passes_password_only() { test_auth!(AuthenticationRequest{ application: "app1".into(), device: "device3".into(), credential: Credential::Password("baz".into()), r#as: None, } => device3_json()); }
use crate::core::{ transactions, Account, DbConnection, Money, Permission, Pool, Product, ServiceResult, Transaction, }; use crate::identity_policy::{Action, RetrievedAccount}; use crate::login_required; use crate::web::utils::HbData; use actix_web::{http, web, HttpRequest, HttpResponse}; use chrono::{Duration, Local, NaiveDateTime}; use handlebars::Handlebars; use uuid::Uuid; /// Helper to deserialize from-to queries #[derive(Deserialize, Serialize)] pub struct FromToQuery { #[serde(with = "naive_date_time_option_serializer")] #[serde(default = "get_none")] pub from: Option<NaiveDateTime>, #[serde(with = "naive_date_time_option_serializer")] #[serde(default = "get_none")] pub to: Option<NaiveDateTime>, } fn get_none() -> Option<NaiveDateTime> { None } /// Helper to deserialize execute queries #[derive(Deserialize)] pub struct Execute { pub total: f32, } #[derive(Debug, Serialize, Deserialize)] pub struct TransactionProduct { pub product_id: Uuid, pub product: Option<Product>, pub amount: i32, pub current_price: Option<Money>, } #[derive(Debug, Serialize, Deserialize)] pub struct TransactionWithProducts { pub transaction: Transaction, pub products: Vec<TransactionProduct>, } impl TransactionProduct { pub fn vec_to_transaction_product(list: Vec<(Product, i32)>) -> Vec<TransactionProduct> { list.into_iter() .map(|(p, a)| TransactionProduct { product_id: p.id, current_price: p.current_price.map(|price| price * a), product: Some(p), amount: a, }) .collect() } #[allow(dead_code)] pub fn vec_from_transaction_product( conn: &DbConnection, list: Vec<TransactionProduct>, ) -> Vec<(Product, i32)> { list.into_iter() .filter_map(|p| match Product::get(&conn, &p.product_id) { Ok(product) => Some((product, p.amount)), _ => None, }) .collect() } } /// GET route for `/admin/transactions/{account_id}` pub async fn get_transactions( pool: web::Data<Pool>, hb: web::Data<Handlebars<'_>>, logged_account: RetrievedAccount, account_id: web::Path<String>, query: web::Query<FromToQuery>, request: HttpRequest, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let conn = &pool.get()?; let account = Account::get(&conn, &Uuid::parse_str(&account_id)?)?; let now = Local::now().naive_local(); let from = query .from .unwrap_or_else(|| now - Duration::days(30)) .date() .and_hms(0, 0, 0); let to = query.to.unwrap_or_else(|| now).date().and_hms(23, 59, 59); let list: Vec<TransactionWithProducts> = transactions::get_by_account(&conn, &account, &from, &to)? .into_iter() .map(|t| { let prods = t.get_products(&conn).unwrap_or_else(|_| Vec::new()); let l = TransactionProduct::vec_to_transaction_product(prods); TransactionWithProducts { transaction: t, products: l, } }) .collect(); let list_str = serde_json::to_string(&list).unwrap_or_else(|_| "[]".to_owned()); let body = HbData::new(&request) .with_account(logged_account) .with_data( "date", &FromToQuery { from: Some(from), to: Some(to), }, ) .with_data("account", &account) .with_data("transactions", &list) .with_data("transactions_str", &list_str) .render(&hb, "admin_transaction_list")?; Ok(HttpResponse::Ok().body(body)) } /// POST route for `/admin/transaction/execute/{account_id}` pub async fn post_execute_transaction( pool: web::Data<Pool>, logged_account: RetrievedAccount, account_id: web::Path<String>, execute_form: web::Form<Execute>, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); if execute_form.total != 0.0 { let conn = &pool.get()?; let mut account = Account::get(&conn, &Uuid::parse_str(&account_id)?)?; transactions::execute( &conn, &mut account, Some(&logged_account.account), (execute_form.total * 100.0) as Money, )?; } Ok(HttpResponse::Found() .header( http::header::LOCATION, format!("/admin/transactions/{}", &account_id), ) .finish()) } /// GET route for `/admin/transaction/{account_id}/{transaction_id}` pub async fn get_transaction_details( pool: web::Data<Pool>, hb: web::Data<Handlebars<'_>>, logged_account: RetrievedAccount, request: HttpRequest, path: web::Path<(String, String)>, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::MEMBER, Action::REDIRECT); let conn = &pool.get()?; let account_id = Uuid::parse_str(&path.0)?; let transaction_id = Uuid::parse_str(&path.1)?; let account = Account::get(&conn, &account_id)?; let transaction = transactions::get_by_account_and_id(&conn, &account, &transaction_id)?; let products = transaction.get_products(&conn)?; let products = TransactionProduct::vec_to_transaction_product(products); let body = HbData::new(&request) .with_account(logged_account) .with_data("account", &account) .with_data("transaction", &transaction) .with_data("products", &products) .render(&hb, "admin_transaction_details")?; Ok(HttpResponse::Ok().body(body)) } /// Serialize/Deserialize a datetime to/from only a date pub mod naive_date_time_option_serializer { use chrono::{NaiveDate, NaiveDateTime}; use serde::{de::Error, de::Visitor, Deserializer, Serializer}; use std::fmt; pub fn serialize<S>(date: &Option<NaiveDateTime>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match date { Some(d) => serializer.serialize_str(&d.format("%Y-%m-%d").to_string()), None => serializer.serialize_str(""), } } pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<NaiveDateTime>, D::Error> where D: Deserializer<'de>, { struct NaiveVisitor; impl<'de> Visitor<'de> for NaiveVisitor { type Value = Option<NaiveDateTime>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("yyyy-mm-dd") } fn visit_str<E>(self, value: &str) -> Result<Option<NaiveDateTime>, E> where E: Error, { Ok(NaiveDate::parse_from_str(value, "%Y-%m-%d") .map(|d| d.and_hms(0, 0, 0)) .ok()) } } match deserializer.deserialize_string(NaiveVisitor) { Ok(x) => Ok(x), Err(_) => Ok(None), } } } /// GET route for `/admin/transactions/generate/{account_id}/` pub async fn get_transaction_generate_random( pool: web::Data<Pool>, hb: web::Data<Handlebars<'_>>, logged_account: RetrievedAccount, request: HttpRequest, path: web::Path<String>, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::ADMIN, Action::REDIRECT); let conn = &pool.get()?; let account_id = Uuid::parse_str(&path)?; let account = Account::get(&conn, &account_id)?; let now = Local::now().naive_local(); let body = HbData::new(&request) .with_account(logged_account) .with_data("account", &account) .with_data( "date", &FromToQuery { from: Some((now - Duration::days(30)).date().and_hms(0, 0, 0)), to: Some(now.date().and_hms(23, 59, 59)), }, ) .render(&hb, "admin_transaction_generate_random")?; Ok(HttpResponse::Ok().body(body)) } /// Helper to deserialize from-to queries #[derive(Deserialize, Serialize)] pub struct GenerateRandomQuery { #[serde(with = "naive_date_time_option_serializer")] #[serde(default = "get_none")] pub from: Option<NaiveDateTime>, #[serde(with = "naive_date_time_option_serializer")] #[serde(default = "get_none")] pub to: Option<NaiveDateTime>, pub avg_up: f32, pub avg_down: f32, pub count_per_day: u32, } /// POST route for `/admin/transactions/generate/{account_id}/` pub async fn post_transaction_generate_random( pool: web::Data<Pool>, logged_account: RetrievedAccount, path: web::Path<String>, data: web::Form<GenerateRandomQuery>, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::ADMIN, Action::REDIRECT); let conn = &pool.get()?; let account_id = Uuid::parse_str(&path)?; let mut account = Account::get(&conn, &account_id)?; let now = Local::now().naive_local(); let from = data .from .unwrap_or_else(|| now - Duration::days(30)) .date() .and_hms(0, 0, 0); let to = data.to.unwrap_or_else(|| now).date().and_hms(23, 59, 59); transactions::generate_transactions( conn, &mut account, from, to, data.count_per_day, (data.avg_down * 100.0) as Money, (data.avg_up * 100.0) as Money, )?; Ok(HttpResponse::Found() .header( http::header::LOCATION, format!("/admin/transactions/{}", &account_id), ) .finish()) } /// GET route for `/admin/transactions/validate` pub async fn get_transactions_validate( pool: web::Data<Pool>, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::ADMIN, Action::REDIRECT); let conn = &pool.get()?; let result = transactions::validate_all(conn)?; Ok(HttpResponse::Ok().json(result)) }
pub use dir::env_dir; pub use edit::env_edit; pub use envs::envs; pub use generate::generate; pub use init::init; pub use ls::ls; pub use new::env_new; pub use pdir::env_pdir; pub use r#use::r#use; pub use rename::rename; pub use run::run; pub use show::{show, DEFAULT_SHOW_FORMAT}; pub use sync::{env_sync, sync_workflow, SyncConfirmEnum, SyncSettings}; pub use vars::vars; mod dir; mod edit; mod envs; mod generate; mod init; mod ls; mod new; mod pdir; mod rename; mod run; mod show; mod sync; mod r#use; mod vars;
extern crate libc; extern crate libz_sys; extern crate openssl_sys; use libc::{c_int, size_t, c_void, c_char, c_long, c_uchar, c_uint, c_ulong}; use libc::ssize_t; // It seems not to matter that ssh_session is really a struct pub enum ssh_session {} // It seems not to matter that ssh_channel is really a struct pub enum ssh_channel {} #[repr(C)] #[allow(non_snake_case)] pub enum ssh_options_e { SSH_OPTIONS_HOST, SSH_OPTIONS_PORT, SSH_OPTIONS_PORT_STR, SSH_OPTIONS_FD, SSH_OPTIONS_USER, SSH_OPTIONS_SSH_DIR, SSH_OPTIONS_IDENTITY, SSH_OPTIONS_ADD_IDENTITY, SSH_OPTIONS_KNOWNHOSTS, SSH_OPTIONS_TIMEOUT, SSH_OPTIONS_TIMEOUT_USEC, SSH_OPTIONS_SSH1, SSH_OPTIONS_SSH2, SSH_OPTIONS_LOG_VERBOSITY, SSH_OPTIONS_LOG_VERBOSITY_STR, SSH_OPTIONS_CIPHERS_C_S, SSH_OPTIONS_CIPHERS_S_C, SSH_OPTIONS_COMPRESSION_C_S, SSH_OPTIONS_COMPRESSION_S_C, SSH_OPTIONS_PROXYCOMMAND, SSH_OPTIONS_BINDADDR, SSH_OPTIONS_STRICTHOSTKEYCHECK, SSH_OPTIONS_COMPRESSION, SSH_OPTIONS_COMPRESSION_LEVEL, SSH_OPTIONS_KEY_EXCHANGE, SSH_OPTIONS_HOSTKEYS, SSH_OPTIONS_GSSAPI_SERVER_IDENTITY, SSH_OPTIONS_GSSAPI_CLIENT_IDENTITY, SSH_OPTIONS_GSSAPI_DELEGATE_CREDENTIALS, SSH_OPTIONS_HMAC_C_S, SSH_OPTIONS_HMAC_S_C } #[link(name = "libssh")] extern { pub fn ssh_new() -> ssh_session; pub fn ssh_free(session: *mut ssh_session) -> c_void; pub fn ssh_disconnect(session: *mut ssh_session) -> c_void; pub fn ssh_channel_new(session: *mut ssh_session) -> ssh_channel; pub fn ssh_channel_open_session(channel: *mut ssh_channel) -> c_int; pub fn ssh_channel_close(channel: *mut ssh_channel) -> c_int; pub fn ssh_channel_free(channel: *mut ssh_channel) -> c_void; pub fn ssh_channel_read(channel: *mut ssh_channel, dest: *mut c_void, count: c_uint, is_stderr: c_int); pub fn ssh_channel_request_exec(channel: *mut ssh_channel, cmd: *mut c_char) -> c_int; pub fn ssh_channel_send_eof(channel: *mut ssh_channel) -> c_int; pub fn ssh_finalize() -> c_int; } #[test] fn base_test() { unsafe { let mut my_ssh_session = ssh_new(); ssh_free(&mut my_ssh_session); } }
use hydroflow::hydroflow_syntax; pub fn main() { // An edge in the input data = a pair of `usize` vertex IDs. let (pairs_send, pairs_recv) = hydroflow::util::unbounded_channel::<(usize, usize)>(); let mut flow = hydroflow_syntax! { // inputs: the origin vertex (vertex 0) and stream of input edges origin = source_iter(vec![0]); stream_of_edges = source_stream(pairs_recv) -> tee(); // the join for reachable vertices reached_vertices[0] -> map(|v| (v, ())) -> [0]my_join; stream_of_edges[1] -> [1]my_join; my_join = join() -> flat_map(|(src, ((), dst))| [src, dst]); // the cycle: my_join gets data from reached_vertices // and provides data back to reached_vertices! origin -> [base]reached_vertices; my_join -> [cycle]reached_vertices; reached_vertices = union()->tee(); // the difference: all_vertices - reached_vertices all_vertices = stream_of_edges[0] -> flat_map(|(src, dst)| [src, dst]) -> tee(); all_vertices[0] -> [pos]unreached_vertices; reached_vertices[1] -> [neg]unreached_vertices; unreached_vertices = difference(); // the output all_vertices[1] -> unique() -> for_each(|v| println!("Received vertex: {}", v)); unreached_vertices -> for_each(|v| println!("unreached_vertices vertex: {}", v)); }; println!( "{}", flow.meta_graph() .expect("No graph found, maybe failed to parse.") .to_mermaid() ); pairs_send.send((5, 10)).unwrap(); pairs_send.send((0, 3)).unwrap(); pairs_send.send((3, 6)).unwrap(); pairs_send.send((6, 5)).unwrap(); pairs_send.send((11, 12)).unwrap(); flow.run_available(); }
//! Maintains a single instance of the FUSE filesystem //! //! The module dolls out shared pointers to the FUSE background //! session. When they all go out of scope, the filesystem shuts //! down. use env_logger; use fuse; use fuse::BackgroundSession; use std::cell::Cell; use std::ffi::OsStr; use std::fs::create_dir; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, Weak}; mod fs; static MOUNTPOINT: &'static str = "./mnt"; pub struct TestFilesystem { _session: BackgroundSession<'static>, } lazy_static! { static ref FILESYSTEM: Mutex<Cell<Weak<TestFilesystem>>> = Mutex::new(Cell::new(Weak::new())); } /// Define the path in terms of the mountpoint pub fn from_mntpt<P: AsRef<Path>>(path: P) -> PathBuf { let mut buf = PathBuf::from(MOUNTPOINT); buf.push(path); buf } /// Mount a filesystem #[deny(dead_code)] // require setup of the filesystem; prevent silly tests! pub fn get_fs() -> Arc<TestFilesystem> { let lock = FILESYSTEM .lock() .expect("unable to acquire filesystem lock"); let weak = lock.take(); let (weak, session) = match weak.upgrade() { Some(session) => (weak, session), None => { let _ignored = env_logger::try_init(); let mntpt = PathBuf::from(&MOUNTPOINT); if !mntpt.exists() { create_dir(&mntpt).expect(&format!( "unable to create mountpoint at {}", mntpt.display() )); } let options = ["-o", "rw", "-o", "fsname=test"] .iter() .map(|o| o.as_ref()) .collect::<Vec<&OsStr>>(); let session = unsafe { fuse::spawn_mount(fs::define_filesystem(), &MOUNTPOINT, &options) .expect("unable to mount filesystem") }; let session = Arc::new(TestFilesystem { _session: session }); (Arc::downgrade(&session), session) } }; lock.set(weak); session }
pub fn process_stream(string: String) -> u32 { let mut string_iterator = string.chars(); let mut sum = 0; let mut level = 0; let mut garbage_mode = false; let mut contains = string_iterator.next(); while contains != None { let c = contains.unwrap(); if c == '<' { garbage_mode = true; } if garbage_mode { match c { '!' => { string_iterator.next(); } '>' => garbage_mode = false, _ => (), } } else { match c { '{' => level += 1, '}' => { sum += level; level -= 1; } _ => (), } } contains = string_iterator.next(); } sum } #[cfg(test)] mod stream_process_test { use super::*; fn stream_gives_sum(string: &str, sum: u32) { let string = String::from(string); assert_eq!(process_stream(string), sum); } #[test] fn test_1() { stream_gives_sum("", 0); } #[test] fn test_2() { stream_gives_sum("{{{}}}", 6); } #[test] fn test_3() { stream_gives_sum("{{<ab>},{<ab>},{<ab>},{<ab>}}", 9); } #[test] fn test_4() { stream_gives_sum("{{<!!>},{<!!>},{<!!>},{<!!>}}", 9); } #[test] fn test_5() { stream_gives_sum("{{<a!>},{<a!>},{<a!>},{<ab>}}", 3); } }
use crate::provider::client_handling::{ClientProcessingData, ClientRequestProcessor}; use crate::provider::mix_handling::{MixPacketProcessor, MixProcessingData}; use crate::provider::storage::ClientStorage; use crypto::identity::{DummyMixIdentityPrivateKey, DummyMixIdentityPublicKey}; use directory_client::presence::MixProviderClient; use futures::io::Error; use futures::lock::Mutex as FMutex; use sfw_provider_requests::AuthToken; use sphinx::route::DestinationAddressBytes; use std::collections::HashMap; use std::net::{Shutdown, SocketAddr}; use std::path::PathBuf; use std::sync::Arc; use std::sync::RwLock; use tokio::prelude::*; use tokio::runtime::Runtime; mod client_handling; mod mix_handling; pub mod presence; mod storage; // TODO: if we ever create config file, this should go there const STORED_MESSAGE_FILENAME_LENGTH: usize = 16; const MESSAGE_RETRIEVAL_LIMIT: usize = 5; pub struct Config { pub client_socket_address: SocketAddr, pub directory_server: String, pub mix_socket_address: SocketAddr, pub public_key: DummyMixIdentityPublicKey, pub secret_key: DummyMixIdentityPrivateKey, pub store_dir: PathBuf, } #[derive(Debug)] pub enum ProviderError { TcpListenerBindingError, TcpListenerConnectionError, TcpListenerUnexpectedEof, TcpListenerUnknownError, } impl From<io::Error> for ProviderError { fn from(err: Error) -> Self { use ProviderError::*; match err.kind() { io::ErrorKind::ConnectionRefused => TcpListenerConnectionError, io::ErrorKind::ConnectionReset => TcpListenerConnectionError, io::ErrorKind::ConnectionAborted => TcpListenerConnectionError, io::ErrorKind::NotConnected => TcpListenerConnectionError, io::ErrorKind::AddrInUse => TcpListenerBindingError, io::ErrorKind::AddrNotAvailable => TcpListenerBindingError, io::ErrorKind::UnexpectedEof => TcpListenerUnexpectedEof, _ => TcpListenerUnknownError, } } } #[derive(Debug)] pub struct ClientLedger(HashMap<AuthToken, DestinationAddressBytes>); impl ClientLedger { fn new() -> Self { ClientLedger(HashMap::new()) } fn add_arc_futures_mutex(self) -> Arc<FMutex<Self>> { Arc::new(FMutex::new(self)) } fn has_token(&self, auth_token: AuthToken) -> bool { return self.0.contains_key(&auth_token); } fn insert_token( &mut self, auth_token: AuthToken, client_address: DestinationAddressBytes, ) -> Option<DestinationAddressBytes> { self.0.insert(auth_token, client_address) } fn current_clients(&self) -> Vec<MixProviderClient> { self.0 .iter() .map(|(_, v)| base64::encode_config(v, base64::URL_SAFE)) .map(|pub_key| MixProviderClient { pub_key }) .collect() } #[allow(dead_code)] fn load(_file: PathBuf) -> Self { unimplemented!() } } pub struct ServiceProvider { directory_server: String, mix_network_address: SocketAddr, client_network_address: SocketAddr, public_key: DummyMixIdentityPublicKey, secret_key: DummyMixIdentityPrivateKey, store_dir: PathBuf, registered_clients_ledger: ClientLedger, } impl ServiceProvider { pub fn new(config: Config) -> Self { ServiceProvider { mix_network_address: config.mix_socket_address, client_network_address: config.client_socket_address, secret_key: config.secret_key, public_key: config.public_key, store_dir: PathBuf::from(config.store_dir.clone()), // TODO: load initial ledger from file registered_clients_ledger: ClientLedger::new(), directory_server: config.directory_server.clone(), } } async fn process_mixnet_socket_connection( mut socket: tokio::net::TcpStream, processing_data: Arc<RwLock<MixProcessingData>>, ) { let mut buf = [0u8; sphinx::PACKET_SIZE]; // In a loop, read data from the socket and write the data back. loop { match socket.read(&mut buf).await { // socket closed Ok(n) if n == 0 => { println!("Remote connection closed."); return; } Ok(_) => { let store_data = match MixPacketProcessor::process_sphinx_data_packet( buf.as_ref(), processing_data.as_ref(), ) { Ok(sd) => sd, Err(e) => { eprintln!("failed to process sphinx packet; err = {:?}", e); return; } }; ClientStorage::store_processed_data( store_data, processing_data.read().unwrap().store_dir.as_path(), ) .unwrap_or_else(|e| { eprintln!("failed to store processed sphinx message; err = {:?}", e); return; }); } Err(e) => { eprintln!("failed to read from socket; err = {:?}", e); return; } }; // Write the some data back if let Err(e) = socket.write_all(b"foomp").await { eprintln!("failed to write reply to socket; err = {:?}", e); return; } } } async fn send_response(mut socket: tokio::net::TcpStream, data: &[u8]) { if let Err(e) = socket.write_all(data).await { eprintln!("failed to write reply to socket; err = {:?}", e) } if let Err(e) = socket.shutdown(Shutdown::Write) { eprintln!("failed to close write part of the socket; err = {:?}", e) } } // TODO: FIGURE OUT HOW TO SET READ_DEADLINES IN TOKIO async fn process_client_socket_connection( mut socket: tokio::net::TcpStream, processing_data: Arc<ClientProcessingData>, ) { let mut buf = [0; 1024]; // TODO: restore the for loop once we go back to persistent tcp socket connection let response = match socket.read(&mut buf).await { // socket closed Ok(n) if n == 0 => { println!("Remote connection closed."); Err(()) } Ok(n) => { match ClientRequestProcessor::process_client_request( buf[..n].as_ref(), processing_data, ) .await { Err(e) => { eprintln!("failed to process client request; err = {:?}", e); Err(()) } Ok(res) => Ok(res), } } Err(e) => { eprintln!("failed to read from socket; err = {:?}", e); Err(()) } }; if let Err(e) = socket.shutdown(Shutdown::Read) { eprintln!("failed to close read part of the socket; err = {:?}", e) } match response { Ok(res) => { println!("should send this response! {:?}", res); ServiceProvider::send_response(socket, &res).await; } _ => { println!("we failed..."); ServiceProvider::send_response(socket, b"bad foomp").await; } } } async fn start_mixnet_listening( address: SocketAddr, secret_key: DummyMixIdentityPrivateKey, store_dir: PathBuf, ) -> Result<(), ProviderError> { let mut listener = tokio::net::TcpListener::bind(address).await?; let processing_data = MixProcessingData::new(secret_key, store_dir).add_arc_rwlock(); loop { let (socket, _) = listener.accept().await?; // do note that the underlying data is NOT copied here; arc is incremented and lock is shared // (if I understand it all correctly) let thread_processing_data = processing_data.clone(); tokio::spawn(async move { ServiceProvider::process_mixnet_socket_connection(socket, thread_processing_data) .await }); } } async fn start_client_listening( address: SocketAddr, store_dir: PathBuf, client_ledger: Arc<FMutex<ClientLedger>>, secret_key: DummyMixIdentityPrivateKey, ) -> Result<(), ProviderError> { let mut listener = tokio::net::TcpListener::bind(address).await?; let processing_data = ClientProcessingData::new(store_dir, client_ledger, secret_key).add_arc(); loop { let (socket, _) = listener.accept().await?; // do note that the underlying data is NOT copied here; arc is incremented and lock is shared // (if I understand it all correctly) let thread_processing_data = processing_data.clone(); tokio::spawn(async move { ServiceProvider::process_client_socket_connection(socket, thread_processing_data) .await }); } } // Note: this now consumes the provider pub fn start(self) -> Result<(), Box<dyn std::error::Error>> { // Create the runtime, probably later move it to Provider struct itself? // TODO: figure out the difference between Runtime and Handle let mut rt = Runtime::new()?; // let mut h = rt.handle(); let initial_client_ledger = self.registered_clients_ledger; let thread_shareable_ledger = initial_client_ledger.add_arc_futures_mutex(); let presence_notifier = presence::Notifier::new( self.directory_server, self.client_network_address.clone(), self.mix_network_address.clone(), self.public_key, thread_shareable_ledger.clone(), ); let presence_future = rt.spawn(presence_notifier.run()); let mix_future = rt.spawn(ServiceProvider::start_mixnet_listening( self.mix_network_address, self.secret_key.clone(), self.store_dir.clone(), )); let client_future = rt.spawn(ServiceProvider::start_client_listening( self.client_network_address, self.store_dir.clone(), thread_shareable_ledger, self.secret_key, )); // Spawn the root task rt.block_on(async { let future_results = futures::future::join3(mix_future, client_future, presence_future).await; assert!(future_results.0.is_ok() && future_results.1.is_ok()); }); // this line in theory should never be reached as the runtime should be permanently blocked on listeners eprintln!("The server went kaput..."); Ok(()) } }
// Copyright (c) 2019 Ant Financial // // 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. //! Sync server of ttrpc. //! #[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use protobuf::{CodedInputStream, Message}; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}; use std::sync::{Arc, Mutex}; use std::thread; use std::thread::JoinHandle; use super::utils::{response_error_to_channel, response_to_channel}; use crate::context; use crate::error::{get_status, Error, Result}; use crate::proto::{Code, MessageHeader, Request, Response, MESSAGE_TYPE_REQUEST}; use crate::sync::channel::{read_message, write_message}; use crate::sync::sys::{PipeConnection, PipeListener}; use crate::{MethodHandler, TtrpcContext}; // poll_queue will create WAIT_THREAD_COUNT_DEFAULT threads in begin. // If wait thread count < WAIT_THREAD_COUNT_MIN, create number to WAIT_THREAD_COUNT_DEFAULT. // If wait thread count > WAIT_THREAD_COUNT_MAX, wait thread will quit to WAIT_THREAD_COUNT_DEFAULT. const DEFAULT_WAIT_THREAD_COUNT_DEFAULT: usize = 3; const DEFAULT_WAIT_THREAD_COUNT_MIN: usize = 1; const DEFAULT_WAIT_THREAD_COUNT_MAX: usize = 5; type MessageSender = Sender<(MessageHeader, Vec<u8>)>; type MessageReceiver = Receiver<(MessageHeader, Vec<u8>)>; type WorkloadSender = crossbeam::channel::Sender<(MessageHeader, Result<Vec<u8>>)>; type WorkloadReceiver = crossbeam::channel::Receiver<(MessageHeader, Result<Vec<u8>>)>; /// A ttrpc Server (sync). pub struct Server { listeners: Vec<Arc<PipeListener>>, listener_quit_flag: Arc<AtomicBool>, connections: Arc<Mutex<HashMap<i32, Connection>>>, methods: Arc<HashMap<String, Box<dyn MethodHandler + Send + Sync>>>, handler: Option<JoinHandle<()>>, reaper: Option<(Sender<i32>, JoinHandle<()>)>, thread_count_default: usize, thread_count_min: usize, thread_count_max: usize, } struct Connection { connection: Arc<PipeConnection>, quit: Arc<AtomicBool>, handler: Option<JoinHandle<()>>, } impl Connection { fn close(&self) { self.connection.close().unwrap_or(()); } fn shutdown(&self) { self.quit.store(true, Ordering::SeqCst); // in case the connection had closed self.connection.shutdown().unwrap_or(()); } } struct ThreadS<'a> { connection: &'a Arc<PipeConnection>, workload_rx: &'a WorkloadReceiver, wtc: &'a Arc<AtomicUsize>, quit: &'a Arc<AtomicBool>, methods: &'a Arc<HashMap<String, Box<dyn MethodHandler + Send + Sync>>>, res_tx: &'a MessageSender, control_tx: &'a SyncSender<()>, cancel_rx: &'a crossbeam::channel::Receiver<()>, default: usize, min: usize, max: usize, } #[allow(clippy::too_many_arguments)] fn start_method_handler_thread( connection: Arc<PipeConnection>, workload_rx: WorkloadReceiver, wtc: Arc<AtomicUsize>, quit: Arc<AtomicBool>, methods: Arc<HashMap<String, Box<dyn MethodHandler + Send + Sync>>>, res_tx: MessageSender, control_tx: SyncSender<()>, cancel_rx: crossbeam::channel::Receiver<()>, min: usize, max: usize, ) { thread::spawn(move || { while !quit.load(Ordering::SeqCst) { let c = wtc.fetch_add(1, Ordering::SeqCst) + 1; if c > max { wtc.fetch_sub(1, Ordering::SeqCst); break; } let result = workload_rx.recv(); if quit.load(Ordering::SeqCst) { // notify the connection dealing main thread to stop. control_tx .send(()) .unwrap_or_else(|err| trace!("Failed to send {:?}", err)); break; } let c = wtc.fetch_sub(1, Ordering::SeqCst) - 1; if c < min { trace!("notify client handler to create much more worker threads!"); control_tx .send(()) .unwrap_or_else(|err| trace!("Failed to send {:?}", err)); } let mh; let buf; match result { Ok((x, Ok(y))) => { mh = x; buf = y; } Ok((mh, Err(e))) => { if let Err(x) = response_error_to_channel(mh.stream_id, e, res_tx.clone()) { debug!("response_error_to_channel get error {:?}", x); quit_connection(quit, control_tx); break; } continue; } Err(x) => match x { crossbeam::channel::RecvError => { trace!("workload_rx recv error"); quit_connection(quit, control_tx); trace!("workload_rx recv error, send control_tx"); break; } }, } if mh.type_ != MESSAGE_TYPE_REQUEST { continue; } let mut s = CodedInputStream::from_bytes(&buf); let mut req = Request::new(); if let Err(x) = req.merge_from(&mut s) { let status = get_status(Code::INVALID_ARGUMENT, x.to_string()); let mut res = Response::new(); res.set_status(status); if let Err(x) = response_to_channel(mh.stream_id, res, res_tx.clone()) { debug!("response_to_channel get error {:?}", x); quit_connection(quit, control_tx); break; } continue; } trace!("Got Message request {:?}", req); let path = format!("/{}/{}", req.service, req.method); let method = if let Some(x) = methods.get(&path) { x } else { let status = get_status(Code::INVALID_ARGUMENT, format!("{path} does not exist")); let mut res = Response::new(); res.set_status(status); if let Err(x) = response_to_channel(mh.stream_id, res, res_tx.clone()) { info!("response_to_channel get error {:?}", x); quit_connection(quit, control_tx); break; } continue; }; let ctx = TtrpcContext { fd: connection.id(), cancel_rx: cancel_rx.clone(), mh, res_tx: res_tx.clone(), metadata: context::from_pb(&req.metadata), timeout_nano: req.timeout_nano, }; if let Err(x) = method.handler(ctx, req) { debug!("method handle {} get error {:?}", path, x); quit_connection(quit, control_tx); break; } } }); } fn start_method_handler_threads(num: usize, ts: &ThreadS) { for _ in 0..num { if ts.quit.load(Ordering::SeqCst) { break; } start_method_handler_thread( ts.connection.clone(), ts.workload_rx.clone(), ts.wtc.clone(), ts.quit.clone(), ts.methods.clone(), ts.res_tx.clone(), ts.control_tx.clone(), ts.cancel_rx.clone(), ts.min, ts.max, ); } } fn check_method_handler_threads(ts: &ThreadS) { let c = ts.wtc.load(Ordering::SeqCst); if c < ts.min { start_method_handler_threads(ts.default - c, ts); } } impl Default for Server { fn default() -> Self { Server { listeners: Vec::with_capacity(1), listener_quit_flag: Arc::new(AtomicBool::new(false)), connections: Arc::new(Mutex::new(HashMap::new())), methods: Arc::new(HashMap::new()), handler: None, reaper: None, thread_count_default: DEFAULT_WAIT_THREAD_COUNT_DEFAULT, thread_count_min: DEFAULT_WAIT_THREAD_COUNT_MIN, thread_count_max: DEFAULT_WAIT_THREAD_COUNT_MAX, } } } impl Server { pub fn new() -> Server { Server::default() } pub fn bind(mut self, sockaddr: &str) -> Result<Server> { if !self.listeners.is_empty() { return Err(Error::Others( "ttrpc-rust just support 1 sockaddr now".to_string(), )); } let listener = PipeListener::new(sockaddr)?; self.listeners.push(Arc::new(listener)); Ok(self) } #[cfg(unix)] pub fn add_listener(mut self, fd: RawFd) -> Result<Server> { if !self.listeners.is_empty() { return Err(Error::Others( "ttrpc-rust just support 1 sockaddr now".to_string(), )); } let listener = PipeListener::new_from_fd(fd)?; self.listeners.push(Arc::new(listener)); Ok(self) } pub fn register_service( mut self, methods: HashMap<String, Box<dyn MethodHandler + Send + Sync>>, ) -> Server { let mut_methods = Arc::get_mut(&mut self.methods).unwrap(); mut_methods.extend(methods); self } pub fn set_thread_count_default(mut self, count: usize) -> Server { self.thread_count_default = count; self } pub fn set_thread_count_min(mut self, count: usize) -> Server { self.thread_count_min = count; self } pub fn set_thread_count_max(mut self, count: usize) -> Server { self.thread_count_max = count; self } pub fn start_listen(&mut self) -> Result<()> { let connections = self.connections.clone(); if self.listeners.is_empty() { return Err(Error::Others("ttrpc-rust not bind".to_string())); } self.listener_quit_flag.store(false, Ordering::SeqCst); let listener = self.listeners[0].clone(); let methods = self.methods.clone(); let default = self.thread_count_default; let min = self.thread_count_min; let max = self.thread_count_max; let listener_quit_flag = self.listener_quit_flag.clone(); let reaper_tx = match self.reaper.take() { None => { let reaper_connections = connections.clone(); let (reaper_tx, reaper_rx) = channel(); let reaper_handler = thread::Builder::new() .name("reaper".into()) .spawn(move || { for fd in reaper_rx.iter() { reaper_connections .lock() .unwrap() .remove(&fd) .map(|mut cn| { cn.handler.take().map(|handler| { handler.join().unwrap(); cn.close() }) }); } info!("reaper thread exited"); }) .unwrap(); self.reaper = Some((reaper_tx.clone(), reaper_handler)); reaper_tx } Some(r) => { let reaper_tx = r.0.clone(); self.reaper = Some(r); reaper_tx } }; let handler = thread::Builder::new() .name("listener_loop".into()) .spawn(move || { loop { trace!("listening..."); let pipe_connection = match listener.accept(&listener_quit_flag) { Ok(None) => { continue; } Ok(Some(conn)) => Arc::new(conn), Err(e) => { error!("listener accept got {:?}", e); break; } }; let methods = methods.clone(); let quit = Arc::new(AtomicBool::new(false)); let child_quit = quit.clone(); let reaper_tx_child = reaper_tx.clone(); let pipe_connection_child = pipe_connection.clone(); let handler = thread::Builder::new() .name("client_handler".into()) .spawn(move || { debug!("Got new client"); // Start response thread let quit_res = child_quit.clone(); let pipe = pipe_connection_child.clone(); let (res_tx, res_rx): (MessageSender, MessageReceiver) = channel(); let handler = thread::spawn(move || { for r in res_rx.iter() { trace!("response thread get {:?}", r); if let Err(e) = write_message(&pipe, r.0, r.1) { error!("write_message got {:?}", e); quit_res.store(true, Ordering::SeqCst); break; } } trace!("response thread quit"); }); let (control_tx, control_rx): (SyncSender<()>, Receiver<()>) = sync_channel(0); // start read message thread let quit_reader = child_quit.clone(); let pipe_reader = pipe_connection_child.clone(); let (workload_tx, workload_rx): (WorkloadSender, WorkloadReceiver) = crossbeam::channel::unbounded(); let (cancel_tx, cancel_rx) = crossbeam::channel::unbounded::<()>(); let control_tx_reader = control_tx.clone(); let reader = thread::spawn(move || { while !quit_reader.load(Ordering::SeqCst) { let msg = read_message(&pipe_reader); match msg { Ok((x, y)) => { let res = workload_tx.send((x, y)); match res { Ok(_) => {} Err(crossbeam::channel::SendError(e)) => { error!("Send workload error {:?}", e); quit_reader.store(true, Ordering::SeqCst); control_tx_reader.send(()).unwrap_or_else( |err| trace!("Failed to send {:?}", err), ); break; } } } Err(x) => match x { Error::Socket(y) => { trace!("Socket error {}", y); drop(cancel_tx); quit_reader.store(true, Ordering::SeqCst); // the client connection would be closed and // the connection dealing main thread would // have exited. control_tx_reader.send(()).unwrap_or_else(|err| { trace!("Failed to send {:?}", err) }); trace!("Socket error send control_tx"); break; } _ => { trace!("Other error {:?}", x); continue; } }, } } trace!("read message thread quit"); }); let pipe = pipe_connection_child.clone(); let ts = ThreadS { connection: &pipe, workload_rx: &workload_rx, wtc: &Arc::new(AtomicUsize::new(0)), methods: &methods, res_tx: &res_tx, control_tx: &control_tx, cancel_rx: &cancel_rx, quit: &child_quit, default, min, max, }; start_method_handler_threads(ts.default, &ts); while !child_quit.load(Ordering::SeqCst) { check_method_handler_threads(&ts); if control_rx.recv().is_err() { break; } } // drop the control_rx, thus all of the method handler threads would // terminated. drop(control_rx); // drop the res_tx, thus the res_rx would get terminated notification. drop(res_tx); drop(workload_rx); handler.join().unwrap_or(()); reader.join().unwrap_or(()); // client_handler should not close fd before exit // , which prevent fd reuse issue. reaper_tx_child.send(pipe.id()).unwrap(); debug!("client thread quit"); }) .unwrap(); let mut cns = connections.lock().unwrap(); let id = pipe_connection.id(); cns.insert( id, Connection { connection: pipe_connection, handler: Some(handler), quit: quit.clone(), }, ); } // end loop // notify reaper thread to exit. drop(reaper_tx); info!("ttrpc server listener stopped"); }) .unwrap(); self.handler = Some(handler); info!("server listen started"); Ok(()) } pub fn start(&mut self) -> Result<()> { if self.thread_count_default >= self.thread_count_max { return Err(Error::Others( "thread_count_default should smaller than thread_count_max".to_string(), )); } if self.thread_count_default <= self.thread_count_min { return Err(Error::Others( "thread_count_default should bigger than thread_count_min".to_string(), )); } self.start_listen()?; info!("server started"); Ok(()) } pub fn stop_listen(mut self) -> Self { self.listener_quit_flag.store(true, Ordering::SeqCst); self.listeners[0] .close() .unwrap_or_else(|e| warn!("failed to close connection with error: {}", e)); info!("close monitor"); if let Some(handler) = self.handler.take() { handler.join().unwrap(); } info!("listener thread stopped"); self } pub fn disconnect(mut self) { info!("begin to shutdown connection"); let connections = self.connections.lock().unwrap(); for (_fd, c) in connections.iter() { c.shutdown(); } // release connections's lock, since the following handler.join() // would wait on the other thread's exit in which would take the lock. drop(connections); info!("connections closed"); if let Some(r) = self.reaper.take() { drop(r.0); r.1.join().unwrap(); } info!("reaper thread stopped"); } pub fn shutdown(self) { self.stop_listen().disconnect(); } } #[cfg(unix)] impl FromRawFd for Server { unsafe fn from_raw_fd(fd: RawFd) -> Self { Self::default().add_listener(fd).unwrap() } } #[cfg(unix)] impl AsRawFd for Server { fn as_raw_fd(&self) -> RawFd { self.listeners[0].as_raw_fd() } } fn quit_connection(quit: Arc<AtomicBool>, control_tx: SyncSender<()>) { quit.store(true, Ordering::SeqCst); // the client connection would be closed and // the connection dealing main thread would // have exited. control_tx .send(()) .unwrap_or_else(|err| debug!("Failed to send {:?}", err)); }
#[macro_use] extern crate conrod_core; pub mod core;
fn main() { let mut i = 0; while i < 50 { i += 1; if i % 3 == 0 { continue; } if i * i > 400 { break; } print!("{} ", i * i); } println!(""); }
use super::prelude::*; use super::schema::{user, user_auth}; #[derive(Debug, Clone, Validate, Serialize, Deserialize)] pub struct QueryNewUser { #[validate(length(min = 8))] pub(crate) user_name: String, #[validate(length(min = 1))] pub(crate) nick_name: String, #[validate(length(max = 11))] pub(crate) mobile: String, #[validate(email)] pub(crate) email: String, #[validate(length(min = 8))] pub(crate) certificate: String, } #[derive(Queryable, Identifiable, AsChangeset, Debug, Clone, Serialize, Deserialize)] #[table_name = "user"] pub struct User { pub id: u64, pub user_name: String, pub nick_name: String, pub mobile: String, pub email: String, pub face: String, pub status: i8, pub created_time: NaiveDateTime, pub updated_time: NaiveDateTime, } #[derive(Insertable, Debug, Serialize, Deserialize)] #[table_name = "user"] pub struct NewUser { user_name: String, nick_name: String, mobile: String, email: String, } #[derive(Queryable, Identifiable, AsChangeset, Debug, Clone, Serialize, Deserialize)] #[table_name = "user"] pub struct UpdateUser { id: u64, user_name: String, nick_name: String, mobile: String, email: String, } impl From<&QueryNewUser> for NewUser { fn from(value: &QueryNewUser) -> NewUser { NewUser { user_name: value.user_name.clone(), nick_name: value.nick_name.clone(), mobile: value.mobile.clone(), email: value.email.clone(), } } } pub struct NewUserAuths(pub [NewUserAuth; 3]); //QueryNewUser impl From<(QueryNewUser, u64)> for NewUserAuths { fn from( ( QueryNewUser { user_name, mobile, email, certificate, .. }, user_id, ): (QueryNewUser, u64), ) -> NewUserAuths { let user_auth_arr: [NewUserAuth; 3]; let encrypted_certificate = get_encrypted_certificate_by_raw_certificate(&certificate); let mobile_auth = NewUserAuth { user_id, identity_type: types::IdentityType::Mobile as u8, identifier: mobile, certificate: encrypted_certificate.clone(), status: state::user_auth::State::Health as i8, }; let email_auth = NewUserAuth { user_id, identity_type: types::IdentityType::Email as u8, identifier: email, certificate: encrypted_certificate.clone(), status: state::user_auth::State::Health as i8, }; let username_auth = NewUserAuth { user_id, identity_type: types::IdentityType::Username as u8, identifier: user_name, certificate: encrypted_certificate, status: state::user_auth::State::Health as i8, }; user_auth_arr = [mobile_auth, email_auth, username_auth]; NewUserAuths(user_auth_arr) } } pub fn get_encrypted_certificate_by_raw_certificate(certificate: &str) -> String { let encrypted_certificate_digest = digest(&SHA256, certificate.as_bytes()); hex::encode(encrypted_certificate_digest.as_ref()) } #[derive(Queryable, Identifiable, AsChangeset, Debug, Clone, Serialize, Deserialize)] #[table_name = "user_auth"] pub struct UserAuth { pub id: i64, pub user_id: u64, pub identity_type: u8, pub identifier: String, pub certificate: String, pub status: i8, pub created_time: NaiveDateTime, pub updated_time: NaiveDateTime, } #[derive(Insertable, Debug, Serialize, Deserialize)] #[table_name = "user_auth"] pub struct NewUserAuth { user_id: u64, identity_type: u8, identifier: String, certificate: String, status: i8, } #[derive(Debug, Serialize, Deserialize)] pub struct UserAuthLogin { pub(crate) login_type: u8, pub(crate) account: String, pub(crate) password: String, } #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub(crate) struct QueryParamsUser { id: Option<u64>, user_name: Option<String>, nick_name: Option<String>, mobile: Option<String>, email: Option<String>, status: Option<i8>, pub(crate) per_page: i64, pub(crate) page: i64, } #[derive(Debug, Copy, Clone, Serialize, Deserialize)] pub(crate) struct UserId { pub(crate) user_id: u64, } pub(crate) struct UserQueryBuilder; impl UserQueryBuilder { pub(crate) fn query_all_columns() -> user::BoxedQuery<'static, Mysql> { user::table.into_boxed().select(user::all_columns) } pub(crate) fn query_count() -> user::BoxedQuery<'static, Mysql, diesel::sql_types::Bigint> { user::table.into_boxed().count() } } impl QueryParamsUser { pub(crate) fn query_filter<ST>( self, mut statement_builder: user::BoxedQuery<'static, Mysql, ST>, ) -> user::BoxedQuery<'static, Mysql, ST> { if let Some(user_id) = self.id { statement_builder = statement_builder.filter(user::id.eq(user_id)); } if let Some(status) = self.status { statement_builder = statement_builder.filter(user::status.eq(status)); } else { statement_builder = statement_builder.filter(user::status.ne(state::user::State::Forbidden as i8)); } if let Some(user_name) = self.user_name { statement_builder = statement_builder.filter(user::user_name.like(user_name)); } if let Some(mobile) = self.mobile { statement_builder = statement_builder.filter(user::mobile.eq(mobile)); } if let Some(email) = self.email { statement_builder = statement_builder.filter(user::email.eq(email)); } statement_builder.order(user::id.desc()) } }
#[doc = "Reader of register DDRCTRL_DRAMTMG4"] pub type R = crate::R<u32, super::DDRCTRL_DRAMTMG4>; #[doc = "Writer for register DDRCTRL_DRAMTMG4"] pub type W = crate::W<u32, super::DDRCTRL_DRAMTMG4>; #[doc = "Register DDRCTRL_DRAMTMG4 `reset()`'s with value 0x0504_0405"] impl crate::ResetValue for super::DDRCTRL_DRAMTMG4 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0504_0405 } } #[doc = "Reader of field `T_RP`"] pub type T_RP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `T_RP`"] pub struct T_RP_W<'a> { w: &'a mut W, } impl<'a> T_RP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f); self.w } } #[doc = "Reader of field `T_RRD`"] pub type T_RRD_R = crate::R<u8, u8>; #[doc = "Write proxy for field `T_RRD`"] pub struct T_RRD_W<'a> { w: &'a mut W, } impl<'a> T_RRD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `T_CCD`"] pub type T_CCD_R = crate::R<u8, u8>; #[doc = "Write proxy for field `T_CCD`"] pub struct T_CCD_W<'a> { w: &'a mut W, } impl<'a> T_CCD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `T_RCD`"] pub type T_RCD_R = crate::R<u8, u8>; #[doc = "Write proxy for field `T_RCD`"] pub struct T_RCD_W<'a> { w: &'a mut W, } impl<'a> T_RCD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 24)) | (((value as u32) & 0x1f) << 24); self.w } } impl R { #[doc = "Bits 0:4 - T_RP"] #[inline(always)] pub fn t_rp(&self) -> T_RP_R { T_RP_R::new((self.bits & 0x1f) as u8) } #[doc = "Bits 8:11 - T_RRD"] #[inline(always)] pub fn t_rrd(&self) -> T_RRD_R { T_RRD_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 16:19 - T_CCD"] #[inline(always)] pub fn t_ccd(&self) -> T_CCD_R { T_CCD_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 24:28 - T_RCD"] #[inline(always)] pub fn t_rcd(&self) -> T_RCD_R { T_RCD_R::new(((self.bits >> 24) & 0x1f) as u8) } } impl W { #[doc = "Bits 0:4 - T_RP"] #[inline(always)] pub fn t_rp(&mut self) -> T_RP_W { T_RP_W { w: self } } #[doc = "Bits 8:11 - T_RRD"] #[inline(always)] pub fn t_rrd(&mut self) -> T_RRD_W { T_RRD_W { w: self } } #[doc = "Bits 16:19 - T_CCD"] #[inline(always)] pub fn t_ccd(&mut self) -> T_CCD_W { T_CCD_W { w: self } } #[doc = "Bits 24:28 - T_RCD"] #[inline(always)] pub fn t_rcd(&mut self) -> T_RCD_W { T_RCD_W { w: self } } }
#[doc = "BLESS DDFT configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ddft_config](ddft_config) module"] pub type DDFT_CONFIG = crate::Reg<u32, _DDFT_CONFIG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DDFT_CONFIG; #[doc = "`read()` method returns [ddft_config::R](ddft_config::R) reader structure"] impl crate::Readable for DDFT_CONFIG {} #[doc = "`write(|w| ..)` method takes [ddft_config::W](ddft_config::W) writer structure"] impl crate::Writable for DDFT_CONFIG {} #[doc = "BLESS DDFT configuration register"] pub mod ddft_config; #[doc = "Crystal clock divider configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [xtal_clk_div_config](xtal_clk_div_config) module"] pub type XTAL_CLK_DIV_CONFIG = crate::Reg<u32, _XTAL_CLK_DIV_CONFIG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _XTAL_CLK_DIV_CONFIG; #[doc = "`read()` method returns [xtal_clk_div_config::R](xtal_clk_div_config::R) reader structure"] impl crate::Readable for XTAL_CLK_DIV_CONFIG {} #[doc = "`write(|w| ..)` method takes [xtal_clk_div_config::W](xtal_clk_div_config::W) writer structure"] impl crate::Writable for XTAL_CLK_DIV_CONFIG {} #[doc = "Crystal clock divider configuration register"] pub mod xtal_clk_div_config; #[doc = "Link Layer interrupt status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_stat](intr_stat) module"] pub type INTR_STAT = crate::Reg<u32, _INTR_STAT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_STAT; #[doc = "`read()` method returns [intr_stat::R](intr_stat::R) reader structure"] impl crate::Readable for INTR_STAT {} #[doc = "`write(|w| ..)` method takes [intr_stat::W](intr_stat::W) writer structure"] impl crate::Writable for INTR_STAT {} #[doc = "Link Layer interrupt status register"] pub mod intr_stat; #[doc = "Link Layer interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"] pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASK; #[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"] impl crate::Readable for INTR_MASK {} #[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"] impl crate::Writable for INTR_MASK {} #[doc = "Link Layer interrupt mask register"] pub mod intr_mask; #[doc = "Link Layer primary clock enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ll_clk_en](ll_clk_en) module"] pub type LL_CLK_EN = crate::Reg<u32, _LL_CLK_EN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _LL_CLK_EN; #[doc = "`read()` method returns [ll_clk_en::R](ll_clk_en::R) reader structure"] impl crate::Readable for LL_CLK_EN {} #[doc = "`write(|w| ..)` method takes [ll_clk_en::W](ll_clk_en::W) writer structure"] impl crate::Writable for LL_CLK_EN {} #[doc = "Link Layer primary clock enable"] pub mod ll_clk_en; #[doc = "BLESS LF clock control and BLESS revision ID indicator\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [lf_clk_ctrl](lf_clk_ctrl) module"] pub type LF_CLK_CTRL = crate::Reg<u32, _LF_CLK_CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _LF_CLK_CTRL; #[doc = "`read()` method returns [lf_clk_ctrl::R](lf_clk_ctrl::R) reader structure"] impl crate::Readable for LF_CLK_CTRL {} #[doc = "`write(|w| ..)` method takes [lf_clk_ctrl::W](lf_clk_ctrl::W) writer structure"] impl crate::Writable for LF_CLK_CTRL {} #[doc = "BLESS LF clock control and BLESS revision ID indicator"] pub mod lf_clk_ctrl; #[doc = "External TX PA and RX LNA control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ext_pa_lna_ctrl](ext_pa_lna_ctrl) module"] pub type EXT_PA_LNA_CTRL = crate::Reg<u32, _EXT_PA_LNA_CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EXT_PA_LNA_CTRL; #[doc = "`read()` method returns [ext_pa_lna_ctrl::R](ext_pa_lna_ctrl::R) reader structure"] impl crate::Readable for EXT_PA_LNA_CTRL {} #[doc = "`write(|w| ..)` method takes [ext_pa_lna_ctrl::W](ext_pa_lna_ctrl::W) writer structure"] impl crate::Writable for EXT_PA_LNA_CTRL {} #[doc = "External TX PA and RX LNA control"] pub mod ext_pa_lna_ctrl; #[doc = "Link Layer Last Received packet RSSI/Channel energy and channel number\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ll_pkt_rssi_ch_energy](ll_pkt_rssi_ch_energy) module"] pub type LL_PKT_RSSI_CH_ENERGY = crate::Reg<u32, _LL_PKT_RSSI_CH_ENERGY>; #[allow(missing_docs)] #[doc(hidden)] pub struct _LL_PKT_RSSI_CH_ENERGY; #[doc = "`read()` method returns [ll_pkt_rssi_ch_energy::R](ll_pkt_rssi_ch_energy::R) reader structure"] impl crate::Readable for LL_PKT_RSSI_CH_ENERGY {} #[doc = "Link Layer Last Received packet RSSI/Channel energy and channel number"] pub mod ll_pkt_rssi_ch_energy; #[doc = "BT clock captured on an LL DSM exit\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [bt_clock_capt](bt_clock_capt) module"] pub type BT_CLOCK_CAPT = crate::Reg<u32, _BT_CLOCK_CAPT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _BT_CLOCK_CAPT; #[doc = "`read()` method returns [bt_clock_capt::R](bt_clock_capt::R) reader structure"] impl crate::Readable for BT_CLOCK_CAPT {} #[doc = "BT clock captured on an LL DSM exit"] pub mod bt_clock_capt; #[doc = "MT Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mt_cfg](mt_cfg) module"] pub type MT_CFG = crate::Reg<u32, _MT_CFG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MT_CFG; #[doc = "`read()` method returns [mt_cfg::R](mt_cfg::R) reader structure"] impl crate::Readable for MT_CFG {} #[doc = "`write(|w| ..)` method takes [mt_cfg::W](mt_cfg::W) writer structure"] impl crate::Writable for MT_CFG {} #[doc = "MT Configuration Register"] pub mod mt_cfg; #[doc = "MT Delay configuration for state transitions\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mt_delay_cfg](mt_delay_cfg) module"] pub type MT_DELAY_CFG = crate::Reg<u32, _MT_DELAY_CFG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MT_DELAY_CFG; #[doc = "`read()` method returns [mt_delay_cfg::R](mt_delay_cfg::R) reader structure"] impl crate::Readable for MT_DELAY_CFG {} #[doc = "`write(|w| ..)` method takes [mt_delay_cfg::W](mt_delay_cfg::W) writer structure"] impl crate::Writable for MT_DELAY_CFG {} #[doc = "MT Delay configuration for state transitions"] pub mod mt_delay_cfg; #[doc = "MT Delay configuration for state transitions\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mt_delay_cfg2](mt_delay_cfg2) module"] pub type MT_DELAY_CFG2 = crate::Reg<u32, _MT_DELAY_CFG2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MT_DELAY_CFG2; #[doc = "`read()` method returns [mt_delay_cfg2::R](mt_delay_cfg2::R) reader structure"] impl crate::Readable for MT_DELAY_CFG2 {} #[doc = "`write(|w| ..)` method takes [mt_delay_cfg2::W](mt_delay_cfg2::W) writer structure"] impl crate::Writable for MT_DELAY_CFG2 {} #[doc = "MT Delay configuration for state transitions"] pub mod mt_delay_cfg2; #[doc = "MT Delay configuration for state transitions\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mt_delay_cfg3](mt_delay_cfg3) module"] pub type MT_DELAY_CFG3 = crate::Reg<u32, _MT_DELAY_CFG3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MT_DELAY_CFG3; #[doc = "`read()` method returns [mt_delay_cfg3::R](mt_delay_cfg3::R) reader structure"] impl crate::Readable for MT_DELAY_CFG3 {} #[doc = "`write(|w| ..)` method takes [mt_delay_cfg3::W](mt_delay_cfg3::W) writer structure"] impl crate::Writable for MT_DELAY_CFG3 {} #[doc = "MT Delay configuration for state transitions"] pub mod mt_delay_cfg3; #[doc = "MT Configuration Register to control VIO switches\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mt_vio_ctrl](mt_vio_ctrl) module"] pub type MT_VIO_CTRL = crate::Reg<u32, _MT_VIO_CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MT_VIO_CTRL; #[doc = "`read()` method returns [mt_vio_ctrl::R](mt_vio_ctrl::R) reader structure"] impl crate::Readable for MT_VIO_CTRL {} #[doc = "`write(|w| ..)` method takes [mt_vio_ctrl::W](mt_vio_ctrl::W) writer structure"] impl crate::Writable for MT_VIO_CTRL {} #[doc = "MT Configuration Register to control VIO switches"] pub mod mt_vio_ctrl; #[doc = "MT Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mt_status](mt_status) module"] pub type MT_STATUS = crate::Reg<u32, _MT_STATUS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MT_STATUS; #[doc = "`read()` method returns [mt_status::R](mt_status::R) reader structure"] impl crate::Readable for MT_STATUS {} #[doc = "MT Status Register"] pub mod mt_status; #[doc = "Link Layer Power Control FSM Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [pwr_ctrl_sm_st](pwr_ctrl_sm_st) module"] pub type PWR_CTRL_SM_ST = crate::Reg<u32, _PWR_CTRL_SM_ST>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PWR_CTRL_SM_ST; #[doc = "`read()` method returns [pwr_ctrl_sm_st::R](pwr_ctrl_sm_st::R) reader structure"] impl crate::Readable for PWR_CTRL_SM_ST {} #[doc = "Link Layer Power Control FSM Status Register"] pub mod pwr_ctrl_sm_st; #[doc = "HVLDO Configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [hvldo_ctrl](hvldo_ctrl) module"] pub type HVLDO_CTRL = crate::Reg<u32, _HVLDO_CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _HVLDO_CTRL; #[doc = "`read()` method returns [hvldo_ctrl::R](hvldo_ctrl::R) reader structure"] impl crate::Readable for HVLDO_CTRL {} #[doc = "`write(|w| ..)` method takes [hvldo_ctrl::W](hvldo_ctrl::W) writer structure"] impl crate::Writable for HVLDO_CTRL {} #[doc = "HVLDO Configuration register"] pub mod hvldo_ctrl; #[doc = "Radio Buck and Active regulator enable control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [misc_en_ctrl](misc_en_ctrl) module"] pub type MISC_EN_CTRL = crate::Reg<u32, _MISC_EN_CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MISC_EN_CTRL; #[doc = "`read()` method returns [misc_en_ctrl::R](misc_en_ctrl::R) reader structure"] impl crate::Readable for MISC_EN_CTRL {} #[doc = "`write(|w| ..)` method takes [misc_en_ctrl::W](misc_en_ctrl::W) writer structure"] impl crate::Writable for MISC_EN_CTRL {} #[doc = "Radio Buck and Active regulator enable control"] pub mod misc_en_ctrl; #[doc = "EFUSE mode configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [efuse_config](efuse_config) module"] pub type EFUSE_CONFIG = crate::Reg<u32, _EFUSE_CONFIG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EFUSE_CONFIG; #[doc = "`read()` method returns [efuse_config::R](efuse_config::R) reader structure"] impl crate::Readable for EFUSE_CONFIG {} #[doc = "`write(|w| ..)` method takes [efuse_config::W](efuse_config::W) writer structure"] impl crate::Writable for EFUSE_CONFIG {} #[doc = "EFUSE mode configuration register"] pub mod efuse_config; #[doc = "EFUSE timing control register (common for Program and Read modes)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [efuse_tim_ctrl1](efuse_tim_ctrl1) module"] pub type EFUSE_TIM_CTRL1 = crate::Reg<u32, _EFUSE_TIM_CTRL1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EFUSE_TIM_CTRL1; #[doc = "`read()` method returns [efuse_tim_ctrl1::R](efuse_tim_ctrl1::R) reader structure"] impl crate::Readable for EFUSE_TIM_CTRL1 {} #[doc = "`write(|w| ..)` method takes [efuse_tim_ctrl1::W](efuse_tim_ctrl1::W) writer structure"] impl crate::Writable for EFUSE_TIM_CTRL1 {} #[doc = "EFUSE timing control register (common for Program and Read modes)"] pub mod efuse_tim_ctrl1; #[doc = "EFUSE timing control Register (for Read)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [efuse_tim_ctrl2](efuse_tim_ctrl2) module"] pub type EFUSE_TIM_CTRL2 = crate::Reg<u32, _EFUSE_TIM_CTRL2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EFUSE_TIM_CTRL2; #[doc = "`read()` method returns [efuse_tim_ctrl2::R](efuse_tim_ctrl2::R) reader structure"] impl crate::Readable for EFUSE_TIM_CTRL2 {} #[doc = "`write(|w| ..)` method takes [efuse_tim_ctrl2::W](efuse_tim_ctrl2::W) writer structure"] impl crate::Writable for EFUSE_TIM_CTRL2 {} #[doc = "EFUSE timing control Register (for Read)"] pub mod efuse_tim_ctrl2; #[doc = "EFUSE timing control Register (for Program)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [efuse_tim_ctrl3](efuse_tim_ctrl3) module"] pub type EFUSE_TIM_CTRL3 = crate::Reg<u32, _EFUSE_TIM_CTRL3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EFUSE_TIM_CTRL3; #[doc = "`read()` method returns [efuse_tim_ctrl3::R](efuse_tim_ctrl3::R) reader structure"] impl crate::Readable for EFUSE_TIM_CTRL3 {} #[doc = "`write(|w| ..)` method takes [efuse_tim_ctrl3::W](efuse_tim_ctrl3::W) writer structure"] impl crate::Writable for EFUSE_TIM_CTRL3 {} #[doc = "EFUSE timing control Register (for Program)"] pub mod efuse_tim_ctrl3; #[doc = "EFUSE Lower read data\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [efuse_rdata_l](efuse_rdata_l) module"] pub type EFUSE_RDATA_L = crate::Reg<u32, _EFUSE_RDATA_L>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EFUSE_RDATA_L; #[doc = "`read()` method returns [efuse_rdata_l::R](efuse_rdata_l::R) reader structure"] impl crate::Readable for EFUSE_RDATA_L {} #[doc = "EFUSE Lower read data"] pub mod efuse_rdata_l; #[doc = "EFUSE higher read data\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [efuse_rdata_h](efuse_rdata_h) module"] pub type EFUSE_RDATA_H = crate::Reg<u32, _EFUSE_RDATA_H>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EFUSE_RDATA_H; #[doc = "`read()` method returns [efuse_rdata_h::R](efuse_rdata_h::R) reader structure"] impl crate::Readable for EFUSE_RDATA_H {} #[doc = "EFUSE higher read data"] pub mod efuse_rdata_h; #[doc = "EFUSE lower write word\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [efuse_wdata_l](efuse_wdata_l) module"] pub type EFUSE_WDATA_L = crate::Reg<u32, _EFUSE_WDATA_L>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EFUSE_WDATA_L; #[doc = "`read()` method returns [efuse_wdata_l::R](efuse_wdata_l::R) reader structure"] impl crate::Readable for EFUSE_WDATA_L {} #[doc = "`write(|w| ..)` method takes [efuse_wdata_l::W](efuse_wdata_l::W) writer structure"] impl crate::Writable for EFUSE_WDATA_L {} #[doc = "EFUSE lower write word"] pub mod efuse_wdata_l; #[doc = "EFUSE higher write word\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [efuse_wdata_h](efuse_wdata_h) module"] pub type EFUSE_WDATA_H = crate::Reg<u32, _EFUSE_WDATA_H>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EFUSE_WDATA_H; #[doc = "`read()` method returns [efuse_wdata_h::R](efuse_wdata_h::R) reader structure"] impl crate::Readable for EFUSE_WDATA_H {} #[doc = "`write(|w| ..)` method takes [efuse_wdata_h::W](efuse_wdata_h::W) writer structure"] impl crate::Writable for EFUSE_WDATA_H {} #[doc = "EFUSE higher write word"] pub mod efuse_wdata_h; #[doc = "Divide by 625 for FW Use\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [div_by_625_cfg](div_by_625_cfg) module"] pub type DIV_BY_625_CFG = crate::Reg<u32, _DIV_BY_625_CFG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DIV_BY_625_CFG; #[doc = "`read()` method returns [div_by_625_cfg::R](div_by_625_cfg::R) reader structure"] impl crate::Readable for DIV_BY_625_CFG {} #[doc = "`write(|w| ..)` method takes [div_by_625_cfg::W](div_by_625_cfg::W) writer structure"] impl crate::Writable for DIV_BY_625_CFG {} #[doc = "Divide by 625 for FW Use"] pub mod div_by_625_cfg; #[doc = "Output of divide by 625 divider\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [div_by_625_sts](div_by_625_sts) module"] pub type DIV_BY_625_STS = crate::Reg<u32, _DIV_BY_625_STS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DIV_BY_625_STS; #[doc = "`read()` method returns [div_by_625_sts::R](div_by_625_sts::R) reader structure"] impl crate::Readable for DIV_BY_625_STS {} #[doc = "Output of divide by 625 divider"] pub mod div_by_625_sts; #[doc = "Packet counter 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [packet_counter0](packet_counter0) module"] pub type PACKET_COUNTER0 = crate::Reg<u32, _PACKET_COUNTER0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PACKET_COUNTER0; #[doc = "`read()` method returns [packet_counter0::R](packet_counter0::R) reader structure"] impl crate::Readable for PACKET_COUNTER0 {} #[doc = "`write(|w| ..)` method takes [packet_counter0::W](packet_counter0::W) writer structure"] impl crate::Writable for PACKET_COUNTER0 {} #[doc = "Packet counter 0"] pub mod packet_counter0; #[doc = "Packet counter 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [packet_counter2](packet_counter2) module"] pub type PACKET_COUNTER2 = crate::Reg<u32, _PACKET_COUNTER2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PACKET_COUNTER2; #[doc = "`read()` method returns [packet_counter2::R](packet_counter2::R) reader structure"] impl crate::Readable for PACKET_COUNTER2 {} #[doc = "`write(|w| ..)` method takes [packet_counter2::W](packet_counter2::W) writer structure"] impl crate::Writable for PACKET_COUNTER2 {} #[doc = "Packet counter 2"] pub mod packet_counter2; #[doc = "Master Initialization Vector 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [iv_master0](iv_master0) module"] pub type IV_MASTER0 = crate::Reg<u32, _IV_MASTER0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IV_MASTER0; #[doc = "`read()` method returns [iv_master0::R](iv_master0::R) reader structure"] impl crate::Readable for IV_MASTER0 {} #[doc = "`write(|w| ..)` method takes [iv_master0::W](iv_master0::W) writer structure"] impl crate::Writable for IV_MASTER0 {} #[doc = "Master Initialization Vector 0"] pub mod iv_master0; #[doc = "Slave Initialization Vector 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [iv_slave0](iv_slave0) module"] pub type IV_SLAVE0 = crate::Reg<u32, _IV_SLAVE0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IV_SLAVE0; #[doc = "`read()` method returns [iv_slave0::R](iv_slave0::R) reader structure"] impl crate::Readable for IV_SLAVE0 {} #[doc = "`write(|w| ..)` method takes [iv_slave0::W](iv_slave0::W) writer structure"] impl crate::Writable for IV_SLAVE0 {} #[doc = "Slave Initialization Vector 0"] pub mod iv_slave0; #[doc = "Encryption Key register 0-3\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [enc_key](enc_key) module"] pub type ENC_KEY = crate::Reg<u32, _ENC_KEY>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ENC_KEY; #[doc = "`write(|w| ..)` method takes [enc_key::W](enc_key::W) writer structure"] impl crate::Writable for ENC_KEY {} #[doc = "Encryption Key register 0-3"] pub mod enc_key; #[doc = "MIC input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mic_in0](mic_in0) module"] pub type MIC_IN0 = crate::Reg<u32, _MIC_IN0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MIC_IN0; #[doc = "`read()` method returns [mic_in0::R](mic_in0::R) reader structure"] impl crate::Readable for MIC_IN0 {} #[doc = "`write(|w| ..)` method takes [mic_in0::W](mic_in0::W) writer structure"] impl crate::Writable for MIC_IN0 {} #[doc = "MIC input register"] pub mod mic_in0; #[doc = "MIC output register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mic_out0](mic_out0) module"] pub type MIC_OUT0 = crate::Reg<u32, _MIC_OUT0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MIC_OUT0; #[doc = "`read()` method returns [mic_out0::R](mic_out0::R) reader structure"] impl crate::Readable for MIC_OUT0 {} #[doc = "MIC output register"] pub mod mic_out0; #[doc = "Encryption Parameter register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [enc_params](enc_params) module"] pub type ENC_PARAMS = crate::Reg<u32, _ENC_PARAMS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ENC_PARAMS; #[doc = "`read()` method returns [enc_params::R](enc_params::R) reader structure"] impl crate::Readable for ENC_PARAMS {} #[doc = "`write(|w| ..)` method takes [enc_params::W](enc_params::W) writer structure"] impl crate::Writable for ENC_PARAMS {} #[doc = "Encryption Parameter register"] pub mod enc_params; #[doc = "Encryption Configuration\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [enc_config](enc_config) module"] pub type ENC_CONFIG = crate::Reg<u32, _ENC_CONFIG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ENC_CONFIG; #[doc = "`read()` method returns [enc_config::R](enc_config::R) reader structure"] impl crate::Readable for ENC_CONFIG {} #[doc = "`write(|w| ..)` method takes [enc_config::W](enc_config::W) writer structure"] impl crate::Writable for ENC_CONFIG {} #[doc = "Encryption Configuration"] pub mod enc_config; #[doc = "Encryption Interrupt enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [enc_intr_en](enc_intr_en) module"] pub type ENC_INTR_EN = crate::Reg<u32, _ENC_INTR_EN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ENC_INTR_EN; #[doc = "`read()` method returns [enc_intr_en::R](enc_intr_en::R) reader structure"] impl crate::Readable for ENC_INTR_EN {} #[doc = "`write(|w| ..)` method takes [enc_intr_en::W](enc_intr_en::W) writer structure"] impl crate::Writable for ENC_INTR_EN {} #[doc = "Encryption Interrupt enable"] pub mod enc_intr_en; #[doc = "Encryption Interrupt status and clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [enc_intr](enc_intr) module"] pub type ENC_INTR = crate::Reg<u32, _ENC_INTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ENC_INTR; #[doc = "`read()` method returns [enc_intr::R](enc_intr::R) reader structure"] impl crate::Readable for ENC_INTR {} #[doc = "`write(|w| ..)` method takes [enc_intr::W](enc_intr::W) writer structure"] impl crate::Writable for ENC_INTR {} #[doc = "Encryption Interrupt status and clear register"] pub mod enc_intr; #[doc = "Programmable B1 Data register (0-3)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [b1_data_reg](b1_data_reg) module"] pub type B1_DATA_REG = crate::Reg<u32, _B1_DATA_REG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _B1_DATA_REG; #[doc = "`read()` method returns [b1_data_reg::R](b1_data_reg::R) reader structure"] impl crate::Readable for B1_DATA_REG {} #[doc = "`write(|w| ..)` method takes [b1_data_reg::W](b1_data_reg::W) writer structure"] impl crate::Writable for B1_DATA_REG {} #[doc = "Programmable B1 Data register (0-3)"] pub mod b1_data_reg; #[doc = "Encryption memory base address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [enc_mem_base_addr](enc_mem_base_addr) module"] pub type ENC_MEM_BASE_ADDR = crate::Reg<u32, _ENC_MEM_BASE_ADDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ENC_MEM_BASE_ADDR; #[doc = "`read()` method returns [enc_mem_base_addr::R](enc_mem_base_addr::R) reader structure"] impl crate::Readable for ENC_MEM_BASE_ADDR {} #[doc = "`write(|w| ..)` method takes [enc_mem_base_addr::W](enc_mem_base_addr::W) writer structure"] impl crate::Writable for ENC_MEM_BASE_ADDR {} #[doc = "Encryption memory base address"] pub mod enc_mem_base_addr; #[doc = "LDO Trim register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [trim_ldo_0](trim_ldo_0) module"] pub type TRIM_LDO_0 = crate::Reg<u32, _TRIM_LDO_0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIM_LDO_0; #[doc = "`read()` method returns [trim_ldo_0::R](trim_ldo_0::R) reader structure"] impl crate::Readable for TRIM_LDO_0 {} #[doc = "`write(|w| ..)` method takes [trim_ldo_0::W](trim_ldo_0::W) writer structure"] impl crate::Writable for TRIM_LDO_0 {} #[doc = "LDO Trim register 0"] pub mod trim_ldo_0; #[doc = "LDO Trim register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [trim_ldo_1](trim_ldo_1) module"] pub type TRIM_LDO_1 = crate::Reg<u32, _TRIM_LDO_1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIM_LDO_1; #[doc = "`read()` method returns [trim_ldo_1::R](trim_ldo_1::R) reader structure"] impl crate::Readable for TRIM_LDO_1 {} #[doc = "`write(|w| ..)` method takes [trim_ldo_1::W](trim_ldo_1::W) writer structure"] impl crate::Writable for TRIM_LDO_1 {} #[doc = "LDO Trim register 1"] pub mod trim_ldo_1; #[doc = "LDO Trim register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [trim_ldo_2](trim_ldo_2) module"] pub type TRIM_LDO_2 = crate::Reg<u32, _TRIM_LDO_2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIM_LDO_2; #[doc = "`read()` method returns [trim_ldo_2::R](trim_ldo_2::R) reader structure"] impl crate::Readable for TRIM_LDO_2 {} #[doc = "`write(|w| ..)` method takes [trim_ldo_2::W](trim_ldo_2::W) writer structure"] impl crate::Writable for TRIM_LDO_2 {} #[doc = "LDO Trim register 2"] pub mod trim_ldo_2; #[doc = "LDO Trim register 3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [trim_ldo_3](trim_ldo_3) module"] pub type TRIM_LDO_3 = crate::Reg<u32, _TRIM_LDO_3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIM_LDO_3; #[doc = "`read()` method returns [trim_ldo_3::R](trim_ldo_3::R) reader structure"] impl crate::Readable for TRIM_LDO_3 {} #[doc = "`write(|w| ..)` method takes [trim_ldo_3::W](trim_ldo_3::W) writer structure"] impl crate::Writable for TRIM_LDO_3 {} #[doc = "LDO Trim register 3"] pub mod trim_ldo_3; #[doc = "MXD die Trim registers\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [trim_mxd](trim_mxd) module"] pub type TRIM_MXD = crate::Reg<u32, _TRIM_MXD>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIM_MXD; #[doc = "`read()` method returns [trim_mxd::R](trim_mxd::R) reader structure"] impl crate::Readable for TRIM_MXD {} #[doc = "`write(|w| ..)` method takes [trim_mxd::W](trim_mxd::W) writer structure"] impl crate::Writable for TRIM_MXD {} #[doc = "MXD die Trim registers"] pub mod trim_mxd; #[doc = "LDO Trim register 4\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [trim_ldo_4](trim_ldo_4) module"] pub type TRIM_LDO_4 = crate::Reg<u32, _TRIM_LDO_4>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIM_LDO_4; #[doc = "`read()` method returns [trim_ldo_4::R](trim_ldo_4::R) reader structure"] impl crate::Readable for TRIM_LDO_4 {} #[doc = "`write(|w| ..)` method takes [trim_ldo_4::W](trim_ldo_4::W) writer structure"] impl crate::Writable for TRIM_LDO_4 {} #[doc = "LDO Trim register 4"] pub mod trim_ldo_4; #[doc = "LDO Trim register 5\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [trim_ldo_5](trim_ldo_5) module"] pub type TRIM_LDO_5 = crate::Reg<u32, _TRIM_LDO_5>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIM_LDO_5; #[doc = "`read()` method returns [trim_ldo_5::R](trim_ldo_5::R) reader structure"] impl crate::Readable for TRIM_LDO_5 {} #[doc = "`write(|w| ..)` method takes [trim_ldo_5::W](trim_ldo_5::W) writer structure"] impl crate::Writable for TRIM_LDO_5 {} #[doc = "LDO Trim register 5"] pub mod trim_ldo_5;
use std::io; use std::task::Poll; pub(crate) fn async_io<F, T>(mut op: F) -> Poll<io::Result<T>> where F: FnMut() -> io::Result<T> { loop { match op() { Ok(v) => return Poll::Ready(Ok(v)), Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return Poll::Pending, Err(e) => return Poll::Ready(Err(e)), } } }
use std::collections::HashMap; use std::fs::{self, File}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; use std::process::Command; use crate::bro_types::Connection; use crate::features::{ DirectionInferenceMethod, FlowFeatures, NormalizedFlowFeatures, PacketFeatures, }; use crate::flow_aggregator::FlowAggregator; use crate::packet::Packet; use failure::Error; use flate2::write::GzEncoder; use flate2::Compression; use itertools::Itertools; use rayon::prelude::*; use tempdir::TempDir; use url_queue::capture::{CaptureWork, CaptureWorkType}; use url_queue::work::WorkReportRequest; pub struct Dataset { classes: HashMap<CaptureWorkType, Vec<FlowData>>, } impl Dataset { /// Loads a dataset from a directory pub fn load<P>(data_dir: P) -> Result<Self, Error> where P: AsRef<Path>, { // Copy path let data_dir = data_dir.as_ref(); // Ensure the data directory is a directory ensure!(data_dir.is_dir(), "Path to dataset must be a directory"); // Open the report let mut report_path = PathBuf::from(data_dir); report_path.push("report.json"); ensure!(report_path.is_file(), "Data path must contain report.json"); let report_file = File::open(report_path)?; let report_file = BufReader::new(report_file); // Read and parse report file let mut work: Vec<WorkReportRequest<CaptureWorkType, CaptureWork>> = report_file .lines() .flatten() .flat_map(|line| serde_json::from_str(&line)) .collect(); // Sort reports by type and name work.par_sort_unstable_by_key(|report| (report.work_type, report.work.index)); // Extract data from each work item let classes = work .into_par_iter() // Filter out failed work .filter(|report| report.success) // Load flow data from the PCAP for this work .flat_map(|report| FlowData::load(report, data_dir)) // Separate out group type so we can aggregate .map(|flow_data| (flow_data.class, flow_data)) // Collect into one big vector .collect::<Vec<_>>() // Convert to iterator for itertools .into_iter() // Group by type .into_group_map(); Ok(Dataset { classes }) } // Saves a dataset to a json file /// # Parameters /// * `output_path` - Path to write the class datasets to pub fn save<P>(self, output_path: P) -> Result<(), Error> where P: AsRef<Path>, { // This type is used to represent flows as tensors instead of raw features #[derive(Serialize)] struct FlowDataTensor { #[serde(rename = "c")] class: CaptureWorkType, #[serde(rename = "u")] url: String, #[serde(rename = "f")] is_first_of_class: bool, #[serde(rename = "pl")] payload_length_freq_bins: Vec<f64>, #[serde(rename = "iaf")] interarrival_freq_from_client_bins: Vec<f64>, #[serde(rename = "iat")] interarrival_freq_to_client_bins: Vec<f64>, }; impl FlowDataTensor { fn from_flow_data(flow: FlowData) -> Self { FlowDataTensor { class: flow.class, url: flow.url, is_first_of_class: flow.is_first_of_class, payload_length_freq_bins: flow.features.payload_length_freq_bins, interarrival_freq_from_client_bins: flow .features .interarrival_freq_from_client_bins, interarrival_freq_to_client_bins: flow .features .interarrival_freq_to_client_bins, } } } // Save each class for (class, flows) in self.classes { let class_filename = output_path .as_ref() .join(class.to_string()) .with_extension("json.gz"); // Open a write handle to the file let output_file = File::create(class_filename)?; let output_file_writer = BufWriter::new(output_file); // Write to the file using gzip let mut gz_writer = GzEncoder::new(output_file_writer, Compression::fast()); // Write bytes from each data point to the file for flow in flows { serde_json::to_writer(&mut gz_writer, &FlowDataTensor::from_flow_data(flow))?; gz_writer.write(b"\n")?; } // Flush the writer gz_writer.flush()?; } Ok(()) } } /// Represents data from a single flow. Many of these can exist per pcap file #[derive(Debug)] pub struct FlowData { /// Class of data gathered in this pcap class: CaptureWorkType, /// The URL that was requested that this flow was performed as part of url: String, /// Whether this pcap was the first of its class to be run on the worker /// This matters for meek (first time initialization) pub is_first_of_class: bool, /// Features of the packets of this flow features: NormalizedFlowFeatures, } impl FlowData { /// Loads a class dataset from a directory #[allow(unused)] pub fn load<P>( report: WorkReportRequest<CaptureWorkType, CaptureWork>, data_path: P, ) -> Result<Self, Error> where P: AsRef<Path>, { // Split report let WorkReportRequest { work_type: class, work, type_index, .. } = report; // Split work let CaptureWork { url, filename, .. } = work; // Copy the paths let data_path = data_path.as_ref(); // Create a scratch dir // TODO: change name here when we change the crate name let scratch_dir = TempDir::new("data_generator")?; // Get path to scratch dir let scratch_path = scratch_dir.path(); // Ensure the data directory is a directory ensure!(data_path.is_dir(), "Class directory must be a directory"); // Iterate over the PCAP files in the class directory // Get path to the pcap file using the data directory and filename let pcap_path = data_path.join(filename); // Ensure pcap_file is a file ensure!( pcap_path.is_file(), "Items in a class directory must be files" ); // Ensure the scratch directory is a directory ensure!( scratch_path.is_dir(), "Scratch directory must be a directory" ); // Run BRO on the pcap file info!("Running bro on {:?}", pcap_path); let bro_return = Command::new("bro") .current_dir(scratch_path) .arg("-b") .arg("-e") .arg("redef LogAscii::use_json=T") .arg("-C") .arg("-r") .arg( pcap_path .to_str() .ok_or_else(|| format_err!("Path string could not be parsed"))?, ) .arg("base/protocols/conn") .status()?; info!("Finished running bro on {:?}", pcap_path); // Check error code ensure!(bro_return.success(), "Bro exited with failure code"); info!("Loading connection log for {:?}", pcap_path); // Load the connection log let conn_log_path = scratch_path.join("conn.log"); let connections = Connection::load_connections(&conn_log_path)? .filter(|connection| connection.orig_port == 443 || connection.resp_port == 443); // Delete the bro folder info!("Cleaning up bro scratch dir"); scratch_dir.close()?; // Read in packets from the pcap info!("Loading packets from {:?}", pcap_path); let packets = Packet::load_from_pcap(&pcap_path)? .filter(|packet| packet.src_port == 443 || packet.dst_port == 443) .collect(); // Aggregate the connection log and pcap // Initialize a flow aggregator info!("Performing packet aggregation"); let mut flow_aggregator = FlowAggregator::new(connections, 1_000_000_000, 5_000_000_000); // Load the packets into the aggregator flow_aggregator.load_packets(packets); // Create a set of directional inference methods // TODO: take this as config let dir_inference_methods = vec![DirectionInferenceMethod::ServerPort(443)]; // Create a set of feature generation bins // TODO: take this as config let payload_size_bins: Vec<usize> = (10..=100) .step_by(10) .chain((200..=1000).step_by(100)) .chain((2000..=10000).step_by(1000)) .chain(Some(65536)) .collect(); // Create variable so it's easier to keep track of time periods // Our timestamps are in nanoseconds. Convert here to ms let ms: u64 = 1_000_000; let interarrival_from_client_bins: Vec<u64> = (1 * ms..=10 * ms) .step_by(1 * ms as usize) .chain((20 * ms..=100 * ms).step_by(10 * ms as usize)) .chain((200 * ms..=1000 * ms).step_by(100 * ms as usize)) .chain(Some(10_000 * ms)) .collect(); // Use the same periods for to_client let interarrival_to_client_bins = interarrival_from_client_bins.clone(); // Extract the aggregated flows from the aggregator let (num_flows, features) = flow_aggregator .into_aggregated_flows() .into_iter() // Convert each flow's packets into features .map(move |(_, packets)| { PacketFeatures::from_stripped_packets(packets, &dir_inference_methods) }) // Encapsulate the flow .map(|features| { FlowFeatures::generate( &features, &payload_size_bins, &interarrival_from_client_bins, &interarrival_to_client_bins, ) }) // Aggregate the many flows associated with a request into a single flow .fold( ( 0, FlowFeatures::empty( payload_size_bins.len(), interarrival_from_client_bins.len(), interarrival_to_client_bins.len(), ), ), |(count, flow_acc), flow| (0, flow_acc + flow), ); Ok(FlowData { class, url: url.clone(), is_first_of_class: type_index == 1, features: features.normalize(), }) } } #[derive(Serialize)] struct ClassMetadata { num_samples: usize, sample_size: Vec<usize>, } impl ClassMetadata { fn new(num_samples: usize, sample_size: Vec<usize>) -> Self { ClassMetadata { num_samples, sample_size, } } }
extern crate rand; extern crate spatialos_gdk; #[macro_use] extern crate spatialos_gdk_derive; use rand::Rng; use schema::Schema; use schema::demogame::Movement; use schema::improbable::Position; use spatialos_gdk::{Connection, ConnectionParameters, Entities, EntityId, System, World, WorldError, Write}; use std::{env, thread, time}; // Include the code generated components which is built in the build.rs file. include!(concat!(env!("OUT_DIR"), "/generated.rs")); const FRAME_INTERVAL_S: f64 = 1.0 / 30.0; // Define the components which we want to iterate over, as well as the access which // we would like (`Read` or `Write`). // // You can also use `ModifiedRead` and `ModifiedWrite` to only match entities where // the component value has changed since the last frame. #[derive(ComponentGroup)] pub struct MovementData<'a> { pub movement: Write<'a, Schema, Movement>, pub position: Write<'a, Schema, Position>, pub entity_id: EntityId, } struct MovementSystem {} impl System<Schema> for MovementSystem { fn on_update(&mut self, _world: &mut World<Schema>, entities: &mut Entities<Schema>) { // `entities` can be used to iterate over the entities in the world. // `_world` can be used to perform other actions like send commands or // get a specific entity's data. for mut entity in entities.get::<MovementData>() { if *entity.movement.moving_right && entity.position.coords.x > 10.0 { *entity.movement.moving_right = false; } else if !*entity.movement.moving_right && entity.position.coords.x < -10.0 { *entity.movement.moving_right = true; } let delta_x = FRAME_INTERVAL_S * 4.0 * (if *entity.movement.moving_right { 1.0 } else { -1.0 }); entity.position.coords.x += delta_x; } } } fn get_connection(params: ConnectionParameters) -> Connection { let mut args: Vec<String> = env::args().collect(); args.remove(0); if args.len() == 0 { let worker_id = format!( "server{}", rand::thread_rng().gen::<u16>().to_string().as_str() ); Connection::connect_with_receptionist( "server", "127.0.0.1", 7777, worker_id.as_str(), params, ) } else if args.len() == 4 { if args[0] == "receptionist" { Connection::connect_with_receptionist( "server", args[1].as_str(), args[2].parse().unwrap(), args[3].as_str(), params, ) } else { panic!("Unknown connection type: {}", args[0]); } } else { panic!("Must have 0 arguments for default connection or 4 arguments for configured connection\n of the form <receptionist> <receptionist_ip> <receptionist_port> <worker_id>"); } } fn main() { let mut world = World::<Schema>::new(get_connection(ConnectionParameters::default())); world.register(MovementSystem {}); loop { if let Result::Err(WorldError::ConnectionLost) = world.process(0) { panic!("Connection lost.") } thread::sleep(time::Duration::from_millis( (FRAME_INTERVAL_S * 1000.0) as u64, )); } }
use crate::typing::Type; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct FunType { pub arg: Box<Type>, pub ret: Box<Type>, } impl fmt::Display for FunType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({} -> {})", self.arg, self.ret) } } impl FunType { fn sup(&self, other: &Self) -> Self { // this calculation is imprecise in a sense. // See notes/function_union.md let arg = self.arg.sup(&other.arg); let ret = self.ret.sup(&other.ret); Self { arg: arg.into(), ret: ret.into(), } } fn inf(&self, other: &Self) -> Option<Self> { // since f: A1 -> R1 and f: A2 -> R2, // f x ≠ ⊥ implies x ∈ A1 ∧ x ∈ A2 ∧ f x ∈ R1 ∧ f x ∈ R2. // therefore, f: A1 ∩ A2 -> R1 ∩ R2. let arg = self.arg.inf(&other.arg); let ret = self.ret.inf(&other.ret); // coalesce ⊥ -> R and A -> ⊥ into ⊥ if arg.is_bottom() || ret.is_bottom() { None } else { Some(Self { arg: arg.into(), ret: ret.into(), }) } } } #[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct FunDomain { fun: Option<FunType>, } impl FunDomain { pub fn new(arg: Type, ret: Type) -> Self { Self { fun: Some(FunType { arg: arg.into(), ret: ret.into(), }), } } pub fn is_bottom(&self) -> bool { self.fun.is_none() } pub fn sup(&self, other: &Self) -> Self { let fun = match (&self.fun, &other.fun) { (Some(f1), Some(f2)) => Some(f1.sup(f2)), (Some(f), _) | (_, Some(f)) => Some(f.clone()), (None, None) => None, }; Self { fun } } pub fn inf(&self, other: &Self) -> Self { let fun = match (&self.fun, &other.fun) { (Some(f1), Some(f2)) => f1.inf(f2), (None, _) | (_, None) => None, }; Self { fun } } pub fn fmt(&self, f: &mut fmt::Formatter, first: bool) -> fmt::Result { match &self.fun { None => Ok(()), Some(fun) => { if !first { f.write_str(" ∪ ")?; } write!(f, "{}", fun) } } } pub fn as_fun(&self) -> Option<&FunType> { self.fun.as_ref() } }
#[doc = "Register `GICD_TYPER` reader"] pub type R = crate::R<GICD_TYPER_SPEC>; #[doc = "Field `ITLINESNUMBER` reader - ITLINESNUMBER"] pub type ITLINESNUMBER_R = crate::FieldReader; #[doc = "Field `CPUNUMBER` reader - CPUNUMBER"] pub type CPUNUMBER_R = crate::FieldReader; #[doc = "Field `SECURITYEXTN` reader - SECURITYEXTN"] pub type SECURITYEXTN_R = crate::BitReader; #[doc = "Field `LSPI` reader - LSPI"] pub type LSPI_R = crate::FieldReader; impl R { #[doc = "Bits 0:4 - ITLINESNUMBER"] #[inline(always)] pub fn itlinesnumber(&self) -> ITLINESNUMBER_R { ITLINESNUMBER_R::new((self.bits & 0x1f) as u8) } #[doc = "Bits 5:7 - CPUNUMBER"] #[inline(always)] pub fn cpunumber(&self) -> CPUNUMBER_R { CPUNUMBER_R::new(((self.bits >> 5) & 7) as u8) } #[doc = "Bit 10 - SECURITYEXTN"] #[inline(always)] pub fn securityextn(&self) -> SECURITYEXTN_R { SECURITYEXTN_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bits 11:15 - LSPI"] #[inline(always)] pub fn lspi(&self) -> LSPI_R { LSPI_R::new(((self.bits >> 11) & 0x1f) as u8) } } #[doc = "GICD interrupt controller type register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicd_typer::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GICD_TYPER_SPEC; impl crate::RegisterSpec for GICD_TYPER_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gicd_typer::R`](R) reader structure"] impl crate::Readable for GICD_TYPER_SPEC {} #[doc = "`reset()` method sets GICD_TYPER to value 0xfc28"] impl crate::Resettable for GICD_TYPER_SPEC { const RESET_VALUE: Self::Ux = 0xfc28; }
//! A temporary in-memory database meant to hold us over until the pager and //! B+Tree modules are finalized. //! //! This module will be removed once the pager and B+Tree are functional. use std::borrow::Cow; use std::collections::BTreeSet; use columnvalueops::{ColumnValueOps, ColumnValueOpsExt}; use databaseinfo::{DatabaseInfo, TableInfo, ColumnInfo}; use databasestorage::{Group, DatabaseStorage}; use identifier::Identifier; use types::{DbType, Variant}; use sqlsyntax::ast; use queryplan::{self, ExecuteQueryPlan, QueryPlan}; mod table; use self::table::Table; pub struct TempDb { tables: Vec<Table> } pub enum ExecuteStatementResponse<'a> { Created, Inserted(u64), Select { column_names: Box<[String]>, rows: Box<Iterator<Item=Box<[Variant]>> + 'a> }, Explain(String) } pub type ExecuteStatementResult<'a> = Result<ExecuteStatementResponse<'a>, String>; impl DatabaseInfo for TempDb { type Table = Table; type ColumnValue = Variant; fn find_table_by_name(&self, name: &Identifier) -> Option<&Table> { self.tables.iter().find(|t| &t.name == name) } } struct ScanGroup<'a> { table: &'a Table } impl<'a> Group for ScanGroup<'a> { type ColumnValue = Variant; fn get_any_row<'b>(&'b self) -> Option<Cow<'b, [Variant]>> { self.iter().nth(0) } fn count(&self) -> u64 { self.table.rowid_index.len() as u64 } fn iter<'b>(&'b self) -> Box<Iterator<Item=Cow<'b, [Variant]>> + 'b> { let table = self.table; let columns: &'b [self::table::Column] = &table.columns; Box::new(table.rowid_index.iter().map(move |key_v| { use byteutils; use std::borrow::Cow; let raw_key: &[u8] = &key_v; trace!("KEY: {:?}", raw_key); let variable_column_count = columns.iter().filter(|column| { column.dbtype.is_variable_length() }).count(); let variable_lengths: Vec<_> = (0..variable_column_count).map(|i| { let o = raw_key.len() - variable_column_count*8 + i*8; byteutils::read_udbinteger(&raw_key[o..o+8]) }).collect(); trace!("variable lengths: {:?}", variable_lengths); let _rowid: u64 = byteutils::read_udbinteger(&raw_key[0..8]); let mut variable_length_offset = 0; let mut key_offset = 8; let v: Vec<Variant> = columns.iter().map(|column| { let is_null = if column.nullable { let flag = raw_key[key_offset]; key_offset += 1; flag != 0 } else { false }; if is_null { ColumnValueOpsExt::null() } else { let size = match column.dbtype.get_fixed_length() { Some(l) => l as usize, None => { let l = variable_lengths[variable_length_offset]; variable_length_offset += 1; l as usize } }; let bytes = &raw_key[key_offset..key_offset + size]; trace!("from bytes: {:?}, {:?}", column.dbtype, bytes); let value = ColumnValueOps::from_bytes(column.dbtype, Cow::Borrowed(bytes)).unwrap(); key_offset += size; value } }).collect(); Cow::Owned(v) })) } } impl DatabaseStorage for TempDb { type Info = TempDb; fn scan_table<'a>(&'a self, table: &'a Table) -> Box<Group<ColumnValue=Variant> + 'a> { Box::new(ScanGroup { table: table }) } } impl TempDb { pub fn new() -> TempDb { TempDb { tables: Vec::new() } } pub fn execute_statement(&mut self, stmt: ast::Statement) -> ExecuteStatementResult { match stmt { ast::Statement::Create(create_stmt) => { match create_stmt { ast::CreateStatement::Table(s) => self.create_table(s) } }, ast::Statement::Insert(insert_stmt) => self.insert_into(insert_stmt), ast::Statement::Select(select_stmt) => self.select(select_stmt), ast::Statement::Explain(explain_stmt) => self.explain(explain_stmt) } } fn create_table(&mut self, stmt: ast::CreateTableStatement) -> ExecuteStatementResult { if stmt.table.database_name.is_some() { unimplemented!() } let table_name = Identifier::new(&stmt.table.table_name).unwrap(); let columns_result: Result<_, String>; columns_result = stmt.columns.into_iter().enumerate().map(|(i, column)| { let name = Identifier::new(&column.column_name).unwrap(); let type_name = Identifier::new(&column.type_name).unwrap(); let type_array_size = match column.type_array_size { Some(Some(s)) => { let v = try!(self.parse_number_as_u64(s)); Some(Some(v)) }, Some(None) => Some(None), None => None }; let dbtype = try!(DbType::from_identifier(&type_name, type_array_size).ok_or(format!("{} is not a valid column type", type_name))); let nullable = column.constraints.iter().any(|c| { c.constraint == ast::CreateTableColumnConstraintType::Nullable }); Ok(table::Column { offset: i as u32, name: name, dbtype: dbtype, nullable: nullable }) }).collect(); let columns = try!(columns_result); try!(self.add_table(Table { name: table_name, columns: columns, next_rowid: 1, rowid_index: BTreeSet::new() })); Ok(ExecuteStatementResponse::Created) } fn insert_into(&mut self, stmt: ast::InsertStatement) -> ExecuteStatementResult { trace!("inserting row: {:?}", stmt); let table_name = stmt.table.table_name; let column_types: Vec<(DbType, bool)>; let ast_index_to_column_index: Vec<u32>; { let table = try!(self.get_table_mut(&table_name)); column_types = table.get_columns().iter().map(|c| { (c.dbtype, c.nullable) }).collect(); ast_index_to_column_index = match stmt.into_columns { // Column names listed; map specified columns Some(v) => try!(v.into_iter().map(|column_name| { let ident = Identifier::new(&column_name).unwrap(); match table.find_column_by_name(&ident) { Some(column) => Ok(column.get_offset()), None => Err(format!("column {} not in table", column_name)) } }).collect()), // No column names are listed; map all columns None => (0..table.get_column_count()).collect() }; trace!("ast_index_to_column_index: {:?}", ast_index_to_column_index); } match stmt.source { ast::InsertSource::Values(rows) => { let mut count = 0; for row in rows { if ast_index_to_column_index.len() != row.len() { return Err(format!("INSERT value contains wrong amount of columns")); } let mut exprs: Vec<Option<ast::Expression>>; exprs = (0..column_types.len()).map(|_| None).collect(); for (i, expr) in row.into_iter().enumerate() { exprs[ast_index_to_column_index[i] as usize] = Some(expr); } // TODO: don't allow expressions that SELECT the same table that's being inserted into let v: Vec<_> = try!({column_types.iter().zip(exprs.into_iter()).map(|(&(dbtype, nullable), expr)| { match expr { Some(expr) => { // TODO - allocate buffer outside of loop let mut buf = Vec::new(); let execute = ExecuteQueryPlan::new(self); let sexpr = match queryplan::compile_ast_expression(self, expr).map_err(|e| format!("{}", e)) { Ok(v) => v, Err(e) => return Err(e) }; let value = try!(execute.execute_expression(&sexpr)); let is_null = try!(variant_to_data(value, dbtype, nullable, &mut buf)); Ok((buf.into_boxed_slice(), is_null)) }, None => { // use default value for column type let is_null = if nullable { Some(true) } else { None }; Ok((dbtype.get_default().into_owned().into_boxed_slice(), is_null)) } } }).collect()}); let mut table = try!(self.get_table_mut(&table_name)); try!(table.insert_row(v.into_iter()).map_err(|e| format!("{}", e))); count += 1; } Ok(ExecuteStatementResponse::Inserted(count)) }, ast::InsertSource::Select(_s) => unimplemented!() } } fn select(&self, stmt: ast::SelectStatement) -> ExecuteStatementResult { let plan = try!(QueryPlan::compile_select(self, stmt).map_err(|e| format!("{}", e))); debug!("{}", plan); let mut rows = Vec::new(); let execute = ExecuteQueryPlan::new(self); try!(execute.execute_query_plan(&plan.expr, &mut |r| { rows.push(r.to_vec().into_boxed_slice()); Ok(()) })); let column_names: Vec<String> = plan.out_column_names.iter().map(|ident| ident.to_string()).collect(); Ok(ExecuteStatementResponse::Select { column_names: column_names.into_boxed_slice(), rows: Box::new(rows.into_iter()) }) } fn explain(&self, stmt: ast::ExplainStatement) -> ExecuteStatementResult { use queryplan::QueryPlan; match stmt { ast::ExplainStatement::Select(select) => { let plan = try!(QueryPlan::compile_select(self, select).map_err(|e| format!("{}", e))); Ok(ExecuteStatementResponse::Explain(plan.to_string())) } } } fn add_table(&mut self, table: Table) -> Result<(), String> { if self.tables.iter().any(|t| t.name == table.name) { Err(format!("Table {} already exists", table.name)) } else { debug!("adding table: {:?}", table); self.tables.push(table); Ok(()) } } fn get_table_mut(&mut self, table_name: &str) -> Result<&mut Table, String> { let table_name = try!(Identifier::new(table_name).ok_or(format!("Bad table name: {}", table_name))); match self.tables.iter_mut().find(|t| t.name == table_name) { Some(s) => Ok(s), None => Err(format!("Could not find table named {}", table_name)) } } fn parse_number_as_u64(&self, number: String) -> Result<u64, String> { number.parse().map_err(|_| format!("{} is not a valid number", number)) } } fn variant_to_data(value: Variant, column_type: DbType, nullable: bool, buf: &mut Vec<u8>) -> Result<Option<bool>, String> { match (value.is_null(), nullable) { (true, true) => Ok(Some(true)), (true, false) => { Err(format!("cannot insert NULL into column that doesn't allow NULL")) }, (false, nullable) => { let bytes = value.to_bytes(column_type).unwrap(); buf.extend_from_slice(&bytes); Ok(if nullable { Some(false) } else { None }) } } }
pub fn problem_045() -> u64 { let n:u64 = 100000000000; let mut triangular = (1..n).map(|i| i * (i + 1)/2 ); let mut pentagonal = (1..n).map(|i| i * (3 * i - 1)/2 ); let hexagonal = (1..n).map(|i| i * (2 * i - 1)); let mut p: u64 = 40756; let mut t: u64 = 40756; for h in hexagonal { while p < h { match pentagonal.next(){ Some(x) => {p = x;}, None => break, } } while t < h { match triangular.next(){ Some(x) => {t = x;}, None => break, } } if (p == h) & (t==h) { return h } } 0 } #[cfg(test)] mod test { use super::*; use test::Bencher; #[test] fn test_problem_045() { let ans: u64 = problem_045(); println!("Answer to Problem 45: {}", ans); assert!(ans == 1533776805) } #[bench] fn bench_problem_045(b: &mut Bencher) { b.iter(|| problem_045()); } }
use cookie_factory::*; use flate2::Compression; use flate2::read::GzDecoder; use flate2::write::GzEncoder; use nom::{ErrorKind, be_u16, be_u32, be_u8}; use sha2::{Digest, Sha256}; use std::io::{Read, Write}; use crypto::frame::{gen_session_key, session_key}; use data::frame::{certificate, gen_certificate, gen_hash, gen_lease_set, gen_router_info, gen_session_tag, gen_tunnel_id, hash, lease_set, router_info, session_tag, tunnel_id, gen_i2p_date, i2p_date}; use super::*; // // Utils // fn iv<'a>(input: &'a [u8]) -> IResult<&'a [u8], [u8; 16]> { match take!(input, 16) { IResult::Done(i, iv) => { let mut x = [0u8; 16]; x.copy_from_slice(iv); IResult::Done(i, x) } IResult::Error(e) => IResult::Error(e), IResult::Incomplete(n) => IResult::Incomplete(n), } } // // Common structures // pub fn build_request_record<'a>( input: &'a [u8], to_peer: Hash, ) -> IResult<&'a [u8], BuildRequestRecord> { #[cfg_attr(rustfmt, rustfmt_skip)] do_parse!( input, receive_tid: tunnel_id >> our_ident: hash >> next_tid: tunnel_id >> next_ident: hash >> layer_key: session_key >> iv_key: session_key >> reply_key: session_key >> reply_iv: iv >> flag: be_u8 >> request_time: be_u32 >> send_msg_id: be_u32 >> take!(29) >> (BuildRequestRecord { to_peer, receive_tid, our_ident, next_tid, next_ident, layer_key, iv_key, reply_key, reply_iv, flag, request_time, send_msg_id, }) ) } fn validate_build_response_record<'a>( input: &'a [u8], hash: Hash, padding: &[u8], reply: u8, ) -> IResult<&'a [u8], ()> { let mut hasher = Sha256::default(); hasher.input(padding); hasher.input(&[reply]); let res = hasher.result(); if hash.eq(&Hash::from_bytes(array_ref![res, 0, 32])) { IResult::Done(input, ()) } else { IResult::Error(error_code!(ErrorKind::Custom(1))) } } named!(pub build_response_record<BuildResponseRecord>, do_parse!( hash: hash >> padding: take!(495) >> reply: be_u8 >> call!(validate_build_response_record, hash, padding, reply) >> (BuildResponseRecord { reply }) ) ); // // Message payloads // // DatabaseStore fn compressed_ri<'a>(input: &'a [u8]) -> IResult<&'a [u8], RouterInfo> { match do_parse!(input, size: be_u16 >> payload: take!(size) >> (payload)) { IResult::Done(i, payload) => { let mut buf = Vec::new(); let mut d = GzDecoder::new(payload); match d.read_to_end(&mut buf) { Ok(_) => {} Err(e) => return IResult::Error(ErrorKind::Custom(1)), }; match router_info(&buf) { IResult::Done(x, ri) => IResult::Done(i, ri), IResult::Error(e) => IResult::Error(e), IResult::Incomplete(n) => IResult::Incomplete(n), } } IResult::Error(e) => IResult::Error(e), IResult::Incomplete(n) => IResult::Incomplete(n), } } fn gen_compressed_ri<'a>( input: (&'a mut [u8], usize), ri: &RouterInfo, ) -> Result<(&'a mut [u8], usize), GenError> { let mut buf = Vec::new(); gen_router_info((&mut buf, 0), ri); let mut e = GzEncoder::new(Vec::new(), Compression::best()); e.write(&buf); match e.finish() { Ok(payload) => do_gen!(input, gen_be_u16!(payload.len()) >> gen_slice!(payload)), Err(e) => Err(GenError::CustomError(1)), } } #[cfg_attr(rustfmt, rustfmt_skip)] named!( reply_path<Option<ReplyPath>>, do_parse!( reply_tok: be_u32 >> reply: cond!( reply_tok > 0, do_parse!( reply_tid: tunnel_id >> reply_gw: hash >> (ReplyPath { token: reply_tok, tid: reply_tid, gateway: reply_gw, }) ) ) >> (reply) ) ); fn gen_reply_path<'a>( input: (&'a mut [u8], usize), reply: &Option<ReplyPath>, ) -> Result<(&'a mut [u8], usize), GenError> { match *reply { Some(ref path) => do_gen!( input, gen_be_u32!(path.token) >> gen_tunnel_id(&path.tid) >> gen_hash(&path.gateway) ), None => gen_be_u32!(input, 0), } } #[cfg_attr(rustfmt, rustfmt_skip)] named!( database_store<MessagePayload>, do_parse!( key: hash >> ds_type: be_u8 >> reply: reply_path >> data: switch!(value!(ds_type), 0 => do_parse!(ri: compressed_ri >> (DatabaseStoreData::RI(ri))) | 1 => do_parse!(ls: lease_set >> (DatabaseStoreData::LS(ls))) ) >> (MessagePayload::DatabaseStore(DatabaseStore { key, ds_type, reply, data, })) ) ); fn gen_database_store_data<'a>( input: (&'a mut [u8], usize), data: &DatabaseStoreData, ) -> Result<(&'a mut [u8], usize), GenError> { match data { &DatabaseStoreData::RI(ref ri) => gen_compressed_ri(input, &ri), &DatabaseStoreData::LS(ref ls) => gen_lease_set(input, &ls), } } fn gen_database_store<'a>( input: (&'a mut [u8], usize), ds: &DatabaseStore, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!( input, gen_hash(&ds.key) >> gen_be_u8!(ds.ds_type) >> gen_reply_path(&ds.reply) >> gen_database_store_data(&ds.data) ) } // DatabaseLookup #[cfg_attr(rustfmt, rustfmt_skip)] named!( database_lookup_flags<DatabaseLookupFlags>, bits!(do_parse!( take_bits!(u8, 4) >> lookup_type: take_bits!(u8, 2) >> encryption: take_bits!(u8, 1) >> delivery: take_bits!(u8, 1) >> (DatabaseLookupFlags { delivery: delivery > 0, encryption: encryption > 0, lookup_type, }) )) ); fn gen_database_lookup_flags<'a>( input: (&'a mut [u8], usize), flags: &DatabaseLookupFlags, ) -> Result<(&'a mut [u8], usize), GenError> { let mut x: u8 = 0; if flags.delivery { x |= 0b01; } if flags.encryption { x |= 0b10; } x |= (flags.lookup_type << 2) & 0b1100; gen_be_u8!(input, x) } #[cfg_attr(rustfmt, rustfmt_skip)] named!( database_lookup<MessagePayload>, do_parse!( key: hash >> from: hash >> flags: database_lookup_flags >> reply_tid: cond!(flags.delivery, call!(tunnel_id)) >> excluded_peers: length_count!(be_u16, hash) >> reply_key: cond!(flags.encryption, call!(session_key)) >> tags: cond!(flags.encryption, length_count!(be_u8, session_tag)) >> (MessagePayload::DatabaseLookup(DatabaseLookup { key, from, flags, reply_tid, excluded_peers, reply_key, tags, })) ) ); fn gen_database_lookup<'a>( input: (&'a mut [u8], usize), dl: &DatabaseLookup, ) -> Result<(&'a mut [u8], usize), GenError> { #[cfg_attr(rustfmt, rustfmt_skip)] do_gen!( input, gen_hash(&dl.key) >> gen_hash(&dl.from) >> gen_database_lookup_flags(&dl.flags) >> gen_cond!( dl.flags.delivery, do_gen!(gen_tunnel_id(dl.reply_tid.as_ref().unwrap())) ) >> gen_be_u16!(dl.excluded_peers.len() as u16) >> gen_many!(&dl.excluded_peers, gen_hash) >> gen_cond!( dl.flags.encryption, do_gen!(gen_session_key(dl.reply_key.as_ref().unwrap())) ) >> gen_cond!( dl.flags.encryption, do_gen!( gen_be_u8!(dl.tags.as_ref().unwrap().len() as u8) >> gen_many!(dl.tags.as_ref().unwrap(), gen_session_tag) ) ) ) } // DatabaseSearchReply named!( database_search_reply<MessagePayload>, do_parse!( key: hash >> peers: length_count!(be_u8, hash) >> from: hash >> (MessagePayload::DatabaseSearchReply(DatabaseSearchReply { key, peers, from })) ) ); fn gen_database_search_reply<'a>( input: (&'a mut [u8], usize), dsr: &DatabaseSearchReply, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!( input, gen_hash(&dsr.key) >> gen_be_u8!(dsr.peers.len() as u8) >> gen_many!(&dsr.peers, gen_hash) >> gen_hash(&dsr.from) ) } // DeliveryStatus named!( delivery_status<MessagePayload>, do_parse!( msg_id: be_u32 >> time_stamp: i2p_date >> (MessagePayload::DeliveryStatus(DeliveryStatus { msg_id, time_stamp })) ) ); fn gen_delivery_status<'a>( input: (&'a mut [u8], usize), ds: &DeliveryStatus, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!( input, gen_be_u32!(ds.msg_id) >> gen_i2p_date(&ds.time_stamp) ) } // Garlic #[cfg_attr(rustfmt, rustfmt_skip)] named!( garlic_clove_delivery_instructions<GarlicCloveDeliveryInstructions>, do_parse!( flags: bits!(do_parse!( encrypted: take_bits!(u8, 1) >> delivery_type: take_bits!(u8, 2) >> delay_set: take_bits!(u8, 1) >> take_bits!(u8, 4) >> (encrypted > 0, delivery_type, delay_set > 0) )) >> session_key: cond!(flags.0, call!(session_key)) >> to_hash: cond!(flags.1 != 0, call!(hash)) >> tid: cond!(flags.1 == 3, call!(tunnel_id)) >> delay: cond!(flags.2, call!(be_u32)) >> (GarlicCloveDeliveryInstructions { encrypted: flags.0, delivery_type: flags.1, delay_set: flags.2, session_key, to_hash, tid, delay, }) ) ); fn gen_garlic_clove_delivery_instructions<'a>( input: (&'a mut [u8], usize), gcdi: &GarlicCloveDeliveryInstructions, ) -> Result<(&'a mut [u8], usize), GenError> { let mut flags: u8 = 0; if gcdi.encrypted { flags |= 0b10000000; } flags |= (gcdi.delivery_type << 5) & 0b1100000; if gcdi.delay_set { flags |= 0b10000; } #[cfg_attr(rustfmt, rustfmt_skip)] do_gen!( input, gen_be_u8!(flags) >> gen_cond!( gcdi.encrypted, do_gen!(gen_session_key(gcdi.session_key.as_ref().unwrap())) ) >> gen_cond!( gcdi.delivery_type != 0, do_gen!(gen_hash(gcdi.to_hash.as_ref().unwrap())) ) >> gen_cond!( gcdi.delivery_type == 3, do_gen!(gen_tunnel_id(gcdi.tid.as_ref().unwrap())) ) >> gen_cond!( gcdi.delay_set, do_gen!(gen_be_u32!(gcdi.delay.unwrap())) ) ) } #[cfg_attr(rustfmt, rustfmt_skip)] named!( garlic_clove<GarlicClove>, do_parse!( delivery_instructions: garlic_clove_delivery_instructions >> msg: message >> clove_id: be_u32 >> expiration: i2p_date >> cert: certificate >> (GarlicClove { delivery_instructions, msg, clove_id, expiration, cert, }) ) ); fn gen_garlic_clove<'a>( input: (&'a mut [u8], usize), clove: &GarlicClove, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!( input, gen_garlic_clove_delivery_instructions(&clove.delivery_instructions) >> gen_message(&clove.msg) >> gen_be_u32!(clove.clove_id) >> gen_i2p_date(&clove.expiration) >> gen_certificate(&clove.cert) ) } #[cfg_attr(rustfmt, rustfmt_skip)] named!( garlic<MessagePayload>, do_parse!( cloves: length_count!(be_u8, garlic_clove) >> cert: certificate >> msg_id: be_u32 >> expiration: i2p_date >> (MessagePayload::Garlic(Garlic { cloves, cert, msg_id, expiration, })) ) ); fn gen_garlic<'a>( input: (&'a mut [u8], usize), g: &Garlic, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!( input, gen_be_u8!(g.cloves.len() as u8) >> gen_many!(&g.cloves, gen_garlic_clove) >> gen_certificate(&g.cert) >> gen_be_u32!(g.msg_id) >> gen_i2p_date(&g.expiration) ) } // TunnelData named!( tunnel_data<MessagePayload>, do_parse!( tid: tunnel_id >> data: take!(1024) >> (MessagePayload::TunnelData(TunnelData::from(tid, array_ref![data, 0, 1024]))) ) ); fn gen_tunnel_data<'a>( input: (&'a mut [u8], usize), td: &TunnelData, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!(input, gen_tunnel_id(&td.tid) >> gen_slice!(td.data)) } // TunnelGateway named!( tunnel_gateway<MessagePayload>, do_parse!( tid: tunnel_id >> data: length_bytes!(be_u16) >> (MessagePayload::TunnelGateway(TunnelGateway { tid, data: Vec::from(data), })) ) ); fn gen_tunnel_gateway<'a>( input: (&'a mut [u8], usize), tg: &TunnelGateway, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!(input, gen_tunnel_id(&tg.tid) >> gen_slice!(tg.data)) } // Data named!( data<MessagePayload>, do_parse!(data: length_bytes!(be_u32) >> (MessagePayload::Data(Vec::from(data)))) ); fn gen_data<'a>( input: (&'a mut [u8], usize), d: &Vec<u8>, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!(input, gen_be_u32!(d.len()) >> gen_slice!(d)) } // TunnelBuild fn tunnel_build<'a>(input: &'a [u8]) -> IResult<&'a [u8], MessagePayload> { match count!(input, take!(528), 8) { IResult::Done(i, r) => { let mut xs = [[0u8; 528]; 8]; r.iter().enumerate().map(|(i, &s)| xs[i].copy_from_slice(s)); IResult::Done(i, MessagePayload::TunnelBuild(xs)) } IResult::Error(e) => IResult::Error(e), IResult::Incomplete(n) => IResult::Incomplete(n), } } fn gen_tunnel_build<'a>( input: (&'a mut [u8], usize), tb: &[[u8; 528]; 8], ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!( input, gen_slice!(tb[0]) >> gen_slice!(tb[1]) >> gen_slice!(tb[2]) >> gen_slice!(tb[3]) >> gen_slice!(tb[4]) >> gen_slice!(tb[5]) >> gen_slice!(tb[6]) >> gen_slice!(tb[7]) ) } // TunnelBuildReply fn tunnel_build_reply<'a>(input: &'a [u8]) -> IResult<&'a [u8], MessagePayload> { match count!(input, take!(528), 8) { IResult::Done(i, r) => { let mut xs = [[0u8; 528]; 8]; r.iter().enumerate().map(|(i, &s)| xs[i].copy_from_slice(s)); IResult::Done(i, MessagePayload::TunnelBuildReply(xs)) } IResult::Error(e) => IResult::Error(e), IResult::Incomplete(n) => IResult::Incomplete(n), } } fn gen_tunnel_build_reply<'a>( input: (&'a mut [u8], usize), tb: &[[u8; 528]; 8], ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!( input, gen_slice!(tb[0]) >> gen_slice!(tb[1]) >> gen_slice!(tb[2]) >> gen_slice!(tb[3]) >> gen_slice!(tb[4]) >> gen_slice!(tb[5]) >> gen_slice!(tb[6]) >> gen_slice!(tb[7]) ) } // VariableTunnelBuild fn variable_tunnel_build<'a>(input: &'a [u8]) -> IResult<&'a [u8], MessagePayload> { match length_count!(input, be_u8, take!(528)) { IResult::Done(i, r) => IResult::Done( i, MessagePayload::VariableTunnelBuild( r.iter() .map(|&s| { let mut x = [0u8; 528]; x.copy_from_slice(s); x }) .collect(), ), ), IResult::Error(e) => IResult::Error(e), IResult::Incomplete(n) => IResult::Incomplete(n), } } fn gen_variable_tunnel_build<'a>( input: (&'a mut [u8], usize), tb: &Vec<[u8; 528]>, ) -> Result<(&'a mut [u8], usize), GenError> { // TODO: Fail if tb is too big let mut x = gen_be_u8!(input, tb.len() as u8)?; for record in tb { x = gen_slice!(x, record)?; } Ok(x) } // VariableTunnelBuildReply fn variable_tunnel_build_reply<'a>(input: &'a [u8]) -> IResult<&'a [u8], MessagePayload> { match length_count!(input, be_u8, take!(528)) { IResult::Done(i, r) => IResult::Done( i, MessagePayload::VariableTunnelBuildReply( r.iter() .map(|&s| { let mut x = [0u8; 528]; x.copy_from_slice(s); x }) .collect(), ), ), IResult::Error(e) => IResult::Error(e), IResult::Incomplete(n) => IResult::Incomplete(n), } } fn gen_variable_tunnel_build_reply<'a>( input: (&'a mut [u8], usize), tbr: &Vec<[u8; 528]>, ) -> Result<(&'a mut [u8], usize), GenError> { // TODO: Fail if tbr is too big let mut x = gen_be_u8!(input, tbr.len() as u8)?; for record in tbr { x = gen_slice!(x, record)?; } Ok(x) } // // I2NP message framing // fn checksum(buf: &[u8]) -> u8 { let mut hasher = Sha256::default(); hasher.input(&buf); let hash = hasher.result(); hash[0] } fn validate_checksum<'a>(input: &'a [u8], cs: u8, buf: &[u8]) -> IResult<&'a [u8], ()> { if cs.eq(&checksum(&buf)) { IResult::Done(input, ()) } else { IResult::Error(error_code!(ErrorKind::Custom(1))) } } fn gen_checksum<'a>( input: (&'a mut [u8], usize), start: usize, end: usize, ) -> Result<(&'a mut [u8], usize), GenError> { gen_be_u8!(input, checksum(&input.0[start..end])) } named!( header<(u8, u32, I2PDate, u16, u8)>, do_parse!( msg_type: be_u8 >> msg_id: be_u32 >> expiration: i2p_date >> size: be_u16 >> cs: be_u8 >> ((msg_type, msg_id, expiration, size, cs)) ) ); named!(pub message<Message>, do_parse!( hdr: header >> payload_bytes: peek!(take!(hdr.3)) >> call!(validate_checksum, hdr.4, payload_bytes) >> payload: switch!(value!(hdr.0), 1 => call!(database_store) | 2 => call!(database_lookup) | 3 => call!(database_search_reply) | 10 => call!(delivery_status) | 11 => call!(garlic) | 18 => call!(tunnel_data) | 19 => call!(tunnel_gateway) | 20 => call!(data) | 21 => call!(tunnel_build) | 22 => call!(tunnel_build_reply) | 23 => call!(variable_tunnel_build) | 24 => call!(variable_tunnel_build_reply) ) >> (Message { id: hdr.1, expiration: hdr.2, payload: payload, }) ) ); fn gen_message_type<'a>( input: (&'a mut [u8], usize), msg: &Message, ) -> Result<(&'a mut [u8], usize), GenError> { let msg_type = match &msg.payload { &MessagePayload::DatabaseStore(_) => 1, &MessagePayload::DatabaseLookup(_) => 2, &MessagePayload::DatabaseSearchReply(_) => 3, &MessagePayload::DeliveryStatus(_) => 10, &MessagePayload::Garlic(_) => 11, &MessagePayload::TunnelData(_) => 18, &MessagePayload::TunnelGateway(_) => 19, &MessagePayload::Data(_) => 20, &MessagePayload::TunnelBuild(_) => 21, &MessagePayload::TunnelBuildReply(_) => 22, &MessagePayload::VariableTunnelBuild(_) => 23, &MessagePayload::VariableTunnelBuildReply(_) => 24, }; gen_be_u8!(input, msg_type) } fn gen_payload<'a>( input: (&'a mut [u8], usize), payload: &MessagePayload, ) -> Result<(&'a mut [u8], usize), GenError> { match payload { &MessagePayload::DatabaseStore(ref ds) => gen_database_store(input, &ds), &MessagePayload::DatabaseLookup(ref dl) => gen_database_lookup(input, &dl), &MessagePayload::DatabaseSearchReply(ref dsr) => gen_database_search_reply(input, &dsr), &MessagePayload::DeliveryStatus(ref ds) => gen_delivery_status(input, &ds), &MessagePayload::Garlic(ref g) => gen_garlic(input, &g), &MessagePayload::TunnelData(ref td) => gen_tunnel_data(input, &td), &MessagePayload::TunnelGateway(ref tg) => gen_tunnel_gateway(input, &tg), &MessagePayload::Data(ref d) => gen_data(input, &d), &MessagePayload::TunnelBuild(tb) => gen_tunnel_build(input, &tb), &MessagePayload::TunnelBuildReply(tbr) => gen_tunnel_build_reply(input, &tbr), &MessagePayload::VariableTunnelBuild(ref vtb) => gen_variable_tunnel_build(input, &vtb), &MessagePayload::VariableTunnelBuildReply(ref vtbr) => { gen_variable_tunnel_build_reply(input, &vtbr) } } } pub fn gen_message<'a>( input: (&'a mut [u8], usize), msg: &Message, ) -> Result<(&'a mut [u8], usize), GenError> { do_gen!(input, gen_message_type(msg) >> gen_be_u32!(msg.id) >> gen_i2p_date(&msg.expiration) >> size: gen_skip!(2) >> cs: gen_skip!(1) >> start: gen_payload(&msg.payload) >> end: gen_at_offset!(size, gen_be_u16!(end-start)) >> gen_at_offset!(cs, gen_checksum(start, end)) ) } #[cfg(test)] mod tests { use super::*; #[test] fn test_validate_checksum() { let a = b"payloadspam"; assert_eq!( validate_checksum(&a[..], 0x23, &a[..7]), IResult::Done(&a[..], ()) ); assert_eq!( validate_checksum(&a[..], 0x23, &a[..8]), IResult::Error(ErrorKind::Custom(1)) ); } #[test] fn test_gen_checksum() { // Valid payload checksum let a = b"#payloadspam"; // Copy payload into a buffer with an empty checksum let mut b = Vec::new(); b.push(0); b.extend(a[1..].iter().cloned()); // Generate and validate checksum of payload let res = gen_checksum((&mut b[..], 0), 1, 8); assert!(res.is_ok()); let (o, n) = res.unwrap(); assert_eq!(o.as_ref(), &a[..]); assert_eq!(n, 1); } }
//! Retrieve basic data about a protein from a local UniprotKB file //! //! # File format //! //! Files should be tab delimited, with 4 fields: Uniprot Accession, Gene Name, //! Molecular Weight, and Protein Sequence. Each protein appears on it's own //! line in the file, and no header //! should be present //! //! ```text //! $ cat uniprot.txt //! ... //! Q13526 PIN1 18243 MADEEKLPPGWEKRMSRSSGRVYYF ... GEMSGPVFTDSGIHIILRTE //! Q13547 HDAC1 55103 MAQTQGTRRKVCYYYDGDVGNYYYG ... EKTKEEKPEAKGVKEEVKLA //! ... //! ``` //! //! # Example //! //! ```rust,ignore //! # use uniprot::Uniprot; //! let db: Uniprot = match Uniprot::load("uniprot.txt") { //! Ok(db) => db, //! Err(e) => panic!("Error loading local Uniprot database: {}", e), //! }; //! ``` //! pub mod kw; use memchr::{memchr_iter, Memchr}; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::{self, prelude::*}; use std::path::Path; use std::str; pub mod fasta; struct Pitchfork<'a> { pos: usize, haystack: &'a [u8], inner: Memchr<'a>, } impl<'a> Pitchfork<'a> { pub fn new(needle: u8, haystack: &'a [u8]) -> Self { Self { pos: 0, haystack, inner: memchr_iter(needle, haystack), } } } impl<'a> Iterator for Pitchfork<'a> { type Item = &'a [u8]; #[inline] fn next(&mut self) -> Option<Self::Item> { let end = match self.inner.next() { Some(e) => e, None => { if self.pos < self.haystack.len() { self.haystack.len() } else { return None; } } }; let slice = &self.haystack[self.pos..end]; self.pos = end + 1; Some(slice) } } #[derive(Debug, PartialEq, Clone)] /// Represents an entry in the locally-stored UniprotKB database pub struct Entry { /// Uniprot accession identifier pub accession: String, /// Gene name pub identifier: String, /// Protein sequence pub sequence: String, } #[derive(Debug, PartialEq, Clone)] /// Wraps a hashtable pub struct Uniprot { inner: HashMap<String, Entry>, } impl Uniprot { /// Load a UniprotKB file to build a [`Uniprot`] object /// /// # File format /// /// Files should be tab delimited, with 4 fields: Uniprot Accession, Gene /// Name, Molecular Weight, and Protein Sequence. Each protein appears /// on it's own line in the file, and no header /// should be present /// /// ```text /// $ cat uniprot.txt /// ... /// Q13526 PIN1 18243 MADEEKLPPGWEKRMSRSSGRVYYF ... GEMSGPVFTDSGIHIILRTE /// Q13547 HDAC1 55103 MAQTQGTRRKVCYYYDGDVGNYYYG ... EKTKEEKPEAKGVKEEVKLA /// ... /// ``` /// /// # Example /// /// ```rust,ignore /// # use uniprot::Uniprot; /// /// let db: Uniprot = match Uniprot::load("uniprot.txt") { /// Ok(db) => db, /// Err(e) => panic!("Error loading local Uniprot database: {}", e), /// }; /// ``` // pub fn load<P: AsRef<Path>>(path: P) -> io::Result<Uniprot> { // let mut buf = String::new(); // File::open(path)?.read_to_string(&mut buf)?; // let mut inner = HashMap::new(); // let mut iter = Pitchfork::new('\n' as u8, buf.as_bytes()).filter(|x| x.len() != 0); // let mut last = iter.next().unwrap(); // let mut id = ""; // let mut seq = String::new(); // for line in iter { // if line[0] == '>' as u8 { // let id = str::from_utf8(last).unwrap(); // last = line; // if id != "" { // let deets = id.split('|').skip(1).take(2).collect::<Vec<&str>>(); // if deets.len() != 2 { // panic!("{}", id); // } // inner.insert(deets[0].into(), Entry { // accession: deets[0].into(), // identifier: deets[1].into(), // sequence: seq, // }); // seq = String::new(); // } // } else { // seq.push_str(str::from_utf8(line).unwrap().trim()); // } // } // Ok(Uniprot { // inner // }) // } #[deprecated(since = "0.2.0", note = "Use fasta::Fasta interface instead")] pub fn load<T: AsRef<Path>>(path: T) -> io::Result<Self> { let mut buffer = String::new(); let mut inner = HashMap::new(); File::open(path)?.read_to_string(&mut buffer)?; for line in buffer.lines() { let s = line.split('\t').collect::<Vec<_>>(); let entry = Entry { accession: s[0].into(), identifier: s[1].into(), sequence: s[3].into(), // molecular_weight: s[2] // .parse::<u32>() // .map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?, }; inner.insert(entry.accession.clone(), entry); } Ok(Uniprot { inner }) } /// Search a [`Uniprot`] database object by Uniprot accession /// /// # Example /// /// ```rust,ignore /// # use uniprot::Uniprot; /// # let uni = Uniprot::load("./data/uniprot/db").unwrap(); /// /// let seq: &String = match uni.lookup("Q13526") { /// Some(entry) => &entry.sequence, /// None => 0, /// }; /// ``` pub fn lookup<T: AsRef<str>>(&self, acc: T) -> Option<&Entry> { self.inner.get(acc.as_ref()) } } impl Entry { pub fn assign_residue(&self, seq: &str) -> Option<usize> { let peptide = if seq.contains(".") { seq.split(".").skip(1).next()? } else { seq }; match peptide.find('*') { Some(offset) => { let needle = peptide.chars().filter(|&c| c != '*').collect::<String>(); self.sequence.find(&needle).map(|idx| idx + offset) } None => self.sequence.find(peptide), } } }
pub fn raindrops(n: u32) -> String { let factors = [(3, "Pling"), (5, "Plang"), (7, "Plong")]; let mut result = String::new(); for (f, s) in &factors { if n % f == 0 { result.push_str(s); } } if result.is_empty() { return n.to_string(); } result }
// Copyright 2021 Google LLC // // 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. extern crate http; extern crate hyper; // Add a simple union type of our various sources of HTTP-ish errors. #[derive(Debug)] pub enum HttpError { Hyper(hyper::Error), Generic(http::Error), Status(hyper::StatusCode), Uri, Body, UploadFailed, } impl From<hyper::Error> for HttpError { fn from(err: hyper::Error) -> Self { HttpError::Hyper(err) } } impl From<http::uri::InvalidUri> for HttpError { fn from(_: http::uri::InvalidUri) -> Self { HttpError::Uri } } impl From<http::Error> for HttpError { fn from(err: http::Error) -> Self { HttpError::Generic(err) } } impl HttpError { // Encode the GCS rules on retrying. pub fn should_retry_gcs(&self) -> bool { match self { // If hyper says this is a user or parse error, it won't // change on a retry. Self::Hyper(e) => !e.is_parse() && !e.is_user(), // https://cloud.google.com/storage/docs/json_api/v1/status-codes // come in handy as a guide. In fact, it lists *408* as an // additional thing you should retry on (not just the usual 429). Self::Status(code) => match code.as_u16() { // All 2xx are good (and aren't expected here, but are okay) 200..=299 => true, // Any 3xx is "bad". 300..=399 => false, // Both 429 *and* 408 are documented as needing retries. 408 | 429 => true, // Other 4xx should not be retried. 400..=499 => false, // Any 5xx is fair game for retry. 500..=599 => true, // Anything else is a real surprise. _ => false, }, // TODO(boulos): Add more here. As we need them. _ => { debug!("Asked for should_retry_gcs({:#?}). Saying no", self); false } } } }
use crate::{ runtime::Runtimes, watchdog::{ControlCommand, WatchdogQuery}, }; use std::future::Future; use tokio::{ sync::{mpsc, oneshot}, task::JoinHandle, }; pub struct WatchdogMonitor { runtimes: Runtimes, control_command: mpsc::Sender<ControlCommand>, watchdog_finished: oneshot::Receiver<()>, } impl WatchdogMonitor { pub(crate) fn new( runtimes: Runtimes, control_command: mpsc::Sender<ControlCommand>, watchdog_finished: oneshot::Receiver<()>, ) -> Self { WatchdogMonitor { runtimes, control_command, watchdog_finished, } } pub fn control(&self) -> WatchdogQuery { WatchdogQuery::new( self.runtimes.watchdog().handle().clone(), self.control_command.clone(), ) } pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output> where F: Future + Send + 'static, F::Output: Send + 'static, { self.runtimes.watchdog().handle().spawn(future) } pub fn wait_finished(self) { let Self { mut runtimes, watchdog_finished, .. } = self; runtimes .watchdog_mut() .block_on(async move { watchdog_finished.await.unwrap() }) } }
#[macro_use] extern crate cycle_match; fn main() { let data = "1234567890"; let mut data_n_index = 0usize; let mut iter = data.as_bytes().into_iter(); loop_match!((iter.next()) -> || { Some(a) => data_n_index += *a as usize, _ => break, }); assert_eq!(data_n_index, 525); }
use crate::ast; use crate::{ParseError, Parser}; use crate::{Spanned, ToTokens}; /// A literal expression. #[derive(Debug, Clone, ToTokens, Spanned)] pub struct ExprLit { /// Attributes associated with the literal expression. #[rune(iter)] pub attributes: Vec<ast::Attribute>, /// The literal in the expression. pub lit: ast::Lit, } impl ExprLit { /// Test if the literal expression is constant. pub fn is_const(&self) -> bool { self.lit.is_const() } /// Parse the literal expression with attributes. pub fn parse_with_attributes( parser: &mut Parser<'_>, attributes: Vec<ast::Attribute>, ) -> Result<Self, ParseError> { Ok(Self { attributes, lit: parser.parse()?, }) } }
use crate::{ models::money_node::{MoneyNode, NewMoneyNode, UpdateMoneyNode}, schema::{money_nodes, money_nodes::dsl::money_nodes as money_nodes_query}, }; use diesel::prelude::*; use crate::db::finance::FilterQuery; pub fn all(conn: &PgConnection) -> QueryResult<Vec<MoneyNode>> { money_nodes_query .order(money_nodes::id.asc()) .load::<MoneyNode>(conn) } pub fn by_id(conn: &PgConnection, id: i32) -> QueryResult<MoneyNode> { money_nodes_query.find(id).get_result::<MoneyNode>(conn) } pub fn new(conn: &PgConnection, money_node: NewMoneyNode) -> QueryResult<MoneyNode> { diesel::insert_into(money_nodes::table) .values(money_node) .get_result::<MoneyNode>(conn) } pub fn update(conn: &PgConnection, money_node: UpdateMoneyNode, id: i32) -> QueryResult<MoneyNode> { diesel::update(money_nodes_query.find(id)) .set(money_node) .get_result::<MoneyNode>(conn) } pub fn delete(conn: &PgConnection, id: i32) -> QueryResult<MoneyNode> { diesel::delete(money_nodes_query.find(id)).get_result::<MoneyNode>(conn) } pub fn by_query(conn: &PgConnection, query: FilterQuery) -> QueryResult<Vec<MoneyNode>> { let mut db_query = money_nodes_query .order(money_nodes::id.asc()).into_boxed(); if let Some(option) = query.processed { db_query = db_query.filter(money_nodes::processed.eq(option)) } if let Some(option) = query.branch { db_query = db_query.filter(money_nodes::branch.eq(option)) } if let Some(option) = query.from { db_query = db_query.filter(money_nodes::added.ge(option)) } if let Some(option) = query.until { db_query = db_query.filter(money_nodes::added.le(option)) } db_query.load::<MoneyNode>(conn) }
use tokio::io::AsyncRead; use crate::error::{TychoError, TychoResult}; use crate::read::async_::func::{read_byte_async, read_bytes_async}; use crate::read::async_::length::read_length_async; pub(crate) async fn read_string_async<R: AsyncRead + Unpin>(reader: &mut R) -> TychoResult<String> { let length = read_length_async(reader).await?; match String::from_utf8(read_bytes_async(reader, length).await?) { Ok(s) => Ok(s), Err(e) => Err(TychoError::StringError(e)) } } pub(crate) async fn read_tstring_async<R: AsyncRead + Unpin>(reader: &mut R) -> TychoResult<String> { let mut buffer = Vec::new(); loop { let byte = read_byte_async(reader).await?; if byte == 0x00 { break; } buffer.push(byte); } match String::from_utf8(buffer) { Ok(s) => Ok(s), Err(e) => Err(TychoError::StringError(e)) } } pub(crate) async fn read_char_async<R: AsyncRead + Unpin>(reader: &mut R) -> TychoResult<char> { let mut buffer = Vec::new(); let byte = read_byte_async(reader).await?; if byte >> 7 == 0 { buffer.push(byte); } else { let count = if byte & 0b01000000 == 0x00 { 1 } else if byte & 0b00100000 == 0x00 { 2 } else if byte & 0b00010000 == 0x00 { 3 } else if byte & 0b00001000 == 0x00 { 4 } else if byte & 0b00000100 == 0x00 { 5 } else if byte & 0b00000010 == 0x00 { 6 } else { 0 }; buffer.extend_from_slice(&read_bytes_async(reader, count).await?); } match String::from_utf8(buffer) { Ok(s) => Ok(s.chars().nth(0).unwrap().clone()), //todo: unwrap :( Err(e) => Err(TychoError::StringError(e)) } }
// 参考文档: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name trait Animal { fn baby_name() -> String; } struct Dog; impl Dog { fn baby_name() -> String { String::from("Spot") } } impl Animal for Dog { fn baby_name() -> String { String::from("puppy") } } fn main() { assert_eq!(Dog::baby_name(), "Spot".to_string()); assert_eq!(<Dog as Animal>::baby_name(), "puppy".to_string()); }
pub mod models; pub mod operations; #[allow(dead_code)] pub const API_VERSION: &str = "2017-06-01.5.1";
use na::geometry::*; use na::Real; use na::Vector2; type Point = Point2<f32>; type Vector = Vector2<f32>; pub fn get_cross_points_with_sphere( center: &Point, radius: f32, from: &Point, to: &Point, ) -> Vec<Point> { let translate = Vector::new(center.x, center.y); let origin_from = from - translate; let origin_to = to - translate; let result = get_cross_points(radius, &origin_from, &origin_to); let ray = origin_to - origin_from; result .iter() .filter(|p| (*p - origin_from).dot(&ray) > 0.) .map(|p| p + translate) .collect::<Vec<Point>>() } fn get_cross_points(radius: f32, from: &Point, to: &Point) -> Vec<Point> { const EPS: f32 = 0.000001; let a = from.y - to.y; let b = to.x - from.x; let c = from.x * to.y - to.x * from.y; let len = a * a + b * b; let x0 = -a * c / len; let y0 = -b * c / len; if c * c > radius * radius * len + EPS { return vec![]; } if Real::abs(c * c - radius * radius * len) < EPS { return vec![Point::new(x0, y0)]; } let d = radius * radius - c * c / len; let multiplicands = Real::sqrt(d / len); let point1 = Point::new(x0 + b * multiplicands, y0 - a * multiplicands); let point2 = Point::new(x0 - b * multiplicands, y0 + a * multiplicands); return vec![point1, point2]; }
fn main() { println!("Hello, world!"); let s1 = "literal"; // literal, immutable, fixed memory //literal is stored on stack let mut s2 = String::from("string"); //string, mutable //stored on heap s2.push_str("version2"); let s3 = String::from("example"); let x = s3; //value of s3 was burrowed, we can't refer to s3 anymore //when we would free memory for s3 and x after function ended, it would be double free //println!("value of s3: {}", s3); //we can't refer to s3 anymore //let x = s3.push_str("ff"); //we can't do that neither let i1 = 1; let i2 = i1; //this is copy, we can change both values separately println!("i1 value: {}", i1); println!("i2 value: {}", i2); //this works because size is fixed and they are both on stack let u1 = String::from("promotion"); check_something(u1); //the function check_something has now ownership of u1 //println!("{}", u1); //error let u2 = 1; check_something_on_stack(u2); //we are copying integer because it's on stack println!("still here, {}", u2); // we can still use it let b2 = returning_something(); println!("Hi, I took ownership, {}", b2); let c1 = String::from("my ownership will be gave back"); let c2 = take_ownership_and_return(c1); //println!("c1: {}", c1); //we can't access c1 here, it was moved //we gave c1 ownership, so we don't have to drop it //c2 will be dropped after end of the scope //the value will be cleaned up by drop unless the data has been moved to be owned by another variable } fn check_something(u1:String) { println!("I'm here now: {}!", u1); } //after this function is finished, we are calling drop() because it's on heap fn check_something_on_stack(u2:i32) { println!("Yo, {}", u2); } //u2 is Copy, so we don't call drop() here fn returning_something() -> String { String::from("sth sth") } fn take_ownership_and_return(c1:String) -> String //c1 moved here and then ownerships is going back to c2 { c1 }
use crate::{ alphabet::Alphabet, dfa::standard::StandardDFA, nfa::{ standard::{StandardNFA, Transition}, standard_eps::StandardEpsilonNFA, }, range_set::Range, state::State, }; use core::{ hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, iter::once, }; use fxhash::FxHasher; use hashbrown::{HashMap, HashSet}; use valis_ds::{ repr::ReprUsize, set::{Set, VectorSet}, }; // Papers of interest // // Treatment of Epsilon Moves in Subset Construction // - Gertjan van Noord // - https://sci-hub.se/10.1162/089120100561638 // // Generic epsilon-removal // - Vivien Delmon // - https://www.lrde.epita.fr/dload/20070523-Seminar/delmon-eps-removal-vcsn-report.pdf // // Effcient Approaches to Subset Construction // - Ted Leslie // - http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=318E0FC96DD030FC1E7A1AE52148DD83?doi=10.1.1.8.7435&rep=rep1&type=pdf // - This paper is not very clear, but if you can decipher it then it holds an // efficient implementation and description of data structures for subset // construction (determinization) // Convert an NFA enabled with epsilon transitions to an equivalent one without pub fn remove_epsilon_transitions<A: Alphabet, I: State>( nfa: &StandardEpsilonNFA<A, I>, ) -> StandardNFA<A, I> { let start_states: HashSet<I> = nfa .epsilon_reachable_states(once(*nfa.start_state())) .collect(); let states = *nfa.states(); let accept_states = nfa.accept_states().clone(); let transitions: Vec<VectorSet<Transition<A, I>>> = nfa .states() .into_iter() .map(|state| { A::value_iter() .flat_map(|sym| { nfa.epsilon_reachable_states(nfa.lookup_concrete(state, sym)) .map(move |next_state| Transition(sym, next_state)) }) .collect::<VectorSet<_>>() }) .collect(); StandardNFA::new(states, transitions, accept_states, start_states) } // From a standard NFA, remove all states that are unreachable from the starting // states pub fn prune_unreachable_states_nfa<A: Alphabet, I: State>( nfa: &StandardNFA<A, I>, ) -> StandardNFA<A, I> { let mut state_mapping = Vec::with_capacity(nfa.states().size()); let mut stack = Vec::<I>::new(); stack.extend(nfa.start_states()); while let Some(node) = stack.pop() { match state_mapping.binary_search(&node) { Ok(_) => {}, Err(idx) => { state_mapping.insert(idx, node); for sym in A::value_iter() { stack.extend(nfa.lookup(node, sym)) } }, } } let new_states: Range<I> = (ReprUsize::from_usize(0)..ReprUsize::from_usize(state_mapping.len())).into(); let new_accept_states = nfa .accept_states() .into_iter() .filter_map(|state| match state_mapping.binary_search(state) { Ok(idx) => Some(I::from_usize(idx)), Err(_) => None, }) .collect(); let new_start_states = nfa .start_states() .into_iter() .filter_map(|state| match state_mapping.binary_search(state) { Ok(idx) => Some(I::from_usize(idx)), Err(_) => None, }) .collect(); let new_transitions = nfa .transitions() .iter() .map(|trans_set| { trans_set .as_slice() .iter() .filter_map( |Transition(sym, state)| match state_mapping.binary_search(state) { Ok(idx) => Some(Transition(*sym, I::from_usize(idx))), Err(_) => None, }, ) .collect() }) .collect(); StandardNFA::new( new_states, new_transitions, new_accept_states, new_start_states, ) } // Before calling this function, the StandardNFA should have all of its // unreachable states pruned. This will reduce the amount of work pub fn determinize<A: Alphabet, I: State>(nfa: &StandardNFA<A, I>) -> StandardDFA<A, I> { let hash_builder = BuildHasherDefault::<FxHasher>::default(); let mut state_mapping: HashMap<u64, (VectorSet<I>, I)> = HashMap::new(); let mut last_added_state = 0; let nfa_transitions = nfa.transitions(); let mut new_transitions: Vec<(I, A, I)> = Vec::new(); // hashes of sets stored in order that they will be worked on let mut set_keys = Vec::new(); // Initialize data structures with starting state let start_states: VectorSet<I> = nfa.start_states().into_iter().cloned().collect(); let start_hash = hash_item(&start_states, &hash_builder); state_mapping.insert(start_hash, (start_states, I::from_usize(last_added_state))); set_keys.push(start_hash); let mut state_counter = 0; while state_counter <= last_added_state { for sym in A::value_iter() { let mut destination_state = VectorSet::new(); let current_state = &state_mapping.get(&set_keys[state_counter]).unwrap().0; for state in current_state { for trans in nfa_transitions[state.to_usize()].as_slice() { if trans.0 == sym { destination_state.insert(trans.1); } } } let destination_state_hash = hash_item(&destination_state, &hash_builder); if let Some((_, existing_state)) = state_mapping.get(&destination_state_hash) { new_transitions.push((I::from_usize(state_counter), sym, *existing_state)); } else { last_added_state += 1; state_mapping.insert( destination_state_hash, (destination_state, I::from_usize(last_added_state)), ); new_transitions.push(( I::from_usize(state_counter), sym, I::from_usize(last_added_state), )); set_keys.push(destination_state_hash); } } state_counter += 1; } let dfa_states: Range<I> = (I::from_usize(0)..=I::from_usize(last_added_state)).into(); new_transitions.sort_by_key(|val| (val.0, val.1.to_usize(), val.2)); let dfa_transitions = new_transitions .into_iter() .map(|(_, _, dest_state)| dest_state) .collect::<Vec<_>>() .into_boxed_slice(); let dfa_start_state = I::from_usize(0); let dfa_dead_state = state_mapping .values() .find(|(nfa_states, _)| nfa_states.size() == 0) .map(|(_, state)| *state); let dfa_accept_states = state_mapping .values() .filter_map(|(nfa_states, new_state)| { let contains_accept = nfa_states .as_slice() .iter() .any(|state| nfa.accept_states().contains(state)); if contains_accept { Some(*new_state) } else { None } }) .collect(); StandardDFA::new( dfa_states, dfa_transitions, dfa_accept_states, dfa_start_state, dfa_dead_state, ) } fn hash_item<T: Hash, S: BuildHasher>(item: T, builder: &S) -> u64 { let mut hasher = builder.build_hasher(); item.hash(&mut hasher); hasher.finish() }
use fibers::sync::oneshot::MonitorError; use std::io; use std::sync::mpsc::SendError; use stun_codec::rfc5389::attributes::ErrorCode; use stun_codec::AttributeType; use trackable::error::{self, ErrorKindExt, TrackableError}; /// This crate specific `Error` type. #[derive(Debug, Clone, TrackableError)] pub struct Error(TrackableError<ErrorKind>); impl From<MonitorError<Error>> for Error { fn from(f: MonitorError<Error>) -> Self { f.unwrap_or_else(|| { ErrorKind::Other .cause("Monitor channel has disconnected") .into() }) } } impl From<io::Error> for Error { fn from(f: io::Error) -> Self { ErrorKind::Other.cause(f).into() } } impl<T> From<SendError<T>> for Error { fn from(_: SendError<T>) -> Self { ErrorKind::Other.cause("Receiver has terminated").into() } } impl From<bytecodec::Error> for Error { fn from(f: bytecodec::Error) -> Self { let original_error_kind = *f.kind(); let kind = match original_error_kind { bytecodec::ErrorKind::InvalidInput => ErrorKind::InvalidInput, _ => ErrorKind::Other, }; track!(kind.takes_over(f); original_error_kind).into() } } impl From<MessageError> for Error { fn from(f: MessageError) -> Self { ErrorKind::InvalidMessage(f.kind().clone()) .takes_over(f) .into() } } impl From<ErrorCode> for Error { fn from(f: ErrorCode) -> Self { ErrorKind::Other .cause(format!("STUN error response: {f:?}")) .into() } } impl From<fibers_transport::Error> for Error { fn from(f: fibers_transport::Error) -> Self { let original_error_kind = *f.kind(); let kind = match original_error_kind { fibers_transport::ErrorKind::InvalidInput => ErrorKind::InvalidInput, _ => ErrorKind::Other, }; track!(kind.takes_over(f); original_error_kind).into() } } /// Possible error kinds. #[derive(Debug, Clone)] pub enum ErrorKind { /// Input is invalid. InvalidInput, /// A message is invalid. /// /// This error does not affect the overall execution of a channel/client/server. InvalidMessage(MessageErrorKind), /// Other errors. Other, } impl error::ErrorKind for ErrorKind {} /// Message level error. #[derive(Debug, Clone, TrackableError)] #[trackable(error_kind = "MessageErrorKind")] pub struct MessageError(TrackableError<MessageErrorKind>); impl From<MonitorError<MessageError>> for MessageError { fn from(f: MonitorError<MessageError>) -> Self { f.unwrap_or_else(|| { MessageErrorKind::Other .cause("`Channel` instance has dropped") .into() }) } } impl From<Error> for MessageError { fn from(f: Error) -> Self { let original_error_kind = f.kind().clone(); track!(MessageErrorKind::Other.takes_over(f); original_error_kind).into() } } impl From<fibers_transport::Error> for MessageError { fn from(f: fibers_transport::Error) -> Self { let original_error_kind = *f.kind(); let kind = match original_error_kind { fibers_transport::ErrorKind::InvalidInput => MessageErrorKind::InvalidInput, _ => MessageErrorKind::Other, }; track!(kind.takes_over(f); original_error_kind).into() } } /// Possible error kinds. #[derive(Debug, Clone)] pub enum MessageErrorKind { /// Unexpected response message. UnexpectedResponse, /// There are some malformed attributes in a message. MalformedAttribute, /// There are unknown comprehension-required attributes. /// /// If a server receives a message that contains unknown comprehension-required attributes, /// it should reply an `ErrorResponse` message that has the [`UnknownAttribute`] error code and /// an [`UnknownAttributes`] attribute. /// /// [`UnknownAttribute`]: https://docs.rs/stun_codec/0.1/stun_codec/rfc5389/errors/struct.UnknownAttribute.html /// [`UnknownAttributes`]: https://docs.rs/stun_codec/0.1/stun_codec/rfc5389/attributes/struct.UnknownAttributes.html UnknownAttributes(Vec<AttributeType>), /// Input is invalid. InvalidInput, /// Operation timed out. Timeout, /// Other errors. Other, } impl error::ErrorKind for MessageErrorKind {}
//! The Splunk HEC generator. mod acknowledgements; use std::{ num::{NonZeroU32, NonZeroUsize}, time::Duration, }; use acknowledgements::Channels; use byte_unit::{Byte, ByteUnit}; use http::{ header::{AUTHORIZATION, CONTENT_LENGTH}, Method, Request, Uri, }; use hyper::{client::HttpConnector, Body, Client}; use metrics::{counter, gauge}; use once_cell::sync::OnceCell; use rand::{prelude::StdRng, SeedableRng}; use serde::Deserialize; use tokio::{ sync::{Semaphore, SemaphorePermit}, time::timeout, }; use tracing::info; use crate::{ block::{self, chunk_bytes, construct_block_cache, Block}, generator::splunk_hec::acknowledgements::Channel, payload, payload::SplunkHecEncoding, signals::Shutdown, throttle::{self, Throttle}, }; static CONNECTION_SEMAPHORE: OnceCell<Semaphore> = OnceCell::new(); const SPLUNK_HEC_ACKNOWLEDGEMENTS_PATH: &str = "/services/collector/ack"; const SPLUNK_HEC_JSON_PATH: &str = "/services/collector/event"; const SPLUNK_HEC_TEXT_PATH: &str = "/services/collector/raw"; const SPLUNK_HEC_CHANNEL_HEADER: &str = "x-splunk-request-channel"; /// Optional Splunk HEC indexer acknowledgements configuration #[derive(Deserialize, Debug, Clone, Copy, PartialEq)] pub struct AckSettings { /// The time in seconds between queries to /services/collector/ack pub ack_query_interval_seconds: u64, /// The time in seconds an ackId can remain pending before assuming data was /// dropped pub ack_timeout_seconds: u64, } /// Configuration for [`SplunkHec`] #[derive(Deserialize, Debug, PartialEq)] pub struct Config { /// The seed for random operations against this target pub seed: [u8; 32], /// The URI for the target, must be a valid URI #[serde(with = "http_serde::uri")] pub target_uri: Uri, /// Format used when submitting event data to Splunk HEC pub format: SplunkHecEncoding, /// Splunk HEC authentication token pub token: String, /// Splunk HEC indexer acknowledgements behavior options pub acknowledgements: Option<AckSettings>, /// The maximum size in bytes of the cache of prebuilt messages pub maximum_prebuild_cache_size_bytes: byte_unit::Byte, /// The bytes per second to send or receive from the target pub bytes_per_second: byte_unit::Byte, /// The block sizes for messages to this target pub block_sizes: Option<Vec<byte_unit::Byte>>, /// The total number of parallel connections to maintain pub parallel_connections: u16, /// The load throttle configuration #[serde(default)] pub throttle: throttle::Config, } #[derive(thiserror::Error, Debug, Clone, Copy)] /// Errors produced by [`SplunkHec`]. pub enum Error { /// User supplied HEC path is invalid. #[error("User supplied HEC path is not valid")] InvalidHECPath, /// Interior acknowledgement error. #[error("Interior error: {0}")] Acknowledgements(acknowledgements::Error), /// Creation of payload blocks failed. #[error("Block creation error: {0}")] Block(#[from] block::Error), } /// Defines a task that emits variant lines to a Splunk HEC server controlling /// throughput. #[derive(Debug)] pub struct SplunkHec { uri: Uri, token: String, parallel_connections: u16, throttle: Throttle, block_cache: Vec<Block>, metric_labels: Vec<(String, String)>, channels: Channels, shutdown: Shutdown, } /// Derive the intended path from the format configuration // https://docs.splunk.com/Documentation/Splunk/latest/Data/FormateventsforHTTPEventCollector#Event_data fn get_uri_by_format(base_uri: &Uri, format: payload::SplunkHecEncoding) -> Uri { let path = match format { payload::SplunkHecEncoding::Text => SPLUNK_HEC_TEXT_PATH, payload::SplunkHecEncoding::Json => SPLUNK_HEC_JSON_PATH, }; Uri::builder() .authority(base_uri.authority().unwrap().to_string()) .scheme("http") .path_and_query(path) .build() .unwrap() } impl SplunkHec { /// Create a new [`SplunkHec`] instance /// /// # Errors /// /// Creation will fail if the underlying governor capacity exceeds u32. /// /// # Panics /// /// Function will panic if user has passed non-zero values for any byte /// values. Sharp corners. #[allow(clippy::cast_possible_truncation)] pub fn new(config: Config, shutdown: Shutdown) -> Result<Self, Error> { let mut rng = StdRng::from_seed(config.seed); let block_sizes: Vec<NonZeroUsize> = config .block_sizes .unwrap_or_else(|| { vec![ Byte::from_unit(1.0 / 8.0, ByteUnit::MB).unwrap(), Byte::from_unit(1.0 / 4.0, ByteUnit::MB).unwrap(), Byte::from_unit(1.0 / 2.0, ByteUnit::MB).unwrap(), Byte::from_unit(1_f64, ByteUnit::MB).unwrap(), Byte::from_unit(2_f64, ByteUnit::MB).unwrap(), Byte::from_unit(4_f64, ByteUnit::MB).unwrap(), ] }) .iter() .map(|sz| NonZeroUsize::new(sz.get_bytes() as usize).expect("bytes must be non-zero")) .collect(); let labels = vec![ ("component".to_string(), "generator".to_string()), ("component_name".to_string(), "splunk_hec".to_string()), ]; let bytes_per_second = NonZeroU32::new(config.bytes_per_second.get_bytes() as u32).unwrap(); gauge!( "bytes_per_second", f64::from(bytes_per_second.get()), &labels ); let uri = get_uri_by_format(&config.target_uri, config.format); let block_chunks = chunk_bytes( &mut rng, NonZeroUsize::new(config.maximum_prebuild_cache_size_bytes.get_bytes() as usize) .expect("bytes must be non-zero"), &block_sizes, )?; let payload_config = payload::Config::SplunkHec { encoding: config.format, }; let block_cache = construct_block_cache(&mut rng, &payload_config, &block_chunks, &labels); let mut channels = Channels::new(config.parallel_connections); if let Some(ack_settings) = config.acknowledgements { let ack_uri = Uri::builder() .authority(uri.authority().unwrap().to_string()) .scheme("http") .path_and_query(SPLUNK_HEC_ACKNOWLEDGEMENTS_PATH) .build() .unwrap(); channels.enable_acknowledgements(ack_uri, config.token.clone(), ack_settings); } CONNECTION_SEMAPHORE .set(Semaphore::new(config.parallel_connections as usize)) .unwrap(); Ok(Self { channels, parallel_connections: config.parallel_connections, uri, token: config.token, block_cache, throttle: Throttle::new_with_config(config.throttle, bytes_per_second), metric_labels: labels, shutdown, }) } /// Run [`SplunkHec`] to completion or until a shutdown signal is received. /// /// # Errors /// /// Function will error if unable to enable acknowledgements when configured /// to do so. /// /// # Panics /// /// Function will panic if it is unable to create HTTP requests for the /// target. pub async fn spin(mut self) -> Result<(), Error> { let client: Client<HttpConnector, Body> = Client::builder() .pool_max_idle_per_host(self.parallel_connections as usize) .retry_canceled_requests(false) .set_host(false) .build_http(); let uri = self.uri; let labels = self.metric_labels; gauge!( "maximum_requests", f64::from(self.parallel_connections), &labels ); let mut blocks = self.block_cache.iter().cycle().peekable(); let mut channels = self.channels.iter().cycle(); loop { let channel: Channel = channels.next().unwrap().clone(); let blk = blocks.peek().unwrap(); let total_bytes = blk.total_bytes; tokio::select! { _ = self.throttle.wait_for(total_bytes) => { let client = client.clone(); let labels = labels.clone(); let uri = uri.clone(); let blk = blocks.next().unwrap(); // actually advance through the blocks let body = Body::from(blk.bytes.clone()); let block_length = blk.bytes.len(); let request: Request<Body> = Request::builder() .method(Method::POST) .uri(uri) .header(AUTHORIZATION, format!("Splunk {}", self.token)) .header(CONTENT_LENGTH, block_length) .header(SPLUNK_HEC_CHANNEL_HEADER, channel.id()) .body(body) .unwrap(); // NOTE once JoinSet is in tokio stable we can make this // much, much tidier by spawning requests in the JoinSet. I // think we could also possibly have the send request return // the AckID, meaning we could just keep the channel logic // in this main loop here and avoid the AckService entirely. let permit = CONNECTION_SEMAPHORE.get().unwrap().acquire().await.unwrap(); tokio::spawn(send_hec_request(permit, block_length, labels, channel, client, request, self.shutdown.clone())); } _ = self.shutdown.recv() => { info!("shutdown signal received"); // When we shut down we may leave dangling, active // requests. This is acceptable. As we do not today // coordinate with the target it's possible that the target // will have been shut down and an in-flight request is // waiting for an ack from it, causing this to jam forever // if we attempt to acquire all semaphore permits. return Ok(()); }, } } } } async fn send_hec_request( permit: SemaphorePermit<'_>, block_length: usize, labels: Vec<(String, String)>, channel: Channel, client: Client<HttpConnector>, request: Request<Body>, mut shutdown: Shutdown, ) { counter!("requests_sent", 1, &labels); let work = client.request(request); tokio::select! { tm = timeout(Duration::from_secs(1), work) => { match tm { Ok(tm) => match tm { Ok(response) => { counter!("bytes_written", block_length as u64, &labels); let (parts, body) = response.into_parts(); let status = parts.status; let mut status_labels = labels.clone(); status_labels.push(("status_code".to_string(), status.as_u16().to_string())); counter!("request_ok", 1, &status_labels); channel .send(async { let body_bytes = hyper::body::to_bytes(body).await.unwrap(); let hec_ack_response = serde_json::from_slice::<HecAckResponse>(&body_bytes).unwrap(); hec_ack_response.ack_id }) .await; } Err(err) => { let mut error_labels = labels.clone(); error_labels.push(("error".to_string(), err.to_string())); counter!("request_failure", 1, &error_labels); } } Err(err) => { let mut error_labels = labels.clone(); error_labels.push(("error".to_string(), err.to_string())); counter!("request_timeout", 1, &error_labels); } } } _ = shutdown.recv() => {}, } drop(permit); } #[derive(Deserialize, Debug)] struct HecAckResponse { #[allow(dead_code)] text: String, #[allow(dead_code)] code: u8, #[serde(rename = "ackId")] ack_id: u64, }
use crate::app::application::Application; use crate::app::UpdateResult; use crate::renderer::renderer::Renderer; use crate::ui::*; use rider_config::*; use sdl2::rect::Point; use sdl2::VideoSubsystem as VS; use std::fs::{read_to_string, File}; use std::io::Write; use std::sync::*; pub struct AppState { menu_bar: MenuBar, project_tree: ProjectTreeSidebar, files: Vec<EditorFile>, config: Arc<RwLock<Config>>, file_editor: FileEditor, modal: Option<ModalType>, } impl AppState { pub fn new(config: Arc<RwLock<Config>>) -> Self { Self { menu_bar: MenuBar::new(config.clone()), project_tree: ProjectTreeSidebar::new( Application::current_working_directory(), config.clone(), ), files: vec![], file_editor: FileEditor::new(config.clone()), modal: None, config, } } #[cfg_attr(tarpaulin, skip)] pub fn open_file<R>(&mut self, file_path: String, renderer: &mut R) -> Result<(), String> where R: Renderer + CharacterSizeManager + ConfigHolder, { let buffer = read_to_string(&file_path) .map_err(|file_path| format!("Failed to open file: {}", file_path))?; let mut file = EditorFile::new(file_path.clone(), buffer, self.config.clone()); file.prepare_ui(renderer); match self.file_editor.open_file(file) { Some(old) => self.files.push(old), _ => (), } Ok(()) } pub fn save_file(&self) -> Result<(), String> { let editor_file = match self.file_editor.file() { Some(f) => f, _ => Err("No buffer found".to_string())?, }; let mut f = File::create(editor_file.path()) .or_else(|_| Err("File can't be opened".to_string()))?; f.write_all(editor_file.buffer().as_bytes()) .or_else(|_| Err("Failed to write to file".to_string()))?; f.flush() .or_else(|_| Err("Failed to write to file".to_string()))?; Ok(()) } pub fn open_settings<R>(&mut self, renderer: &mut R) -> Result<(), String> where R: Renderer + CharacterSizeManager + ConfigHolder, { match self.modal { None => { let mut settings = Settings::new(self.config.clone()); settings.prepare_ui(renderer); self.modal = Some(ModalType::Settings(settings)); } _ => return Ok(()), } Ok(()) } pub fn close_modal(&mut self) -> Result<(), String> { self.modal = None; Ok(()) } pub fn open_directory<R>(&mut self, dir_path: String, renderer: &mut R) where R: Renderer + CharacterSizeManager + ConfigHolder, { match self.modal.as_mut() { Some(ModalType::OpenFile(modal)) => modal.open_directory(dir_path, renderer), None => self.project_tree.open_directory(dir_path, renderer), _ => (), }; } #[cfg_attr(tarpaulin, skip)] pub fn file_editor(&self) -> &FileEditor { &self.file_editor } #[cfg_attr(tarpaulin, skip)] pub fn file_editor_mut(&mut self) -> &mut FileEditor { &mut self.file_editor } pub fn set_open_file_modal(&mut self, modal: Option<OpenFile>) { self.modal = if let Some(modal) = modal { Some(ModalType::OpenFile(modal)) } else { None }; } pub fn scroll_by(&mut self, x: i32, y: i32) { match self.modal.as_mut() { Some(ModalType::OpenFile(modal)) => modal.scroll_by(x, y), Some(ModalType::Settings(modal)) => modal.scroll_by(x, y), _ => self.file_editor_mut().scroll_by(x, y), }; } pub fn open_file_modal(&self) -> Option<&OpenFile> { match self.modal { Some(ModalType::OpenFile(ref m)) => Some(m), _ => None, } } pub fn settings_modal(&self) -> Option<&Settings> { match self.modal { Some(ModalType::Settings(ref m)) => Some(m), _ => None, } } } #[cfg_attr(tarpaulin, skip)] impl AppState { pub fn render<C, R>(&self, canvas: &mut C, renderer: &mut R, _context: &RenderContext) where C: CanvasAccess, R: Renderer + ConfigHolder + CharacterSizeManager, { // file editor self.file_editor .render(canvas, renderer, &RenderContext::Nothing); // menu bar self.menu_bar .render(canvas, renderer, &RenderContext::Nothing); // project tree self.project_tree .render(canvas, renderer, &RenderContext::Nothing); // settings modal match self.modal.as_ref() { Some(ModalType::OpenFile(modal)) => { return modal.render(canvas, renderer, &RenderContext::Nothing) } Some(ModalType::Settings(modal)) => { return modal.render(canvas, renderer, &RenderContext::Nothing) } _ => (), }; } pub fn prepare_ui<R>(&mut self, renderer: &mut R) where R: Renderer + CharacterSizeManager + ConfigHolder, { self.menu_bar.prepare_ui(); self.project_tree.prepare_ui(renderer); self.file_editor.prepare_ui(renderer); } pub fn update(&mut self, ticks: i32, context: &UpdateContext) -> UpdateResult { let res = match self.modal.as_mut() { Some(ModalType::OpenFile(modal)) => modal.update(ticks, context.clone()), Some(ModalType::Settings(modal)) => modal.update(ticks, context.clone()), None => UpdateResult::NoOp, }; if res != UpdateResult::NoOp { return res; } // menu bar self.menu_bar.update(ticks, context); // sidebar self.project_tree.update(ticks, context); // file editor let context = UpdateContext::ParentPosition( self.project_tree.full_rect().top_right() + Point::new(10, 0), ); self.file_editor.update(ticks, &context); UpdateResult::NoOp } } impl AppState { #[cfg_attr(tarpaulin, skip)] pub fn on_left_click(&mut self, point: &Point, video_subsystem: &mut VS) -> UpdateResult { if self .project_tree .is_left_click_target(point, &UpdateContext::Nothing) { return self .project_tree .on_left_click(point, &UpdateContext::Nothing); } match self.modal.as_mut() { Some(ModalType::OpenFile(modal)) => { return modal.on_left_click(point, &UpdateContext::Nothing) } Some(ModalType::Settings(modal)) => { return modal.on_left_click(point, &UpdateContext::Nothing) } _ => (), }; if self .menu_bar .is_left_click_target(point, &UpdateContext::Nothing) { video_subsystem.text_input().stop(); return self.menu_bar.on_left_click(point, &UpdateContext::Nothing); } else if !self .file_editor .is_left_click_target(point, &UpdateContext::Nothing) { return UpdateResult::NoOp; } else { video_subsystem.text_input().start(); return self .file_editor .on_left_click(point, &UpdateContext::Nothing); } } pub fn is_left_click_target(&self, _point: &Point) -> bool { true } } impl ConfigHolder for AppState { fn config(&self) -> &ConfigAccess { &self.config } } #[cfg(test)] mod tests { use super::*; use crate::tests::*; use rider_derive::*; #[test] fn must_return_none_for_default_file() { let config = build_config(); let state = AppState::new(config.clone()); let file = state.file_editor().file(); assert_eq!(file.is_none(), true); } #[test] fn must_scroll_file_when_no_modal() { let config = build_config(); let mut state = AppState::new(config.clone()); let old_scroll = state.file_editor().scroll(); state.set_open_file_modal(None); state.scroll_by(10, 10); assert_ne!(state.file_editor().scroll(), old_scroll); } #[test] fn must_scroll_modal_when_modal_was_set() { let config = build_config(); let mut state = AppState::new(config.clone()); let modal = OpenFile::new("/".to_owned(), 100, 100, config.clone()); let file_scroll = state.file_editor().scroll(); let old_scroll = state.file_editor().scroll(); state.set_open_file_modal(Some(modal)); state.scroll_by(10, 10); assert_eq!(state.file_editor().scroll(), file_scroll); assert_ne!( state .open_file_modal() .unwrap_or_else(|| panic!("Failed to open file modal")) .scroll(), old_scroll ); } #[test] fn must_fail_save_file_when_none_is_open() { let config = build_config(); let state = AppState::new(config.clone()); let result = state.save_file(); assert_eq!(result, Err(format!("No buffer found"))); } #[test] fn must_succeed_save_file_when_file_is_open() { assert_eq!(std::fs::create_dir_all("/tmp").is_ok(), true); assert_eq!( std::fs::write( "/tmp/must_succeed_save_file_when_file_is_open.md", "Foo bar" ) .is_ok(), true ); build_test_renderer!(renderer); let mut state = AppState::new(config.clone()); let result = state.open_file( format!("/tmp/must_succeed_save_file_when_file_is_open.md"), &mut renderer, ); assert_eq!(result, Ok(())); let result = state.save_file(); assert_eq!(result, Ok(())); } #[test] fn must_succeed_save_file_when_file_does_not_exists() { assert_eq!(std::fs::create_dir_all("/tmp").is_ok(), true); assert_eq!( std::fs::write( "/tmp/must_succeed_save_file_when_file_does_not_exists.md", "Foo bar" ) .is_ok(), true ); build_test_renderer!(renderer); let mut state = AppState::new(config.clone()); let result = state.open_file( format!("/tmp/must_succeed_save_file_when_file_does_not_exists.md"), &mut renderer, ); assert_eq!(result, Ok(())); let result = state.save_file(); assert_eq!(result, Ok(())); } #[test] fn must_close_modal_when_no_modal_is_open() { let config = build_config(); let mut state = AppState::new(config.clone()); assert_eq!(state.close_modal(), Ok(())); } #[test] fn must_close_modal_when_some_modal_is_open() { let config = build_config(); let mut state = AppState::new(config.clone()); let modal = OpenFile::new("/".to_owned(), 100, 100, config.clone()); state.set_open_file_modal(Some(modal)); assert_eq!(state.close_modal(), Ok(())); } #[test] fn open_settings_when_there_is_no_other_modal() { build_test_renderer!(renderer); let mut state = AppState::new(config.clone()); assert_eq!(state.open_settings(&mut renderer), Ok(())); } #[test] fn open_settings_when_other_modal_is_open() { build_test_renderer!(renderer); let mut state = AppState::new(config.clone()); let modal = OpenFile::new("/".to_owned(), 100, 100, config.clone()); state.set_open_file_modal(Some(modal)); assert_eq!(state.open_settings(&mut renderer), Ok(())); } #[test] fn must_open_directory() { assert_eq!( std::fs::create_dir_all("/tmp/must_open_directory").is_ok(), true ); build_test_renderer!(renderer); let mut state = AppState::new(config.clone()); state.open_directory("/must_open_directory".to_owned(), &mut renderer); } }