text
stringlengths
8
4.13M
use bls12_381::Scalar; use ff::{Field, PrimeField}; use group::{Curve, Group, GroupEncoding}; mod mint2_contract; mod vm; use mint2_contract::{load_params, load_zkvm}; fn unpack<F: PrimeField>(value: F) -> Vec<Scalar> { let mut bits = Vec::new(); print!("Unpack: "); for (i, bit) in value.to_le_bits().into_iter().cloned().enumerate() { match bit { true => bits.push(Scalar::one()), false => bits.push(Scalar::zero()), } print!("{}", if bit { 1 } else { 0 }); } println!(""); bits } fn unpack_u64(value: u64) -> Vec<Scalar> { let mut result = Vec::with_capacity(64); for i in 0..64 { if (value >> i) & 1 == 1 { result.push(Scalar::one()); } else { result.push(Scalar::zero()); } } result } fn do_vcr_test(value: &jubjub::Fr) { let mut curbase = zcash_primitives::constants::VALUE_COMMITMENT_RANDOMNESS_GENERATOR; let mut result = jubjub::SubgroupPoint::identity(); //let value = jubjub::Fr::from(7); for (i, bit) in value.to_le_bits().into_iter().cloned().enumerate() { let thisbase = if bit { curbase.clone() } else { jubjub::SubgroupPoint::identity() }; result += thisbase; curbase = curbase.double(); print!("{}", if bit { 1 } else { 0 }); } println!(""); let result = jubjub::ExtendedPoint::from(result).to_affine(); println!("cvr1: {:?}", result); let randomness_commit = zcash_primitives::constants::VALUE_COMMITMENT_RANDOMNESS_GENERATOR * value; let randomness_commit = jubjub::ExtendedPoint::from(randomness_commit).to_affine(); println!("cvr2: {:?}", randomness_commit); } fn main() -> std::result::Result<(), vm::ZKVMError> { use rand::rngs::OsRng; let public_point = jubjub::ExtendedPoint::from(jubjub::SubgroupPoint::random(&mut OsRng)); let public_affine = public_point.to_affine(); let value = 110; let randomness_value: jubjub::Fr = jubjub::Fr::random(&mut OsRng); //let randomness_value = jubjub::Fr::from(7); let value_commit = (zcash_primitives::constants::VALUE_COMMITMENT_VALUE_GENERATOR * jubjub::Fr::from(value)) + (zcash_primitives::constants::VALUE_COMMITMENT_RANDOMNESS_GENERATOR * randomness_value); ///// let randomness_commit = zcash_primitives::constants::VALUE_COMMITMENT_RANDOMNESS_GENERATOR * randomness_value; ///// do_vcr_test(&randomness_value); let mut vm = load_zkvm(); vm.setup(); let mut params = vec![public_affine.get_u(), public_affine.get_v()]; for x in unpack(randomness_value) { params.push(x); } let params = load_params(params); println!("Size of params: {}", params.len()); vm.initialize(&params)?; let proof = vm.prove(); let public = vm.public(); assert_eq!(public.len(), 2); // Use this code for testing point doubling let dbl = public_point.double().to_affine(); println!("{:?}", dbl.get_u()); println!("{:?}", public[0]); println!("{:?}", dbl.get_v()); println!("{:?}", public[1]); //assert_eq!(public.len(), 2); //assert_eq!(public[0], dbl.get_u()); //assert_eq!(public[1], dbl.get_v()); assert!(vm.verify(&proof, &public)); Ok(()) }
#[doc = "Reader of register POC_REG__TIM_CONTROL"] pub type R = crate::R<u32, super::POC_REG__TIM_CONTROL>; #[doc = "Writer for register POC_REG__TIM_CONTROL"] pub type W = crate::W<u32, super::POC_REG__TIM_CONTROL>; #[doc = "Register POC_REG__TIM_CONTROL `reset()`'s with value 0"] impl crate::ResetValue for super::POC_REG__TIM_CONTROL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `BB_CLK_FREQ_MINUS_1`"] pub type BB_CLK_FREQ_MINUS_1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `BB_CLK_FREQ_MINUS_1`"] pub struct BB_CLK_FREQ_MINUS_1_W<'a> { w: &'a mut W, } impl<'a> BB_CLK_FREQ_MINUS_1_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 << 3)) | (((value as u32) & 0x1f) << 3); self.w } } #[doc = "Reader of field `START_SLOT_OFFSET`"] pub type START_SLOT_OFFSET_R = crate::R<u8, u8>; #[doc = "Write proxy for field `START_SLOT_OFFSET`"] pub struct START_SLOT_OFFSET_W<'a> { w: &'a mut W, } impl<'a> START_SLOT_OFFSET_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 } } impl R { #[doc = "Bits 3:7 - LLH clock configuration. The clock frequency of the clock input to this design is configured in this register. This is used to derive a 1MHz clock."] #[inline(always)] pub fn bb_clk_freq_minus_1(&self) -> BB_CLK_FREQ_MINUS_1_R { BB_CLK_FREQ_MINUS_1_R::new(((self.bits >> 3) & 0x1f) as u8) } #[doc = "Bits 8:11 - LLH clock configuration. The start of slot signal is offset by this value. If value is 0, the start of slot signal is generated at the 625us. The offset value is in terms of us."] #[inline(always)] pub fn start_slot_offset(&self) -> START_SLOT_OFFSET_R { START_SLOT_OFFSET_R::new(((self.bits >> 8) & 0x0f) as u8) } } impl W { #[doc = "Bits 3:7 - LLH clock configuration. The clock frequency of the clock input to this design is configured in this register. This is used to derive a 1MHz clock."] #[inline(always)] pub fn bb_clk_freq_minus_1(&mut self) -> BB_CLK_FREQ_MINUS_1_W { BB_CLK_FREQ_MINUS_1_W { w: self } } #[doc = "Bits 8:11 - LLH clock configuration. The start of slot signal is offset by this value. If value is 0, the start of slot signal is generated at the 625us. The offset value is in terms of us."] #[inline(always)] pub fn start_slot_offset(&mut self) -> START_SLOT_OFFSET_W { START_SLOT_OFFSET_W { w: self } } }
// 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 http://mozilla.org/MPL/2.0/. use crate::string::{CStr, NoNullStr, ByteStr}; use core::{mem}; // &[u8] -> &ByteStr // &[u8] -> Result<&NoNullStr> // &[u8] -> Result<&CStr> // &[i8] -> Result<&CStr> // &mut [u8] -> &mut ByteStr // &mut [u8] -> Result<&mut NoNullStr> // &mut [u8] -> Result<&mut CStr> // &mut [i8] -> Result<&mut CStr> // &str -> &ByteStr // &str -> Result<&NoNullStr> // &str -> Result<&CStr> // &ByteStr -> &[u8] // &ByteStr -> Result<&str> // &ByteStr -> Result<&NoNullStr> // &ByteStr -> Result<&CStr> // &mut ByteStr -> &mut [u8] // &mut ByteStr -> Result<&mut NoNullStr> // &mut ByteStr -> Result<&mut CStr> // &NoNullStr -> &[u8] // &NoNullStr -> &ByteStr // &NoNullStr -> Result<&str> // &mut NoNullStr -> &mut NoNullStr // &CStr -> &[u8] // &CStr -> &ByteStr // &CStr -> &NoNullStr // &CStr -> Result<&str> // &mut CStr -> &mut NoNullStr impl AsRef<ByteStr> for [u8] { fn as_ref(&self) -> &ByteStr { unsafe { mem::transmute(self) } } } //impl_try_as_ref!(ByteStr, [u8]); // //impl TryAsRef<NoNullStr> for [u8] { // fn try_as_ref(&self) -> Result<&NoNullStr> { // if memchr(self, 0).is_none() { // Ok(unsafe { mem::cast(self) }) // } else { // Err(error::InvalidArgument) // } // } //} // //impl TryAsRef<CStr> for [u8] { // fn try_as_ref(&self) -> Result<&CStr> { // if memchr(self, 0) == Some(self.len() - 1) { // Ok(unsafe { mem::cast(&self[..self.len()-1]) }) // } else { // Err(error::InvalidArgument) // } // } //} // //impl TryAsRef<CStr> for [i8] { // fn try_as_ref(&self) -> Result<&CStr> { // (self.as_ref():&[u8]).try_as_ref() // } //} impl AsMut<ByteStr> for [u8] { fn as_mut(&mut self) -> &mut ByteStr { unsafe { mem::transmute(self) } } } //impl_try_as_mut!(ByteStr, [u8]); // //impl TryAsMut<NoNullStr> for [u8] { // fn try_as_mut(&mut self) -> Result<&mut NoNullStr> { // if memchr(self, 0).is_none() { // Ok(unsafe { mem::cast(self) }) // } else { // Err(error::InvalidArgument) // } // } //} // //impl TryAsMut<CStr> for [i8] { // fn try_as_mut(&mut self) -> Result<&mut CStr> { // (self.as_mut():&mut [u8]).try_as_mut() // } //} // //impl TryAsMut<CStr> for [u8] { // fn try_as_mut(&mut self) -> Result<&mut CStr> { // let len = self.len(); // if memchr(self, 0) == Some(len - 1) { // Ok(unsafe { mem::cast(&mut self[..len-1]) }) // } else { // Err(error::InvalidArgument) // } // } //} impl AsRef<ByteStr> for str { fn as_ref(&self) -> &ByteStr { let b: &[u8] = self.as_ref(); b.as_ref() } } //impl_try_as_ref!(ByteStr, str); // //impl TryAsRef<NoNullStr> for str { // fn try_as_ref(&self) -> Result<&NoNullStr> { // (self.as_ref():&[u8]).try_as_ref() // } //} // //impl TryAsRef<CStr> for str { // fn try_as_ref(&self) -> Result<&CStr> { // (self.as_ref():&[u8]).try_as_ref() // } //} impl AsRef<[u8]> for ByteStr { fn as_ref(&self) -> &[u8] { unsafe { mem::transmute(self) } } } //impl_try_as_ref!([u8], ByteStr); // //impl TryAsRef<str> for ByteStr { // fn try_as_ref(&self) -> Result<&str> { // (self.as_ref():&[u8]).try_as_ref() // } //} // //impl TryAsRef<NoNullStr> for ByteStr { // fn try_as_ref(&self) -> Result<&NoNullStr> { // (self.as_ref():&[u8]).try_as_ref() // } //} // //impl TryAsRef<CStr> for ByteStr { // fn try_as_ref(&self) -> Result<&CStr> { // (self.as_ref():&[u8]).try_as_ref() // } //} impl AsMut<[u8]> for ByteStr { fn as_mut(&mut self) -> &mut [u8] { unsafe { mem::transmute(self) } } } //impl_try_as_mut!([u8], ByteStr); // //impl TryAsMut<NoNullStr> for ByteStr { // fn try_as_mut(&mut self) -> Result<&mut NoNullStr> { // (self.as_mut():&mut [u8]).try_as_mut() // } //} // //impl TryAsMut<CStr> for ByteStr { // fn try_as_mut(&mut self) -> Result<&mut CStr> { // (self.as_mut():&mut [u8]).try_as_mut() // } //} impl AsRef<[u8]> for NoNullStr { fn as_ref(&self) -> &[u8] { unsafe { mem::transmute(self) } } } //impl_try_as_ref!([u8], NoNullStr); impl AsRef<ByteStr> for NoNullStr { fn as_ref(&self) -> &ByteStr { let b: &[u8] = self.as_ref(); b.as_ref() } } //impl_try_as_ref!(ByteStr, NoNullStr); // //impl TryAsRef<str> for NoNullStr { // fn try_as_ref(&self) -> Result<&str> { // (self.as_ref():&[u8]).try_as_ref() // } //} impl AsRef<[u8]> for CStr { fn as_ref(&self) -> &[u8] { unsafe { mem::transmute(self) } } } //impl_try_as_ref!([u8], CStr); impl AsRef<ByteStr> for CStr { fn as_ref(&self) -> &ByteStr { let b: &[u8] = self.as_ref(); b.as_ref() } } //impl_try_as_ref!(ByteStr, CStr); impl AsRef<NoNullStr> for CStr { fn as_ref(&self) -> &NoNullStr { unsafe { mem::transmute(self) } } } //impl_try_as_ref!(NoNullStr, CStr); // //impl TryAsRef<str> for CStr { // fn try_as_ref(&self) -> Result<&str> { // (self.as_ref():&[u8]).try_as_ref() // } //} impl AsMut<NoNullStr> for CStr { fn as_mut(&mut self) -> &mut NoNullStr { unsafe { mem::transmute(self) } } } //impl_try_as_mut!(NoNullStr, CStr);
extern crate blorb; extern crate glulx; use std::env::args; use std::error::Error; use std::fs::File; use std::io::Read; use std::path::Path; use blorb::{ BlorbCursor, Chunk, Usage, }; mod machine; type Result<T> = std::result::Result<T, Box<Error + Send + Sync>>; fn run_blorb(exec: Chunk, blorb: BlorbCursor<File>) -> Result<i32> { use blorb::Chunk::*; match exec { Adrift{..} | AdvSys{..} | Agt{..} | Alan{..} | Exec{..} | Hugo{..} | Level9{..} | MagneticScrolls{..} | Tads2{..} | Tads3{..} | ZCode{..} => { println!("unsupported game type"); Ok(1) }, Unknown{..} => { println!("unrecognized chunk"); Ok(1) }, Glulx{code} => { machine::glulx::run_blorb(code, blorb); Ok(0) }, _ => { println!("non-executable chunk found"); Ok(1) } } } fn run(file: String) -> Result<i32> { let file = Path::new(&file); if let Some("ulx") = file.extension().and_then(|x|x.to_str()) { File::open(file) .map_err(|err| err.into()) .and_then(|mut rom| { let mut code = Vec::new(); rom.read_to_end(&mut code)?; machine::glulx::run(code); Ok(0) }) } else { File::open(file) .and_then(|rom| BlorbCursor::from_file(rom)) .and_then(|mut blorb| blorb.load_resource(Usage::Exec, 0) .map(|chunk| (chunk, blorb))) .map_err(|err| err.into()) .and_then(|(chunk, blorb)| run_blorb(chunk, blorb)) } } fn main() { match args().nth(1) .ok_or_else(||"no file provided".into()) .and_then(run) { Ok(ret) => { println!("finished running"); std::process::exit(ret) }, Err(ref err) => { println!("error occured: {}", err); std::process::exit(1) }, } }
/// An enum to represent all characters in the HangulJamoExtendedA block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum HangulJamoExtendedA { /// \u{a960}: 'ꥠ' HangulChoseongTikeutDashMieum, /// \u{a961}: 'ꥡ' HangulChoseongTikeutDashPieup, /// \u{a962}: 'ꥢ' HangulChoseongTikeutDashSios, /// \u{a963}: 'ꥣ' HangulChoseongTikeutDashCieuc, /// \u{a964}: 'ꥤ' HangulChoseongRieulDashKiyeok, /// \u{a965}: 'ꥥ' HangulChoseongRieulDashSsangkiyeok, /// \u{a966}: 'ꥦ' HangulChoseongRieulDashTikeut, /// \u{a967}: 'ꥧ' HangulChoseongRieulDashSsangtikeut, /// \u{a968}: 'ꥨ' HangulChoseongRieulDashMieum, /// \u{a969}: 'ꥩ' HangulChoseongRieulDashPieup, /// \u{a96a}: 'ꥪ' HangulChoseongRieulDashSsangpieup, /// \u{a96b}: 'ꥫ' HangulChoseongRieulDashKapyeounpieup, /// \u{a96c}: 'ꥬ' HangulChoseongRieulDashSios, /// \u{a96d}: 'ꥭ' HangulChoseongRieulDashCieuc, /// \u{a96e}: 'ꥮ' HangulChoseongRieulDashKhieukh, /// \u{a96f}: 'ꥯ' HangulChoseongMieumDashKiyeok, /// \u{a970}: 'ꥰ' HangulChoseongMieumDashTikeut, /// \u{a971}: 'ꥱ' HangulChoseongMieumDashSios, /// \u{a972}: 'ꥲ' HangulChoseongPieupDashSiosDashThieuth, /// \u{a973}: 'ꥳ' HangulChoseongPieupDashKhieukh, /// \u{a974}: 'ꥴ' HangulChoseongPieupDashHieuh, /// \u{a975}: 'ꥵ' HangulChoseongSsangsiosDashPieup, /// \u{a976}: 'ꥶ' HangulChoseongIeungDashRieul, /// \u{a977}: 'ꥷ' HangulChoseongIeungDashHieuh, /// \u{a978}: 'ꥸ' HangulChoseongSsangcieucDashHieuh, /// \u{a979}: 'ꥹ' HangulChoseongSsangthieuth, /// \u{a97a}: 'ꥺ' HangulChoseongPhieuphDashHieuh, /// \u{a97b}: 'ꥻ' HangulChoseongHieuhDashSios, /// \u{a97c}: 'ꥼ' HangulChoseongSsangyeorinhieuh, } impl Into<char> for HangulJamoExtendedA { fn into(self) -> char { match self { HangulJamoExtendedA::HangulChoseongTikeutDashMieum => 'ꥠ', HangulJamoExtendedA::HangulChoseongTikeutDashPieup => 'ꥡ', HangulJamoExtendedA::HangulChoseongTikeutDashSios => 'ꥢ', HangulJamoExtendedA::HangulChoseongTikeutDashCieuc => 'ꥣ', HangulJamoExtendedA::HangulChoseongRieulDashKiyeok => 'ꥤ', HangulJamoExtendedA::HangulChoseongRieulDashSsangkiyeok => 'ꥥ', HangulJamoExtendedA::HangulChoseongRieulDashTikeut => 'ꥦ', HangulJamoExtendedA::HangulChoseongRieulDashSsangtikeut => 'ꥧ', HangulJamoExtendedA::HangulChoseongRieulDashMieum => 'ꥨ', HangulJamoExtendedA::HangulChoseongRieulDashPieup => 'ꥩ', HangulJamoExtendedA::HangulChoseongRieulDashSsangpieup => 'ꥪ', HangulJamoExtendedA::HangulChoseongRieulDashKapyeounpieup => 'ꥫ', HangulJamoExtendedA::HangulChoseongRieulDashSios => 'ꥬ', HangulJamoExtendedA::HangulChoseongRieulDashCieuc => 'ꥭ', HangulJamoExtendedA::HangulChoseongRieulDashKhieukh => 'ꥮ', HangulJamoExtendedA::HangulChoseongMieumDashKiyeok => 'ꥯ', HangulJamoExtendedA::HangulChoseongMieumDashTikeut => 'ꥰ', HangulJamoExtendedA::HangulChoseongMieumDashSios => 'ꥱ', HangulJamoExtendedA::HangulChoseongPieupDashSiosDashThieuth => 'ꥲ', HangulJamoExtendedA::HangulChoseongPieupDashKhieukh => 'ꥳ', HangulJamoExtendedA::HangulChoseongPieupDashHieuh => 'ꥴ', HangulJamoExtendedA::HangulChoseongSsangsiosDashPieup => 'ꥵ', HangulJamoExtendedA::HangulChoseongIeungDashRieul => 'ꥶ', HangulJamoExtendedA::HangulChoseongIeungDashHieuh => 'ꥷ', HangulJamoExtendedA::HangulChoseongSsangcieucDashHieuh => 'ꥸ', HangulJamoExtendedA::HangulChoseongSsangthieuth => 'ꥹ', HangulJamoExtendedA::HangulChoseongPhieuphDashHieuh => 'ꥺ', HangulJamoExtendedA::HangulChoseongHieuhDashSios => 'ꥻ', HangulJamoExtendedA::HangulChoseongSsangyeorinhieuh => 'ꥼ', } } } impl std::convert::TryFrom<char> for HangulJamoExtendedA { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { 'ꥠ' => Ok(HangulJamoExtendedA::HangulChoseongTikeutDashMieum), 'ꥡ' => Ok(HangulJamoExtendedA::HangulChoseongTikeutDashPieup), 'ꥢ' => Ok(HangulJamoExtendedA::HangulChoseongTikeutDashSios), 'ꥣ' => Ok(HangulJamoExtendedA::HangulChoseongTikeutDashCieuc), 'ꥤ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashKiyeok), 'ꥥ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashSsangkiyeok), 'ꥦ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashTikeut), 'ꥧ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashSsangtikeut), 'ꥨ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashMieum), 'ꥩ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashPieup), 'ꥪ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashSsangpieup), 'ꥫ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashKapyeounpieup), 'ꥬ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashSios), 'ꥭ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashCieuc), 'ꥮ' => Ok(HangulJamoExtendedA::HangulChoseongRieulDashKhieukh), 'ꥯ' => Ok(HangulJamoExtendedA::HangulChoseongMieumDashKiyeok), 'ꥰ' => Ok(HangulJamoExtendedA::HangulChoseongMieumDashTikeut), 'ꥱ' => Ok(HangulJamoExtendedA::HangulChoseongMieumDashSios), 'ꥲ' => Ok(HangulJamoExtendedA::HangulChoseongPieupDashSiosDashThieuth), 'ꥳ' => Ok(HangulJamoExtendedA::HangulChoseongPieupDashKhieukh), 'ꥴ' => Ok(HangulJamoExtendedA::HangulChoseongPieupDashHieuh), 'ꥵ' => Ok(HangulJamoExtendedA::HangulChoseongSsangsiosDashPieup), 'ꥶ' => Ok(HangulJamoExtendedA::HangulChoseongIeungDashRieul), 'ꥷ' => Ok(HangulJamoExtendedA::HangulChoseongIeungDashHieuh), 'ꥸ' => Ok(HangulJamoExtendedA::HangulChoseongSsangcieucDashHieuh), 'ꥹ' => Ok(HangulJamoExtendedA::HangulChoseongSsangthieuth), 'ꥺ' => Ok(HangulJamoExtendedA::HangulChoseongPhieuphDashHieuh), 'ꥻ' => Ok(HangulJamoExtendedA::HangulChoseongHieuhDashSios), 'ꥼ' => Ok(HangulJamoExtendedA::HangulChoseongSsangyeorinhieuh), _ => Err(()), } } } impl Into<u32> for HangulJamoExtendedA { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for HangulJamoExtendedA { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for HangulJamoExtendedA { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl HangulJamoExtendedA { /// The character with the lowest index in this unicode block pub fn new() -> Self { HangulJamoExtendedA::HangulChoseongTikeutDashMieum } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("HangulJamoExtendedA{:#?}", self); string_morph::to_sentence_case(&s) } }
use std::collections::{HashMap,HashSet}; #[derive(PartialEq,Eq,Clone,Hash,Debug)] pub enum VarType { Unknown, Float, Int, Number, String, Bool, Unify(Vec<String>) } pub type TypeMap = HashMap<String,VarType>; #[derive(Debug,PartialEq,Eq)] pub enum TypeOrd{ Sub,Super,Same,Unrelated,Cross} impl VarType { pub fn type_cmp(&self,other:&Self) -> TypeOrd { use self::VarType::*; use self::TypeOrd::*; match (self,other) { (&Unknown,_) => Super, (_,&Unknown) => Sub, (&Float,&Number) | (&Int,&Number) | (&Float,&Int) => Sub, (&Number,&Float) | (&Number,&Int) | (&Int,&Float) => Super, (&Float,&Float) | (&Int,&Int) | (&Bool,&Bool) | (&String,&String) | (&Number,&Number) => Same, (&ref x,&ref y) if x==y => Same, (&Unify(_),&Unify(_)) => Cross, (_,&Unify(_)) => Sub, (&Unify(_),_) => Super, (&String,& Float) | (&Bool,& Float) | (&Int,& Bool) | (&Float,&String) | (&Float,&Bool) | (&Int,&String) | (&Number,&String) | (&Number,&Bool) | (&String,&Int) | (&String,&Number) | (&String,&Bool) | (&Bool,&Int) | (&Bool,&Number) | (&Bool,&String) => Unrelated } } pub fn precise_type(&self, other:&Self) -> Result<Self,TIError> { match self.type_cmp(other) { TypeOrd::Sub => Ok(self.clone()), TypeOrd::Super => Ok(other.clone()), TypeOrd::Same => Ok(self.clone()), TypeOrd::Unrelated => Err(TIError::Contradiction), TypeOrd::Cross => match (self,other) {(&VarType::Unify(ref x),&VarType::Unify(ref y)) => {let mut nv = x.clone();nv.extend(y.clone()); Ok(VarType::Unify(nv))}, _=> panic!("Impossible Type Comparison")} } } pub fn unify_var(&mut self, other:String) { if let &mut VarType::Unify(ref mut v) = self { v.push(other); } } } // Error types for Type Inference #[derive(Debug,PartialEq,Eq)] pub enum TIError { Contradiction } impl TIError { pub fn contra<T>() -> Result<T,TIError> {Err(TIError::Contradiction)} } pub mod implication { use super::*; use ::parser::{UnaryOperator,BinaryOperator,Variable,Expr,Literal,Term}; use ::parser::BinaryOperator::*; pub trait ImpliesType { fn implies(&self) -> VarType { VarType::Unknown } } impl ImpliesType for Literal { fn implies(&self) -> VarType { match *self { Literal::Int(_) => VarType::Int, Literal::Float(_) => VarType::Float, Literal::Bool(_) => VarType::Bool, Literal::String(_) => VarType::String, } } } impl ImpliesType for Variable { fn implies(&self) -> VarType { match *self { Variable::Hole => {VarType::Unknown}, Variable::Name(ref n) => {VarType::Unify(vec![n.0.clone()])} } } } impl ImpliesType for Term { fn implies(&self) -> VarType { match *self { Term::Literal(ref l) => {l.implies()}, Term::Variable(ref v) => {v.implies()} } } } impl ImpliesType for BinaryOperator { fn implies(&self) -> VarType { match *self { Add | Subtract | Multiply | Divide => VarType::Number, Modulus => VarType::Int, And | Or | Xor => VarType::Int, LessThan | LessThanEq | Eq | NotEq | GreaterThanEq | GreaterThan => VarType::Number } } } impl ImpliesType for UnaryOperator { fn implies(&self) -> VarType { match *self { UnaryOperator::BoolNegate => VarType::Bool, UnaryOperator::ArithNegate => VarType::Number, } } } impl ImpliesType for Expr { fn implies(&self) -> VarType { use ::parser::Expr::*; match self { &Value(ref x) => {x.implies()}, &Variable(ref v) => {v.implies()}, &Paren(ref e) => {e.implies()}, &BinaryResult((_,ref o, _)) => {o.implies()}, &UnaryResult((ref o,_)) => {o.implies()} } } } } pub trait TypeInferable { fn get_vars(&self,VarType) -> Result<TypeMap,TIError> { Ok(HashMap::new())} fn empty_type_map() -> Result<TypeMap,TIError> { Ok(HashMap::new())} } mod type_inference { use super::*; use ::parser::*; use compiler::implication::*; pub fn merge_maps(a:Result<TypeMap,TIError>,b:Result<TypeMap,TIError>) -> Result<TypeMap,TIError> { match (a,b) { (Err(e),_) => Err(e), (_,Err(e)) => Err(e), (Ok(x),Ok(y)) => { let (smaller,mut larger) = if x.len() < y.len() {(x,y)} else {(y,x)}; for (sv,st) in smaller.into_iter() { match larger.get(&sv).and_then(|t| Some(t.type_cmp(&st))) { None => {larger.insert(sv,st);}, Some(TypeOrd::Sub) => {}, _ => {} } } Ok(larger) } } } use std::collections::HashSet; fn unify_map(a:HashMap<String,VarType>) -> HashMap<String,VarType> { let mut need = HashMap::new(); let mut have :HashMap<String,VarType> = HashMap::new(); for (v,t) in a.into_iter() { match t { VarType::Unify(rvs) => {for rv in rvs{need.entry(rv).or_insert(vec![]).push(v.clone())}}, nt => {have.insert(v,nt);} } } let mut inferable : Vec<String> = have.keys().filter(|k| have.get(*k) != Some(&VarType::Unknown)).collect::<HashSet<&String>>() .intersection(&need.keys().collect::<HashSet<&String>>()) .map(|x| ((*x).clone())).collect(); while let Some(curr_var) = inferable.pop() { let curr_type = if let Some(t_type) = have.get(&curr_var) { t_type.clone() } else {panic!("Take that Borrow Checker!")}; for resolvable_var in need.remove(&curr_var).into_iter().flat_map(|x| x.into_iter()) { // The following line will need to change to check for Type Conflicts use std::collections::hash_map::Entry; match have.entry(resolvable_var.clone()) { Entry::Vacant(x) => {x.insert(curr_type.clone());}, Entry::Occupied(x) => { let has_type : &VarType = x.get(); let union_type = has_type.precise_type(&curr_type); } } have.insert(resolvable_var.clone(),curr_type.clone()); inferable.push(resolvable_var); } } for (rv,mut vs) in need.drain() { for v in vs.drain(..) { have.entry(v).or_insert(VarType::Unify(vec![])).unify_var(rv.clone()); } } have } impl TypeInferable for Identifier {} impl TypeInferable for Variable { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { match self { &Variable::Hole => {Ok(HashMap::new())}, &Variable::Name(Identifier(ref name)) => { let mut ret = HashMap::new(); ret.insert(name.clone(),t); Ok(ret) } } } } impl TypeInferable for Number { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { use ::compiler::TypeOrd::*; match t.type_cmp(&VarType::Number) { Sub | Super | Same => Self::empty_type_map(), _ => TIError::contra() } } } impl TypeInferable for BinaryOperator {} impl TypeInferable for UnaryOperator {} impl TypeInferable for Expr { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { match self { &Expr::Value(_) => {Ok(HashMap::new())}, &Expr::Variable(ref x) => {x.get_vars(t)}, &Expr::Paren(ref x) => {x.get_vars(t)}, &Expr::BinaryResult((ref l,ref o,ref r)) => { let nt = o.implies(); if nt != t && t != VarType::Unknown { return Err(TIError::Contradiction) } merge_maps(l.get_vars(nt.clone()),r.get_vars(nt)) } &Expr::UnaryResult((ref o,ref r)) => { let nt = o.implies(); if nt != t && t != VarType::Unknown {return Err(TIError::Contradiction)} r.get_vars(nt) } } } } impl TypeInferable for Equation { fn get_vars(&self,_:VarType) -> Result<TypeMap,TIError> { let right_map = self.expr.get_vars(VarType::Unknown); let right_type = self.expr.implies(); if let Variable::Name(ref v) = self.value { let mut left_map = HashMap::new(); left_map.insert(v.0.clone(),right_type); merge_maps(Ok(left_map),right_map) } else { right_map } } } impl TypeInferable for SemiRange { fn get_vars(&self,_:VarType) -> Result<TypeMap,TIError> { use std::collections::Bound::*; let lower_type = match self.lower { Included(ref l) => l.implies(), Excluded(ref l) => l.implies(), Unbounded => VarType::Unknown }; let upper_type = match self.upper { Included(ref u) => u.implies(), Excluded(ref u) => u.implies(), Unbounded => VarType::Unknown }; if let Ok(union_type) = lower_type.precise_type(&upper_type) { let lower_map = match &self.lower { &Included(ref l) => l.get_vars(union_type.clone()), &Excluded(ref l) => l.get_vars(union_type.clone()), &Unbounded => Ok(HashMap::new()) }; let upper_map = match &self.upper { &Included(ref u) => u.get_vars(union_type.clone()), &Excluded(ref u) => u.get_vars(union_type.clone()), &Unbounded => Ok(HashMap::new()) }; let val_map = if let Variable::Name(ref id) = self.val { let mut vmap = HashMap::new(); vmap.insert(id.0.clone(),union_type.clone()); vmap } else {HashMap::new()}; merge_maps(Ok(val_map),merge_maps(lower_map,upper_map)) } else { TIError::contra() } } } impl TypeInferable for Literal {} impl TypeInferable for Term { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { match self { &Term::Literal(ref l) => l.get_vars(t), &Term::Variable(ref v) => v.get_vars(t) } } } impl TypeInferable for RowFact { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { self.terms.iter().map(|x| x.get_vars(t.clone())).fold(Ok(HashMap::new()),merge_maps) } } impl TypeInferable for TreeTerm { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { match self { &TreeTerm::Term(ref term) => term.get_vars(t), &TreeTerm::Tree(ref tree) => tree.get_vars(t) } } } impl TypeInferable for TreeFact { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { merge_maps( self.avs.iter().map(|&(ref r,ref rr)| merge_maps(r.get_vars(t.clone()),rr.get_vars(t.clone()))).fold(self.entity.get_vars(t.clone()),merge_maps), self.t.get_vars(t)) } } impl TypeInferable for Fact { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { self.0.get_vars(t) } } impl TypeInferable for Pred { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { match self { &Pred::RowFact(ref x) => x.get_vars(t), &Pred::TreeFact(ref x) => x.get_vars(t), &Pred::Equation(ref x) => x.get_vars(t), &Pred::SemiRange(ref x) => x.get_vars(t) } } } impl TypeInferable for Relation { fn get_vars(&self,t:VarType) -> Result<TypeMap,TIError> { merge_maps( self.vars.iter().map(|x| x.get_vars(t.clone())).fold(Ok(HashMap::new()), merge_maps), self.preps.iter().map(|x| x.get_vars(t.clone())).fold(Ok(HashMap::new()), merge_maps), ) } } } #[cfg(test)] mod tests { use ::parser::*; use ::parser::parse_fns::*; use nom::*; use super::*; use quickcheck::*; use ::compiler::type_inference::*; use rand::thread_rng; #[test] fn sample_equations() { let testo = ["a = 1+2","b=1+false","a = b > (c | d)"]; for t in testo.iter() { let res = equation(&t.as_bytes()); println!("{:?}",res); if let IResult::Done(_,t) = res { println!("{:?}",t.get_vars(VarType::Unknown)); } else { assert!(false) } } } #[test] fn commutative_merge() { fn prop(r:Relation,s:Relation) -> bool { println!("Attempting to gather Vars"); let lr = merge_maps(r.get_vars(VarType::Unknown),s.get_vars(VarType::Unknown)); let rl = merge_maps(s.get_vars(VarType::Unknown),r.get_vars(VarType::Unknown)); println!("Gathered Vars"); lr == rl } println!("------Starting commutativity check------"); QuickCheck::new() .gen(StdGen::new(thread_rng(),10)) .tests(1000) .max_tests(5000) .quickcheck(prop as fn(Relation,Relation)-> bool); } #[test] fn print_sample_type_maps() { let mut g = StdGen::new(thread_rng(),10); println!("\n-----------------------------------"); for _ in 0..5 { let r :Relation = Arbitrary::arbitrary(&mut g); println!("String: {}",r); println!("{:?}",r.get_vars(VarType::Unknown)); println!("---"); } } }
use super::fraction_normal::Fraction; #[derive(Clone)] pub struct ContinuedFraction { root: u128, list: Vec<u128>, } impl ContinuedFraction { pub fn from_square_root(n: u128) -> Self { let root = (n as f64).sqrt().floor() as u128; if n == root * root { return Self { root, list: vec![], }; } let mut a = root; let mut b = 1; let mut k = n - a * a; let mut list = vec![]; loop { let a1 = (root + a) / k; list.push(a1); if k == 1 { break; } b = k; a = a1 * k - a; k = (n - a * a) / b; } Self { root, list, } } pub fn get_convergent_fraction(&self, idx: usize) -> Fraction { if idx == 0 || self.list.len() == 0 { Fraction::new(self.root, 1) } else { let idx = idx - 1; let list_len = self.list.len(); let pos = idx % list_len; let mut res = Fraction::new(self.list[pos], 1); for i in 1..=idx { let pos = (idx - i) % list_len; res = self.list[pos] + 1 / res; } self.root + 1 / res } } } use std::fmt; impl fmt::Debug for ContinuedFraction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[{}, {:?}]", self.root, self.list) } }
use super::schema::*; use diesel::*; use diesel::pg::Pg; use diesel::deserialize::{self, FromSql}; use diesel::serialize::{self, IsNull, Output, ToSql}; use std::io::Write; use juniper::FieldResult; #[derive(SqlType)] #[postgres(type_name = "episode")] pub struct EpisodeSqlType; #[derive(GraphQLEnum, Debug, PartialEq, FromSqlRow, AsExpression)] #[sql_type = "EpisodeSqlType"] enum Episode { NewHope, Empire, Jedi, } impl ToSql<EpisodeSqlType, Pg> for Episode { fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result { match *self { Episode::NewHope => out.write_all(b"a_new_hope")?, Episode::Empire => out.write_all(b"empire_strikes_back")?, Episode::Jedi => out.write_all(b"return_of_the_jedi")?, }; Ok(IsNull::No) } } impl FromSql<EpisodeSqlType, Pg> for Episode { fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> { match not_none!(bytes) { b"a_new_hope" => Ok(Episode::NewHope), b"empire_strikes_back" => Ok(Episode::Empire), b"return_of_the_jedi" => Ok(Episode::Jedi), _ => Err("Unrecognized enum variant".into()), } } } #[derive(GraphQLObject, Queryable)] struct Human { id: String, name: String, appears_in: Vec<Episode>, home_planet: String, } #[derive(GraphQLInputObject, Insertable)] #[table_name = "humans"] struct NewHuman { name: String, appears_in: Vec<Episode>, home_planet: String, }
use crate::completions::{Completer, CompletionOptions, MatchAlgorithm, SortBy}; use nu_parser::FlatShape; use nu_protocol::{ engine::{EngineState, StateWorkingSet}, Span, }; use reedline::Suggestion; use std::sync::Arc; pub struct CommandCompletion { engine_state: Arc<EngineState>, flattened: Vec<(Span, FlatShape)>, flat_shape: FlatShape, force_completion_after_space: bool, } impl CommandCompletion { pub fn new( engine_state: Arc<EngineState>, _: &StateWorkingSet, flattened: Vec<(Span, FlatShape)>, flat_shape: FlatShape, force_completion_after_space: bool, ) -> Self { Self { engine_state, flattened, flat_shape, force_completion_after_space, } } fn external_command_completion( &self, prefix: &str, match_algorithm: MatchAlgorithm, ) -> Vec<String> { let mut executables = vec![]; let paths = self.engine_state.get_env_var("PATH"); if let Some(paths) = paths { if let Ok(paths) = paths.as_list() { for path in paths { let path = path.as_string().unwrap_or_default(); if let Ok(mut contents) = std::fs::read_dir(path) { while let Some(Ok(item)) = contents.next() { if self.engine_state.config.max_external_completion_results > executables.len() as i64 && !executables.contains( &item .path() .file_name() .map(|x| x.to_string_lossy().to_string()) .unwrap_or_default(), ) && matches!( item.path().file_name().map(|x| match_algorithm .matches_str(&x.to_string_lossy(), prefix)), Some(true) ) && is_executable::is_executable(&item.path()) { if let Ok(name) = item.file_name().into_string() { executables.push(name); } } } } } } } executables } fn complete_commands( &self, working_set: &StateWorkingSet, span: Span, offset: usize, find_externals: bool, match_algorithm: MatchAlgorithm, ) -> Vec<Suggestion> { let partial = working_set.get_span_contents(span); let filter_predicate = |command: &[u8]| match_algorithm.matches_u8(command, partial); let results = working_set .find_commands_by_predicate(filter_predicate) .into_iter() .map(move |x| Suggestion { value: String::from_utf8_lossy(&x.0).to_string(), description: x.1, extra: None, span: reedline::Span { start: span.start - offset, end: span.end - offset, }, append_whitespace: true, }); let results_aliases = working_set .find_aliases_by_predicate(filter_predicate) .into_iter() .map(move |x| Suggestion { value: String::from_utf8_lossy(&x).to_string(), description: None, extra: None, span: reedline::Span { start: span.start - offset, end: span.end - offset, }, append_whitespace: true, }); let mut results = results.chain(results_aliases).collect::<Vec<_>>(); let partial = working_set.get_span_contents(span); let partial = String::from_utf8_lossy(partial).to_string(); if find_externals { let results_external = self .external_command_completion(&partial, match_algorithm) .into_iter() .map(move |x| Suggestion { value: x, description: None, extra: None, span: reedline::Span { start: span.start - offset, end: span.end - offset, }, append_whitespace: true, }); for external in results_external { if results.contains(&external) { results.push(Suggestion { value: format!("^{}", external.value), description: None, extra: None, span: external.span, append_whitespace: true, }) } else { results.push(external) } } results } else { results } } } impl Completer for CommandCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, _prefix: Vec<u8>, span: Span, offset: usize, pos: usize, options: &CompletionOptions, ) -> Vec<Suggestion> { let last = self .flattened .iter() .rev() .skip_while(|x| x.0.end > pos) .take_while(|x| { matches!( x.1, FlatShape::InternalCall | FlatShape::External | FlatShape::ExternalArg | FlatShape::Literal | FlatShape::String ) }) .last(); // The last item here would be the earliest shape that could possible by part of this subcommand let subcommands = if let Some(last) = last { self.complete_commands( working_set, Span { start: last.0.start, end: pos, }, offset, false, options.match_algorithm, ) } else { vec![] }; if !subcommands.is_empty() { return subcommands; } let config = working_set.get_config(); let commands = if matches!(self.flat_shape, nu_parser::FlatShape::External) || matches!(self.flat_shape, nu_parser::FlatShape::InternalCall) || ((span.end - span.start) == 0) { // we're in a gap or at a command if working_set.get_span_contents(span).is_empty() && !self.force_completion_after_space { return vec![]; } self.complete_commands( working_set, span, offset, config.enable_external_completion, options.match_algorithm, ) } else { vec![] }; subcommands .into_iter() .chain(commands.into_iter()) .collect::<Vec<_>>() } fn get_sort_by(&self) -> SortBy { SortBy::LevenshteinDistance } }
use anyhow::bail; use std::process::Command; pub fn execute_gnuplot(script_path: impl AsRef<std::path::Path>) -> anyhow::Result<()> { let output = Command::new("gnuplot") .args(&[script_path.as_ref()]) .output()?; if !output.status.success() { if let Ok(err) = String::from_utf8(output.stderr) { bail!("Gnuplot error: {}", err); } } Ok(()) } pub fn normalize_filename(s: &str) -> String { let mut t = String::new(); let mut replaced = false; for c in s.to_ascii_lowercase().chars() { if c.is_ascii_alphanumeric() { replaced = false; t.push(c); } else if !replaced { replaced = true; t.push('-'); } } t.trim_matches('-').to_owned() }
#[test] fn ui() { if option_env!("CARGO") .unwrap_or("cargo") .ends_with("cargo-tarpaulin") { eprintln!( "Skipping ui tests to avoid incompatibility between cargo-tarpaulin and trybuild" ); return; } let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); }
use crate::common::head_list_node; use crate::common::ListNode; struct Solution; impl Solution { // 参考别人的 pub fn swap_pairs(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut dummy = ListNode::new(0); let mut tail = &mut dummy; while let Some(mut n1) = head { head = n1.next.take(); // 取下 n1 if let Some(mut n2) = head { head = n2.next.take(); // 取下 n2 n2.next.replace(n1); // n2.next -> n1 tail.next.replace(n2); // tail.next -> n2 tail = tail.next.as_mut().unwrap().next.as_mut().unwrap(); // tail = tail.next.next } else { // 只有一个节点了,挂到 tail 后面。 tail.next.replace(n1); } } dummy.next } pub fn swap_pairs1(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut dummy = Some(Box::new(ListNode::new(0))); let mut ptr = &mut dummy; loop { let (first, remain) = head_list_node(head); let (second, remain) = head_list_node(remain); let should_break = second.is_none(); if second.is_some() { if let Some(p) = ptr { p.next = second; ptr = &mut p.next; } } if first.is_some() { if let Some(p) = ptr { p.next = first; ptr = &mut p.next; } } head = remain; if should_break { break; } } dummy.unwrap().next } } #[cfg(test)] mod tests { use super::*; #[test] fn test_swap_pairs() { let head = ListNode::new_from_arr(&vec![1, 2, 3, 4]); let want = ListNode::new_from_arr(&vec![2, 1, 4, 3]); let ans = Solution::swap_pairs(head); assert_eq!(ans, want); } }
use wasm_bindgen::prelude::*; use mycrate_core; #[wasm_bindgen] pub fn add(a: i32, b: i32) -> i32 { mycrate_core::add(a, b) }
extern crate num_bigint; use num_bigint::BigUint; use std::collections::HashMap; pub fn hash_map_to_string<T, R>(num: &HashMap<T, R>) -> String where T: std::cmp::Ord + std::hash::Hash + std::fmt::Display, R: std::fmt::Display { let mut num_list = vec![]; for k in num.keys() { num_list.push(k); } num_list.sort(); let mut s = String::new(); for k in num_list { s = format!("{}:{}_{}", s, k, num.get(&k).unwrap()) } s } pub fn select<T>(list: &Vec<T>, n: usize) -> Vec<Vec<T>> where T: Clone { if n == 1 { let mut res = vec![]; for v in list { res.push(vec![v.clone()]) } return res; } if n >= list.len() { return vec![list.to_vec()]; } let mut res = vec![]; for i in 0..=list.len() - n { let v = &list[i]; let sub_list_list = select(&list[i + 1..].to_vec(), n - 1); for mut sub_list in sub_list_list { sub_list.push(v.clone()); res.push(sub_list); } } res } pub fn get_all_order<T>(list: &Vec<T>) -> Vec<Vec<T>> where T: Clone { let mut res = vec![]; if list.len() <= 1 { res.push(list.to_vec()); } else { let mut list = list.to_vec(); for i in 0..list.len() { if i > 0 { let tmp = list[i].clone(); list[i] = list[0].clone(); list[0] = tmp; } let v = list[0].clone(); let sub_list_list = get_all_order(&list[1..].to_vec()); for mut sub_list in sub_list_list { sub_list.push(v.clone()); res.push(sub_list); } if i > 0 { let tmp = list[i].clone(); list[i] = list[0].clone(); list[0] = tmp; } } } res } pub fn a2i(num_str: String) -> i32 { let mut res = 0; let zero = '0' as u8; for i in num_str.as_bytes() { res = res * 10; res = res + (*i - zero) as i32; } res } pub fn i2a(n: i32) -> String { if n == 0 { return "0".to_string(); } let mut res = vec![]; let mut num = n; let zero = '0' as u8; while num > 0 { res.push((num % 10) as u8 + zero); num = num / 10; } res.reverse(); String::from_utf8(res).unwrap() } pub fn l2i(num_list: Vec<i32>) -> u64 { let mut res = 0; for i in num_list { res = res * 10; res = res + i as u64; } res } pub fn i2l(n: u128) -> Vec<i32> { if n == 0 { return vec![0]; } let mut res = vec![]; let mut num = n; while num > 0 { res.push((num % 10) as i32); num = num / 10; } res.reverse(); res } pub fn bi2l(num: &BigUint) -> Vec<i32> { let mut s = vec![]; for ch in num.to_str_radix(10).as_bytes() { s.push(*ch as i32 - '0' as i32); } s } pub fn factorial(n: u64) -> u64 { if n == 0 { 1 } else { n * factorial(n - 1) } } pub fn read_file() -> String { use std::fs; const FILE_NAME: &str = "/Users/qiweiyu/Documents/work/rust/learn/project_euler/data.txt"; fs::read_to_string(FILE_NAME).unwrap() } pub fn change_to_base2(n: i32) -> String { let mut list = vec![]; let mut num = n; let zero = '0' as u8; while num > 0 { list.push((num & 1) as u8 + zero); num = num / 2; } list.reverse(); String::from_utf8(list).unwrap() } pub fn i_sqrt(n: u64) -> Option<u64> { let root = (n as f64).sqrt().floor() as u64; if n == root * root { Some(root) } else { None } } pub fn check_permutation(a: u128, b: u128) -> bool { fn n2l(mut n: u128) -> Vec<u8> { let mut res = vec![0; 10]; while n > 0 { let rem = (n % 10) as usize; res[rem] = res[rem] + 1; n = n / 10; } res } if a % 9 != b % 9 { false } else { n2l(a) == n2l(b) } }
/* https://projecteuler.net The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. NOTES: */ fn mypow(n : u64) -> u64 { let mut rv = n; for _ in 1..n { if rv == 0 { // exit early if we get to 0 value break; } rv *= n; rv %= 10_000_000_000; } rv } fn solve() -> u64 { let mut rv = 0; for i in 1..=1000 { rv += mypow(i); rv %= 10_000_000_000; } rv } fn main() { let start_time = std::time::Instant::now(); let sol = solve(); let elapsed = start_time.elapsed().as_micros(); println!("\nSolution: {}", sol); let mut remain = elapsed; let mut s = String::new(); if remain == 0 { s.insert(0,'0'); } while remain > 0 { let temp = remain%1000; remain /= 1000; if remain > 0 { s = format!(",{:03}",temp) + &s; } else { s = format!("{}",temp) + &s; } } println!("Elasped time: {} us", s); }
fn main() { 'outer: loop { println!("Entered the outer dungeon - "); 'inner: loop { println!("Entered the inner dungeon - "); break 'outer; } println!("This treasure can sadly never be reached - "); } println!("Exited the outer dungeon!"); }
pub mod sha3_512; pub struct Hash { pub mac: [u8; 32], pub encrypt: [u8; 32], } pub trait Hasher { fn make(key: &str) -> Hash; }
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::Path; use std::sync::{Arc, Mutex}; use ignore::Walk as WalkDir; use json5; use regex::Regex; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; #[derive(Debug)] pub struct Database { pub basic_data: BasicData, pub api_docs: HashMap<String, ApiDoc>, // {fileanme:api_doc} pub api_data: HashMap<String, Vec<Arc<Mutex<ApiData>>>>, // {url:[a_api_doc1, a_api_data2]} pub fileindex_data: HashMap<String, HashSet<String>>, // ref和相关文件的索引,当文件更新后,要找到所有ref他的地方,然后进行更新 pub websocket_api: Arc<Mutex<ApiData>>, pub auth_doc: Option<AuthDoc>, pub settings: Option<Value>, pub menus: HashMap<String, Menu>, } #[derive(Debug)] pub struct BasicData { pub read_me: String, pub project_name: String, pub project_desc: String, pub global_value: Value, } #[derive(Debug, Clone)] pub struct ApiDoc { // 接口文档的数据 pub name: String, pub desc: String, pub order: i64, pub filename: String, pub apis: Vec<Arc<Mutex<ApiData>>>, } #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct Menu { pub name: String, pub desc: String, pub filetype: String, pub order: i32, pub filename: String, pub children: HashMap<String, Menu>, } #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct ApiData { // 单个接口的数据 pub name: String, pub desc: String, pub url: String, pub url_param: Value, pub method: Vec<String>, pub auth: bool, pub body_mode: String, pub body: Value, pub query: Value, pub request_headers: Value, pub response_headers: Value, pub response: Value, pub test_data: Value, } #[derive(Debug, Clone, Serialize, Deserialize, Default)] /// auth认证中心文档 pub struct AuthDoc { pub name: String, // auth 文档名称 pub desc: String, // auth 相关说明 pub auth_type: String, // auth 类型 pub auth_place: String, // auth 放在什么地方:headers 或者是 url上 pub filename: String, // 文件名称 pub groups: Vec<AuthData>, pub no_perm_response: Value, } #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct AuthData { pub name: String, pub desc: String, pub users: HashMap<String, Value>, pub has_perms: HashMap<String, HashSet<String>>, pub no_perms: HashMap<String, HashSet<String>>, pub no_perm_response: Value, } fn fix_json(org_string: String) -> String { let re = Regex::new(r#":\s*["']{1}(?P<s>[\s\S]*?\n*[\s\S]*?)["']{1}"#).unwrap(); // 把多换行变为一行 let re2 = Regex::new(r"(\\?(?P<n>[ \t ]*)(?P<h>[\r\n]+))").unwrap(); let mut new_string = org_string.clone(); for cap in re.captures_iter(&org_string) { if let Some(x) = cap.name("s") { let x0 = x.as_str(); if x0.contains("\n") || x0.contains("\r") { let x = x0.replace("\r\n", "\n"); let x = x.replace("\r", "\n"); let x = x.as_str(); let y = re2.replace_all(x, r#"$n\n"#).to_string(); new_string = new_string.replace(x0, &y); } } } new_string } /// 加载auth认证的相关数据 pub fn load_auth_data(api_docs: &HashMap<String, ApiDoc>) -> Option<AuthDoc> { let auth_files = ["_auth.json5", "_auth.json"]; let mut auth_value = json!({}); let mut filename = ""; for file in auth_files.iter() { match fs::read_to_string(file) { Ok(v) => { let v = fix_json(v); match json5::from_str(&v) { Ok(v) => { filename = file; auth_value = v; break; } Err(e) => { println!("Parse json file {} error : {:?}", file, e); return None; } } } Err(_) => return None, }; } if filename == "" { return None; } let obj = auth_value.as_object().unwrap(); let name = match obj.get("name") { Some(name) => name.as_str().unwrap(), None => "Panda api auth", }; let desc = match obj.get("desc") { Some(name) => name.as_str().unwrap(), None => "Panda api desc", }; let auth_type = match obj.get("auth_type") { Some(name) => name.as_str().unwrap(), None => "Bearer", }; let auth_place = match obj.get("auth_place") { Some(v) => v.as_str().unwrap(), None => "headers", }; let no_perm_response = match obj.get("no_perm_response") { Some(v) => v.clone(), None => json!({"code":-1, "error":"no perm to visit"}), }; let mut groups: Vec<AuthData> = Vec::new(); if let Some(test_data_value) = obj.get("groups") { if let Some(items) = test_data_value.as_array() { for data in items { let test_data_name = match data.get("name") { Some(v) => v.as_str().unwrap(), None => "", }; let test_data_desc = match data.get("desc") { Some(v) => v.as_str().unwrap(), None => "", }; let mut users: HashMap<String, Value> = HashMap::new(); if let Some(v) = data.get("users") { if let Some(uu) = v.as_array() { for user in uu { if let Some(t) = user.get("token") { if let Some(token) = t.as_str() { users.insert(token.to_string(), user.clone()); } } } } }; let has_perms = parse_auth_perms(data.get("has_perms"), api_docs); let no_perms = parse_auth_perms(data.get("no_perms"), api_docs); let test_data_no_perm_response = match data.get("no_perm_response") { Some(v) => v.clone(), None => no_perm_response.clone(), }; groups.push(AuthData { name: test_data_name.to_string(), desc: test_data_desc.to_string(), users: users, has_perms: has_perms, no_perms: no_perms, no_perm_response: test_data_no_perm_response, }) } } } Some(AuthDoc { name: name.to_string(), desc: desc.to_string(), auth_type: auth_type.to_string(), auth_place: auth_place.to_string(), filename: filename.to_string(), groups: groups, no_perm_response: no_perm_response, }) } pub fn load_basic_data() -> (BasicData, Option<Value>) { let settings_files = ["_settings.json5", "_settings.json"]; let mut setting_value = json!({}); let mut return_value: Option<Value> = None; for settings_file in settings_files.iter() { match fs::read_to_string(settings_file) { Ok(v) => { let v = fix_json(v); match json5::from_str(&v) { Ok(v) => { setting_value = v; return_value = Some(setting_value.clone()); break; } Err(e) => { println!("Parse json file {} error : {:?}", settings_file, e); } } } Err(_) => (), }; } let obj = setting_value.as_object().unwrap(); let project_name = match obj.get("project_name") { Some(name) => name.as_str().unwrap(), None => "Panda api docs", }; let project_name = project_name.to_string(); let project_desc = match obj.get("project_desc") { Some(name) => name.as_str().unwrap(), None => "", }; let project_desc = project_desc.to_string(); let read_me = match fs::read_to_string("README.md") { Ok(x) => x, Err(_) => { if &project_desc == "" { "Panda api docs".to_string() } else { project_desc.clone() } } }; let global_value = match obj.get("global") { Some(v) => v.clone(), None => Value::Null, }; ( BasicData { read_me, project_name, project_desc, global_value, }, return_value, ) } impl Database { /// 加载api docs 接口的json数据、配置、相关文档 pub fn load() -> Database { let (basic_data, settings) = load_basic_data(); let mut api_docs = HashMap::new(); let mut api_data: HashMap<String, Vec<Arc<Mutex<ApiData>>>> = HashMap::new(); let mut fileindex_data: HashMap<String, HashSet<String>> = HashMap::new(); let mut menus: HashMap<String, Menu> = HashMap::new(); let websocket_api = Arc::new(Mutex::new(ApiData::default())); for entry in WalkDir::new("./") { let e = entry.unwrap(); let doc_file = e.path().to_str().unwrap().trim_start_matches("./"); if doc_file == "README.md" { continue; } if doc_file.ends_with(".md") { Self::load_a_md_doc(doc_file, &mut menus); } else if doc_file.ends_with(".json5") { Self::load_a_api_json_file( doc_file, &basic_data, &mut api_data, &mut api_docs, websocket_api.clone(), &mut fileindex_data, &mut menus, ); } } let auth_doc = load_auth_data(&api_docs); Database { basic_data, api_data, api_docs, menus, fileindex_data, websocket_api, auth_doc, settings, } } /// 加载md文档 pub fn load_a_md_doc(doc_file: &str, mut menus: &mut HashMap<String, Menu>) { let paths: Vec<&str> = doc_file.split("/").collect(); let l = paths.len(); let mut tmp_path = "".to_string(); for (i, &path) in paths.iter().enumerate() { if path == "$_folder.md" { return; } if &tmp_path == "" { tmp_path = path.to_string(); } else { tmp_path = format!("{}/{}", tmp_path, path); } let mut is_exist = false; if let Some(_x) = menus.get(&tmp_path) { is_exist = true; } if is_exist { menus = &mut menus.get_mut(&tmp_path).unwrap().children; } else { let (mut order, mut menu_title) = get_order_and_title_from_filename(path, "md"); let mut desc = "".to_string(); let mut md_content = "".to_string(); let mut filename = String::new(); if i + 1 == l { filename = doc_file.to_string(); load_md_doc_config( doc_file, &mut order, &mut menu_title, &mut desc, &mut md_content, &mut filename, ); } else { load_folder_config( &tmp_path, &mut order, &mut menu_title, &mut desc, &mut md_content, &mut filename, ); }; menus.insert( tmp_path.clone(), Menu { desc, filename, order, filetype: "md".to_string(), name: menu_title, children: HashMap::new(), }, ); menus = &mut menus.get_mut(&tmp_path).unwrap().children; } } } /// 只加载一个api_doc文件的数据 /// pub fn load_a_api_json_file( doc_file: &str, basic_data: &BasicData, api_data: &mut HashMap<String, Vec<Arc<Mutex<ApiData>>>>, api_docs: &mut HashMap<String, ApiDoc>, websocket_api: Arc<Mutex<ApiData>>, fileindex_data: &mut HashMap<String, HashSet<String>>, mut menus: &mut HashMap<String, Menu>, ) -> i32 { if !doc_file.ends_with(".json5") || doc_file == "_settings.json5" || doc_file == "_auth.json5" || doc_file.contains("_data/") || doc_file.starts_with(".") || doc_file.contains("/.") { return -1; } let d = match fs::read_to_string(Path::new(doc_file)) { Ok(d) => { if &d == "" { return -2; } d }, Err(_e) => { // println!("Unable to read file: {} {:?}", doc_file, e); // 文件被删除 return -2; } }; let d = fix_json(d); let json_value: Value = match json5::from_str(&d) { Ok(v) => v, Err(e) => { log::error!("Parse json file {} error : {:?}", doc_file, e); return -3; } }; let doc_file_obj = match json_value.as_object() { Some(doc_file_obj) => doc_file_obj, None => { log::error!("file {} json5 data is not a object", doc_file); return -4; } }; let (mut menu_order0, mut menu_title0) = get_order_and_title_from_filename(doc_file, "json5"); let mut doc_name = match doc_file_obj.get("name") { Some(name) => match name.as_str() { Some(v) => { menu_title0 = v.to_string(); v.to_string() } None => format!("{}", name), }, None => doc_file.to_string(), }; if &doc_name == "" { // 如果接口文档name为空,那么就用文件名作为文档名称 doc_name = doc_file.to_string(); } let doc_desc = match doc_file_obj.get("desc") { Some(desc) => desc.as_str().unwrap(), None => "", }; let doc_desc = doc_desc.to_string(); let doc_order: i64 = match doc_file_obj.get("order") { Some(order) => { let order = order.as_i64().expect("order is not number"); menu_order0 = order as i32; order } None => 0, }; let apis = match doc_file_obj.get("apis") { Some(api) => api.clone(), None => json!([]), }; let api_vec = load_apis_from_api_doc( apis, doc_file_obj, doc_file, fileindex_data, basic_data, api_data, websocket_api.clone(), ); let api_doc = ApiDoc { name: doc_name, desc: doc_desc.clone(), order: doc_order, filename: doc_file.to_string(), apis: api_vec, }; api_docs.insert(doc_file.to_string(), api_doc); // 根据路径加载接口文档的菜单 let paths: Vec<&str> = doc_file.split("/").collect(); let l = paths.len(); let mut tmp_path = "".to_string(); for (i, &path) in paths.iter().enumerate() { if &tmp_path == "" { tmp_path = path.to_string(); } else { tmp_path = format!("{}/{}", tmp_path, path); } let mut is_exist = false; if let Some(_x) = menus.get(&tmp_path) { is_exist = true; } if is_exist { menus = &mut menus.get_mut(&tmp_path).unwrap().children; } else { let mut menu_order = 0; let mut menu_title = "".to_string(); let mut desc = "".to_string(); let mut md_content = "".to_string(); let mut filename = "".to_string(); let mut filetype = "".to_string(); if i + 1 == l { menu_order = menu_order0; menu_title = menu_title0.clone(); filename = tmp_path.clone(); filetype = "json5".to_string(); desc = doc_desc.clone() } else { filename = "".to_string(); filetype = "md".to_string(); let (menu_order1, menu_title1) = get_order_and_title_from_filename(path, "md"); menu_order = menu_order1; menu_title = menu_title1; load_folder_config( &tmp_path, &mut menu_order, &mut menu_title, &mut desc, &mut md_content, &mut filename, ); }; menus.insert( tmp_path.clone(), Menu { desc, filename, filetype, order: menu_order, name: menu_title, children: HashMap::new(), }, ); menus = &mut menus.get_mut(&tmp_path).unwrap().children; } } 1 } } /// 把接口文档的所有接口加载到一个Vec中 fn load_apis_from_api_doc( apis: Value, doc_file_obj: &Map<String, Value>, doc_file: &str, fileindex_data: &mut HashMap<String, HashSet<String>>, basic_data: &BasicData, api_data: &mut HashMap<String, Vec<Arc<Mutex<ApiData>>>>, websocket_api: Arc<Mutex<ApiData>>, ) -> Vec<Arc<Mutex<ApiData>>> { let mut api_vec = Vec::new(); if let Some(api_array) = apis.as_array() { for api in api_array { let mut ref_data = Value::Null; // 存储api接口上直接$ref一个接口模型的Value let mut ref_files: Vec<String> = Vec::new(); // $ref的文件列表,用于建立ref文件和源文件的索引,方便更新 if let Some(ref_file_path_v) = api.get("$ref") { // 处理api $ref加载数据 if let Some(ref_file_path) = ref_file_path_v.as_str() { let (ref_file, ref_value) = load_ref_file_data(ref_file_path, doc_file); if &ref_file != "" { match fileindex_data.get_mut(&ref_file) { Some(x) => { x.insert(doc_file.to_string()); } None => { let mut b = HashSet::new(); b.insert(doc_file.to_string()); fileindex_data.insert(ref_file, b); } } } if let Some(value) = ref_value { let (mut ref_files2, value) = parse_attribute_ref_value(value, doc_file_obj, doc_file); ref_files.append(&mut ref_files2); ref_data = value; } } } let name = get_api_field_string_value( "name", doc_file.to_string(), api, &ref_data, &basic_data.global_value, ); let desc = get_api_field_string_value( "desc", "".to_string(), api, &ref_data, &basic_data.global_value, ); let mut url = get_api_field_string_value( "url", "".to_string(), api, &ref_data, &basic_data.global_value, ); let base_path = get_api_field_string_value( "base_path", "".to_string(), api, &ref_data, &basic_data.global_value, ); if &base_path != "" { url = format!("{}{}", base_path.trim_end_matches("/"), url); } let mut method = get_api_field_array_value( "method", vec!["GET".to_string()], api, &ref_data, &basic_data.global_value, ); for m in method.iter_mut() { *m = m.to_uppercase(); } let body_mode = get_api_field_string_value( "body_mode", "json".to_string(), api, &ref_data, &basic_data.global_value, ); let auth = get_api_field_bool_value("auth", false, api, &ref_data, &basic_data.global_value); let url_param = match api.get("url_param") { Some(url_param) => url_param.clone(), None => match ref_data.get("url_param") { Some(v) => v.clone(), None => Value::Null, }, }; let (mut ref_files2, url_param) = parse_attribute_ref_value(url_param, doc_file_obj, doc_file); ref_files.append(&mut ref_files2); let body = match api.get("body") { Some(body) => body.clone(), None => match ref_data.get("body") { Some(v) => v.clone(), None => Value::Null, }, }; let (mut ref_files2, body) = parse_attribute_ref_value(body, doc_file_obj, doc_file); ref_files.append(&mut ref_files2); let request_headers = match api.get("request_headers") { Some(request_headers) => request_headers.clone(), None => match ref_data.get("request_headers") { Some(v) => v.clone(), None => Value::Null, }, }; let (mut ref_files2, request_headers) = parse_attribute_ref_value(request_headers, doc_file_obj, doc_file); ref_files.append(&mut ref_files2); let response_headers = match api.get("response_headers") { Some(response_headers) => response_headers.clone(), None => match ref_data.get("response_headers") { Some(v) => v.clone(), None => Value::Null, }, }; let (mut ref_files2, response_headers) = parse_attribute_ref_value(response_headers, doc_file_obj, doc_file); ref_files.append(&mut ref_files2); let query = match api.get("query") { Some(query) => query.clone(), None => match ref_data.get("query") { Some(v) => v.clone(), None => Value::Null, }, }; let (mut ref_files2, query) = parse_attribute_ref_value(query, doc_file_obj, doc_file); ref_files.append(&mut ref_files2); // 最后查询global_value let mut response: Map<String, Value> = match basic_data.global_value.pointer("/apis/response") { Some(v) => v.as_object().unwrap().clone(), None => json!({}).as_object().unwrap().clone(), }; if let Some(r) = ref_data.get("response") { if let Some(rm) = r.as_object() { for (k, v) in rm { response.insert(k.to_string(), v.clone()); } } } let mut is_special_private = false; if let Some(r) = api.get("response") { if let Some(rm) = r.as_object() { for (k, v) in rm { response.insert(k.to_string(), v.clone()); } } else { // 允许response返回任意格式的数据 response.insert("$_special_private".to_string(), r.clone()); is_special_private = true; } } // 处理response中的$ref let (mut ref_files2, mut response) = parse_attribute_ref_value(Value::Object(response), doc_file_obj, doc_file); if is_special_private { response = response.pointer("/$_special_private").unwrap().clone(); } ref_files.append(&mut ref_files2); for ref_file in ref_files { if &ref_file != "" { match fileindex_data.get_mut(&ref_file) { Some(x) => { x.insert(doc_file.to_string()); } None => { let mut b = HashSet::new(); b.insert(doc_file.to_string()); fileindex_data.insert(ref_file, b); } } } } let test_data = match api.get("test_data") { Some(test_data) => test_data.clone(), None => match ref_data.get("test_data") { Some(v) => v.clone(), None => Value::Null, }, }; if !test_data.is_null() && !test_data.is_array() { log::error!("test_data need a array"); } let o_api_data = ApiData { name, desc, body_mode, body, query, response, test_data, url_param, request_headers, response_headers, auth: auth, url: url.clone(), method: method.clone(), }; let a_api_data = Arc::new(Mutex::new(o_api_data.clone())); if method.contains(&"WEBSOCKET".to_string()) { // 如果method是websocket,表面有websocket接口, 那么就把websocket接口更新配置到websocket配置 let mut websocket_api = websocket_api.lock().unwrap(); *websocket_api = o_api_data.clone(); } // 形成 { url: {method:api} } match api_data.get_mut(&url) { Some(data) => { data.push(a_api_data.clone()); } None => { let mut x = Vec::new(); x.push(a_api_data.clone()); api_data.insert(url.clone(), x); } } api_vec.push(a_api_data.clone()); } } api_vec } /// 从md文件名中获取 排序和菜单名称 pub fn get_order_and_title_from_filename(doc_file: &str, file_type: &str) -> (i32, String) { let paths: Vec<&str> = doc_file.split("/").collect(); let filename = paths.last().unwrap(); let mut order = 0; let mut name = doc_file.to_string(); let re = Regex::new(&format!(r"^(\$)?(\d+)?\s*(.*?)(\.{})?$", file_type)).unwrap(); //捕获文件名中的排序 for cap in re.captures_iter(filename) { if let Some(v) = &cap.get(2) { order = v.as_str().parse().unwrap(); } if let Some(v) = &cap.get(3) { name = v.as_str().to_string(); } } (order, name) } /// 加载md文档中文件头的config内容, /// 以```{开头```}结尾 pub fn load_md_doc_config( doc_file: &str, order: &mut i32, menu_title: &mut String, desc: &mut String, md_content: &mut String, filename: &mut String, ) { if let Ok(content) = fs::read_to_string(Path::new(doc_file)) { *md_content = content.clone(); // 获取md文档顶部的配置信息 let re = Regex::new(r"^\s*(```)?\s*(\{[\s\S]*?\})\s*(```)\s*").unwrap(); for cap in re.captures_iter(&content) { if let Some(v) = &cap.get(2) { let config_str = v.as_str(); let mut l = config_str.len() + 6; if let Some(v0) = &cap.get(0) { l = v0.as_str().len(); } if let Ok(v) = json5::from_str::<Value>(config_str) { *md_content = { &content[l..] }.to_string(); if let Some(conf) = v.as_object() { if let Some(v2) = conf.get("menu_title") { if let Some(v3) = v2.as_str() { *menu_title = v3.to_string(); } } if let Some(v2) = conf.get("order") { if let Some(v3) = v2.as_i64() { *order = v3 as i32; } } let mut show_content = true; if let Some(v2) = conf.get("show_content") { if let Some(v3) = v2.as_bool() { show_content = v3; } } if doc_file.ends_with("$_folder.md") { if show_content { *filename = doc_file.to_string(); } } else { *filename = doc_file.to_string(); } if let Some(v2) = conf.get("desc") { if let Some(v3) = v2.as_str() { *desc = v3.to_string(); } } } } } break; } } } /// 加载目录的菜单配置文件 fn load_folder_config( foldername: &str, order: &mut i32, menu_title: &mut String, desc: &mut String, md_content: &mut String, filename: &mut String, ) { let folder_md_doc = format!("{0}/$_folder.md", foldername); load_md_doc_config( &folder_md_doc, order, menu_title, desc, md_content, filename, ) } /// 加载ref对应文件的数据 fn load_ref_file_data(ref_file: &str, doc_file: &str) -> (String, Option<Value>) { let ref_info: Vec<&str> = ref_file.split(":").collect(); match ref_info.get(0) { Some(filename) => { let mut file_path; if filename.starts_with("./_data") { let path = Path::new(doc_file).parent().unwrap(); file_path = format!( "{}/{}", path.to_str().unwrap(), filename.trim_start_matches("./") ); } else if filename.starts_with("/_data") { file_path = filename.trim_start_matches("/").to_string(); } else { file_path = filename.to_string(); } file_path = file_path.trim_start_matches("/").to_string(); // 加载数据文件 if let Ok(d) = fs::read_to_string(Path::new(&file_path)) { let d = fix_json(d); let data: Value = match json5::from_str(&d) { Ok(v) => v, Err(e) => { println!("Parse json file {} error : {:?}", filename, e); return ("".to_string(), None); } }; if let Some(key) = ref_info.get(1) { // if let Some(v) = data.pointer(&format!("/{}", &key.replace(".", "/"))) { if let Some(v) = data.pointer(&format!("/{}", key)) { return (file_path, Some(v.clone())); } } } else { println!("file {} not found", &file_path); return (file_path, None); } } None => (), }; ("".to_string(), None) } /// 从value中获取array fn get_array_from_value(key: &str, value: &Value) -> Option<Vec<String>> { if let Some(v) = value.get(key) { if v.is_string() { if let Some(v) = v.as_str() { return Some(vec![v.to_string()]); } else { return Some(vec![format!("{}", v)]); } } else if v.is_array() { if let Some(v_list) = v.as_array() { let mut r = Vec::new(); for i in v_list { if let Some(x) = i.as_str() { r.push(x.to_string()); } } return Some(r); } } } None } /// 获取值可能是数组的字段值 /// 例如method,可能填写是字符串,也可能是数组 fn get_api_field_array_value( key: &str, default_value: Vec<String>, api: &Value, ref_data: &Value, global_data: &Value, ) -> Vec<String> { // 如果直接在api接口上有设置值 if let Some(v) = get_array_from_value(key, api) { return v; } // 如果在ref_data上有设置值 if let Some(v) = get_array_from_value(key, ref_data) { return v; } // 最后查询global_value if let Some(v) = global_data.get("apis") { if let Some(v) = get_array_from_value(key, v) { return v; } } default_value } /// 获取api里面字段的数据 /// 如 url, name等 fn get_api_field_string_value( key: &str, default_value: String, api: &Value, ref_data: &Value, global_data: &Value, ) -> String { match api.get(key) { Some(d) => { match d { Value::String(v) => { if v == "$del" { // 如果设置$del,那么就删除返默认值 return default_value; } return v.to_owned(); } Value::Object(v) => { if let Some(v2) = v.get("$del") { // 如果设置$del,那么就删除返默认值 if let Some(true) = v2.as_bool() { return default_value; } } } _ => { return format!("{}", d); } } } None => (), } if let Some(d) = ref_data.get(key) { if let Some(v) = d.as_str() { return v.to_owned(); } else { return format!("{}", d); } } // 最后查询global_value match global_data.get("apis") { Some(v) => match v.get(key) { Some(v2) => { if let Some(d) = v2.as_str() { return d.to_owned(); } else { return format!("{}", v2); } } None => (), }, None => (), } default_value } fn get_api_field_bool_value( key: &str, default_value: bool, api: &Value, ref_data: &Value, global_data: &Value, ) -> bool { match api.get(key) { Some(d) => { if let Some(v) = d.as_bool() { return v; } else { println!("{} value is not a bool", key) } } None => (), } if let Some(d) = ref_data.get(key) { if let Some(v) = d.as_bool() { return v; } else { println!("{} value is not a bool", key) } } match global_data.get("apis") { Some(v) => match v.get(key) { Some(d) => { if let Some(v2) = d.as_bool() { return v2; } else { println!("{} value is not a bool", key) } } None => (), }, None => (), } default_value } /// parse 分析value的值,处理各种语法优化 /// $ref引用数据, /// 继承字段, /// 重写字段, /// 删除字段 /// $enum /// 标注object类型 /// /// 第一个参数表示获取到的值,body, query, resonse 等, 判断是否有引用值 或者 全局值 /// 对不满足要求的数据会全部进行过滤 fn parse_attribute_ref_value( value: Value, doc_file_obj: &Map<String, Value>, doc_file: &str, ) -> (Vec<String>, Value) { let mut ref_files: Vec<String> = Vec::new(); if value.is_null() { return (ref_files, value); } if value.is_object() { let value_obj = value.as_object().unwrap(); let mut new_value = value_obj.clone(); let mut is_rec = false; // 是否是递归 if let Some(type_v) = value_obj.get("$type") { if let Some(type_v) = type_v.as_str() { if type_v == "rec" { is_rec = true; } } } // 如果是递归,就不进行文件的引入操作,递归的文件引入在生成mock数据时才进行引入 if !is_rec { // 处理文件引入 new_value = load_a_ref_value(new_value, &mut ref_files, value_obj, doc_file_obj, doc_file); } for (field_key, field_attrs) in value_obj { if let Some(is_del) = field_attrs.pointer("/$del") { // 处理当字段设置了{$del:true}属性,那么就不显示这个字段 if let Some(true) = is_del.as_bool() { new_value.remove(field_key); continue; } } if field_attrs.is_string() && field_attrs.as_str().unwrap() == "$del" { // 删除不要的字段 new_value.remove(field_key); continue; } else if field_key == "$del" || field_key == "$ref" || field_key == "$exclude" || field_key == "$include" || field_key == "$name" || field_key == "$type" || field_key == "$desc" || field_key == "$required" || field_key == "$max_length" || field_key == "$min_length" || field_key == "$length" { continue; } // 处理属性中的value let (mut ref_files2, field_value) = parse_attribute_ref_value(field_attrs.clone(), doc_file_obj, doc_file); ref_files.append(&mut ref_files2); // new_value.insert(field_key.trim_start_matches("$").to_string(), field_value); new_value.insert(field_key.to_string(), field_value); } let field_type = get_field_type(&Value::Object(new_value.clone())); if field_type == "object" { new_value.insert("$type".to_string(), Value::String(field_type)); } // 处理嵌套增加或修改属性值的问题 category/category_name let mut new_value_value = Value::Object(new_value.clone()); for (field_key, field_attrs) in &new_value { if field_key.contains("/") { new_value_value = modify_val_from_value(new_value_value, field_key, field_attrs); } } return (ref_files, new_value_value); } else if value.is_array() { // 处理array if let Some(value_array) = value.as_array() { if value_array.len() == 1 { if let Some(value_array_one) = value_array.get(0) { let (ref_files, array_item_value) = parse_attribute_ref_value(value_array_one.clone(), doc_file_obj, doc_file); return (ref_files, Value::Array(vec![array_item_value])); } else { println!(" file array value empty '{}' got {:?}", doc_file, value); } } else { return (ref_files, value); } } } (ref_files, value) } /// 加载某个$ref 路径的数据出来 fn load_a_ref_value( mut new_value: Map<String, Value>, ref_files: &mut Vec<String>, value_obj: &Map<String, Value>, doc_file_obj: &Map<String, Value>, doc_file: &str, ) -> Map<String, Value> { if let Some(ref_val) = value_obj.get("$ref") { let mut v_str = ref_val.as_str().unwrap(); let mut new_v_str = "".to_string(); if v_str.contains("$") { match doc_file_obj.get("define") { Some(defined) => { let re = Regex::new(r"\$\w+").unwrap(); match re.find(v_str) { Some(m) => { let m_str = &v_str[m.start() + 1..m.end()]; match defined.get(m_str) { Some(v3) => { new_v_str = format!("{}{}", v3.as_str().unwrap(), &v_str[m.end()..]); } None => (), } } None => (), }; } None => (), } } if new_v_str != "".to_string() { v_str = new_v_str.as_str(); } // 处理response, body里面的ref let (ref_file, ref_data) = load_ref_file_data(v_str, doc_file); ref_files.push(ref_file); let mut has_include = false; if let Some(vv) = ref_data { let (mut ref_files2, mut vv) = parse_attribute_ref_value(vv, doc_file_obj, doc_file); ref_files.append(&mut ref_files2); new_value = match vv.as_object() { Some(ref_data_map) => { // 判断是否有include 字段,然后只引入include let mut new_result = Map::new(); if let Some(e) = value_obj.get("$include") { for v2 in e.as_array().unwrap() { has_include = true; let key_str = v2.as_str().unwrap(); if let Some(v) = ref_data_map.get(key_str) { new_result.insert(key_str.to_string(), v.clone()); } } } if has_include { new_value.insert("$type".to_string(), Value::String("object".to_string())); new_result } else { ref_data_map.clone() } } None => { println!(" file value error '{}' got {:?}", v_str, vv); json!({}).as_object().unwrap().clone() } } } // 移除exclude中的字段 if let Some(e) = value_obj.get("$exclude") { for v2 in e.as_array().unwrap() { let key_str = v2.as_str().unwrap(); if key_str.contains("/") { // 如果exclude中含有/斜杠,表示要嵌套的去移除字段 let v = remove_val_from_value(Value::Object(new_value), key_str); new_value = v.as_object().unwrap().clone(); } else { new_value.remove(key_str); } } } } new_value } /// auth文件里面,可能是按文件加载接口地址 fn load_all_api_docs_url( result: &mut HashMap<String, HashSet<String>>, doc_file: &str, methods: HashSet<String>, api_docs: &HashMap<String, ApiDoc>, exclude: &HashMap<String, HashSet<String>>, ) { let mut all_methods: HashSet<String> = HashSet::with_capacity(7); for v in &["POST", "GET", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"] { all_methods.insert(v.to_string()); } let doc_file = doc_file.trim_start_matches("$"); if let Some(api_doc) = api_docs.get(doc_file) { for a in &api_doc.apis { let api = a.lock().unwrap(); // 如果exclude 排除这个url,并且排除所有方法,那么就没有任何这个url的权限 if let Some(exclude_methods) = exclude.get(&api.url) { if exclude_methods.is_empty() { result.insert(api.url.clone(), methods.clone()); continue; } if exclude_methods.contains("*") { continue; } let mut new_methods: HashSet<String>; if methods.contains("*") { new_methods = all_methods.clone(); } else { new_methods = methods.clone(); } for m in exclude_methods { new_methods.remove(&m.to_uppercase()); } if new_methods.len() > 0 { if new_methods == all_methods { let mut m = HashSet::new(); m.insert("*".to_string()); result.insert(api.url.clone(), m); } else { result.insert(api.url.clone(), new_methods); } } } else { result.insert(api.url.clone(), methods.clone()); } } } } /// 把权限解析为一个map fn parse_auth_perms( perms_data: Option<&Value>, api_docs: &HashMap<String, ApiDoc>, ) -> HashMap<String, HashSet<String>> { let mut result: HashMap<String, HashSet<String>> = HashMap::new(); if let Some(perms) = perms_data { if let Some(perms) = perms.as_array() { for perm in perms { let mut methods = HashSet::new(); let mut url = ""; let mut exclude: HashMap<String, HashSet<String>> = HashMap::new(); match perm { Value::String(perm_str) => { // 如果直接是一个字符串,表示字符串就是接口,然后拥有所有请求方法 methods.insert("*".to_string()); url = perm_str; } Value::Array(perm_array) => { for (i, p) in perm_array.iter().enumerate() { match p { Value::String(perm_str) => { if i == 0 { url = perm_str; } else { methods.insert(perm_str.to_uppercase()); } } _ => continue, } } } Value::Object(perm_obj) => { exclude = parse_auth_perms(perm_obj.get("$exclude"), api_docs); if let Some(m) = perm_obj.get("methods") { if m.is_string() { let m = m.as_str().unwrap(); methods.insert(m.to_uppercase()); } else if m.is_array() { let m = m.as_array().unwrap(); for i in m { let i = i.as_str().unwrap(); methods.insert(i.to_uppercase()); } } } else { methods.insert("*".to_string()); } // 如果是一个对象,那么可能是{$ref:"auth.json5", $exclude:["/login/", ["/logout/", "GET", "POST"]]} if let Some(perm_str) = perm_obj.get("$ref") { if let Some(perm_str) = perm_str.as_str() { load_all_api_docs_url( &mut result, perm_str, methods, api_docs, &exclude, ); } continue; } url = match perm_obj.get("url") { Some(url) => url.as_str().unwrap(), None => continue, }; } _ => { continue; } } // 如果没有设置methods,默认就是所有方法 if url.starts_with("$") { // 按接口文件加载urls load_all_api_docs_url(&mut result, url, methods, api_docs, &exclude); } else { result.insert(url.to_string(), methods); } } } else if perms.is_string() { let url = perms.as_str().unwrap(); let mut methods = HashSet::new(); methods.insert("*".to_string()); if url.starts_with("$") { // 按接口文件加载urls let exclude: HashMap<String, HashSet<String>> = HashMap::new(); load_all_api_docs_url(&mut result, url, methods, api_docs, &exclude); } else { result.insert(url.to_string(), methods); } } }; result } fn parse_index(s: &str) -> Option<usize> { if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) { return None; } s.parse().ok() } /// 为修改value中嵌套的某一个值或者增加某一个值 /category/id fn modify_val_from_value(mut value: Value, pointer: &str, new_value: &Value) -> Value { if pointer == "" { return value; } let tokens: Vec<&str> = pointer .trim_start_matches("/") .trim_end_matches("/") .split("/") .collect(); if tokens.len() == 0 { return value; } let mut target = &mut value; let l = tokens.len() - 1; for (i, &token) in tokens.iter().enumerate() { let target_once = target; let target_opt = match target_once { Value::Object(ref mut map) => { if i == 0 { map.remove(pointer); } if i == l { map.insert(token.to_string(), new_value.clone()); break; } else { map.get_mut(token) } } Value::Array(ref mut list) => parse_index(&token).and_then(move |x| list.get_mut(x)), _ => break, }; if let Some(t) = target_opt { target = t; } else { break; } } value } /// 从value中嵌套的删除某一个值 /category/id fn remove_val_from_value(mut value: Value, pointer: &str) -> Value { if pointer == "" { return value; } let tokens: Vec<&str> = pointer .trim_start_matches("/") .trim_end_matches("/") .split("/") .collect(); if tokens.len() == 0 { return value; } let mut target = &mut value; let l = tokens.len() - 1; for (i, &token) in tokens.iter().enumerate() { let target_once = target; let target_opt = match target_once { Value::Object(ref mut map) => { if i == l { map.remove(token); break; } else { map.get_mut(token) } } Value::Array(ref mut list) => parse_index(&token).and_then(move |x| list.get_mut(x)), _ => break, }; if let Some(t) = target_opt { target = t; } else { break; } } value } /// 获取字段的类型 pub fn get_field_type(field_attr: &Value) -> String { if field_attr.is_array() { return "array".to_lowercase(); } if let Some(v) = field_attr.get("type") { if v.is_string() { return v.as_str().unwrap().to_lowercase(); } } if let Some(v) = field_attr.get("$type") { return v.as_str().unwrap().to_lowercase(); } if field_attr.is_object() { if let Some(field_attr_object) = field_attr.as_object() { if let Some(v2) = field_attr_object.get("name") { if v2.is_string() { return "string".to_lowercase(); } } for (k, v) in field_attr_object { if v.is_object() || v.is_array() { return "object".to_lowercase(); } } } } return "string".to_lowercase(); } #[cfg(test)] mod test { use super::*; #[test] fn get_field_type_test() { let data = json!({ "id":{"name":"ID", "type":"i32"}, "name":{"name":"User name"} }); assert_eq!("object", get_field_type(&data)); let data = json!({"name":"ID", "type":"i32"}); assert_eq!("i32", get_field_type(&data)); let data = json!([{"name":"ID", "enum":[1,2,3]}]); assert_eq!("array", get_field_type(&data)); } }
//! The `ncp` module implements the network control plane. use crdt; use packet; use result::Result; use std::net::UdpSocket; use std::sync::atomic::AtomicBool; use std::sync::mpsc::channel; use std::sync::{Arc, RwLock}; use std::thread::JoinHandle; use streamer; pub struct Ncp { pub thread_hdls: Vec<JoinHandle<()>>, } impl Ncp { pub fn new( crdt: Arc<RwLock<crdt::Crdt>>, window: Arc<RwLock<Vec<Option<packet::SharedBlob>>>>, gossip_listen_socket: UdpSocket, gossip_send_socket: UdpSocket, exit: Arc<AtomicBool>, ) -> Result<Ncp> { let blob_recycler = packet::BlobRecycler::default(); let (request_sender, request_receiver) = channel(); trace!( "Ncp: id: {:?}, listening on: {:?}", &crdt.read().unwrap().me[..4], gossip_listen_socket.local_addr().unwrap() ); let t_receiver = streamer::blob_receiver( exit.clone(), blob_recycler.clone(), gossip_listen_socket, request_sender, )?; let (response_sender, response_receiver) = channel(); let t_responder = streamer::responder( gossip_send_socket, exit.clone(), blob_recycler.clone(), response_receiver, ); let t_listen = crdt::Crdt::listen( crdt.clone(), window, blob_recycler.clone(), request_receiver, response_sender.clone(), exit.clone(), ); let t_gossip = crdt::Crdt::gossip(crdt.clone(), blob_recycler, response_sender, exit); let thread_hdls = vec![t_receiver, t_responder, t_listen, t_gossip]; Ok(Ncp { thread_hdls }) } } #[cfg(test)] mod tests { use crdt::{Crdt, TestNode}; use ncp::Ncp; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; #[test] // test that stage will exit when flag is set fn test_exit() { let exit = Arc::new(AtomicBool::new(false)); let tn = TestNode::new(); let crdt = Crdt::new(tn.data.clone()); let c = Arc::new(RwLock::new(crdt)); let w = Arc::new(RwLock::new(vec![])); let d = Ncp::new( c.clone(), w, tn.sockets.gossip, tn.sockets.gossip_send, exit.clone(), ).unwrap(); exit.store(true, Ordering::Relaxed); for t in d.thread_hdls { t.join().expect("thread join"); } } }
use std::rc::Rc; fn main() { // concstructs a new Rc let five = Rc::new(5); // try_unwrap assert_eq!(Rc::try_unwrap(five),Ok(5)); }
use crate::{grid::builder::Builder, undo_redo_buffer, util, Grid, State}; use std::{borrow::Cow, time::Instant}; use terminal::{ util::{Color, Point}, Terminal, }; #[derive(Debug, Clone, Copy, PartialEq)] pub enum Cell { /// An umarked cell. Empty, /// Used to mark filled cells. Filled, /// Used to mark cells that may be filled. Useful for doing "what if" reasoning. Maybed, /// Used to mark cells that are certainly empty. Crossed, /// Used for indicating cells that were measured using the measurement tool. /// /// When this cell is saved, the index is not preserved. Measured(Option<usize>), } impl Default for Cell { fn default() -> Self { Cell::Empty } } impl From<bool> for Cell { fn from(filled: bool) -> Self { filled.then(|| Cell::Filled).unwrap_or_default() } } impl Cell { pub fn get_color(&self) -> Color { match self { Cell::Empty => Color::default(), Cell::Filled => Color::White, Cell::Maybed => Color::Blue, Cell::Crossed => Color::Red, Cell::Measured(_) => Color::Green, } } pub fn get_highlighted_color(&self) -> Color { match self { Cell::Empty => Color::DarkGray, Cell::Filled => Color::Gray, Cell::Maybed => Color::DarkBlue, Cell::Crossed => Color::DarkRed, Cell::Measured(_) => Color::DarkGreen, } } pub fn draw(&self, terminal: &mut Terminal, point: Point, highlight: bool) { /// Every 5 cells, the color changes to make the grid and its cells easier to look at and distinguish. const SEPARATION_POINT: u16 = 5; fn draw( terminal: &mut Terminal, foreground_color: Option<Color>, background_color: Color, content: Cow<'static, str>, ) { terminal.set_background_color(background_color); if let Some(foreground_color) = foreground_color { terminal.set_foreground_color(foreground_color); } terminal.write(&content); } let mut background_color = if highlight { self.get_highlighted_color() } else { self.get_color() }; let (foreground_color, background_color, content) = match self { Cell::Empty => { let x_reached_point = point.x / SEPARATION_POINT % 2 == 0; let y_reached_point = point.y / SEPARATION_POINT % 2 == 0; let mut background_color_byte = if x_reached_point ^ y_reached_point { 238 } else { 240 }; if highlight { background_color_byte -= 3; } background_color = Color::Byte(background_color_byte); (None, background_color, " ".into()) } Cell::Measured(index) => { let (foreground_color, content) = if let Some(index) = index { (Some(Color::Black), format!("{:>2}", index).into()) } else { (None, " ".into()) }; (foreground_color, background_color, content) } _ => (None, background_color, " ".into()), }; draw(terminal, foreground_color, background_color, content); } } #[derive(Default)] pub struct CellPlacement { pub cell: Option<Cell>, /// The time of when the first cell was placed. pub starting_time: Option<Instant>, pub selected_cell_point: Option<Point>, pub measurement_point: Option<Point>, /// Whether the next cell placement will flood-fill. pub fill: bool, } pub const fn get_cell_point_from_cursor_point(cursor_point: Point, builder: &Builder) -> Point { Point { x: (cursor_point.x - builder.point.x) / 2, y: cursor_point.y - builder.point.y, } } pub fn set_measured_cells(grid: &mut Grid, line_points: &[Point]) { for (index, point) in line_points.iter().enumerate() { let cell = grid.get_mut_cell(*point); if let Cell::Empty | Cell::Measured(_) = cell { *cell = Cell::Measured(Some(index + 1)); } } } pub fn draw_highlighted_cells( terminal: &mut Terminal, builder: &Builder, hovered_cell_point: Point, ) { fn highlight_cell(terminal: &mut Terminal, mut cursor_point: Point, builder: &Builder) { if (cursor_point.x - builder.point.x) % 2 != 0 { cursor_point.x -= 1; } terminal.set_cursor(cursor_point); let cell_point = get_cell_point_from_cursor_point(cursor_point, builder); let cell = builder.grid.get_cell(cell_point); cell.draw(terminal, cell_point, true); } // From the left of the grid to the pointer for x in builder.point.x..=hovered_cell_point.x - 2 { let point = Point { x, ..hovered_cell_point }; highlight_cell(terminal, point, builder); } // From the pointer to the right of the grid for x in hovered_cell_point.x + 2..builder.point.x + builder.grid.size.width * 2 { let point = Point { x, ..hovered_cell_point }; highlight_cell(terminal, point, builder); } // From the top of the grid to the pointer for y in builder.point.y..hovered_cell_point.y { let point = Point { y, ..hovered_cell_point }; highlight_cell(terminal, point, builder); } // From the pointer to the bottom of the grid for y in hovered_cell_point.y + 1..builder.point.y + builder.grid.size.height { let point = Point { y, ..hovered_cell_point }; highlight_cell(terminal, point, builder); } terminal.reset_colors(); } impl CellPlacement { pub fn place( &mut self, terminal: &mut Terminal, builder: &mut Builder, selected_cell_point: Point, mut cell_to_place: Cell, editor_toggled: bool, ) -> State { let starting_time = self.starting_time.get_or_insert(Instant::now()); let cell_point = get_cell_point_from_cursor_point(selected_cell_point, builder); let grid_cell = builder.grid.get_mut_cell(cell_point); *grid_cell = if let Some(cell) = self.cell { if *grid_cell == cell { builder.draw_grid(terminal); // We know that this point is hovered draw_highlighted_cells(terminal, &builder, selected_cell_point); return State::Continue; } cell } else { if *grid_cell == cell_to_place { cell_to_place = Cell::default(); } self.cell = Some(cell_to_place); if self.fill { let cell = *grid_cell; super::tools::fill::fill(&mut builder.grid, cell_point, cell, cell_to_place); builder .grid .undo_redo_buffer .push(undo_redo_buffer::Operation::Fill { point: cell_point, first_cell: cell, fill_cell: cell_to_place, }); self.fill = false; let all_clues_solved = builder.draw_all(terminal); if all_clues_solved { return State::Solved(starting_time.elapsed()); } else { return State::ClearAlert; } } cell_to_place }; let cell = *grid_cell; builder .grid .undo_redo_buffer .push(undo_redo_buffer::Operation::SetCell { point: cell_point, cell, }); if editor_toggled { builder.rebuild_clues(terminal, cell_point); // The grid shouldn't be solved while editing it #[allow(unused_must_use)] { builder.draw_all(terminal); } } else { let all_clues_solved = builder.draw_all(terminal); if all_clues_solved { return State::Solved(starting_time.elapsed()); } } // We know that this point is hovered draw_highlighted_cells(terminal, &builder, selected_cell_point); State::Continue } pub fn place_measured_cells( &mut self, terminal: &mut Terminal, builder: &mut Builder, ) -> State { if let Some(selected_cell_point) = self.selected_cell_point { if let Some(measurement_point) = self.measurement_point { // The points we have are screen points so now we convert them to values that we can use // to index the grid. let start_point = super::get_cell_point_from_cursor_point(measurement_point, builder); let end_point = super::get_cell_point_from_cursor_point(selected_cell_point, builder); let line_points: Vec<Point> = util::get_line_points(start_point, end_point).collect(); set_measured_cells(&mut builder.grid, &line_points); builder .grid .undo_redo_buffer .push(undo_redo_buffer::Operation::Measure(line_points)); builder.draw_picture(terminal); builder.draw_grid(terminal); // We know that this point is hovered super::draw_highlighted_cells(terminal, &builder, selected_cell_point); self.measurement_point = None; State::ClearAlert } else { self.measurement_point = Some(selected_cell_point); State::Alert("Set second measurement point".into()) } } else { State::Continue } } }
use std::cell::RefCell; use std::fs::File; use bodyparser::{Json, MaxBodyLength}; use iron::{AfterMiddleware, Chain, Iron, IronResult, Plugin, Request, Response}; use iron::error::IronError; use iron::headers::{ContentType, UserAgent}; use iron::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use iron::status; use persistent::Read; use router::{NoRoute, Router}; use serde_json::Value as JsonValue; use urlencoded::UrlEncodedBody; header! { (XGithubEvent, "X-Github-Event") => [String] } // TODO: Verify github sha1 checksums. fn github_handler(req: &mut Request) -> IronResult<Response> { info!("Got request at `/github`: {:?}", req); let event_type: RefCell<Event>; // New scope to do immutable borrows. { let github_event = match req.headers.get::<XGithubEvent>() { Some(e) => e, None => return Ok(Response::with(status::BadRequest)), }; // Check if the User-Agent header exists and is from GitHub-Hookshot let agent = req.headers.get::<UserAgent>() .map_or(false, |user_agent| { match user_agent { &UserAgent(ref raw) => raw.starts_with("GitHub-Hookshot"), } }); // If the headers are good, try to assign an Event value if let (true, event) = (agent, github_event.to_owned().0) { match parse_event(event) { Ok(e) => event_type = RefCell::new(e), Err(bad) => return Ok(bad), } } else { return Ok(Response::with(status::BadRequest)); } } let json_body = req.get::<Json>(); match json_body { Ok(Some(json_body)) => { match event_type.into_inner() { Event::WildCard => debug!("Got a wildcard"), Event::CommitComment => debug!("Got a commit comment"), Event::Create => debug!("Got a create"), Event::Delete => debug!("Got a delete"), Event::Deployment => debug!("Got a deployment"), Event::DeploymentStatus => debug!("Got a deployment status"), Event::Fork => debug!("Got a fork"), Event::Gollum => debug!("Got a gollum"), Event::IssueComment => { debug!("Got an issue comment"); }, Event::Issues => debug!("Got an issues"), Event::Label => debug!("Got a label"), Event::Member => debug!("Got a member"), Event::Membership => debug!("Got a membership"), Event::Milestone => debug!("Got a milestone"), Event::Organization => debug!("Got an organization"), Event::PageBuild => debug!("Got a page build"), Event::Ping => debug!("Got a ping"), Event::ProjectCard => debug!("Got a project card"), Event::ProjectColumn => debug!("Got a project column"), Event::Project => debug!("Got a project"), Event::Public => debug!("Got a public"), Event::PullRequestReviewComment => debug!("Got a pull request review comment"), Event::PullRequestReview => debug!("Got a pull request review"), Event::PullRequest => { debug!("Got a pull request"); }, Event::Push => { debug!("Got a push"); }, Event::Repository => debug!("Got a repository"), Event::Release => debug!("Got a release"), Event::Status => debug!("Got a status"), Event::Team => debug!("Got a team"), Event::TeamAdd => debug!("Got a team add"), Event::Watch => debug!("Got a watch"), }; Ok(Response::with(status::Ok)) }, Ok(None) => { debug!("No body"); Ok(Response::with(status::BadRequest)) }, Err(e) => { error!("Error: {:?}", e); Ok(Response::with(status::BadRequest)) }, } } // TODO: Verify webhook requests (sha2) // https://docs.travis-ci.com/user/notifications/#Configuring-webhook-notifications fn travis_handler(req: &mut Request) -> IronResult<Response> { info!("Got request at `/travis`: {:?}", req); let json_body: JsonValue = match req.get::<UrlEncodedBody>() { Ok(ref hashmap) => { match hashmap.get("payload") { Some(buf) => match ::serde_json::from_str(&buf[0]) { Ok(json) => json, Err(e) => { error!("Could not parse travis json: {:?}", e); return Ok(Response::with(status::BadRequest)) }, }, None => return Ok(Response::with(status::BadRequest)), } }, Err(ref e) => { error!("Could not parse travis webhook: {:?}", e); return Ok(Response::with(status::BadRequest)) }, }; debug!("json_body: {:?}", json_body); Ok(Response::with(status::Ok)) } fn index_handler(req: &mut Request) -> IronResult<Response> { info!("Got request at `/`: {:?}", req); let file = File::open("html/index.html").expect("index.html not found"); let mut res = Response::with((status::Ok, file)); res.headers.set(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![(Attr::Charset, Value::Utf8)]))); Ok(res) } fn favicon_handler(req: &mut Request) -> IronResult<Response> { info!("Got request at `/favicon.ico`: {:?}", req); let file = File::open("html/favicon.ico").expect("favicon.ico not found"); let mut res = Response::with((status::Ok, file)); res.headers.set(ContentType(Mime(TopLevel::Image, SubLevel::Ext("ico".to_string()), vec![]))); Ok(res) } struct Custom404; impl AfterMiddleware for Custom404 { fn catch(&self, req: &mut Request, err: IronError) -> IronResult<Response> { debug!("Got 404: {:?}", req); if let Some(_) = err.error.downcast::<NoRoute>() { Ok(Response::with((status::NotFound, "404: Not Found"))) } else { Err(err) } } } #[derive(Debug)] enum Event { WildCard, CommitComment, Create, Delete, Deployment, DeploymentStatus, Fork, Gollum, IssueComment, Issues, Label, Member, Membership, Milestone, Organization, PageBuild, Ping, ProjectCard, ProjectColumn, Project, Public, PullRequestReviewComment, PullRequestReview, PullRequest, Push, Repository, Release, Status, Team, TeamAdd, Watch, } fn parse_event(event: String) -> Result<Event, Response> { match &*event { "*" => Ok(Event::WildCard), "commit_comment" => Ok(Event::CommitComment), "create" => Ok(Event::Create), "delete" => Ok(Event::Delete), "deployment" => Ok(Event::Deployment), "deployment_status" => Ok(Event::DeploymentStatus), "fork" => Ok(Event::Fork), "gollum" => Ok(Event::Gollum), "issue_comment" => Ok(Event::IssueComment), "issues" => Ok(Event::Issues), "label" => Ok(Event::Label), "member" => Ok(Event::Member), "membership" => Ok(Event::Membership), "milestone" => Ok(Event::Milestone), "organization" => Ok(Event::Organization), "page_build" => Ok(Event::PageBuild), "ping" => Ok(Event::Ping), "project_card" => Ok(Event::ProjectCard), "project_column" => Ok(Event::ProjectColumn), "project" => Ok(Event::Project), "public" => Ok(Event::Public), "pull_request_review_comment" => Ok(Event::PullRequestReviewComment), "pull_request_review" => Ok(Event::PullRequestReview), "pull_request" => Ok(Event::PullRequest), "push" => Ok(Event::Push), "repository" => Ok(Event::Repository), "release" => Ok(Event::Release), "status" => Ok(Event::Status), "team" => Ok(Event::Team), "team_add" => Ok(Event::TeamAdd), "watch" => Ok(Event::Watch), _ => Err(Response::with(status::BadRequest)), } } const MAX_BODY_LENGTH: usize = 1024 * 1024 * 10; // The server for managing webhooks and http requests. pub struct Server; impl Server { /// Starts listening on the server. pub fn run(config: ::Config) { let mut router = Router::new(); router.get("/", index_handler, "root"); router.get("/index.html", index_handler, "index"); router.get("/favicon.ico", favicon_handler, "favicon"); router.post("/github", github_handler, "github"); router.post("/travis", travis_handler, "travis"); let mut chain = Chain::new(router); chain.link_before(Read::<MaxBodyLength>::one(MAX_BODY_LENGTH)); chain.link_after(Custom404); match Iron::new(chain).http(config.url()) { Ok(l) => info!("Listening with listener: {:?}", l), Err(e) => error!("Failed to connect: {:?}", e), } } }
//Copyright (c) 2019 #UlinProject Denis Kotlyarov (Денис Котляров) //----------------------------------------------------------------------------- //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. //----------------------------------------------------------------------------- // or //----------------------------------------------------------------------------- //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. // #Ulin Project 1819 /*! Convenient macros for combining cycles (for, while) with a match. # Full use Purpose: To read lines from a file ignoring comments and special characters using macros (for_match, while_match). ```rust #[macro_use] extern crate cycle_match; use std::io::Read; fn main() -> Result<(), std:: io::Error> { let mut read_buffer = [0u8; 128]; let mut buffer = Vec::with_capacity(130); let mut file = std::fs::File::open("./read.txt")?; while_match!((file.read(&mut read_buffer)) -> || { Ok(0) => break, Ok(len) => { let real_array = &read_buffer[..len]; for_match!(@'read (real_array.into_iter()) -> |iter| { Some(13u8) => continue, Some(b'\n') => { if buffer.len() > 0 { println!("#line: {}", unsafe { std::str::from_utf8_unchecked(&buffer) }); buffer.clear(); } }, Some(b'#') => while_match!((iter) -> || { Some(b'\n') => continue 'read, Some(_a) => {}, _ => break 'read, }), Some(a) => buffer.push(*a), _ => break, }); }, Err(e) => return Err(e), }); if buffer.len() > 0 { println!("#line: {}", unsafe { std::str::from_utf8_unchecked(&buffer) }); } Ok(()) } ``` # Use 1 (while_match) Purpose: Convert characters to a digital sequence using a macro while_math. ```rust #[macro_use] extern crate cycle_match; fn main() { let data = b"123456789"; let mut num = 0usize; let mut iter = data.iter(); while_match!((iter) -> || { Some(b'0') => {}, Some(a @ b'0' ..= b'9') => { num *= 10; num += (a - b'0') as usize; }, Some(a) => panic!("Unk byte: {:?}", a), _ => break }); assert_eq!(num, 123456789); } ``` */ #![no_std] #[macro_use] mod while_match; #[macro_use] mod for_match; #[macro_use] mod loop_match; #[doc(hidden)] #[macro_export] macro_rules! cycle_match { // ext version [@$m_type:tt ($($match_args:tt)+): $(#[$name:tt] {$($ext_data:tt)*}),+ $(,)? ] => { $crate::ext_cycle_match! { @$m_type ($($match_args)+): $( #[$name] {$($ext_data)*} )* } }; /* // default version, empty match [@$m_type:tt ($($match_args:tt)+): ] => { compile_error! ( concat!("An internal description of the 'match' language construct was expected. Provided by: \"\" Expected \" Some(a) => ... , None => ... , \" " ) ) }; */ /* // default version, empty version [@$m_type:tt ($($match_args:tt)+): ] => { }; */ // default version [@$m_type:tt ($($match_args:tt)+): $($data:tt)* ] => { match $($match_args)+ { $($data)* } }; } #[doc(hidden)] #[macro_export] macro_rules! ext_cycle_match { [@$m_type:tt (): ] => {}; //break [@$m_type:tt ($($match_args:tt)+): #[begin] {$($data:tt)*} $($all_data:tt)*] => {{ $crate::cycle_match! { @$m_type ($($match_args)+): $($data)* }; $crate::ext_cycle_match! { @$m_type (): $($all_data)* } }}; [@$m_type:tt ($($match_args:tt)+): #[insert] {$($data:tt)*} $($all_data:tt)*] => {{ {$($data)*}; $crate::ext_cycle_match! { @$m_type ($($match_args)+): $($all_data)* } }}; } #[doc(hidden)] #[macro_export] macro_rules! cycle_variables { [ {$($_unk:tt)*} {} {} ] => {}; [ { $($all:tt)* } { $([$($i_next:tt)+])? $(, [$($i:tt)+])* } {$([$($e_next:tt)+])? $(, [$($e:tt)+])*} ] => { $crate::cycle_variables_begin! { { $($all)* } [$($($i_next)*)?] {$([$($i)*]),*} : [$($($e_next)+)?] {$([$($e)+]),*} } }; } #[doc(hidden)] #[macro_export] macro_rules! cycle_variables_begin { [ {$($all_tt:tt)*} [] {} : [] {}] => {}; //break, empty variables //error let _ = $e; [ {$($all_tt:tt)*} [] {$($unk_i:tt)*} : [ $($e:tt)+ ] ] => { //#0 compile_error!( concat!( "For the expression \"", stringify!($($e)+), "\", a name was expected in | ... |, but this was not done. (You can specify either a name or _ to ignore the name) " ) ); }; //error let e = _; [ {$($all_tt:tt)*} [ $($i2:tt)+ ] {$($unk_i:tt)*} : [] ] => { compile_error!( concat!( "For the name \"", stringify!($($i2)+) ,"\", an expression in (...) was expected, but this was not done. (You can specify an expression, or remove the extra name in | ... |) " ) ); }; [ {$($all_tt:tt)*} [ _ ] {$([$($next_i:tt)*])? $(, [$($unk_i:tt)*])*} : [ $($e:tt)+ ] { $([$($next_e:tt)*])? $(, [$($unk_e:tt)*])* } ] => { { $($e)+ }; $crate::cycle_variables_begin! { {$($all_tt)*} [$($($next_i)*)?] { $([$($unk_i)*]),* } : [$($($next_e)*)?] { $([$($unk_e)*]),* } } }; //fn next [ { $( [$($check:tt)*] )? } [ $i:ident ] {$([$($next_i:tt)*])? $(, [$($unk_i:tt)*])*} : [ $($e:tt)+ ] { $([$($next_e:tt)*])? $(, [$($unk_e:tt)*])* } ] => { { $( $crate::cycle_variable_names_check! { [$($check)*]: $i } )? } let mut $i = $($e)+; $crate::cycle_variables_begin! { { $( [$($check)*] )? } [$($($next_i)*)?] { $([$($unk_i)*]),* } : [$($($next_e)*)?] { $([$($unk_e)*]),* } } }; } #[doc(hidden)] #[macro_export] macro_rules! cycle_variable_names_check { [ []: $($__ignore:tt)* ] => {}; //break [ [ {$self_name:ident} $(, {$next_expr:ident} )* ]: $i:ident ] => { macro_rules! check_ident_equality { [ ({$self_name} : {$self_name}) -> $ok:block ] => {$ok}; [ ({$i} : {$i}) -> $ok:block ] => {$ok}; [ ({$self_name} : {$self_name}) -> $ok:block else $err:block ] => {$ok}; [ ({$i} : {$i}) -> $ok:block else $err:block ] => {$ok}; [ ({$self_name} : {$uunk:tt}) -> $ok:block ] => {}; [ ({$self_name} : {$uunk:tt}) -> $ok:block else $err:block ] => {$err}; } check_ident_equality! { ({$self_name} : {$i}) -> { compile_error!( concat!( "Name conflict, possibly undefined behavior. Call the variable \"", stringify!($i) ,"\" something different." ) ); }else { } } $crate::cycle_variable_names_check! { [ $({$next_expr}),* ]: $i } }; }
fn main() -> Result<()> { { let addr = "127.0.0.1:34254" let mut socket = UdpSocket::bind(addr)?; let mut buf = [0; 10]; let (amt, src) = socket.recv_from(&mut buf)?; let buf = &mut buf[..amt]; buf.reverse(); socket.send_to(buf, &src)?; } // the socket is closed here Ok(()) }
mod atc_button; mod error; mod navbar; mod product_card; mod spinner; pub use atc_button::AtcButton; pub use error::Error; pub use navbar::Navbar; pub use spinner::Spinner;
pub mod byte_ops;
use serde::Serialize; use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, RwLock}; use crate::config::ConfigFromFile; use crate::config_store::{ConfigStore, ConfigStoreFunc, Monitor}; use crate::file_store::{FileStore, FileStoreFunc}; use crate::stat_store::{StatStore, StatStoreFunc, Stats}; /* AppState * Acts as the single source of truth. All stores are accessible over the AppState. * It get passend to all places where its needed as a reference. It also offers funtions for actions * where access to multiple stores is needed. Besides the stores it also contains flags to * control the application flow. */ #[derive(Serialize)] pub struct Ping { pub fingerprint: String, pub port: u16, pub weight: f32, pub files: Vec<String>, pub rejected_hashes: Vec<String>, pub capacity_left: u64, pub uploaded_hashes: Vec<String>, pub ipv6: Option<String>, } pub struct AppState { pub file_store: RwLock<FileStore>, pub config_store: RwLock<ConfigStore>, pub stat_store: RwLock<StatStore>, pub stop_services: Arc<AtomicBool>, pub force_ping: Arc<AtomicBool>, } impl AppState { pub fn new( config: ConfigFromFile, stats: Stats, own_monitor: Monitor, monitors: Vec<Monitor>, stop_services: Arc<AtomicBool>, force_ping: Arc<AtomicBool>, path: &str, ) -> AppState { let file_store = RwLock::new(FileStore::new(stats.capacity.value, &path)); let config_store = RwLock::new(ConfigStore::new( &config.manager_addr, own_monitor.clone(), monitors, config.port, &config.fingerprint, config.ipv6, )); let stat_store = RwLock::new(StatStore::new(stats, String::from(path))); AppState { file_store, config_store, stat_store, stop_services, force_ping, } } pub fn generate_ping(&self) -> Ping { let config = self.config_store.read().unwrap(); let capacity_left = self.file_store.read().unwrap().capacity_left(); let ping = Ping { fingerprint: config.fingerprint(), port: config.port(), weight: self.calculate_weight(), files: self.file_store.read().unwrap().hashes(), capacity_left, rejected_hashes: self.file_store.read().unwrap().rejected_hashes(), uploaded_hashes: self.file_store.read().unwrap().uploaded_hashes(), ipv6: self.config_store.read().unwrap().ipv6.clone(), }; self.file_store.write().unwrap().clear_uploaded_hashes(); self.file_store.write().unwrap().clear_rejected_hashes(); return ping; } pub fn add_new_file( &self, content: &[u8], content_type: &str, file_name: &str, distribute: bool, ) -> String { let hash = self.config_store.write().unwrap().hash_content(content); // Add file to file_store and disk self.file_store .write() .unwrap() .save_file(&hash, content, content_type, file_name); // Update uploaded_hashes self.file_store .write() .unwrap() .add_hash_to_uploaded_hashes(&hash); // If needed, enqueue hash to distribution if distribute { self.file_store .write() .unwrap() .insert_file_to_distribute(&hash); } // Force ping service to send a new ping to monitor self.force_ping.swap(true, Ordering::Relaxed); return hash; } // Write file_store and stat_store to disk pub fn serialize_state(&self) { self.file_store.read().unwrap().serialize_state(); self.stat_store.read().unwrap().serialize_state(); } fn calculate_weight(&self) -> f32 { let usage = self.file_store.read().unwrap().capacity_left(); self.stat_store.read().unwrap().total_rating(usage) } }
// Copyright (c) 2017 oic developers // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. //! Context handles are the top level handles created by the library and are used for all error //! handling as well as creating pools and standalone connections to the database. The first call to //! ODPI-C by any application must be `create()` which will create the context as well asvalidate //! the version used by the application. use common::{error, version}; use error::{ErrorKind, Result}; use odpi::constants::{DPI_FAILURE, DPI_MAJOR_VERSION, DPI_MINOR_VERSION}; use odpi::externs; use odpi::opaque::ODPIContext; use odpi::structs::{ODPICommonCreateParams, ODPIConnCreateParams, ODPIErrorInfo, ODPIPoolCreateParams, ODPISubscrCreateParams, ODPIVersionInfo}; use slog::Logger; use std::ptr; use util::ODPIStr; pub mod params; use self::params::{CommonCreate, ConnCreate, PoolCreate, SubscrCreate}; /// This structure represents the context in which all activity in the library takes place. pub struct Context { /// A pointer the the ODPI-C dpiContext struct. context: *mut ODPIContext, /// Optional stdout logger. stdout: Option<Logger>, /// Optoinal stderr logger. stderr: Option<Logger>, } impl Context { /// Create a new `Context` struct. pub fn create() -> Result<Context> { let mut ctxt = ptr::null_mut(); let mut err: ODPIErrorInfo = Default::default(); try_dpi!(externs::dpiContext_create(DPI_MAJOR_VERSION, DPI_MINOR_VERSION, &mut ctxt, &mut err), Ok(Context { context: ctxt, stdout: None, stderr: None, }), ErrorKind::Context("dpiContext_create".to_string())) } /// Get the pointer to the inner ODPI struct. #[doc(hidden)] pub fn inner(&self) -> *mut ODPIContext { self.context } /// Return information about the version of the Oracle Client that is being used. pub fn get_client_version(&self) -> Result<version::Info> { let mut version_info: ODPIVersionInfo = Default::default(); try_dpi!(externs::dpiContext_getClientVersion(self.context, &mut version_info), Ok(version_info.into()), ErrorKind::Connection("dpiContext_getClientVersion".to_string())) } /// Returns error information for the last error that was raised by the library. This function /// must be called with the same thread that generated the error. It must also be called before /// any other ODPI-C library calls are made on the calling thread since the error information /// specific to that thread is cleared at the start of every ODPI-C function call. pub fn get_error(&self) -> error::Info { let mut error_info: ODPIErrorInfo = Default::default(); unsafe { externs::dpiContext_getError(self.context, &mut error_info); error_info.into() } } /// Initializes the `CommonCreate` structure to default values. pub fn init_common_create_params(&self) -> Result<CommonCreate> { let mut ccp: ODPICommonCreateParams = Default::default(); try_dpi!(externs::dpiContext_initCommonCreateParams(self.context, &mut ccp), { let driver_name = "Rust Oracle: 0.1.0"; let driver_name_s = ODPIStr::from(driver_name); ccp.driver_name = driver_name_s.ptr(); ccp.driver_name_length = driver_name_s.len(); Ok(CommonCreate::new(ccp)) }, ErrorKind::Context("dpiContext_initCommonCreateParams".to_string())) } /// Initializes the `ConnCreate` structure to default values. pub fn init_conn_create_params(&self) -> Result<ConnCreate> { let mut conn: ODPIConnCreateParams = Default::default(); try_dpi!(externs::dpiContext_initConnCreateParams(self.context, &mut conn), Ok(ConnCreate::new(conn)), ErrorKind::Context("dpiContext_initConnCreateParams".to_string())) } /// Initializes the `PoolCreate` structure to default values. pub fn init_pool_create_params(&self) -> Result<PoolCreate> { let mut pool: ODPIPoolCreateParams = Default::default(); try_dpi!(externs::dpiContext_initPoolCreateParams(self.context, &mut pool), Ok(PoolCreate::new(pool)), ErrorKind::Context("dpiContext_initPoolCreateParams".to_string())) } /// Initializes the `SubscrCreate` struct to default values. pub fn init_subscr_create_params(&self) -> Result<SubscrCreate> { let mut subscr: ODPISubscrCreateParams = Default::default(); try_dpi!(externs::dpiContext_initSubscrCreateParams(self.context, &mut subscr), Ok(SubscrCreate::new(subscr)), ErrorKind::Context("dpiContext_initSubscrCreateParams".to_string())) } } impl Drop for Context { fn drop(&mut self) { if unsafe { externs::dpiContext_destroy(self.context) } == DPI_FAILURE { try_error!(self.stderr, "Failed to destroy context"); } else { try_info!(self.stdout, "Successfully destroyed context"); } } } #[cfg(test)] mod test { use super::Context; use super::params::AppContext; use odpi::{flags, structs}; use odpi::flags::ODPISubscrNamespace::*; use odpi::flags::ODPISubscrProtocol::*; use std::ffi::CString; #[test] fn create() { match Context::create() { Ok(ref mut _ctxt) => assert!(true), Err(_e) => assert!(false), } } #[test] fn init_common_create_params() { match Context::create() { Ok(ref mut ctxt) => { match ctxt.init_common_create_params() { Ok(ref mut ccp) => { let default_flags = ccp.get_create_mode(); let new_flags = default_flags | flags::DPI_MODE_CREATE_THREADED; let enc_cstr = CString::new("UTF-8").expect("badness"); ccp.set_create_mode(new_flags); ccp.set_edition("1.0"); ccp.set_encoding(enc_cstr.as_ptr()); ccp.set_nchar_encoding(enc_cstr.as_ptr()); assert!(ccp.get_create_mode() == flags::DPI_MODE_CREATE_THREADED | flags::DPI_MODE_CREATE_DEFAULT); assert!(ccp.get_encoding() == "UTF-8"); assert!(ccp.get_nchar_encoding() == "UTF-8"); assert!(ccp.get_edition() == "1.0"); assert!(ccp.get_driver_name() == "Rust Oracle: 0.1.0"); } Err(_e) => assert!(false), } } Err(_e) => assert!(false), } } #[test] fn init_conn_create_params() { match Context::create() { Ok(ref mut ctxt) => { match ctxt.init_conn_create_params() { Ok(ref mut conn) => { let auth_default_flags = conn.get_auth_mode(); let auth_new_flags = auth_default_flags | flags::DPI_MODE_AUTH_SYSDBA; let purity_default_flags = conn.get_purity(); let app_ctxt = AppContext::new("ns", "name", "value"); let app_ctxt_1 = AppContext::new("ns", "name1", "value1"); let mut app_ctxt_vec = Vec::new(); app_ctxt_vec.push(app_ctxt); app_ctxt_vec.push(app_ctxt_1); assert!(purity_default_flags == flags::DPI_PURITY_DEFAULT); conn.set_auth_mode(auth_new_flags); conn.set_connection_class("conn_class"); conn.set_purity(flags::DPI_PURITY_NEW); conn.set_new_password("password"); conn.set_app_context(app_ctxt_vec); conn.set_external_auth(1); conn.set_tag("you're it"); conn.set_match_any_tag(true); let new_app_ctxt_vec = conn.get_app_context(); assert!(conn.get_auth_mode() == flags::DPI_MODE_AUTH_SYSDBA | flags::DPI_MODE_AUTH_DEFAULT); assert!(conn.get_connection_class() == "conn_class"); assert!(conn.get_purity() == flags::DPI_PURITY_NEW); assert!(conn.get_new_password() == "password"); assert!(conn.get_num_app_context() == 2); assert!(new_app_ctxt_vec.len() == 2); for (idx, ac) in new_app_ctxt_vec.iter().enumerate() { assert!(ac.get_namespace_name() == "ns"); match idx { 0 => { assert!(ac.get_name() == "name"); assert!(ac.get_value() == "value"); } 1 => { assert!(ac.get_name() == "name1"); assert!(ac.get_value() == "value1"); } _ => assert!(false), } } assert!(conn.get_external_auth() == 1); assert!(conn.get_tag() == "you're it"); assert!(conn.get_match_any_tag()); assert!(conn.get_out_tag() == ""); assert!(!conn.get_out_tag_found()); } Err(_e) => assert!(false), } } Err(_e) => assert!(false), } } #[test] fn init_pool_create_params() { match Context::create() { Ok(ref mut ctxt) => { match ctxt.init_pool_create_params() { Ok(ref mut pcp) => { assert!(pcp.get_min_sessions() == 1); assert!(pcp.get_max_sessions() == 1); assert!(pcp.get_session_increment() == 0); assert!(pcp.get_ping_interval() == 60); assert!(pcp.get_ping_timeout() == 5000); assert!(pcp.get_homogeneous()); assert!(!pcp.get_external_auth()); assert!(pcp.get_get_mode() == flags::ODPIPoolGetMode::NoWait); assert!(pcp.get_out_pool_name() == ""); pcp.set_min_sessions(10); pcp.set_max_sessions(100); pcp.set_session_increment(5); pcp.set_ping_interval(-1); pcp.set_ping_timeout(1000); pcp.set_homogeneous(false); pcp.set_external_auth(true); pcp.set_get_mode(flags::ODPIPoolGetMode::ForceGet); assert!(pcp.get_min_sessions() == 10); assert!(pcp.get_max_sessions() == 100); assert!(pcp.get_session_increment() == 5); assert!(pcp.get_ping_interval() == -1); assert!(pcp.get_ping_timeout() == 1000); assert!(!pcp.get_homogeneous()); assert!(pcp.get_external_auth()); assert!(pcp.get_get_mode() == flags::ODPIPoolGetMode::ForceGet); } Err(_e) => assert!(false), } } Err(_e) => assert!(false), } } extern "C" fn subscr_callback(_context: *mut ::std::os::raw::c_void, _message: *mut structs::ODPISubscrMessage) { // For testing } #[test] fn init_subscr_create_params() { match Context::create() { Ok(ref mut ctxt) => { match ctxt.init_subscr_create_params() { Ok(ref mut scp) => { assert!(scp.get_subscr_namespace() == DbChange); assert!(scp.get_protocol() == Callback); assert!(scp.get_qos() == flags::DPI_SUBSCR_QOS_NONE); assert!(scp.get_operations() == flags::DPI_OPCODE_ALL_OPS); assert!(scp.get_port_number() == 0); assert!(scp.get_timeout() == 0); assert!(scp.get_name() == ""); assert!(scp.get_callback() == None); // TODO: test callback_context assert!(scp.get_recipient_name() == ""); scp.set_protocol(HTTP); scp.set_qos(flags::DPI_SUBSCR_QOS_BEST_EFFORT | flags::DPI_SUBSCR_QOS_ROWIDS); scp.set_operations(flags::DPI_OPCODE_ALTER | flags::DPI_OPCODE_DROP); scp.set_port_number(32276); scp.set_timeout(10000); scp.set_name("subscription"); scp.set_callback(Some(subscr_callback)); scp.set_recipient_name("yoda"); assert!(scp.get_protocol() == HTTP); assert!(scp.get_qos() == flags::DPI_SUBSCR_QOS_BEST_EFFORT | flags::DPI_SUBSCR_QOS_ROWIDS); assert!(scp.get_operations() == flags::DPI_OPCODE_ALTER | flags::DPI_OPCODE_DROP); assert!(scp.get_port_number() == 32276); assert!(scp.get_timeout() == 10000); assert!(scp.get_name() == "subscription"); assert!(scp.get_recipient_name() == "yoda"); assert!(scp.get_callback() == Some(subscr_callback)); } Err(_e) => assert!(false), } } Err(_e) => assert!(false), } } }
/// Service identifier. pub const SERVICE_ID: u16 = 2;
use std::{cell::RefCell, collections::HashMap, env, error::Error, fs, rc::Rc}; use typed_arena::Arena; type Result<T> = std::result::Result<T, Box<dyn Error>>; fn main() -> Result<()> { let code = fs::read_to_string(env::args().nth(1).ok_or("no file")?)? + " $"; run(code)?; Ok(()) } enum Val<'a> { Nil(), Bool(bool), Int(i64), Pair(V<'a>, V<'a>), Symbol(String), Quote(V<'a>), Func(fn(Vec<V<'a>>) -> Result<Val<'a>>), Form(fn(Ctx<'a>, &Rc<Env<'a>>, Vec<V<'a>>) -> Result<V<'a>>), } type V<'a> = &'a Val<'a>; type Ctx<'a> = &'a Arena<Val<'a>>; use Val::*; impl<'a> Val<'a> { fn to_vec(&self) -> Vec<&Val<'a>> { match self { Pair(x, y) => [y.to_vec(), vec![x]].concat(), _ => vec![], } } fn int(&self) -> Result<i64> { match self { Int(x) => Ok(*x), _ => Err("not int".into()), } } } impl<'a> std::fmt::Display for Val<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Nil() => write!(f, "()"), Bool(true) => write!(f, "#t"), Bool(false) => write!(f, "#f"), Int(i) => write!(f, "{}", i), Pair(x, y) => write!(f, "( {} {} )", x, y), Symbol(x) => write!(f, "{}", x), Quote(x) => write!(f, "'{}", x), Func(_) => write!(f, "<func>"), Form(_) => write!(f, "<form>"), } } } fn run(mut code: String) -> Result<()> { let cs = "()'".chars(); cs.for_each(|c| code = code.replace(c, &format!(" {} ", c))); let mut tokens = code.split_whitespace().rev().collect(); let ctx = Arena::new(); { let root = list(&ctx, &mut tokens)?; eval_list(&ctx, &default_env(&ctx), root.to_vec())?; } Ok(()) } fn list<'a>(ctx: Ctx<'a>, tokens: &mut Vec<&str>) -> Result<&'a Val<'a>> { Ok(match tokens.pop().ok_or("empty")? { x if x == ")" || x == "$" => ctx.alloc(Nil()), x => { tokens.push(x); ctx.alloc(Pair(value(ctx, tokens)?.into(), list(ctx, tokens)?.into())) } }) } fn value<'a>(ctx: Ctx<'a>, tokens: &mut Vec<&str>) -> Result<&'a Val<'a>> { Ok(match tokens.pop().ok_or("empty")? { "(" => list(ctx, tokens)?, "#t" => ctx.alloc(Bool(true)), "#f" => ctx.alloc(Bool(false)), "'" => ctx.alloc(Quote(value(ctx, tokens)?)), x => match x.parse::<i64>() { Ok(i) => ctx.alloc(Int(i)), _ => ctx.alloc(Symbol(x.into())), }, }) } fn eval_list<'a>(ctx: Ctx<'a>, e: &Rc<Env<'a>>, v: Vec<&'a Val<'a>>) -> Result<&'a Val<'a>> { let res = v.into_iter().rev().map(|x| eval(ctx, e, x)).last(); res.unwrap_or(Err("empty".into())) } fn eval<'a>(ctx: Ctx<'a>, e: &Rc<Env<'a>>, v: &'a Val<'a>) -> Result<&'a Val<'a>> { Ok(match v { Nil() | Bool(_) | Int(_) => v, Pair(x, y) => match eval(ctx, e, x)? { Func(f) => { let u = y.to_vec().into_iter().map(|v| eval(ctx, e, v)); ctx.alloc(f(u.collect::<Result<_>>()?)?) } Form(f) => f(ctx, e, y.to_vec())?, x => return Err(format!("not func: {}", x).into()), }, Symbol(x) => e.lookup(x)?, Quote(x) => x.clone(), _ => return Err(format!("eval: {}", v).into()), }) } struct Env<'a> { m: RefCell<HashMap<String, &'a Val<'a>>>, next: Option<Rc<Env<'a>>>, } impl<'a> Env<'a> { fn new(next: Option<Rc<Env<'a>>>) -> Rc<Self> { Rc::new(Env { m: HashMap::new().into(), next, }) } fn lookup(&self, s: &str) -> Result<&'a Val<'a>> { match (self.m.borrow().get(s), self.next.as_ref()) { (Some(v), _) => Ok(v), (_, Some(e)) => e.lookup(s), _ => Err(format!("not found: {}", s).into()), } } fn ensure(self: &Rc<Self>, s: &str, v: &'a Val<'a>) -> Rc<Self> { self.m.borrow_mut().insert(s.to_string(), v); self.clone() } fn with_func(self: Rc<Self>, ctx: Ctx<'a>, s: &str, f: fn(Vec<V>) -> Result<Val>) -> Rc<Self> { self.ensure(s, ctx.alloc(Func(f))) } } fn default_env<'a>(ctx: Ctx<'a>) -> Rc<Env<'a>> { Env::new(None) .with_func(ctx, "print", |v| { print!("{}", v[0]); Ok(Nil()) }) .ensure("begin", ctx.alloc(Form(|ctx, e, v| eval_list(ctx, e, v)))) }
const MEM_LEN: usize = 165; static STARTING_MEM: [i32; MEM_LEN] = [ 1,12,2,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,1,9,19,23,1,13,23,27,1,5,27,31,2,31,6,35,1,35,5,39,1,9,39,43,1,43,5,47,1,47,5,51,2,10,51,55,1,5,55,59,1,59,5,63,2,63,9,67,1,67,5,71,2,9,71,75,1,75,5,79,1,10,79,83,1,83,10,87,1,10,87,91,1,6,91,95,2,95,6,99,2,99,9,103,1,103,6,107,1,13,107,111,1,13,111,115,2,115,9,119,1,119,6,123,2,9,123,127,1,127,5,131,1,131,5,135,1,135,5,139,2,10,139,143,2,143,10,147,1,147,5,151,1,151,2,155,1,155,13,0,99,2,14,0,0 ]; const ADD:i32 = 1; const MUL:i32 = 2; fn cycle(mem: &mut [i32; MEM_LEN], pc: usize) -> usize { let inst = mem[pc]; let p1 = mem[mem[pc+1] as usize]; let p2 = mem[mem[pc+2] as usize]; match inst { ADD => { mem[mem[pc+3] as usize] = p1 + p2; return 4; }, MUL => { mem[mem[pc+3] as usize] = p1 * p2; return 4; }, _ => return 0, } } fn attempt_sentence(noun: i32, verb: i32) -> i32 { let mut mem = STARTING_MEM.clone(); mem[1] = noun; mem[2] = verb; let mut advance = 4; let mut pc = 0; while advance != 0 { advance = cycle(&mut mem, pc); pc += advance; } return mem[0]; } fn main() { let upper = 85; 'outer: for i in 0..upper { for j in 0..upper { if attempt_sentence(i, j) == 19690720 { println!("Correct result found with noun {} and verb {}", i, j); break 'outer; } } } }
pub fn race(v1: i32, v2: i32, g: i32) -> Option<Vec<i32>> { if v1 >= v2 { None } else { let d = (3600 * g) / (v2 - v1); println!("{:?}", vec![d / 3600, d / 60 % 60, d % 60]); Some(vec![d / 3600, d / 60 % 60, d % 60]) } }
use std::iter::FromIterator; #[derive(Debug, Clone)] struct Node<T> { data: T, next: Option<Box<Node<T>>>, } pub struct SimpleLinkedList<T> { head: Option<Box<Node<T>>> } impl<T> SimpleLinkedList<T> where T: PartialOrd + Clone { pub fn new() -> Self { SimpleLinkedList { head: None } } pub fn len(&self) -> usize { let mut length = 0; let mut head = self.head.as_ref(); while let Some(node) = head { length += 1; head = node.next.as_ref(); }; length as usize } pub fn push(&mut self, _element: T) { let head = self.head.take(); self.head = Some(Box::new(Node { data: _element, next: head })); } pub fn pop(&mut self) -> Option<T> { self.head.take().map(|node| { self.head = node.next; node.data }) } pub fn peek(&self) -> Option<&T> { self.head.as_ref().and_then(|node| { Some(&node.data) }) } pub fn rev(self) -> SimpleLinkedList<T> { let mut head = self.head.as_ref(); let mut rev_list = SimpleLinkedList::new(); while let Some(node) = head { let _element_data = node.data.clone(); rev_list.push(_element_data); head = node.next.as_ref(); }; rev_list } } impl<T> FromIterator<T> for SimpleLinkedList<T> where T: PartialOrd + Clone { fn from_iter<I: IntoIterator<Item = T>>(_iter: I) -> Self { let mut list = SimpleLinkedList::new(); for i in _iter { list.push(i); } list } } // In general, it would be preferable to implement IntoIterator for SimpleLinkedList<T> // instead of implementing an explicit conversion to a vector. This is because, together, // FromIterator and IntoIterator enable conversion between arbitrary collections. // Given that implementation, converting to a vector is trivial: // // let vec: Vec<_> = simple_linked_list.into_iter().collect(); // // The reason this exercise's API includes an explicit conversion to Vec<T> instead // of IntoIterator is that implementing that interface is fairly complicated, and // demands more of the student than we expect at this point in the track. impl<T> Into<Vec<T>> for SimpleLinkedList<T> where T: PartialOrd + Clone { fn into(self) -> Vec<T> { let mut vector = Vec::new(); let mut head = self.head.as_ref(); while let Some(node) = head { vector.push(node.data.clone()); head = node.next.as_ref(); }; vector.reverse(); vector } }
use azure_core::prelude::*; use azure_storage::blob::prelude::*; use azure_storage::core::prelude::*; use chrono::{Duration, Utc}; use std::error::Error; fn main() { env_logger::init(); code().unwrap(); } fn code() -> Result<(), Box<dyn Error + Sync + Send>> { // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let container_name = std::env::args() .nth(1) .expect("please specify container name as command line parameter"); let blob_name = std::env::args() .nth(2) .expect("please specify blob name as command line parameter"); // allow for some time skew let now = Utc::now() - Duration::minutes(15); let later = now + Duration::hours(1); let http_client = new_http_client(); let storage_account_client = StorageAccountClient::new_access_key(http_client.clone(), &account, &master_key); let container_client = storage_account_client .as_storage_client() .as_container_client(&container_name); let blob_client = container_client.as_blob_client(&blob_name); let sas = storage_account_client .shared_access_signature()? .with_resource(AccountSasResource::Blob) .with_resource_type(AccountSasResourceType::Object) .with_start(now) .with_expiry(later) .with_permissions(AccountSasPermissions { read: true, ..Default::default() }) .with_protocol(SasProtocol::Https) .finalize(); println!("blob account level token: '{}'", sas.token()); let url = blob_client.generate_signed_blob_url(&sas)?; println!("blob account level url: '{}'", url); let sas = blob_client .shared_access_signature()? .with_expiry(later) .with_start(now) .with_permissions(BlobSasPermissions { write: true, ..Default::default() }) .finalize(); println!("blob service token: {}", sas.token()); let url = blob_client.generate_signed_blob_url(&sas)?; println!("blob service level url: '{}'", url); let sas = container_client .shared_access_signature()? .with_expiry(later) .with_start(now) .with_permissions(BlobSasPermissions { read: true, list: true, write: true, ..Default::default() }) .with_protocol(SasProtocol::HttpHttps) .finalize(); println!("container sas token: {}", sas.token()); let url = container_client.generate_signed_container_url(&sas)?; println!("container level url: '{}'", url); Ok(()) }
#[doc = "Register `DMADSR` reader"] pub type R = crate::R<DMADSR_SPEC>; #[doc = "Register `DMADSR` writer"] pub type W = crate::W<DMADSR_SPEC>; #[doc = "Field `AXWHSTS` reader - AHB Master Write Channel"] pub type AXWHSTS_R = crate::BitReader; #[doc = "Field `AXWHSTS` writer - AHB Master Write Channel"] pub type AXWHSTS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RPS0` reader - DMA Channel Receive Process State"] pub type RPS0_R = crate::FieldReader; #[doc = "Field `RPS0` writer - DMA Channel Receive Process State"] pub type RPS0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `TPS0` reader - DMA Channel Transmit Process State"] pub type TPS0_R = crate::FieldReader; #[doc = "Field `TPS0` writer - DMA Channel Transmit Process State"] pub type TPS0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; impl R { #[doc = "Bit 0 - AHB Master Write Channel"] #[inline(always)] pub fn axwhsts(&self) -> AXWHSTS_R { AXWHSTS_R::new((self.bits & 1) != 0) } #[doc = "Bits 8:11 - DMA Channel Receive Process State"] #[inline(always)] pub fn rps0(&self) -> RPS0_R { RPS0_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - DMA Channel Transmit Process State"] #[inline(always)] pub fn tps0(&self) -> TPS0_R { TPS0_R::new(((self.bits >> 12) & 0x0f) as u8) } } impl W { #[doc = "Bit 0 - AHB Master Write Channel"] #[inline(always)] #[must_use] pub fn axwhsts(&mut self) -> AXWHSTS_W<DMADSR_SPEC, 0> { AXWHSTS_W::new(self) } #[doc = "Bits 8:11 - DMA Channel Receive Process State"] #[inline(always)] #[must_use] pub fn rps0(&mut self) -> RPS0_W<DMADSR_SPEC, 8> { RPS0_W::new(self) } #[doc = "Bits 12:15 - DMA Channel Transmit Process State"] #[inline(always)] #[must_use] pub fn tps0(&mut self) -> TPS0_W<DMADSR_SPEC, 12> { TPS0_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 = "Debug status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dmadsr::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 [`dmadsr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DMADSR_SPEC; impl crate::RegisterSpec for DMADSR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`dmadsr::R`](R) reader structure"] impl crate::Readable for DMADSR_SPEC {} #[doc = "`write(|w| ..)` method takes [`dmadsr::W`](W) writer structure"] impl crate::Writable for DMADSR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets DMADSR to value 0"] impl crate::Resettable for DMADSR_SPEC { const RESET_VALUE: Self::Ux = 0; }
fn main() { let mut prod = 1; for num in (2..21) { //let oldprod = prod; //println!("{}, {}, {}", oldprod, num, gcd(oldprod, num)); prod = prod * num / gcd(prod, num); } println!("LCM is: {}", prod); } fn gcd(num1:u64, num2:u64) -> u64 { if num2 == 0 { return num1; } else { let num3 = num1 % num2; return gcd(num2, num3); } }
#![feature(advanced_slice_patterns, slice_patterns)] extern crate sexp; mod phym; use std::env; /*----------------------------------------------------------------------------*/ /* main */ /*----------------------------------------------------------------------------*/ fn main() { let args: Vec<_> = env::args().collect(); if args.len() > 1 { println!("{:?}",phym::top_interp(args[1].as_str())) } else { let sexp = sexp::parse("(+ 1 2)").unwrap(); println!("{:?}",phym::top_interp("(+ 1 2)")) } }
use app_dirs::{app_dir, AppDataType, AppInfo}; use std::env; use std::path::PathBuf; const ATA_PATH_NAME: &'static str = "ATADB_PATH"; const APP_INFO: AppInfo = AppInfo { name: "atadb", author: "atadb", }; pub fn locate_on_db_path(dbname: String) -> Option<PathBuf> { let mut paths: Vec<PathBuf> = Vec::new(); match env::var_os(ATA_PATH_NAME) { Some(value) => { for path in env::split_paths(&value) { if !path.exists() { paths.push(path); } else { warn!( "Directory \"{}\" was found in environment {}, but it cannot be found.", path.display(), ATA_PATH_NAME ); } } } None => (), }; // TODO @mverleg: change this to something like ~/.local/share/atadb match env::home_dir() { Some(path) => paths.push(path.join(".atadb").join("dbs")), None => (), } // APP_INFO todo match app_dir(AppDataType::UserData, &APP_INFO, "dbs") { Ok(path) => paths.push(path), Err(err) => warn!("Could not create app data directory ({:?})", err), } let mut found: Option<PathBuf> = None; for path in paths { let dbpath = path.join(&dbname).with_extension(".atadb"); if dbpath.exists() { if let Some(prev) = &found { warn!( "Found database {} at \"{}\", but another one was found at \"{}\"", dbname, dbpath.display(), prev.display() ); continue; } found = Some(dbpath); } else { debug!("Searching for {} at \"{}\"", dbname, dbpath.display()); } } found }
#![feature(proc_macro)] extern crate gobject_gen; extern crate gobject_sys; #[macro_use] extern crate glib; extern crate glib_sys; extern crate libc; use gobject_gen::gobject_gen; use std::cell::Cell; use std::ffi::CStr; use std::mem; use std::slice; use glib::object::*; use glib::translate::*; gobject_gen! { class Signaler { val: Cell<u32>, } impl Signaler { signal fn value_changed(&self); signal fn value_changed_to(&self, v: u32); signal fn gimme_an_int(&self) -> u32; pub fn set_value(&self, v: u32) { let private = self.get_priv(); private.val.set(v); self.emit_value_changed(); self.emit_value_changed_to(v); } pub fn get_value(&self) -> u32 { let private = self.get_priv(); private.val.get() } pub fn call_emit_gimme_an_int(&self) -> u32 { self.emit_gimme_an_int() } } } #[cfg(test)] fn check_signal( query: &gobject_sys::GSignalQuery, obj_type: glib_sys::GType, signal_id: libc::c_uint, signal_name: &str, ) { assert_eq!(query.itype, obj_type); assert_eq!(query.signal_id, signal_id); let name = unsafe { CStr::from_ptr(query.signal_name) }; assert_eq!(name.to_str().unwrap(), signal_name); } #[test] fn has_signals() { let obj = Signaler::new(); let obj_type = obj.get_type().to_glib(); unsafe { let mut n_ids: libc::c_uint = 0; let raw_signal_ids = gobject_sys::g_signal_list_ids(obj_type, &mut n_ids); assert_eq!(n_ids, 3); let n_ids = n_ids as usize; let signal_ids = slice::from_raw_parts(raw_signal_ids, n_ids); // value-changed let mut query: gobject_sys::GSignalQuery = mem::zeroed(); gobject_sys::g_signal_query(signal_ids[0], &mut query); check_signal(&query, obj_type, signal_ids[0], "value-changed"); assert_eq!(query.n_params, 0); assert!(query.param_types.is_null()); assert_eq!(query.return_type, gobject_sys::G_TYPE_NONE); // value-changed-to let mut query: gobject_sys::GSignalQuery = mem::zeroed(); gobject_sys::g_signal_query(signal_ids[1], &mut query); check_signal(&query, obj_type, signal_ids[1], "value-changed-to"); assert_eq!(query.n_params, 1); assert!(!query.param_types.is_null()); let param_types = slice::from_raw_parts(query.param_types, query.n_params as usize); assert_eq!(param_types[0], gobject_sys::G_TYPE_UINT); assert_eq!(query.return_type, gobject_sys::G_TYPE_NONE); // gimme-an-int let mut query: gobject_sys::GSignalQuery = mem::zeroed(); gobject_sys::g_signal_query(signal_ids[2], &mut query); check_signal(&query, obj_type, signal_ids[2], "gimme-an-int"); assert_eq!(query.n_params, 0); assert!(query.param_types.is_null()); assert_eq!(query.return_type, gobject_sys::G_TYPE_UINT); } } #[test] fn connects_to_signal() { let obj = Signaler::new(); static mut EMITTED: bool = false; let _id: glib::SignalHandlerId = obj.connect_value_changed(|_| unsafe { EMITTED = true; }); obj.set_value(42); unsafe { assert!(EMITTED); } } #[test] fn connects_to_signal_with_arg() { let obj = Signaler::new(); static mut EMITTED: bool = false; let _id: glib::SignalHandlerId = obj.connect_value_changed_to(|_, v| { assert_eq!(v, 42); unsafe { EMITTED = true; } }); obj.set_value(42); unsafe { assert!(EMITTED); } } #[test] fn connects_to_signal_with_return_value() { let obj = Signaler::new(); obj.connect_gimme_an_int(|_| 42); let ret = obj.call_emit_gimme_an_int(); assert_eq!(ret, 42); }
/*--------------------------------------------------------------------------------------------- * Copyright © 2016-present Earth Computing Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // FIXME: should be a 'synch' operation for two events (i.e. happens before) use std::collections::HashMap; // use std::collections::hash_map::Entry; use std::fmt; use std::sync::{Mutex}; use std::thread; use std::thread::ThreadId; use lazy_static::lazy_static; use serde_json; use serde_json::{Value}; use time; use failure::{Error}; pub fn parse(thread_id: ThreadId) -> u64 { let s = format!("{:?}", thread_id); // looks like : "ThreadId(8)" let r: Vec<&str> = s.split('(').collect(); let parts: Vec<&str> = r[1].split(')').collect(); parts[0].parse().expect(&format!("Problem parsing ThreadId {}", s)) } pub fn timestamp() -> u64 { let timespec = time::get_time(); let t = timespec.sec as f64 + (timespec.nsec as f64/1000./1000./1000.); (t*1000.0*1000.0) as u64 } // -- lazy_static! { static ref EMITTERS: Mutex<HashMap<u64, EventGenerator>> = { let m = Mutex::new(HashMap::new()); m }; } pub fn debug(code: &CodeAttributes, body: &Value) -> Result<(String, String), Error> { under_lock(TraceType::Debug, code, body) } pub fn trace(code: &CodeAttributes, body: &Value) -> Result<(String, String), Error> { under_lock(TraceType::Trace, code, body) } // modifies 'clock' in place fn under_lock(level: TraceType, code: &CodeAttributes, body: &Value) -> Result<(String, String), Error> { let tid = thread::current().id(); let thread_id = parse(tid); let mut locked_map = EMITTERS.lock().unwrap(); let v = locked_map.get_mut(&thread_id).unwrap(); v.build_entry(level, code, body) } // updates 'clock', clones current setting pub fn pregnant() -> EventGenerator { let tid = thread::current().id(); let thread_id = parse(tid); let mut locked_map = EMITTERS.lock().unwrap(); let v = locked_map.get_mut(&thread_id).unwrap(); let mark = v.bump(); let mut event_id = mark.event_id.clone(); event_id.push(0); EventGenerator { thread_id: mark.thread_id, event_id: event_id, epoch: mark.epoch } } pub fn grandfather() { let mut e = EventGenerator::new(); e.stash(); } // -- #[derive(Debug, Copy, Clone, Serialize)] enum TraceType { Trace, Debug, } impl fmt::Display for TraceType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Trace type {}", match self { &TraceType::Trace => "Trace", &TraceType::Debug => "Debug" }) } } // -- #[derive(Debug, Clone, Serialize)] pub struct CodeAttributes { pub module: &'static str, pub function: &'static str, pub line_no: u32, pub format: &'static str } impl CodeAttributes { pub fn get_module(&self) -> &'static str { self.module } pub fn get_function(&self) -> &'static str { self.function } pub fn get_line_no(&self) -> u32 { self.line_no } pub fn get_format(&self) -> &'static str { self.format } } // -- #[derive(Debug, Clone, Serialize)] pub struct EventGenerator { thread_id: u64, event_id: Vec<u64>, epoch: u64 } impl EventGenerator { pub fn new() -> EventGenerator { let tid = thread::current().id(); let thread_id = parse(tid); let now = timestamp(); let event_id = vec![0]; EventGenerator { thread_id: thread_id, event_id: event_id, epoch: now, } } // monotonically increasing fn bump(&mut self) -> EventGenerator { let last = self.event_id.len() - 1; self.event_id[last] += 1; let now = timestamp(); self.epoch = now; self.clone() } // creates a new thread 'clock' (epoch is parent's value) pub fn stash(&mut self) { let tid = thread::current().id(); let thread_id = parse(tid); self.thread_id = thread_id; let mut locked_map = EMITTERS.lock().unwrap(); locked_map.insert(thread_id, self.clone()); } fn build_entry(&mut self, level: TraceType, code: &CodeAttributes, body: &Value) -> Result<(String, String), Error> { let mark = self.bump(); let record = TraceRecord { header: &mark, level: &level, code: code, body: body }; let doc = serde_json::to_string(&record)?; let key = format!("{:?}", &mark); Ok((key, doc)) } } impl fmt::Display for EventGenerator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Thread id {}, Event id {:?} epoch {}", self.thread_id, self.event_id, self.epoch) } } // -- #[derive(Debug, Clone, Serialize)] struct TraceRecord<'a> { header: &'a EventGenerator, level: &'a TraceType, code: &'a CodeAttributes, body: &'a Value }
use mongodb::{Client, Database , options:: {ClientOptions, StreamAddress} }; use rocket::request::{self, FromRequest}; use rocket::{Outcome, Request, State}; use std::env; use std::ops::Deref; pub struct Conn(pub Database); pub fn init() -> Database { let host = env::var("MONGO_HOST").expect("MONGO_HOST env not set."); // TODO check if this is shit for performance let port = env::var("MONGO_PORT").expect("MONGO_PORT env not set."); // TODO check if this is shit for performance let db_name = env::var("MONGO_DB_NAME").expect("MONGO_DB_NAME env not set."); // TODO check if this is shit for performance let options = ClientOptions::builder() .hosts(vec![ StreamAddress { hostname: host, port: Some(port.parse::<u16>().unwrap()), } ]) .build(); match Client::with_options(options) { Ok(client) => client.database(&db_name), Err(e) => panic!("Error: failed to connect to mongodb {}", e), } } /* Create a implementation of FromRequest so Conn can be provided at every api endpoint */ impl<'a, 'r> FromRequest<'a, 'r> for Conn { type Error = (); fn from_request(request: &'a Request<'r>) -> request::Outcome<Conn, ()> { let database = request.guard::<State<Database>>()?; let clone = database.clone(); Outcome::Success(Conn(clone)) } } /* When Conn is dereferencd, return the mongo connection. */ impl Deref for Conn { type Target = Database; fn deref(&self) -> &Self::Target { &self.0 } }
// Copyright (C) 2021 Subspace Labs, Inc. // SPDX-License-Identifier: Apache-2.0 // 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. //! Pallet for issuing rewards to block producers. #![cfg_attr(not(feature = "std"), no_std)] #![forbid(unsafe_code)] #![warn(rust_2018_idioms, missing_debug_implementations)] mod default_weights; use frame_support::traits::{Currency, Get}; use frame_support::weights::Weight; pub use pallet::*; use subspace_runtime_primitives::{FindBlockRewardAddress, FindVotingRewardAddresses}; pub trait WeightInfo { fn on_initialize() -> Weight; } /// Hooks to notify when there are any rewards for specific account. pub trait OnReward<AccountId, Balance> { fn on_reward(account: AccountId, reward: Balance); } impl<AccountId, Balance> OnReward<AccountId, Balance> for () { fn on_reward(_account: AccountId, _reward: Balance) {} } #[frame_support::pallet] mod pallet { use super::{OnReward, WeightInfo}; use frame_support::pallet_prelude::*; use frame_support::traits::Currency; use frame_system::pallet_prelude::*; use subspace_runtime_primitives::{FindBlockRewardAddress, FindVotingRewardAddresses}; type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance; /// Pallet rewards for issuing rewards to block producers. #[pallet::pallet] pub struct Pallet<T>(_); #[pallet::config] pub trait Config: frame_system::Config { /// `pallet-rewards` events type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>; type Currency: Currency<Self::AccountId>; /// Fixed reward for block producer. #[pallet::constant] type BlockReward: Get<BalanceOf<Self>>; /// Fixed reward for voter. #[pallet::constant] type VoteReward: Get<BalanceOf<Self>>; type FindBlockRewardAddress: FindBlockRewardAddress<Self::AccountId>; type FindVotingRewardAddresses: FindVotingRewardAddresses<Self::AccountId>; type WeightInfo: WeightInfo; type OnReward: OnReward<Self::AccountId, BalanceOf<Self>>; } /// `pallet-rewards` events #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { /// Issued reward for the block author. BlockReward { block_author: T::AccountId, reward: BalanceOf<T>, }, /// Issued reward for the voter. VoteReward { voter: T::AccountId, reward: BalanceOf<T>, }, } #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { fn on_initialize(block_number: BlockNumberFor<T>) -> Weight { Self::do_initialize(block_number); T::WeightInfo::on_initialize() } fn on_finalize(now: BlockNumberFor<T>) { Self::do_finalize(now); } } } impl<T: Config> Pallet<T> { fn do_initialize(_block_number: T::BlockNumber) { // Block author may equivocate, in which case they'll not be present here if let Some(block_author) = T::FindBlockRewardAddress::find_block_reward_address() { let reward = T::BlockReward::get(); T::Currency::deposit_creating(&block_author, reward); T::OnReward::on_reward(block_author.clone(), reward); Self::deposit_event(Event::BlockReward { block_author, reward, }); } } fn do_finalize(_block_number: T::BlockNumber) { let reward = T::VoteReward::get(); for voter in T::FindVotingRewardAddresses::find_voting_reward_addresses() { T::Currency::deposit_creating(&voter, reward); T::OnReward::on_reward(voter.clone(), reward); Self::deposit_event(Event::VoteReward { voter, reward }); } } }
use crate::common::*; use anyhow::Result; use chrono::serde::ts_seconds; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_aux::prelude::*; use std::str; #[derive(Serialize, Deserialize, Debug)] pub struct Friend { #[serde(deserialize_with = "deserialize_number_from_string")] pub steamid: SteamId, pub relationship: Relationship, #[serde(with = "ts_seconds")] pub friend_since: DateTime<Utc>, } #[derive(Serialize, Deserialize, Debug)] pub enum Relationship { #[serde(rename = "friend")] Friend, } #[derive(Serialize, Deserialize, Debug)] struct FriendList { friends: Vec<Friend>, } #[derive(Serialize, Deserialize, Debug)] struct FriendListResponse { friendslist: FriendList, } pub struct Response { pub friends: Vec<Friend>, } impl Response { pub fn from(data: &[u8]) -> Result<Self> { let j: FriendListResponse = serde_json::from_slice(&data)?; Ok(Response { friends: j.friendslist.friends, }) } }
use bindgen::{ callbacks::{EnumVariantValue, ParseCallbacks}, Builder, CargoCallbacks, }; use std::{env, path::PathBuf, process::Command}; #[derive(Debug)] struct CustomPrefixCallbacks; impl ParseCallbacks for CustomPrefixCallbacks { fn enum_variant_name( &self, _enum_name: Option<&str>, original_variant_name: &str, _variant_value: EnumVariantValue, ) -> Option<String> { Some(String::from("__") + original_variant_name) } fn include_file(&self, filename: &str) { CargoCallbacks::include_file(&CargoCallbacks, filename) } } fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let path = PathBuf::from(out_dir); cc::Build::new() .file("src/cpuid_loop.S") .compile("cpuid_loop"); Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_consts_x64_generated.rs")) .status() .unwrap(); Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_consts_x86_generated.rs")) .status() .unwrap(); Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_const_asserts_x86_generated.rs")) .status() .unwrap(); Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_const_asserts_x64_generated.rs")) .status() .unwrap(); // These are typically not needed. Uncomment and use when necessary e.g. there are new syscalls /* Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_consts_trait_generated.rs")) .status() .unwrap(); Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_consts_trait_impl_x86_generated.rs")) .status() .unwrap(); Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_consts_trait_impl_x64_generated.rs")) .status() .unwrap(); */ Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_name_arch_x64_generated.rs")) .status() .unwrap(); Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_name_arch_x86_generated.rs")) .status() .unwrap(); Command::new("scripts/generate_syscalls.py") .arg(path.join("syscall_helper_functions_generated.rs")) .status() .unwrap(); Command::new("scripts/generate_syscalls.py") .arg(path.join("check_syscall_numbers_generated.rs")) .status() .unwrap(); println!("cargo:rerun-if-changed=scripts/generate_syscalls.py"); println!("cargo:rerun-if-changed=scripts/syscalls.py"); let signal_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .header("bindgen/signal_wrapper.h") .derive_default(true) .generate() .unwrap(); signal_bindings .write_to_file(path.join("signal_bindings_generated.rs")) .unwrap(); let audit_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .header("bindgen/audit_wrapper.h") .derive_default(true) .generate() .unwrap(); audit_bindings .write_to_file(path.join("audit_bindings_generated.rs")) .unwrap(); let ptrace_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .prepend_enum_name(false) .header("bindgen/ptrace_wrapper.h") .generate() .unwrap(); ptrace_bindings .write_to_file(path.join("ptrace_bindings_generated.rs")) .unwrap(); let perf_event_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .derive_default(true) .prepend_enum_name(false) // Workaround for "error[E0587]: type has conflicting packed and align representation hints" // We don't need these types so just omit them. .blacklist_type("perf_event_mmap_page") .blacklist_type("perf_event_mmap_page__bindgen_ty_1__bindgen_ty_1") .blacklist_type("perf_event_mmap_page__bindgen_ty_1") .header("bindgen/perf_event_wrapper.h") .generate() .unwrap(); perf_event_bindings .write_to_file(path.join("perf_event_bindings_generated.rs")) .unwrap(); let fcntl_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .prepend_enum_name(false) .header("bindgen/fcntl_wrapper.h") .generate() .unwrap(); fcntl_bindings .write_to_file(path.join("fcntl_bindings_generated.rs")) .unwrap(); let sysexits_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .prepend_enum_name(false) .header("bindgen/sysexits_wrapper.h") .generate() .unwrap(); sysexits_bindings .write_to_file(path.join("sysexits_bindings_generated.rs")) .unwrap(); let prctl_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .prepend_enum_name(false) .header("bindgen/prctl_wrapper.h") .generate() .unwrap(); prctl_bindings .write_to_file(path.join("prctl_bindings_generated.rs")) .unwrap(); let kernel_abi_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .derive_default(true) .prepend_enum_name(false) .header("bindgen/kernel_wrapper.h") .generate() .unwrap(); kernel_abi_bindings .write_to_file(path.join("kernel_bindings_generated.rs")) .unwrap(); let gdb_register_bindings = Builder::default() .parse_callbacks(Box::new(CustomPrefixCallbacks)) .prepend_enum_name(false) .header("bindgen/gdb_register_wrapper.h") .generate() .unwrap(); gdb_register_bindings .write_to_file(path.join("gdb_register_bindings_generated.rs")) .unwrap(); let gdb_request_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .prepend_enum_name(false) .header("bindgen/gdb_request_wrapper.h") .generate() .unwrap(); gdb_request_bindings .write_to_file(path.join("gdb_request_bindings_generated.rs")) .unwrap(); let kernel_supplement_bindings = Builder::default() .parse_callbacks(Box::new(CargoCallbacks)) .derive_default(true) .prepend_enum_name(false) .header("bindgen/kernel_supplement_wrapper.h") .generate() .unwrap(); kernel_supplement_bindings .write_to_file(path.join("kernel_supplement_bindings_generated.rs")) .unwrap(); capnpc::CompilerCommand::new() .file("schema/trace.capnp") .run() .unwrap(); }
//! AES related functionality. // TODO: Similarly optimized version for aarch64 #[cfg(target_arch = "x86_64")] mod x86_64; extern crate alloc; use aes::cipher::generic_array::GenericArray; use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit}; use aes::Aes128; use alloc::vec::Vec; use subspace_core_primitives::{PotBytes, PotCheckpoint, PotKey, PotSeed}; /// Creates the AES based proof. pub(crate) fn create( seed: &PotSeed, key: &PotKey, num_checkpoints: u8, checkpoint_iterations: u32, ) -> Vec<PotCheckpoint> { #[cfg(target_arch = "x86_64")] { let checkpoints = unsafe { x86_64::create( seed.as_ref(), key.as_ref(), num_checkpoints, checkpoint_iterations, ) }; checkpoints.into_iter().map(PotCheckpoint::from).collect() } #[cfg(not(target_arch = "x86_64"))] create_generic(seed, key, num_checkpoints, checkpoint_iterations) } #[cfg(any(not(target_arch = "x86_64"), test))] fn create_generic( seed: &PotSeed, key: &PotKey, num_checkpoints: u8, checkpoint_iterations: u32, ) -> Vec<PotCheckpoint> { let key = GenericArray::from(PotBytes::from(*key)); let cipher = Aes128::new(&key); let mut cur_block = GenericArray::from(PotBytes::from(*seed)); let mut checkpoints = Vec::with_capacity(usize::from(num_checkpoints)); for _ in 0..num_checkpoints { for _ in 0..checkpoint_iterations { // Encrypt in place to produce the next block. cipher.encrypt_block(&mut cur_block); } checkpoints.push(PotCheckpoint::from(PotBytes::from(cur_block))); } checkpoints } /// Verifies the AES based proof sequentially. /// /// Panics if `checkpoint_iterations` is not a multiple of `2`. pub(crate) fn verify_sequential( seed: &PotSeed, key: &PotKey, checkpoints: &[PotCheckpoint], checkpoint_iterations: u32, ) -> bool { assert_eq!(checkpoint_iterations % 2, 0); let key = GenericArray::from(PotBytes::from(*key)); let cipher = Aes128::new(&key); let mut inputs = Vec::with_capacity(checkpoints.len()); inputs.push(GenericArray::from(PotBytes::from(*seed))); for checkpoint in checkpoints.iter().rev().skip(1).rev() { inputs.push(GenericArray::from(PotBytes::from(*checkpoint))); } let mut outputs = checkpoints .iter() .map(|checkpoint| GenericArray::from(PotBytes::from(*checkpoint))) .collect::<Vec<_>>(); for _ in 0..checkpoint_iterations / 2 { cipher.encrypt_blocks(&mut inputs); cipher.decrypt_blocks(&mut outputs); } inputs == outputs } #[cfg(test)] mod tests { use super::*; use subspace_core_primitives::{PotCheckpoint, PotKey, PotSeed}; const SEED: [u8; 16] = [ 0xd6, 0x66, 0xcc, 0xd8, 0xd5, 0x93, 0xc2, 0x3d, 0xa8, 0xdb, 0x6b, 0x5b, 0x14, 0x13, 0xb1, 0x3a, ]; const SEED_1: [u8; 16] = [ 0xd7, 0xd6, 0xdc, 0xd8, 0xd5, 0x93, 0xc2, 0x3d, 0xa8, 0xdb, 0x6b, 0x5b, 0x14, 0x13, 0xb1, 0x3a, ]; const KEY: [u8; 16] = [ 0x9a, 0x84, 0x94, 0x0f, 0xfe, 0xf5, 0xb0, 0xd7, 0x01, 0x99, 0xfc, 0x67, 0xf4, 0x6e, 0xa2, 0x7a, ]; const KEY_1: [u8; 16] = [ 0x9b, 0x8b, 0x9b, 0x0f, 0xfe, 0xf5, 0xb0, 0xd7, 0x01, 0x99, 0xfc, 0x67, 0xf4, 0x6e, 0xa2, 0x7a, ]; const BAD_CIPHER: [u8; 16] = [22; 16]; #[test] fn test_create_verify() { let seed = PotSeed::from(SEED); let key = PotKey::from(KEY); let num_checkpoints = 10; let checkpoint_iterations = 100; // Can encrypt/decrypt. let checkpoints = create(&seed, &key, num_checkpoints, checkpoint_iterations); #[cfg(target_arch = "x86_64")] { let generic_checkpoints = create_generic(&seed, &key, num_checkpoints, checkpoint_iterations); assert_eq!(checkpoints, generic_checkpoints); } assert_eq!(checkpoints.len(), num_checkpoints as usize); assert!(verify_sequential( &seed, &key, &checkpoints, checkpoint_iterations )); // Decryption of invalid cipher text fails. let mut checkpoints_1 = checkpoints.clone(); checkpoints_1[0] = PotCheckpoint::from(BAD_CIPHER); assert!(!verify_sequential( &seed, &key, &checkpoints_1, checkpoint_iterations )); // Decryption with wrong number of iterations fails. assert!(!verify_sequential( &seed, &key, &checkpoints, checkpoint_iterations + 2 )); assert!(!verify_sequential( &seed, &key, &checkpoints, checkpoint_iterations - 2 )); // Decryption with wrong seed fails. assert!(!verify_sequential( &PotSeed::from(SEED_1), &key, &checkpoints, checkpoint_iterations )); // Decryption with wrong key fails. assert!(!verify_sequential( &seed, &PotKey::from(KEY_1), &checkpoints, checkpoint_iterations )); } }
use jsonrpc_pubsub::typed::{Sink, Subscriber}; use jsonrpc_pubsub::SubscriptionId; use std::collections::HashMap; use std::ops; pub struct Subscribers<T> { id: u64, subscriptions: HashMap<SubscriptionId, T>, } impl<T> Default for Subscribers<T> { fn default() -> Self { Self { id: 0, subscriptions: HashMap::new(), } } } impl<T> Subscribers<T> { fn next_id(&mut self) -> u64 { let id = self.id; self.id += 1; id } pub fn get(&mut self, id: &SubscriptionId) -> Option<&T> { self.subscriptions.get(id) } pub fn remove(&mut self, id: &SubscriptionId) -> Option<T> { self.subscriptions.remove(id) } } impl<T> Subscribers<Sink<T>> { pub fn add(&mut self, subscriber: Subscriber<T>) -> Option<SubscriptionId> { let id = SubscriptionId::Number(self.next_id()); if let Ok(sink) = subscriber.assign_id(id.clone()) { self.subscriptions.insert(id.clone(), sink); Some(id) } else { None } } } impl<T> ops::Deref for Subscribers<T> { type Target = HashMap<SubscriptionId, T>; fn deref(&self) -> &Self::Target { &self.subscriptions } }
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Segment { id: Option<String>, name: Option<String>, value: Option<String>, ext: Option<SegmentExt>, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct SegmentExt {}
struct Solution {} impl Solution { pub fn is_palindrome(x: i32) -> bool { // Returns whether the given number is a palindrome. if a negative // number is given, the sign position is not preserved. So "-1" // reversed becomes "1-". let forward: String = x.to_string(); let backward: String = forward.chars() .rev() .collect(); forward == backward } } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_palindrome() { assert_eq!( Solution::is_palindrome(121_i32), true, ); assert_eq!( Solution::is_palindrome(-121_i32), false, ); assert_eq!( Solution::is_palindrome(10), false, ); assert_eq!( Solution::is_palindrome(-101), false, ); } }
pub mod emitter; pub mod lexer; pub mod parser;
#[doc = "Register `APBENR1` reader"] pub type R = crate::R<APBENR1_SPEC>; #[doc = "Register `APBENR1` writer"] pub type W = crate::W<APBENR1_SPEC>; #[doc = "Field `TIM2EN` reader - TIM2 timer clock enable"] pub type TIM2EN_R = crate::BitReader; #[doc = "Field `TIM2EN` writer - TIM2 timer clock enable"] pub type TIM2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM3EN` reader - TIM3 timer clock enable"] pub type TIM3EN_R = crate::BitReader; #[doc = "Field `TIM3EN` writer - TIM3 timer clock enable"] pub type TIM3EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM6EN` reader - TIM6 timer clock enable"] pub type TIM6EN_R = crate::BitReader; #[doc = "Field `TIM6EN` writer - TIM6 timer clock enable"] pub type TIM6EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM7EN` reader - TIM7 timer clock enable"] pub type TIM7EN_R = crate::BitReader; #[doc = "Field `TIM7EN` writer - TIM7 timer clock enable"] pub type TIM7EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RTCAPBEN` reader - RTC APB clock enable"] pub type RTCAPBEN_R = crate::BitReader; #[doc = "Field `RTCAPBEN` writer - RTC APB clock enable"] pub type RTCAPBEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WWDGEN` reader - WWDG clock enable"] pub type WWDGEN_R = crate::BitReader; #[doc = "Field `WWDGEN` writer - WWDG clock enable"] pub type WWDGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI2EN` reader - SPI2 clock enable"] pub type SPI2EN_R = crate::BitReader; #[doc = "Field `SPI2EN` writer - SPI2 clock enable"] pub type SPI2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART2EN` reader - USART2 clock enable"] pub type USART2EN_R = crate::BitReader; #[doc = "Field `USART2EN` writer - USART2 clock enable"] pub type USART2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART3EN` reader - USART3 clock enable"] pub type USART3EN_R = crate::BitReader; #[doc = "Field `USART3EN` writer - USART3 clock enable"] pub type USART3EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART4EN` reader - USART4 clock enable"] pub type USART4EN_R = crate::BitReader; #[doc = "Field `USART4EN` writer - USART4 clock enable"] pub type USART4EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPUART1EN` reader - LPUART1 clock enable"] pub type LPUART1EN_R = crate::BitReader; #[doc = "Field `LPUART1EN` writer - LPUART1 clock enable"] pub type LPUART1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C1EN` reader - I2C1 clock enable"] pub type I2C1EN_R = crate::BitReader; #[doc = "Field `I2C1EN` writer - I2C1 clock enable"] pub type I2C1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C2EN` reader - I2C2 clock enable"] pub type I2C2EN_R = crate::BitReader; #[doc = "Field `I2C2EN` writer - I2C2 clock enable"] pub type I2C2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CECEN` reader - HDMI CEC clock enable"] pub type CECEN_R = crate::BitReader; #[doc = "Field `CECEN` writer - HDMI CEC clock enable"] pub type CECEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `UCPD1EN` reader - UCPD1 clock enable"] pub type UCPD1EN_R = crate::BitReader; #[doc = "Field `UCPD1EN` writer - UCPD1 clock enable"] pub type UCPD1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `UCPD2EN` reader - UCPD2 clock enable"] pub type UCPD2EN_R = crate::BitReader; #[doc = "Field `UCPD2EN` writer - UCPD2 clock enable"] pub type UCPD2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBGEN` reader - Debug support clock enable"] pub type DBGEN_R = crate::BitReader; #[doc = "Field `DBGEN` writer - Debug support clock enable"] pub type DBGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PWREN` reader - Power interface clock enable"] pub type PWREN_R = crate::BitReader; #[doc = "Field `PWREN` writer - Power interface clock enable"] pub type PWREN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DAC1EN` reader - DAC1 interface clock enable"] pub type DAC1EN_R = crate::BitReader; #[doc = "Field `DAC1EN` writer - DAC1 interface clock enable"] pub type DAC1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM2EN` reader - LPTIM2 clock enable"] pub type LPTIM2EN_R = crate::BitReader; #[doc = "Field `LPTIM2EN` writer - LPTIM2 clock enable"] pub type LPTIM2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM1EN` reader - LPTIM1 clock enable"] pub type LPTIM1EN_R = crate::BitReader; #[doc = "Field `LPTIM1EN` writer - LPTIM1 clock enable"] pub type LPTIM1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - TIM2 timer clock enable"] #[inline(always)] pub fn tim2en(&self) -> TIM2EN_R { TIM2EN_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - TIM3 timer clock enable"] #[inline(always)] pub fn tim3en(&self) -> TIM3EN_R { TIM3EN_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 4 - TIM6 timer clock enable"] #[inline(always)] pub fn tim6en(&self) -> TIM6EN_R { TIM6EN_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - TIM7 timer clock enable"] #[inline(always)] pub fn tim7en(&self) -> TIM7EN_R { TIM7EN_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 10 - RTC APB clock enable"] #[inline(always)] pub fn rtcapben(&self) -> RTCAPBEN_R { RTCAPBEN_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - WWDG clock enable"] #[inline(always)] pub fn wwdgen(&self) -> WWDGEN_R { WWDGEN_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 14 - SPI2 clock enable"] #[inline(always)] pub fn spi2en(&self) -> SPI2EN_R { SPI2EN_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 17 - USART2 clock enable"] #[inline(always)] pub fn usart2en(&self) -> USART2EN_R { USART2EN_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - USART3 clock enable"] #[inline(always)] pub fn usart3en(&self) -> USART3EN_R { USART3EN_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - USART4 clock enable"] #[inline(always)] pub fn usart4en(&self) -> USART4EN_R { USART4EN_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - LPUART1 clock enable"] #[inline(always)] pub fn lpuart1en(&self) -> LPUART1EN_R { LPUART1EN_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - I2C1 clock enable"] #[inline(always)] pub fn i2c1en(&self) -> I2C1EN_R { I2C1EN_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - I2C2 clock enable"] #[inline(always)] pub fn i2c2en(&self) -> I2C2EN_R { I2C2EN_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 24 - HDMI CEC clock enable"] #[inline(always)] pub fn cecen(&self) -> CECEN_R { CECEN_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - UCPD1 clock enable"] #[inline(always)] pub fn ucpd1en(&self) -> UCPD1EN_R { UCPD1EN_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - UCPD2 clock enable"] #[inline(always)] pub fn ucpd2en(&self) -> UCPD2EN_R { UCPD2EN_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - Debug support clock enable"] #[inline(always)] pub fn dbgen(&self) -> DBGEN_R { DBGEN_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - Power interface clock enable"] #[inline(always)] pub fn pwren(&self) -> PWREN_R { PWREN_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - DAC1 interface clock enable"] #[inline(always)] pub fn dac1en(&self) -> DAC1EN_R { DAC1EN_R::new(((self.bits >> 29) & 1) != 0) } #[doc = "Bit 30 - LPTIM2 clock enable"] #[inline(always)] pub fn lptim2en(&self) -> LPTIM2EN_R { LPTIM2EN_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - LPTIM1 clock enable"] #[inline(always)] pub fn lptim1en(&self) -> LPTIM1EN_R { LPTIM1EN_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - TIM2 timer clock enable"] #[inline(always)] #[must_use] pub fn tim2en(&mut self) -> TIM2EN_W<APBENR1_SPEC, 0> { TIM2EN_W::new(self) } #[doc = "Bit 1 - TIM3 timer clock enable"] #[inline(always)] #[must_use] pub fn tim3en(&mut self) -> TIM3EN_W<APBENR1_SPEC, 1> { TIM3EN_W::new(self) } #[doc = "Bit 4 - TIM6 timer clock enable"] #[inline(always)] #[must_use] pub fn tim6en(&mut self) -> TIM6EN_W<APBENR1_SPEC, 4> { TIM6EN_W::new(self) } #[doc = "Bit 5 - TIM7 timer clock enable"] #[inline(always)] #[must_use] pub fn tim7en(&mut self) -> TIM7EN_W<APBENR1_SPEC, 5> { TIM7EN_W::new(self) } #[doc = "Bit 10 - RTC APB clock enable"] #[inline(always)] #[must_use] pub fn rtcapben(&mut self) -> RTCAPBEN_W<APBENR1_SPEC, 10> { RTCAPBEN_W::new(self) } #[doc = "Bit 11 - WWDG clock enable"] #[inline(always)] #[must_use] pub fn wwdgen(&mut self) -> WWDGEN_W<APBENR1_SPEC, 11> { WWDGEN_W::new(self) } #[doc = "Bit 14 - SPI2 clock enable"] #[inline(always)] #[must_use] pub fn spi2en(&mut self) -> SPI2EN_W<APBENR1_SPEC, 14> { SPI2EN_W::new(self) } #[doc = "Bit 17 - USART2 clock enable"] #[inline(always)] #[must_use] pub fn usart2en(&mut self) -> USART2EN_W<APBENR1_SPEC, 17> { USART2EN_W::new(self) } #[doc = "Bit 18 - USART3 clock enable"] #[inline(always)] #[must_use] pub fn usart3en(&mut self) -> USART3EN_W<APBENR1_SPEC, 18> { USART3EN_W::new(self) } #[doc = "Bit 19 - USART4 clock enable"] #[inline(always)] #[must_use] pub fn usart4en(&mut self) -> USART4EN_W<APBENR1_SPEC, 19> { USART4EN_W::new(self) } #[doc = "Bit 20 - LPUART1 clock enable"] #[inline(always)] #[must_use] pub fn lpuart1en(&mut self) -> LPUART1EN_W<APBENR1_SPEC, 20> { LPUART1EN_W::new(self) } #[doc = "Bit 21 - I2C1 clock enable"] #[inline(always)] #[must_use] pub fn i2c1en(&mut self) -> I2C1EN_W<APBENR1_SPEC, 21> { I2C1EN_W::new(self) } #[doc = "Bit 22 - I2C2 clock enable"] #[inline(always)] #[must_use] pub fn i2c2en(&mut self) -> I2C2EN_W<APBENR1_SPEC, 22> { I2C2EN_W::new(self) } #[doc = "Bit 24 - HDMI CEC clock enable"] #[inline(always)] #[must_use] pub fn cecen(&mut self) -> CECEN_W<APBENR1_SPEC, 24> { CECEN_W::new(self) } #[doc = "Bit 25 - UCPD1 clock enable"] #[inline(always)] #[must_use] pub fn ucpd1en(&mut self) -> UCPD1EN_W<APBENR1_SPEC, 25> { UCPD1EN_W::new(self) } #[doc = "Bit 26 - UCPD2 clock enable"] #[inline(always)] #[must_use] pub fn ucpd2en(&mut self) -> UCPD2EN_W<APBENR1_SPEC, 26> { UCPD2EN_W::new(self) } #[doc = "Bit 27 - Debug support clock enable"] #[inline(always)] #[must_use] pub fn dbgen(&mut self) -> DBGEN_W<APBENR1_SPEC, 27> { DBGEN_W::new(self) } #[doc = "Bit 28 - Power interface clock enable"] #[inline(always)] #[must_use] pub fn pwren(&mut self) -> PWREN_W<APBENR1_SPEC, 28> { PWREN_W::new(self) } #[doc = "Bit 29 - DAC1 interface clock enable"] #[inline(always)] #[must_use] pub fn dac1en(&mut self) -> DAC1EN_W<APBENR1_SPEC, 29> { DAC1EN_W::new(self) } #[doc = "Bit 30 - LPTIM2 clock enable"] #[inline(always)] #[must_use] pub fn lptim2en(&mut self) -> LPTIM2EN_W<APBENR1_SPEC, 30> { LPTIM2EN_W::new(self) } #[doc = "Bit 31 - LPTIM1 clock enable"] #[inline(always)] #[must_use] pub fn lptim1en(&mut self) -> LPTIM1EN_W<APBENR1_SPEC, 31> { LPTIM1EN_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 = "APB peripheral clock enable register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apbenr1::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 [`apbenr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APBENR1_SPEC; impl crate::RegisterSpec for APBENR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apbenr1::R`](R) reader structure"] impl crate::Readable for APBENR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`apbenr1::W`](W) writer structure"] impl crate::Writable for APBENR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APBENR1 to value 0"] impl crate::Resettable for APBENR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate :: { import::*, WsErr }; /// Indicates the state of a Websocket connection. The only state in which it's valid to send and receive messages /// is [WsState::Open]. /// /// See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState) for the ready state values. // #[ allow( missing_docs ) ] // #[ derive( Debug, Clone, Copy, PartialEq, Eq ) ] // pub enum WsState { Connecting, Open , Closing , Closed , } /// Internally ready state is a u16, so it's possible to create one from a u16. Only 0-3 are valid values. /// /// See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState) for the ready state values. // impl TryFrom<u16> for WsState { type Error = WsErr; fn try_from( state: u16 ) -> Result< Self, Self::Error > { match state { WebSocket::CONNECTING => Ok ( WsState::Connecting ) , WebSocket::OPEN => Ok ( WsState::Open ) , WebSocket::CLOSING => Ok ( WsState::Closing ) , WebSocket::CLOSED => Ok ( WsState::Closed ) , _ => Err( WsErr::InvalidWsState{ supplied: state } ) , } } }
#[allow(dead_code)] fn calculate_fuel_part1(mass: u32) -> u32 { (mass / 3) - 2 } fn calculate_fuel_part2(mass: u32) -> u32 { let mass_over_3 = mass / 3; if mass_over_3 <= 2 { 0 } else { let fuel = mass_over_3 - 2; fuel + calculate_fuel_part2(fuel) } } fn main() { let input = include_str!("../input/day1.txt"); let fuel = input.lines().map(|s| s.parse::<u32>()).flatten().map(calculate_fuel_part2).sum::<u32>(); println!("Fuel requirement: {}", fuel); }
use ncurses; use ncurses::{WchResult}; use std::sync::mpsc::{channel, Sender}; use std::thread::spawn; use num::rational::Ratio; use clock; use metronome; // https://unicode.org/charts/PDF/U0000.pdf static CHAR_SPACE: u32 = 0x0020; #[allow(dead_code)] static CHAR_RETURN: u32 = 0x000D; static CHAR_NEWLINE: u32 = 0x000A; #[derive(Debug)] pub struct Terminal {} impl Terminal { pub fn start (metronome_tx: Sender<metronome::Message>) -> Sender<Message> { let (tx, rx) = channel(); let mut signature = clock::Signature::default(); let mut tempo = Ratio::from_integer(0); spawn(move|| { /* Setup ncurses. */ ncurses::initscr(); let locale_conf = ncurses::LcCategory::all; ncurses::setlocale(locale_conf, "en_US.UTF-8"); /* Enable mouse events. */ ncurses::mousemask(ncurses::ALL_MOUSE_EVENTS as ncurses::mmask_t, None); /* Allow for extended keyboard (like F1). */ ncurses::keypad(ncurses::stdscr(), true); ncurses::noecho(); loop { let ch = ncurses::wget_wch(ncurses::stdscr()); match ch { Some(WchResult::KeyCode(ncurses::KEY_MOUSE)) => { } Some(WchResult::KeyCode(ncurses::KEY_UP)) => { let up = Ratio::from_integer(1); metronome_tx.send(metronome::Message::NudgeTempo(up)).unwrap(); } Some(WchResult::KeyCode(ncurses::KEY_DOWN)) => { let down = Ratio::from_integer(-1); metronome_tx.send(metronome::Message::NudgeTempo(down)).unwrap(); } // https://github.com/jeaye/ncurses-rs/blob/master/src/constants.rs Some(WchResult::KeyCode(_)) => { } // Some(WchResult::KeyCode(KEY_ENTER)) => beat(), Some(WchResult::Char(ch)) => { if ch == CHAR_SPACE { metronome_tx.send(metronome::Message::Tap).unwrap(); } if ch == CHAR_NEWLINE { metronome_tx.send(metronome::Message::Reset).unwrap(); } } None => {} } ncurses::refresh(); } // TODO move to Drop trait ncurses::endwin(); }); spawn(move|| { for interface_message in rx { match interface_message { Message::Time(time) => { ncurses::clear(); ncurses::mv(0, 0); print_time(time); print_signature(signature); print_tempo(tempo); }, Message::Signature(next_signature) => { signature = next_signature; }, Message::Tempo(next_tempo) => { tempo = next_tempo; }, } ncurses::refresh(); } }); tx } } pub fn print_time (time: clock::Time) { ncurses::printw("ticks since beat: "); let ticks_since_beat = time.ticks_since_beat(); ncurses::printw(format!("{}\n", ticks_since_beat).as_ref()); if ticks_since_beat.to_integer() == 0 { ncurses::printw("BEAT"); } else { for i in 0..ticks_since_beat.to_integer() { ncurses::printw("-"); } } ncurses::printw("\n"); ncurses::printw("beats since bar: "); let beats_since_bar = time.beats_since_bar(); ncurses::printw(format!("{}\n", beats_since_bar).as_ref()); if beats_since_bar.to_integer() == 0 { ncurses::printw("BAR"); } else { for i in 0..beats_since_bar.to_integer() { ncurses::printw("X"); } } ncurses::printw("\n"); ncurses::printw("bars since loop: "); let bars_since_loop = time.bars_since_loop(); ncurses::printw(format!("{}\n", bars_since_loop).as_ref()); if bars_since_loop.to_integer() == 0 { ncurses::printw("LOOP"); } else { for i in 0..bars_since_loop.to_integer() { ncurses::printw("&"); } } ncurses::printw("\n"); } pub fn print_signature (signature: clock::Signature) { ncurses::printw("ticks per beat: "); ncurses::printw(format!("{}\n", signature.ticks_per_beat).as_ref()); ncurses::printw("beats per bar: "); ncurses::printw(format!("{}\n", signature.beats_per_bar).as_ref()); ncurses::printw("bars per loop: "); ncurses::printw(format!("{}\n", signature.bars_per_loop).as_ref()); } pub fn print_tempo (tempo: clock::Tempo) { ncurses::printw("beats per minute: "); ncurses::printw(format!("{}\n", tempo.to_integer()).as_ref()); } #[derive(Clone, Copy, Debug)] pub enum Message { Time(clock::Time), Signature(clock::Signature), Tempo(clock::Tempo), }
#[cfg(target_os = "macos")] #[nolink] extern mod uuid { fn uuid_generate(out: UUID); fn uuid_generate_random(out: UUID); fn uuid_generate_time(out: UUID); fn uuid_parse(s: *u8, uuid: UUID) -> libc::c_int; fn uuid_unparse(uuid: UUID, out: *u8); fn uuid_unparse_lower(uuid: UUID, out: *u8); fn uuid_unparse_upper(uuid: UUID, out: *u8); } #[cfg(target_os = "linux")] #[cfg(target_os = "freebsd")] extern mod uuid { fn uuid_generate(out: UUID); fn uuid_generate_random(out: UUID); fn uuid_generate_time(out: UUID); fn uuid_parse(s: *u8, uuid: UUID) -> libc::c_int; fn uuid_unparse(uuid: UUID, out: *u8); fn uuid_unparse_lower(uuid: UUID, out: *u8); fn uuid_unparse_upper(uuid: UUID, out: *u8); } /// a uuid value pub struct UUID { a: u32, b: u32, c: u32, d: u32, } impl UUID: cmp::Eq { pure fn eq(other: &UUID) -> bool { self.a == other.a && self.b == other.b && self.c == other.c && self.d == other.d } pure fn ne(other: &UUID) -> bool { !self.eq(other) } } impl UUID: cmp::Ord { pure fn lt(other: &UUID) -> bool { if self.a < other.a { return true; } if other.a < self.a { return false; } if self.b < other.b { return true; } if other.b < self.b { return false; } if self.c < other.c { return true; } if other.c < self.c { return false; } self.d < other.d } pure fn le(other: &UUID) -> bool { !(*other).lt(&self) } pure fn ge(other: &UUID) -> bool { !self.lt(other) } pure fn gt(other: &UUID) -> bool { (*other).lt(&self) } } /// Create a new uuid pub fn UUID() -> UUID { let uuid = UUID { a: 0u32, b: 0u32, c: 0u32, d: 0u32 }; uuid::uuid_generate(uuid); uuid } /// Create a uuid from the current time and mac address pub fn UUID_random() -> UUID { let uuid = UUID { a: 0u32, b: 0u32, c: 0u32, d: 0u32 }; uuid::uuid_generate_random(uuid); uuid } /// Create a uuid from a random number generator pub fn UUID_time() -> UUID { let uuid = UUID { a: 0u32, b: 0u32, c: 0u32, d: 0u32 }; uuid::uuid_generate_time(uuid); uuid } /// Convert a uuid to a string pub impl UUID: to_str::ToStr { fn to_str() -> ~str { let mut s = ~""; str::reserve(&mut s, 36u); unsafe { str::raw::set_len(&mut s, 36u); } do str::as_buf(s) |buf, _len| { uuid::uuid_unparse(self, buf); } s } } pub fn from_str(s: &str) -> Option<UUID> { assert s.len() == 36u; let uuid = UUID { a: 0u32, b: 0u32, c: 0u32, d: 0u32 }; do str::as_buf(s) |buf, _len| { uuid::uuid_parse(buf, uuid); } Some(uuid) } /// Convert a string to a uuid impl UUID: from_str::FromStr { static fn from_str(s: &str) -> Option<UUID> { from_str(s) } } #[cfg(test)] mod test { pub use from_str::FromStr; #[test] fn test() { for uint::range(0u, 100000u) |_i| { let uuid = UUID(); assert from_str(uuid.to_str()) == Some(uuid); let uuid = UUID_random(); assert from_str(uuid.to_str()) == Some(uuid); let uuid = UUID_time(); assert from_str(uuid.to_str()) == Some(uuid) } } }
#![allow(non_snake_case,unused)] use libc;use std::slice;pub type C=libc::c_char;pub type J=libc::c_long; pub type G=libc::c_uchar;pub type S=*const C;pub type SC=libc::c_schar; pub type H=libc::c_short;pub type I=libc::c_int;pub type E=libc::c_float; pub type F=libc::c_double;pub type K=*const K0; pub const KCAP:u8=3; #[repr(C)]#[derive(Debug,Copy,Clone)]pub struct KA{n:J,g0:[G;1]} #[repr(C)]pub union KU{g:G,h:H,i:I,j:J,e:E,f:F,s:S,k:K,v:KA} #[repr(C)]pub struct K0{m:SC,a:SC,pub t:SC,u:C,r:I,k:KU} #[link(name="kdb")] extern"C"{pub fn okx(x:K)->I;pub fn b9(x:I,y:K)->K;pub fn d9(x:K)->K;pub fn ktn(t:I,n:J)->K;pub fn r0(x:K);pub fn khp(x:S,y:I)->I;pub fn ee(x:K)->K;} pub fn tk<'a,T>(k:K)->&'a [T] {unsafe{slice::from_raw_parts((&(*k).k.v.g0)as *const G as *const T,((*k).k.v.n) as usize)} } pub fn mtk<'a,T>(k:K)->&'a mut [T] {unsafe{slice::from_raw_parts_mut((&(*k).k.v.g0)as *const G as *const T as *mut T, ((*k).k.v.n) as usize)}} pub fn gK(k:&K0)->G{unsafe{k.k.g}} pub fn hK(k:&K0)->H{unsafe{k.k.h}} pub fn iK(k:&K0)->I{unsafe{k.k.i}} pub fn jK(k:&K0)->J{unsafe{k.k.j}} pub fn eK(k:&K0)->E{unsafe{k.k.e}} pub fn fK(k:&K0)->F{unsafe{k.k.f}} pub fn sK(k:&K0)->S{unsafe{k.k.s}} pub fn kK(k:&K0)->K{unsafe{k.k.k}} pub fn vK(k:&K0)->KA{unsafe{k.k.v}} pub fn t(k:&K0)->SC{k.t}
extern crate susanoo; use susanoo::{Context, Server, Response, AsyncResult}; use susanoo::contrib::hyper::{Get, Post, StatusCode}; use susanoo::contrib::futures::{future, Future, Stream}; fn index(_ctx: Context) -> AsyncResult { future::ok( Response::new() .with_status(StatusCode::Ok) .with_body("Hello, world") .into(), ).boxed() } fn index_post(ctx: Context) -> AsyncResult { ctx.req .body() .collect() .and_then(|chunks| { let mut body = Vec::new(); for chunk in chunks { body.extend_from_slice(&chunk); } future::ok( Response::new() .with_status(StatusCode::Ok) .with_body(format!("Posted: {}", String::from_utf8_lossy(&body))) .into(), ) }) .map_err(Into::into) .boxed() } fn show_captures(ctx: Context) -> AsyncResult { future::ok( Response::new() .with_status(StatusCode::Ok) .with_body(format!("Captures: {:?}", ctx.cap)) .into(), ).boxed() } fn main() { let server = Server::new() .with_route(Get, "/", index) .with_route(Post, "/", index_post) .with_route(Post, "/post", index_post) .with_route(Get, r"/echo/([^/]+)/(?P<hoge>[^/]+)/([^/]+)", show_captures); server.run("0.0.0.0:4000"); }
pub type ReplaceStoredProcedureResponse = crate::responses::CreateStoredProcedureResponse;
pub type H256 = [u8; 32]; pub type H512 = [u8; 64];
use rand::prelude::*; use web_sys::WebGlRenderingContext as GL; use crate::rendering::{Rectangle, Instance}; pub struct GoL { dimensions: (u32, u32), tiles: Vec<bool>, renderer: Rectangle, } impl GoL { pub fn new(gl: &GL, width: u32, height: u32) -> Self { let mut tiles = Vec::<bool>::new(); let mut rng = rand::thread_rng(); for _ in 0..width * height { tiles.push(rng.gen::<f32>() > 0.9); } Self { dimensions: (width, height), tiles, renderer: Rectangle::new(&gl), } } fn decode(&self, index: usize) -> (u32, u32) { ( index as u32 % self.dimensions.0, index as u32 / self.dimensions.0, ) } fn encode(&self, x: i32, y: i32) -> usize { // If location is negative loop back to end of corresponding coordinate space. let x = if x < 0 { (self.dimensions.0 as i32 + x) as u32 } else { x as u32 }; let y = if y < 0 { (self.dimensions.1 as i32 + y) as u32 } else { y as u32 }; // Perform a modulo on the length of the tiles vector to loop coordinate space. (y * self.dimensions.0 + x) as usize % self.tiles.len() as usize } fn get_active_neighbor_count(&self, x: u32, y: u32) -> u32 { //wrap screen maybe? let mut count = 0; for horizontal_offset in -1..2 { for vertical_offset in -1..2 { if horizontal_offset == 0 && vertical_offset == 0 { continue; } count += self.tiles [self.encode(x as i32 + horizontal_offset, y as i32 + vertical_offset)] as u32; } } count } pub fn update(&mut self, width: i32, height: i32) { let mut tiles_buffer = self.tiles.clone(); for (index, tile) in self.tiles.iter().enumerate() { let (x, y) = self.decode(index); let active_neighbor_count = self.get_active_neighbor_count(x, y); tiles_buffer[index] = active_neighbor_count == 3 || (*tile && active_neighbor_count == 2); } self.tiles = tiles_buffer; } pub fn render(&self, gl: &GL) { let mut instances = Vec::<Instance>::with_capacity(self.tiles.len()); for (index, &active) in self.tiles.iter().enumerate() { let (col, row) = self.decode(index); let width = 2.0 / self.dimensions.0 as f32; let height = 2.0 / self.dimensions.1 as f32; let x: f32 = width * col as f32 - 1.0; let y: f32 = height * row as f32 - 1.0; let color: [f32; 4] = if active { [115.0 / 256.0, 69.0 / 256.0, 124.0 / 256.0, 1.0] } else { [0.0, 0.0, 0.0, 0.0] }; instances.push(Instance { x, y, width, height, angle: 0.0, color, }); } self.renderer.render_instances(gl, instances); } }
use serde::{Deserialize, Serialize}; #[cfg(test)] use std::fs; use std::fs::File; use std::io::prelude::*; #[cfg(test)] use std::path::PathBuf; #[derive(Debug, Deserialize, PartialEq, Serialize, Clone)] struct KeyConf { pri_file: Option<String>, } #[derive(Debug, Deserialize, PartialEq, Serialize, Clone)] struct ServerConf { host: Option<String>, port: Option<u16>, } #[derive(Debug, Deserialize, PartialEq, Serialize, Clone)] struct ChainConf { rpc_host: Option<String>, rpc_port: Option<u16>, } #[derive(Debug, Deserialize, PartialEq, Serialize, Clone)] pub struct FaucetConf { key_conf: Option<KeyConf>, ser_conf: Option<ServerConf>, chain_conf: Option<ChainConf>, } impl FaucetConf { pub(crate) fn pri_file(&self) -> Option<String> { match self.key_conf.clone() { Some(key_conf) => key_conf.pri_file, _ => None, } } pub fn server(&self) -> (String, u16) { let ser_conf = self.ser_conf.clone().expect("server conf is none."); let host = ser_conf.host.expect("address is none."); let port = ser_conf.port.expect("port is none."); (host, port) } pub(crate) fn chain(&self) -> (String, u16) { let ser_conf = self.chain_conf.clone().expect("server conf is none."); let host = ser_conf.rpc_host.expect("address is none."); let port = ser_conf.rpc_port.expect("port is none."); (host, port) } pub fn set_key_file(&mut self, key_file: String) { let key_conf = KeyConf { pri_file: Some(key_file), }; self.key_conf = Some(key_conf); } } pub fn load_faucet_conf(path: String) -> FaucetConf { let file_path = "conf/faucet.toml"; let mut file = match File::open(format!("{}/{}", path, file_path)) { Ok(f) => f, Err(e) => panic!("no such file {} exception:{}", file_path, e), }; let mut str_val = String::new(); match file.read_to_string(&mut str_val) { Ok(s) => s, Err(e) => panic!("Error Reading file: {}", e), }; toml::from_str(&str_val).unwrap() } #[test] fn test_faucet_conf() { let current_dir = PathBuf::from("./"); println!("{:?}", fs::canonicalize(&current_dir)); // let path = ; let conf = load_faucet_conf( fs::canonicalize(&current_dir) .expect("path err.") .to_str() .expect("str err.") .to_string(), ); println!("conf: {:?}", conf); }
mod command; mod entity; pub mod interpreter;
use indexmap::IndexMap; use std::{ convert::TryFrom, }; use syn::{ Error, Ident, Visibility, }; use crate::parsing::ParseEcs; use crate::TypeId; pub mod component; pub mod query; pub mod system; pub mod task; pub mod unique; use component::Component; use unique::Unique; use query::Query; pub type AllComponents = IndexMap<TypeId, Component>; pub type AllUniques = IndexMap<TypeId, Unique>; pub type AllQueries = IndexMap<TypeId, Query>; #[derive(Debug)] pub struct ValidatedEcs { pub visibility: Visibility, pub name: Ident, pub components: AllComponents, //Note: we should probably be using a different hash algorithm? pub uniques: AllUniques, pub queries: AllQueries, } impl TryFrom<ParseEcs> for ValidatedEcs { type Error = Error; fn try_from(pecs: ParseEcs) -> Result<Self, Self::Error> { let components = Component::try_into_component_list(pecs.components)?; let uniques = Unique::try_into_unique_list(pecs.uniques, &components)?; let queries = Query::try_into_query_list(pecs.queries, &components, &uniques)?; // let mut systems = Vec::new(); // let mut tasks = Vec::new(); Ok(Self { visibility: pecs.visibility, name: pecs.name, components, uniques, queries, // systems, // tasks, }) } }
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket_contrib::json; use rocket_contrib::json::{Json, JsonValue}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] struct Message { contents: String, } #[put("/", data = "<msg>")] fn update(msg: Json<Message>) -> JsonValue { println!("{}", msg.0.contents); json!({ "message": msg.0.contents }) } #[get("/hello/<name>")] fn hello(name: String) -> String { format!("Hello, {}!", name) } fn main() { rocket::ignite().mount("/", routes![update, hello]).launch(); }
use { crate::Error, rewryte_parser::models::{Column, ColumnDefault, Enum, ForeignKey, Item, Schema, Table, Types}, std::io, }; pub fn write_schema(schema: &Schema, writer: &mut impl io::Write) -> Result<(), Error> { for (i, item) in schema.items.iter().enumerate() { write_item(item, writer)?; writeln!(writer)?; if i != schema.items.len() - 1 { writeln!(writer)?; } } Ok(()) } pub fn write_item(item: &Item, writer: &mut impl io::Write) -> Result<(), Error> { match &item { Item::Enum(decl) => write_enum(decl, writer)?, Item::Table(decl) => write_table(decl, writer)?, } Ok(()) } pub fn write_enum(_decl: &Enum, _writer: &mut impl io::Write) -> Result<(), Error> { // TODO: maybe log a warning? Ok(()) } pub fn write_table(decl: &Table, writer: &mut impl io::Write) -> Result<(), Error> { write!(writer, "CREATE TABLE")?; if decl.not_exists { write!(writer, " IF NOT EXISTS")?; } write!(writer, " {} (", decl.name)?; writeln!(writer)?; for column in &decl.columns { write_column(column, writer)?; write!(writer, ",")?; writeln!(writer)?; } write!(writer, " PRIMARY KEY (")?; for (i, primary) in decl.primary_keys.iter().enumerate() { write!(writer, "{}", primary)?; if i != decl.primary_keys.len() - 1 { write!(writer, ", ")?; } } write!(writer, ")")?; if !decl.foreign_keys.is_empty() { write!(writer, ",")?; writeln!(writer)?; for (i, foreign_key) in decl.foreign_keys.iter().enumerate() { write_foreign_key(foreign_key, writer)?; if i != decl.foreign_keys.len() - 1 { write!(writer, ",")?; writeln!(writer)?; } } if decl.unique_keys.is_empty() { writeln!(writer)?; } } else if decl.unique_keys.is_empty() { writeln!(writer)?; } if !decl.unique_keys.is_empty() { write!(writer, ",")?; writeln!(writer)?; write!(writer, " UNIQUE (")?; for (i, unique) in decl.unique_keys.iter().enumerate() { write!(writer, "{}", unique)?; if i != decl.unique_keys.len() - 1 { write!(writer, ", ")?; } } write!(writer, ")")?; writeln!(writer)?; } write!(writer, ");")?; Ok(()) } pub fn write_column(column: &Column, writer: &mut impl io::Write) -> Result<(), Error> { write!(writer, " {} ", column.name,)?; write_types(&column.typ, writer)?; if !column.null { write!(writer, " NOT NULL")?; } write_column_default(&column.default, writer)?; Ok(()) } pub fn write_types(types: &Types, writer: &mut impl io::Write) -> Result<(), Error> { write!( writer, "{}", match types { Types::Char | Types::Text => "TEXT", Types::Varchar => "VARCHAR", Types::Number | Types::SmallInt | Types::MediumInt | Types::Int | Types::Serial => { "INTEGER" } Types::BigInt => "BIGINT", Types::Float | Types::Real | Types::Numeric => "REAL", Types::Decimal => "DECIMAL", Types::DateTime => "DATETIME", Types::Boolean => "BOOLEAN", Types::Raw(raw) => raw, } )?; Ok(()) } pub fn write_column_default( column_default: &ColumnDefault, writer: &mut impl io::Write, ) -> Result<(), Error> { if column_default != &ColumnDefault::None { write!(writer, " DEFAULT")?; match column_default { ColumnDefault::Now => { write!(writer, " (DATETIME('now', 'utc'))")?; } ColumnDefault::Null => { write!(writer, " NULL")?; } ColumnDefault::Raw(raw) => { write!(writer, " {}", raw)?; } ColumnDefault::None => unreachable!(), } } Ok(()) } pub fn write_foreign_key( foreign_key: &ForeignKey, writer: &mut impl io::Write, ) -> Result<(), Error> { write!( writer, " FOREIGN KEY ({}) REFERENCES {}({}) ON UPDATE {} ON DELETE {}", foreign_key.local, foreign_key.table, foreign_key.foreign, foreign_key.update, foreign_key.delete, )?; Ok(()) } // TODO: Maybe I can clean this up #[cfg(test)] mod tests { use {crate::sqlite::write_table, rewryte_parser::models::*}; #[test] fn simple() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, PRIMARY KEY (Id) );", utf8_buff.as_str() ); } #[test] fn multiple_primary_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Key", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Value", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Key", "Value"], foreign_keys: vec![], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Key TEXT NOT NULL, Value TEXT NOT NULL, PRIMARY KEY (Key, Value) );", utf8_buff.as_str() ); } #[test] fn foreign_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Other", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![ForeignKey { local: "Other", table: "Other", foreign: "Id", delete: Action::default(), update: Action::default(), }], unique_keys: vec![], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, Other TEXT NOT NULL, PRIMARY KEY (Id), FOREIGN KEY (Other) REFERENCES Other(Id) ON UPDATE NO ACTION ON DELETE NO ACTION );", utf8_buff.as_str() ); } #[test] fn unique_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Key", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Value", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![], unique_keys: vec!["Key"], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Key TEXT NOT NULL, Value TEXT NOT NULL, PRIMARY KEY (Id), UNIQUE (Key) );", utf8_buff.as_str() ); } #[test] fn unique_keys_foreign_keys() { let table = Table { name: "Example", not_exists: true, columns: vec![ Column { name: "Id", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Name", typ: Types::Text, null: false, default: ColumnDefault::None, }, Column { name: "Other", typ: Types::Text, null: false, default: ColumnDefault::None, }, ], primary_keys: vec!["Id"], foreign_keys: vec![ForeignKey { local: "Other", table: "Other", foreign: "Id", delete: Action::default(), update: Action::default(), }], unique_keys: vec!["Name"], }; let mut buff = Vec::new(); write_table(&table, &mut buff).expect("Unable to write table to buffer"); let utf8_buff = String::from_utf8(buff).expect("Unable to convert buff into string"); assert_eq!( "CREATE TABLE IF NOT EXISTS Example ( Id TEXT NOT NULL, Name TEXT NOT NULL, Other TEXT NOT NULL, PRIMARY KEY (Id), FOREIGN KEY (Other) REFERENCES Other(Id) ON UPDATE NO ACTION ON DELETE NO ACTION, UNIQUE (Name) );", utf8_buff.as_str() ); } }
mod back_of_house; mod front_of_house; // use self::front_of_house::hosting; pub use crate::front_of_house::hosting; pub fn eat_at_restaurant() { // absolute path hosting::add_to_waitlist(); // relative path hosting::seat_at_table(); hosting::seat_at_table(); let mut meal = back_of_house::Breakfast::summer("Rye"); meal.toast = String::from("Wheat"); println!("I'd like {} toast please", meal.toast); let order = back_of_house::Appetizer::Soup; }
mod deserialize; mod error; mod osekai; mod osu_daily; mod osu_stats; mod osu_tracker; mod rkyv_impls; mod score; mod snipe; mod twitch; use std::{ borrow::Cow, fmt::{Display, Write}, hash::Hash, }; use bytes::Bytes; use chrono::{DateTime, Utc}; use hashbrown::HashSet; use http::{ header::{CONTENT_LENGTH, COOKIE}, request::Builder as RequestBuilder, Response, StatusCode, }; use hyper::{ client::{connect::dns::GaiResolver, Client as HyperClient, HttpConnector}, header::{CONTENT_TYPE, USER_AGENT}, Body, Method, Request, }; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; use leaky_bucket_lite::LeakyBucket; use rosu_v2::prelude::{GameMode, GameMods, User}; use serde::Serialize; use serde_json::{Map, Value}; use tokio::time::{interval, sleep, timeout, Duration}; use twilight_model::channel::Attachment; use crate::{ core::BotConfig, util::{ constants::{ common_literals::{COUNTRY, MODS, SORT, USER_ID}, HUISMETBENEN, OSU_BASE, OSU_DAILY_API, TWITCH_STREAM_ENDPOINT, TWITCH_USERS_ENDPOINT, TWITCH_VIDEOS_ENDPOINT, }, numbers::round, osu::ModSelection, ExponentialBackoff, }, CONFIG, }; #[cfg(not(debug_assertions))] use http::header::AUTHORIZATION; #[cfg(not(debug_assertions))] use hyper::header::HeaderValue; #[cfg(not(debug_assertions))] use crate::util::constants::TWITCH_OAUTH; pub use self::{ error::*, osekai::*, osu_daily::*, osu_stats::*, osu_tracker::*, score::*, snipe::*, twitch::*, }; use self::{deserialize::*, rkyv_impls::*, score::ScraperScores}; type ClientResult<T> = Result<T, CustomClientError>; static MY_USER_AGENT: &str = env!("CARGO_PKG_NAME"); const APPLICATION_JSON: &str = "application/json"; const APPLICATION_URLENCODED: &str = "application/x-www-form-urlencoded"; #[derive(Copy, Clone, Eq, Hash, PartialEq)] #[repr(u8)] enum Site { DiscordAttachment, Huismetbenen, Osekai, OsuAvatar, OsuBadge, OsuDaily, OsuHiddenApi, OsuMapFile, OsuMapsetCover, OsuStats, OsuTracker, #[cfg(not(debug_assertions))] Twitch, } type Client = HyperClient<HttpsConnector<HttpConnector<GaiResolver>>, Body>; pub struct CustomClient { client: Client, osu_session: &'static str, #[cfg(not(debug_assertions))] twitch: TwitchData, ratelimiters: [LeakyBucket; 11 + !cfg!(debug_assertions) as usize], } #[cfg(not(debug_assertions))] struct TwitchData { client_id: HeaderValue, oauth_token: TwitchOAuthToken, } impl CustomClient { pub async fn new(config: &'static BotConfig) -> ClientResult<Self> { let connector = HttpsConnectorBuilder::new() .with_webpki_roots() .https_or_http() .enable_http1() .build(); let client = HyperClient::builder().build(connector); #[cfg(not(debug_assertions))] let twitch = { let twitch_client_id = &config.tokens.twitch_client_id; let twitch_token = &config.tokens.twitch_token; Self::get_twitch_token(&client, twitch_client_id, twitch_token).await? }; let ratelimiter = |per_second| { LeakyBucket::builder() .max(per_second) .tokens(per_second) .refill_interval(Duration::from_millis(1000 / per_second as u64)) .refill_amount(1) .build() }; let ratelimiters = [ ratelimiter(2), // DiscordAttachment ratelimiter(2), // Huismetbenen ratelimiter(2), // Osekai ratelimiter(10), // OsuAvatar ratelimiter(10), // OsuBadge ratelimiter(2), // OsuDaily ratelimiter(2), // OsuHiddenApi ratelimiter(5), // OsuMapFile ratelimiter(10), // OsuMapsetCover ratelimiter(2), // OsuStats ratelimiter(2), // OsuTracker #[cfg(not(debug_assertions))] ratelimiter(5), // Twitch ]; Ok(Self { client, osu_session: &config.tokens.osu_session, #[cfg(not(debug_assertions))] twitch, ratelimiters, }) } #[cfg(not(debug_assertions))] async fn get_twitch_token( client: &Client, client_id: &str, token: &str, ) -> ClientResult<TwitchData> { // Skipping twitch initialization on debug if cfg!(debug_assertions) { let data = TwitchData { client_id: HeaderValue::from_str("").unwrap(), oauth_token: TwitchOAuthToken::default(), }; return Ok(data); } let form = &[ ("grant_type", "client_credentials"), ("client_id", client_id), ("client_secret", token), ]; let form_body = serde_urlencoded::to_string(form)?; let client_id = HeaderValue::from_str(client_id)?; let req = Request::builder() .method(Method::POST) .uri(TWITCH_OAUTH) .header("Client-ID", client_id.clone()) .header(USER_AGENT, MY_USER_AGENT) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body(Body::from(form_body))?; let response = client.request(req).await?; let bytes = Self::error_for_status(response, TWITCH_OAUTH).await?; let oauth_token = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::TwitchToken))?; Ok(TwitchData { client_id, oauth_token, }) } async fn ratelimit(&self, site: Site) { self.ratelimiters[site as usize].acquire_one().await } async fn make_get_request(&self, url: impl AsRef<str>, site: Site) -> ClientResult<Bytes> { trace!("GET request of url {}", url.as_ref()); let req = self .make_get_request_(url.as_ref(), site) .body(Body::empty())?; self.ratelimit(site).await; let response = self.client.request(req).await?; Self::error_for_status(response, url.as_ref()).await } #[cfg(debug_assertions)] async fn make_twitch_get_request<I, U, V>( &self, _: impl AsRef<str>, _: I, ) -> ClientResult<Bytes> where I: IntoIterator<Item = (U, V)>, U: Display, V: Display, { Err(CustomClientError::NoTwitchOnDebug) } #[cfg(not(debug_assertions))] async fn make_twitch_get_request<I, U, V>( &self, url: impl AsRef<str>, data: I, ) -> ClientResult<Bytes> where I: IntoIterator<Item = (U, V)>, U: Display, V: Display, { trace!("GET request of url {}", url.as_ref()); let mut uri = format!("{}?", url.as_ref()); let mut iter = data.into_iter(); if let Some((key, value)) = iter.next() { let _ = write!(uri, "{key}={value}"); for (key, value) in iter { let _ = write!(uri, "&{key}={value}"); } } let req = self .make_get_request_(uri, Site::Twitch) .body(Body::empty())?; self.ratelimit(Site::Twitch).await; let response = self.client.request(req).await?; Self::error_for_status(response, url.as_ref()).await } fn make_get_request_(&self, url: impl AsRef<str>, site: Site) -> RequestBuilder { let req = Request::builder() .uri(url.as_ref()) .method(Method::GET) .header(USER_AGENT, MY_USER_AGENT); match site { Site::OsuHiddenApi => req.header(COOKIE, format!("osu_session={}", self.osu_session)), #[cfg(not(debug_assertions))] Site::Twitch => req .header("Client-ID", self.twitch.client_id.clone()) .header(AUTHORIZATION, format!("Bearer {}", self.twitch.oauth_token)), _ => req, } } async fn make_post_request<F: Serialize>( &self, url: impl AsRef<str>, site: Site, form: &F, ) -> ClientResult<Bytes> { trace!("POST request of url {}", url.as_ref()); let form_body = serde_urlencoded::to_string(form)?; let req = Request::builder() .method(Method::POST) .uri(url.as_ref()) .header(USER_AGENT, MY_USER_AGENT) .header(CONTENT_TYPE, APPLICATION_URLENCODED) .body(Body::from(form_body))?; self.ratelimit(site).await; let response = self.client.request(req).await?; Self::error_for_status(response, url.as_ref()).await } async fn error_for_status( response: Response<Body>, url: impl Into<String>, ) -> ClientResult<Bytes> { if response.status().is_client_error() || response.status().is_server_error() { Err(CustomClientError::Status { status: response.status(), url: url.into(), }) } else { let bytes = hyper::body::to_bytes(response.into_body()).await?; Ok(bytes) } } pub async fn get_discord_attachment(&self, attachment: &Attachment) -> ClientResult<Bytes> { self.make_get_request(&attachment.url, Site::DiscordAttachment) .await } pub async fn get_osutracker_country_details( &self, country_code: &str, ) -> ClientResult<OsuTrackerCountryDetails> { let url = format!("https://osutracker.com/api/countries/{country_code}/details"); let bytes = self.make_get_request(url, Site::OsuTracker).await?; let details: OsuTrackerCountryDetails = serde_json::from_slice(&bytes).map_err(|e| { CustomClientError::parsing(e, &bytes, ErrorKind::OsuTrackerCountryDetails) })?; Ok(details) } pub async fn get_osutracker_stats(&self) -> ClientResult<OsuTrackerStats> { let url = "https://osutracker.com/api/stats"; let bytes = self.make_get_request(url, Site::OsuTracker).await?; let stats: OsuTrackerStats = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::OsuTrackerStats))?; Ok(stats) } pub async fn get_osutracker_pp_groups(&self) -> ClientResult<Vec<OsuTrackerPpGroup>> { let url = "https://osutracker.com/api/stats/ppBarrier"; let bytes = self.make_get_request(url, Site::OsuTracker).await?; let groups: Vec<OsuTrackerPpGroup> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::OsuTrackerGroups))?; Ok(groups) } pub async fn get_osekai_badges(&self) -> ClientResult<Vec<OsekaiBadge>> { let url = "https://osekai.net/badges/api/getBadges.php"; let bytes = self.make_get_request(url, Site::Osekai).await?; serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::OsekaiBadges)) } pub async fn get_osekai_badge_owners( &self, badge_id: u32, ) -> ClientResult<Vec<OsekaiBadgeOwner>> { let url = format!("https://osekai.net/badges/api/getUsers.php?badge_id={badge_id}"); let bytes = self.make_get_request(url, Site::Osekai).await?; serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::OsekaiBadgeOwners)) } pub async fn get_osekai_medals(&self) -> ClientResult<Vec<OsekaiMedal>> { let url = "https://osekai.net/medals/api/medals.php"; let form = &[("strSearch", "")]; let bytes = self.make_post_request(url, Site::Osekai, form).await?; let medals: OsekaiMedals = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::OsekaiMedals))?; Ok(medals.0) } pub async fn get_osekai_beatmaps(&self, medal_name: &str) -> ClientResult<Vec<OsekaiMap>> { let url = "https://osekai.net/medals/api/beatmaps.php"; let form = &[("strSearch", medal_name)]; let bytes = self.make_post_request(url, Site::Osekai, form).await?; let maps: OsekaiMaps = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::OsekaiMaps))?; Ok(maps.0.unwrap_or_default()) } pub async fn get_osekai_comments(&self, medal_name: &str) -> ClientResult<Vec<OsekaiComment>> { let url = "https://osekai.net/global/api/comment_system.php"; let form = &[("strMedalName", medal_name), ("bGetComments", "true")]; let bytes = self.make_post_request(url, Site::Osekai, form).await?; let comments: OsekaiComments = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::OsekaiComments))?; Ok(comments.0.unwrap_or_default()) } pub async fn get_osekai_ranking<R: OsekaiRanking>(&self) -> ClientResult<Vec<R::Entry>> { let url = "https://osekai.net/rankings/api/api.php"; let form = &[("App", R::FORM)]; let bytes = self.make_post_request(url, Site::Osekai, form).await?; let ranking = serde_json::from_slice(&bytes).map_err(|e| { CustomClientError::parsing(e, &bytes, ErrorKind::OsekaiRanking(R::REQUEST)) })?; Ok(ranking) } pub async fn get_snipe_player(&self, country: &str, user_id: u32) -> ClientResult<SnipePlayer> { let url = format!( "{HUISMETBENEN}player/{}/{user_id}?type=id", country.to_lowercase(), ); let bytes = self.make_get_request(url, Site::Huismetbenen).await?; let player: SnipePlayer = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::SnipePlayer))?; Ok(player) } pub async fn get_snipe_country(&self, country: &str) -> ClientResult<Vec<SnipeCountryPlayer>> { let url = format!( "{HUISMETBENEN}rankings/{}/pp/weighted", country.to_lowercase() ); let bytes = self.make_get_request(url, Site::Huismetbenen).await?; let country_players: Vec<SnipeCountryPlayer> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::SnipeCountry))?; Ok(country_players) } pub async fn get_country_statistics( &self, country: &str, ) -> ClientResult<SnipeCountryStatistics> { let country = country.to_lowercase(); let url = format!("{HUISMETBENEN}rankings/{country}/statistics"); let bytes = self.make_get_request(url, Site::Huismetbenen).await?; let statistics = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::CountryStatistics))?; Ok(statistics) } pub async fn get_national_snipes( &self, user: &User, sniper: bool, from: DateTime<Utc>, until: DateTime<Utc>, ) -> ClientResult<Vec<SnipeRecent>> { let date_format = "%FT%TZ"; let url = format!( "{HUISMETBENEN}snipes/{}/{}?since={}&until={}", user.user_id, if sniper { "new" } else { "old" }, from.format(date_format), until.format(date_format) ); let bytes = self.make_get_request(url, Site::Huismetbenen).await?; let snipes: Vec<SnipeRecent> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::SnipeRecent))?; Ok(snipes) } pub async fn get_national_firsts( &self, params: &SnipeScoreParams, ) -> ClientResult<Vec<SnipeScore>> { let mut url = format!( "{HUISMETBENEN}player/{country}/{user}/topranks?page={page}&mode={mode}&sort={sort}&order={order}", country = params.country, user = params.user_id, page = params.page, mode = params.mode, sort = params.order, order = if params.descending { "desc" } else { "asc" }, ); if let Some(mods) = params.mods { if let ModSelection::Include(mods) | ModSelection::Exact(mods) = mods { if mods == GameMods::NoMod { url.push_str("&mods=nomod"); } else { let _ = write!(url, "&mods={mods}"); } } } let bytes = self.make_get_request(url, Site::Huismetbenen).await?; let scores: Vec<SnipeScore> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::SnipeScore))?; Ok(scores) } pub async fn get_national_firsts_count( &self, params: &SnipeScoreParams, ) -> ClientResult<usize> { let mut url = format!( "{HUISMETBENEN}player/{country}/{user}/topranks/count?mode={mode}", country = params.country, user = params.user_id, mode = params.mode, ); if let Some(mods) = params.mods { if let ModSelection::Include(mods) | ModSelection::Exact(mods) = mods { if mods == GameMods::NoMod { url.push_str("&mods=nomod"); } else { let _ = write!(url, "&mods={mods}"); } } } let bytes = self.make_get_request(url, Site::Huismetbenen).await?; let count: usize = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::SnipeScoreCount))?; Ok(count) } pub async fn get_country_globals( &self, params: &OsuStatsListParams, ) -> ClientResult<Vec<OsuStatsPlayer>> { let mut map = Map::new(); map.insert("rankMin".to_owned(), params.rank_min.into()); map.insert("rankMax".to_owned(), params.rank_max.into()); map.insert("gamemode".to_owned(), (params.mode as u8).into()); map.insert("page".to_owned(), params.page.into()); if let Some(ref country) = params.country { map.insert(COUNTRY.to_owned(), country.to_string().into()); } let json = serde_json::to_vec(&map).map_err(CustomClientError::Serialize)?; let url = "https://osustats.ppy.sh/api/getScoreRanking"; trace!("Requesting POST from url {url} [page {}]", params.page); let req = Request::builder() .method(Method::POST) .uri(url) .header(USER_AGENT, MY_USER_AGENT) .header(CONTENT_TYPE, APPLICATION_JSON) .header(CONTENT_LENGTH, json.len()) .body(Body::from(json))?; self.ratelimit(Site::OsuStats).await; let response = timeout(Duration::from_secs(4), self.client.request(req)) .await .map_err(|_| CustomClientError::OsuStatsTimeout)??; let bytes = Self::error_for_status(response, url).await?; let players: Vec<OsuStatsPlayer> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::GlobalsList))?; Ok(players) } /// Be sure whitespaces in the username are **not** replaced pub async fn get_global_scores( &self, params: &OsuStatsParams, ) -> ClientResult<(Vec<OsuStatsScore>, usize)> { let mut map = Map::new(); map.insert("accMin".to_owned(), params.acc_min.into()); map.insert("accMax".to_owned(), params.acc_max.into()); map.insert("rankMin".to_owned(), params.rank_min.into()); map.insert("rankMax".to_owned(), params.rank_max.into()); map.insert("gamemode".to_owned(), (params.mode as u8).into()); map.insert("sortBy".to_owned(), (params.order as u8).into()); map.insert( "sortOrder".to_owned(), (!params.descending as u8).to_string().into(), // required as string ); map.insert("page".to_owned(), params.page.into()); map.insert("u1".to_owned(), params.username.to_string().into()); if let Some(selection) = params.mods { let mod_str = match selection { ModSelection::Include(mods) => format!("+{mods}"), ModSelection::Exclude(mods) => format!("-{mods}"), ModSelection::Exact(mods) => format!("!{mods}"), }; map.insert(MODS.to_owned(), mod_str.into()); } let json = serde_json::to_vec(&map).map_err(CustomClientError::Serialize)?; let url = "https://osustats.ppy.sh/api/getScores"; trace!("Requesting POST from url {url}"); let req = Request::builder() .method(Method::POST) .uri(url) .header(USER_AGENT, MY_USER_AGENT) .header(CONTENT_TYPE, APPLICATION_JSON) .header(CONTENT_LENGTH, json.len()) .body(Body::from(json))?; self.ratelimit(Site::OsuStats).await; let response = timeout(Duration::from_secs(4), self.client.request(req)) .await .map_err(|_| CustomClientError::OsuStatsTimeout)??; let status = response.status(); // Don't use Self::error_for_status since osustats returns a 400 // if the user has no scores for the given parameters let bytes = if (status.is_client_error() && status != StatusCode::BAD_REQUEST) || status.is_server_error() { return Err(CustomClientError::Status { status, url: url.to_owned(), }); } else { hyper::body::to_bytes(response.into_body()).await? }; let result: Value = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::OsuStatsGlobal))?; let (scores, amount) = if let Value::Array(mut array) = result { let mut values = array.drain(..2); let scores = serde_json::from_value(values.next().unwrap()).map_err(|e| { CustomClientError::parsing(e, &bytes, ErrorKind::OsuStatsGlobalScores) })?; let amount = serde_json::from_value(values.next().unwrap()).map_err(|e| { CustomClientError::parsing(e, &bytes, ErrorKind::OsuStatsGlobalAmount) })?; (scores, amount) } else { (Vec::new(), 0) }; Ok((scores, amount)) } // Retrieve the leaderboard of a map (national / global) // If mods contain DT / NC, it will do another request for the opposite // If mods dont contain Mirror and its a mania map, it will perform the // same requests again but with Mirror enabled pub async fn get_leaderboard( &self, map_id: u32, national: bool, mods: Option<GameMods>, mode: GameMode, ) -> ClientResult<Vec<ScraperScore>> { let mut scores = self._get_leaderboard(map_id, national, mods).await?; let non_mirror = mods .map(|mods| !mods.contains(GameMods::Mirror)) .unwrap_or(true); // Check if another request for mania's MR is needed if mode == GameMode::MNA && non_mirror { let mods = match mods { None => Some(GameMods::Mirror), Some(mods) => Some(mods | GameMods::Mirror), }; let mut new_scores = self._get_leaderboard(map_id, national, mods).await?; scores.append(&mut new_scores); scores.sort_unstable_by(|a, b| b.score.cmp(&a.score)); let mut uniques = HashSet::with_capacity(50); scores.retain(|s| uniques.insert(s.user_id)); scores.truncate(50); } // Check if DT / NC is included let mods = match mods { Some(mods) if mods.contains(GameMods::DoubleTime) => Some(mods | GameMods::NightCore), Some(mods) if mods.contains(GameMods::NightCore) => { Some((mods - GameMods::NightCore) | GameMods::DoubleTime) } Some(_) | None => None, }; // If DT / NC included, make another request if mods.is_some() { if mode == GameMode::MNA && non_mirror { let mods = mods.map(|mods| mods | GameMods::Mirror); let mut new_scores = self._get_leaderboard(map_id, national, mods).await?; scores.append(&mut new_scores); } let mut new_scores = self._get_leaderboard(map_id, national, mods).await?; scores.append(&mut new_scores); scores.sort_unstable_by(|a, b| b.score.cmp(&a.score)); let mut uniques = HashSet::with_capacity(50); scores.retain(|s| uniques.insert(s.user_id)); scores.truncate(50); } Ok(scores) } // Retrieve the leaderboard of a map (national / global) async fn _get_leaderboard( &self, map_id: u32, national: bool, mods: Option<GameMods>, ) -> ClientResult<Vec<ScraperScore>> { let mut url = format!("{OSU_BASE}beatmaps/{map_id}/scores?"); if national { url.push_str("type=country"); } if let Some(mods) = mods { if mods.is_empty() { url.push_str("&mods[]=NM"); } else { for m in mods.iter() { let _ = write!(url, "&mods[]={m}"); } } } let bytes = self.make_get_request(url, Site::OsuHiddenApi).await?; let scores: ScraperScores = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::Leaderboard))?; Ok(scores.get()) } pub async fn get_avatar(&self, url: &str) -> ClientResult<Bytes> { self.make_get_request(url, Site::OsuAvatar).await } pub async fn get_badge(&self, url: &str) -> ClientResult<Bytes> { self.make_get_request(url, Site::OsuBadge).await } pub async fn get_mapset_cover(&self, cover: &str) -> ClientResult<Bytes> { self.make_get_request(&cover, Site::OsuMapsetCover).await } pub async fn get_map_file(&self, map_id: u32) -> ClientResult<Bytes> { let url = format!("{OSU_BASE}osu/{map_id}"); let backoff = ExponentialBackoff::new(2).factor(500).max_delay(10_000); const ATTEMPTS: usize = 10; for (duration, i) in backoff.take(ATTEMPTS).zip(1..) { let result = self.make_get_request(&url, Site::OsuMapFile).await; if matches!(&result, Err(CustomClientError::Status { status, ..}) if *status == StatusCode::TOO_MANY_REQUESTS) || matches!(&result, Ok(bytes) if bytes.starts_with(b"<html>")) { debug!("Request beatmap retry attempt #{i} | Backoff {duration:?}"); sleep(duration).await; } else { return result; } } Err(CustomClientError::MapFileRetryLimit(map_id)) } pub async fn get_rank_data(&self, mode: GameMode, param: RankParam) -> ClientResult<RankPP> { let key = &CONFIG.get().unwrap().tokens.osu_daily; let mut url = format!("{OSU_DAILY_API}pp.php?k={key}&m={}&", mode as u8); let _ = match param { RankParam::Rank(rank) => write!(url, "t=rank&v={rank}"), RankParam::Pp(pp) => write!(url, "t=pp&v={}", round(pp)), }; let bytes = loop { match self.make_get_request(&url, Site::OsuDaily).await { Ok(bytes) => break bytes, Err(CustomClientError::Status { status, .. }) if status == StatusCode::TOO_MANY_REQUESTS => { debug!("Ratelimited by osudaily, wait a second"); sleep(Duration::from_secs(1)).await; } Err(err) => return Err(err), } }; let rank_pp = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::RankData))?; Ok(rank_pp) } pub async fn get_twitch_user(&self, name: &str) -> ClientResult<Option<TwitchUser>> { let data = [("login", name)]; let bytes = self .make_twitch_get_request(TWITCH_USERS_ENDPOINT, data) .await?; let mut users: TwitchDataList<TwitchUser> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::TwitchUserName))?; Ok(users.data.pop()) } pub async fn get_twitch_user_by_id(&self, user_id: u64) -> ClientResult<Option<TwitchUser>> { let data = [("id", user_id)]; let bytes = self .make_twitch_get_request(TWITCH_USERS_ENDPOINT, data) .await?; let mut users: TwitchDataList<TwitchUser> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::TwitchUserId))?; Ok(users.data.pop()) } pub async fn get_twitch_users(&self, user_ids: &[u64]) -> ClientResult<Vec<TwitchUser>> { let mut users = Vec::with_capacity(user_ids.len()); for chunk in user_ids.chunks(100) { let data: Vec<_> = chunk.iter().map(|&id| ("id", id)).collect(); let bytes = self .make_twitch_get_request(TWITCH_USERS_ENDPOINT, data) .await?; let parsed_response: TwitchDataList<TwitchUser> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::TwitchUsers))?; users.extend(parsed_response.data); } Ok(users) } pub async fn get_twitch_streams(&self, user_ids: &[u64]) -> ClientResult<Vec<TwitchStream>> { let mut streams = Vec::with_capacity(user_ids.len()); let mut interval = interval(Duration::from_millis(1000)); for chunk in user_ids.chunks(100) { interval.tick().await; let mut data: Vec<_> = chunk.iter().map(|&id| (USER_ID, id)).collect(); data.push(("first", chunk.len() as u64)); let bytes = self .make_twitch_get_request(TWITCH_STREAM_ENDPOINT, data) .await?; let parsed_response: TwitchDataList<TwitchStream> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::TwitchStreams))?; streams.extend(parsed_response.data); } Ok(streams) } pub async fn get_last_twitch_vod(&self, user_id: u64) -> ClientResult<Option<TwitchVideo>> { let data = [ (USER_ID, Cow::Owned(user_id.to_string())), ("first", "1".into()), (SORT, "time".into()), ]; let bytes = self .make_twitch_get_request(TWITCH_VIDEOS_ENDPOINT, data) .await?; let mut videos: TwitchDataList<TwitchVideo> = serde_json::from_slice(&bytes) .map_err(|e| CustomClientError::parsing(e, &bytes, ErrorKind::TwitchVideos))?; Ok(videos.data.pop()) } } pub enum RankParam { Rank(usize), Pp(f32), }
#[doc = "Register `MTLTxQDR` reader"] pub type R = crate::R<MTLTX_QDR_SPEC>; #[doc = "Register `MTLTxQDR` writer"] pub type W = crate::W<MTLTX_QDR_SPEC>; #[doc = "Field `TXQPAUSED` reader - Transmit Queue in Pause"] pub type TXQPAUSED_R = crate::BitReader; #[doc = "Field `TXQPAUSED` writer - Transmit Queue in Pause"] pub type TXQPAUSED_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TRCSTS` reader - MTL Tx Queue Read Controller Status"] pub type TRCSTS_R = crate::FieldReader; #[doc = "Field `TRCSTS` writer - MTL Tx Queue Read Controller Status"] pub type TRCSTS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `TWCSTS` reader - MTL Tx Queue Write Controller Status"] pub type TWCSTS_R = crate::BitReader; #[doc = "Field `TWCSTS` writer - MTL Tx Queue Write Controller Status"] pub type TWCSTS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TXQSTS` reader - MTL Tx Queue Not Empty Status"] pub type TXQSTS_R = crate::BitReader; #[doc = "Field `TXQSTS` writer - MTL Tx Queue Not Empty Status"] pub type TXQSTS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TXSTSFSTS` reader - MTL Tx Status FIFO Full Status"] pub type TXSTSFSTS_R = crate::BitReader; #[doc = "Field `TXSTSFSTS` writer - MTL Tx Status FIFO Full Status"] pub type TXSTSFSTS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PTXQ` reader - Number of Packets in the Transmit Queue"] pub type PTXQ_R = crate::FieldReader; #[doc = "Field `PTXQ` writer - Number of Packets in the Transmit Queue"] pub type PTXQ_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `STXSTSF` reader - Number of Status Words in Tx Status FIFO of Queue"] pub type STXSTSF_R = crate::FieldReader; #[doc = "Field `STXSTSF` writer - Number of Status Words in Tx Status FIFO of Queue"] pub type STXSTSF_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; impl R { #[doc = "Bit 0 - Transmit Queue in Pause"] #[inline(always)] pub fn txqpaused(&self) -> TXQPAUSED_R { TXQPAUSED_R::new((self.bits & 1) != 0) } #[doc = "Bits 1:2 - MTL Tx Queue Read Controller Status"] #[inline(always)] pub fn trcsts(&self) -> TRCSTS_R { TRCSTS_R::new(((self.bits >> 1) & 3) as u8) } #[doc = "Bit 3 - MTL Tx Queue Write Controller Status"] #[inline(always)] pub fn twcsts(&self) -> TWCSTS_R { TWCSTS_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - MTL Tx Queue Not Empty Status"] #[inline(always)] pub fn txqsts(&self) -> TXQSTS_R { TXQSTS_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - MTL Tx Status FIFO Full Status"] #[inline(always)] pub fn txstsfsts(&self) -> TXSTSFSTS_R { TXSTSFSTS_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bits 16:18 - Number of Packets in the Transmit Queue"] #[inline(always)] pub fn ptxq(&self) -> PTXQ_R { PTXQ_R::new(((self.bits >> 16) & 7) as u8) } #[doc = "Bits 20:22 - Number of Status Words in Tx Status FIFO of Queue"] #[inline(always)] pub fn stxstsf(&self) -> STXSTSF_R { STXSTSF_R::new(((self.bits >> 20) & 7) as u8) } } impl W { #[doc = "Bit 0 - Transmit Queue in Pause"] #[inline(always)] #[must_use] pub fn txqpaused(&mut self) -> TXQPAUSED_W<MTLTX_QDR_SPEC, 0> { TXQPAUSED_W::new(self) } #[doc = "Bits 1:2 - MTL Tx Queue Read Controller Status"] #[inline(always)] #[must_use] pub fn trcsts(&mut self) -> TRCSTS_W<MTLTX_QDR_SPEC, 1> { TRCSTS_W::new(self) } #[doc = "Bit 3 - MTL Tx Queue Write Controller Status"] #[inline(always)] #[must_use] pub fn twcsts(&mut self) -> TWCSTS_W<MTLTX_QDR_SPEC, 3> { TWCSTS_W::new(self) } #[doc = "Bit 4 - MTL Tx Queue Not Empty Status"] #[inline(always)] #[must_use] pub fn txqsts(&mut self) -> TXQSTS_W<MTLTX_QDR_SPEC, 4> { TXQSTS_W::new(self) } #[doc = "Bit 5 - MTL Tx Status FIFO Full Status"] #[inline(always)] #[must_use] pub fn txstsfsts(&mut self) -> TXSTSFSTS_W<MTLTX_QDR_SPEC, 5> { TXSTSFSTS_W::new(self) } #[doc = "Bits 16:18 - Number of Packets in the Transmit Queue"] #[inline(always)] #[must_use] pub fn ptxq(&mut self) -> PTXQ_W<MTLTX_QDR_SPEC, 16> { PTXQ_W::new(self) } #[doc = "Bits 20:22 - Number of Status Words in Tx Status FIFO of Queue"] #[inline(always)] #[must_use] pub fn stxstsf(&mut self) -> STXSTSF_W<MTLTX_QDR_SPEC, 20> { STXSTSF_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 = "Tx queue debug Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mtltx_qdr::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 [`mtltx_qdr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MTLTX_QDR_SPEC; impl crate::RegisterSpec for MTLTX_QDR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`mtltx_qdr::R`](R) reader structure"] impl crate::Readable for MTLTX_QDR_SPEC {} #[doc = "`write(|w| ..)` method takes [`mtltx_qdr::W`](W) writer structure"] impl crate::Writable for MTLTX_QDR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets MTLTxQDR to value 0"] impl crate::Resettable for MTLTX_QDR_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub mod prefab; use amethyst::prelude::*; use amethyst::renderer::{Event, VirtualKeyCode, WindowEvent, MouseButton, ElementState}; use amethyst::input::{is_key_down, is_close_requested, get_key}; use amethyst::assets::{PrefabLoader, RonFormat}; use amethyst::ecs::prelude::Entity; use amethyst::core::Transform; use amethyst::core::cgmath::{Vector3, Quaternion, Deg, Rotation, MetricSpace, Rotation3, InnerSpace}; use myPrefabData; pub struct Ball { is_rotating: bool, pub sphere: Option<Entity>, previous_location: Option<Vector3<f32>>, rotation: [f32; 4] } impl Default for Ball { fn default() -> Self { Ball { is_rotating: false, sphere: None, previous_location: None, rotation: [0.0, 0.0, 0.0, 0.0] } } } impl<'a, 'b> State<GameData<'a, 'b>> for Ball { fn on_start(&mut self, data: StateData<GameData>) { let StateData { world, .. } = data; // Initialize the scene with an object, a light, and a camera let prefab = world.exec(|loader: PrefabLoader<myPrefabData>| { loader.load("ball/prefab/sphere.ron", RonFormat, (), ()) }); self.sphere = Some(world.create_entity().with(prefab).build()); } fn handle_event(&mut self, data: StateData<GameData>, event: Event) -> Trans<GameData<'a, 'b>> { let StateData { world, .. } = data; if is_close_requested(&event) || is_key_down(&event, VirtualKeyCode::Escape) { return Trans::Quit; } let mouse_down = left_mouse_state_change(&event); match mouse_down { Some(ElementState::Pressed) => { self.is_rotating = true }, Some(ElementState::Released) => { self.is_rotating = false }, _ => {} }; if self.is_rotating { let new_pos = get_new_cursor_position(&event); let mut prev_pos = Vector3 { x: 0.0, y: 0.0, z: 0.0 }; let maybe_rotate = match new_pos { Some(pos) => { prev_pos = match self.previous_location { Some(T) => T, None => prev_pos }; let dir_vec = create_directional_vector(pos, prev_pos); Some(Vector3 { x: dir_vec.y, y: -1.0 * dir_vec.x, z: dir_vec.z }) }, None => None }; match maybe_rotate { Some(T) => { let rel_axis_normalized = Quaternion::from(self.rotation).rotate_vector(T).normalize(); let distance = Quaternion::from_sv(1.0, prev_pos) .distance(Quaternion::from_sv(1.0, new_pos.unwrap())); let new_rot = Quaternion::from_axis_angle( rel_axis_normalized, Deg(distance * 1.0) ); world.write_storage::<Transform>().get_mut(self.sphere.unwrap()).unwrap() .rotation = new_rot; self.rotation = new_rot.into(); self.previous_location = new_pos; }, None => {} }; } Trans::None } fn update(&mut self, data: StateData<GameData>) -> Trans<GameData<'a, 'b>> { data.data.update(&data.world); Trans::None } } fn left_mouse_state_change(event: &Event) -> Option<ElementState> { match *event { Event::WindowEvent { ref event, .. } => match *event { WindowEvent::MouseInput { state, button: MouseButton::Left, .. } => Some(state), _ => None }, _ => None } } fn get_new_cursor_position(event: &Event) -> Option<Vector3<f32>> { match *event { Event::WindowEvent { ref event, .. } => match *event { WindowEvent::CursorMoved { position, .. } => Some(Vector3{ x: position.0 as f32, y: 0.0 as f32, z: position.1 as f32 }), _ => None }, _ => None } } fn create_directional_vector(vector1: Vector3<f32>, vector2: Vector3<f32>) -> Vector3<f32> { Vector3 { x: vector1[0] - vector2[0], y: vector1[1] - vector2[1], z: vector1[2] - vector2[2] } }
// Copyright (c) 2019 Georg Brandl. Licensed under the Apache License, // Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> // or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at // your option. This file may not be copied, modified, or distributed except // according to those terms. use ngc::parse; #[test] fn test_parse() { let src = r#"; Try to exercise as much of the syntax as possible. ; comments anywhere, line numbers, and block deletion /G1 X1 0(a)(b) Y2(a);rest /(a) (a)N1 G#1 X-[10] (a) ; number formats #1=+1. (a) #2=1.5 #3=-.5 ; expressions G[[1+ 2]/ 3*4--5] G+SIN[0] G[ATAN[1]/[2]] G[1 LE 2] ; parameter references #1=[1+2] #<de pth>=1 #<de(a) pth>=2 #[1 ]=3 #-#2=[+ 5] #SIN [0]=7 ; LCNC doesn't like this. # 10 = EXISTS[#<blub>] "#; let parsed = r#"/ G1 X10 Y2 G#1 X-10 #1=1 #2=1.5 #3=-0.5 G[[[[1 + 2] / 3] * 4] - -5] GSIN[0] GATAN[1]/[2] G[1 LE 2] #1=[1 + 2] #<depth>=1 #<de(a)pth>=2 #1=3 #-#2=5 #[SIN[0]]=7 #10=EXISTS[#<blub>] "#; let prog = parse::parse("testfile", src).unwrap(); // make sure we count lines correctly assert_eq!(prog.blocks[0].lineno, 4); println!("{:#?}", prog); assert_eq!(prog.to_string(), parsed.replace("\n", " \n")); } #[test] fn test_invalid() { for snippet in &[ "$", // invalid characters "GG", // missing values "O10", // O-words are unsupported "(", // unclosed comments "(\n)", // comments spanning lines "G(a)1", // comments between letter/value "G1(a)2", // comments within the value "G[1(a)+2]", // comments within an expression "G[1;]", // line comments within expression "G[TEST[x]]", // invalid function "#1.2=5", // fractional parameter number "#1=EXISTS[5]", // invalid EXISTS argument ] { assert!(parse::parse("testfile", snippet).is_err()); } }
use cgmath::Vector2; use specs::{self, Component}; use components::InitFromBlueprint; #[derive(Clone, Debug, Deserialize)] pub enum FireState { Idle, Fire(Vector2<f32>), Cooldown(f32) } impl Default for FireState { fn default() -> Self { FireState::Idle } } #[derive(Clone, Debug, Deserialize)] pub struct Shooter { pub projectile: String, pub velocity: f32, pub delay: f32, #[serde(default)] pub state: FireState, } impl Shooter { pub fn try_firing(&mut self, dir: Vector2<f32>) -> bool { if let FireState::Idle = self.state { self.state = FireState::Fire(dir); return true; } false } } impl Component for Shooter { type Storage = specs::HashMapStorage<Self>; } impl InitFromBlueprint for Shooter {}
use async_std::task; use clap::Clap; use hyperspace_server::{listen, run_bootstrap_node, Opts}; fn main() -> anyhow::Result<()> { env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); let opts: Opts = Opts::parse(); task::block_on(async_main(opts)) } async fn async_main(opts: Opts) -> anyhow::Result<()> { if opts.dht { let (addr, task) = run_bootstrap_node(opts.address).await?; log::info!("bootstrap node address: {}", addr); task.await.map_err(|e| e.into()) } else { listen(opts).await } }
use nix::errno::Errno; use nix::sys::termios; use nix::{Error, unistd}; #[test] fn test_tcgetattr() { for fd in 0..5 { let termios = termios::tcgetattr(fd); match unistd::isatty(fd) { // If `fd` is a TTY, tcgetattr must succeed. Ok(true) => assert!(termios.is_ok()), // If it's an invalid file descriptor, tcgetattr should also return // the same error Err(Error::Sys(Errno::EBADF)) => { assert_eq!(termios.err(), Some(Error::Sys(Errno::EBADF))); }, // Otherwise it should return any error _ => assert!(termios.is_err()) } } }
#[cfg(feature = "case_mod")] pub mod case_mod; pub use super::parser::TeraFilter;
// q0112_path_sum struct Solution; use crate::util::TreeNode; use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, sum: i32) -> bool { if let Some(rrc_t) = root { let tn = rrc_t.borrow(); match (&tn.left, &tn.right) { (Some(ln), Some(rn)) => { let new_sum = sum - tn.val; let new_tree1 = Some(Rc::clone(rn)); let new_tree2 = Some(Rc::clone(ln)); return Solution::has_path_sum(new_tree1, new_sum) || Solution::has_path_sum(new_tree2, new_sum); } (Some(ln), None) => { let new_sum = sum - tn.val; let new_tree = Some(Rc::clone(ln)); return Solution::has_path_sum(new_tree, new_sum); } (None, Some(rn)) => { let new_sum = sum - tn.val; let new_tree = Some(Rc::clone(rn)); return Solution::has_path_sum(new_tree, new_sum); } (None, None) => return tn.val == sum, } } else { return false; } } } #[cfg(test)] mod tests { use super::Solution; use crate::util::TreeNode; #[test] fn it_works() { assert_eq!( true, Solution::has_path_sum( TreeNode::build_with_str("[5,4,8,11,null,13,4,7,2,null,null,null,1]"), 22 ) ); } }
pub fn vec_macro() { let mut v = vec![2, 3, 5, 7]; println!("{:?}", v); assert_eq!(v.iter().fold(1, |a, b| a * b), 210); v.push(11); v.push(13); let fun1 = v.iter().fold(1, |a, b| a * b); println!("{:?}", fun1); assert_eq!(fun1, 30030); }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// AwsAccountAndLambdaRequest : AWS account ID and Lambda ARN. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AwsAccountAndLambdaRequest { /// Your AWS Account ID without dashes. #[serde(rename = "account_id")] pub account_id: String, /// ARN of the Datadog Lambda created during the Datadog-Amazon Web services Log collection setup. #[serde(rename = "lambda_arn")] pub lambda_arn: String, } impl AwsAccountAndLambdaRequest { /// AWS account ID and Lambda ARN. pub fn new(account_id: String, lambda_arn: String) -> AwsAccountAndLambdaRequest { AwsAccountAndLambdaRequest { account_id, lambda_arn, } } }
extern crate wikipedia; use std::env::args; use std::io::stdin; fn pick_a_number() -> usize { let mut selection = String::new(); println!("Please enter the number of the result you want to translate."); stdin().read_line(&mut selection).unwrap(); selection.trim().parse().unwrap() } fn main() { let lang = args().nth(1).map(String::from); let term = args().nth(2).map(String::from); if let (Some(lang), Some(term)) = (lang, term) { let mut wiki = wikipedia::Wikipedia::<wikipedia::http::default::Client>::default(); wiki.language = lang; let results = wiki.search(&term).unwrap(); for (i, result ) in results.iter().enumerate() { println!("{}) {}", i, result); } if let Some(title) = results.get(pick_a_number()) { let page = wiki.page_from_title(title.to_owned()); for lang in page.get_langs().unwrap() { println!("{} ({})", lang.translation, lang.lang); } } } }
pub struct Sprite { pub rows: Vec<u8>, } pub const SPRITE_SIZE: u8 = 5; pub fn init_sprites() -> [Sprite; 0x10] { [Sprite { rows: vec![0xF0, 0x90, 0x90, 0x90, 0xF0], }, Sprite { rows: vec![0x20, 0x60, 0x20, 0x20, 0x70], }, Sprite { rows: vec![0xF0, 0x10, 0xF0, 0x80, 0xF0], }, Sprite { rows: vec![0xF0, 0x10, 0xF0, 0x10, 0xF0], }, Sprite { rows: vec![0x90, 0x90, 0xF0, 0x10, 0x10], }, Sprite { rows: vec![0xF0, 0x80, 0xF0, 0x10, 0xF0], }, Sprite { rows: vec![0xF0, 0x80, 0xF0, 0x90, 0xF0], }, Sprite { rows: vec![0xF0, 0x10, 0x20, 0x40, 0x40], }, Sprite { rows: vec![0xF0, 0x90, 0xF0, 0x90, 0xF0], }, Sprite { rows: vec![0xF0, 0x90, 0xF0, 0x10, 0xF0], }, Sprite { rows: vec![0xF0, 0x90, 0xF0, 0x90, 0x90], }, Sprite { rows: vec![0xE0, 0x90, 0xE0, 0x90, 0xE0], }, Sprite { rows: vec![0xF0, 0x80, 0x80, 0x80, 0xF0], }, Sprite { rows: vec![0xE0, 0x90, 0x90, 0x90, 0xE0], }, Sprite { rows: vec![0xF0, 0x80, 0xF0, 0x80, 0xF0], }, Sprite { rows: vec![0xF0, 0x80, 0xF0, 0x80, 0x80], }] }
#[doc = "Reader of register HVLDO_CTRL"] pub type R = crate::R<u32, super::HVLDO_CTRL>; #[doc = "Writer for register HVLDO_CTRL"] pub type W = crate::W<u32, super::HVLDO_CTRL>; #[doc = "Register HVLDO_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::HVLDO_CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `ADFT_EN`"] pub type ADFT_EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ADFT_EN`"] pub struct ADFT_EN_W<'a> { w: &'a mut W, } impl<'a> ADFT_EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `ADFT_CTRL`"] pub type ADFT_CTRL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ADFT_CTRL`"] pub struct ADFT_CTRL_W<'a> { w: &'a mut W, } impl<'a> ADFT_CTRL_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 << 1)) | (((value as u32) & 0x0f) << 1); self.w } } #[doc = "Reader of field `VREF_EXT_EN`"] pub type VREF_EXT_EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VREF_EXT_EN`"] pub struct VREF_EXT_EN_W<'a> { w: &'a mut W, } impl<'a> VREF_EXT_EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `STATUS`"] pub type STATUS_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - ADFT enable"] #[inline(always)] pub fn adft_en(&self) -> ADFT_EN_R { ADFT_EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 1:4 - ADFT select"] #[inline(always)] pub fn adft_ctrl(&self) -> ADFT_CTRL_R { ADFT_CTRL_R::new(((self.bits >> 1) & 0x0f) as u8) } #[doc = "Bit 6 - Vref ext input enable."] #[inline(always)] pub fn vref_ext_en(&self) -> VREF_EXT_EN_R { VREF_EXT_EN_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 31 - hvldo LV detect status"] #[inline(always)] pub fn status(&self) -> STATUS_R { STATUS_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - ADFT enable"] #[inline(always)] pub fn adft_en(&mut self) -> ADFT_EN_W { ADFT_EN_W { w: self } } #[doc = "Bits 1:4 - ADFT select"] #[inline(always)] pub fn adft_ctrl(&mut self) -> ADFT_CTRL_W { ADFT_CTRL_W { w: self } } #[doc = "Bit 6 - Vref ext input enable."] #[inline(always)] pub fn vref_ext_en(&mut self) -> VREF_EXT_EN_W { VREF_EXT_EN_W { w: self } } }
use chrono::{DateTime, Local, Duration}; use arduino_mqtt_pin::pin::{PinState, PinValue, Temperature}; use crate::config::{ControlNodes, Settings}; use crate::repository::PinStateRepository; use arduino_mqtt_pin::helper::percent_to_analog; use crate::zone::{Zone}; use derive_new::{new}; #[derive(new)] pub struct ZoneStateDecider<'a> { temp_decider: &'a TemperatureStateDecider<'a>, config: &'a Settings } impl ZoneStateDecider<'_> { pub fn should_be_on(&self, last_state: &PinState, zone: &Zone, current_temperature: &Temperature, now: &DateTime<Local>) -> bool { if let Some(expected_temperature) = zone.get_expected_temperature(&now.time()) { if last_state.is_on() { *current_temperature < expected_temperature } else { *current_temperature < expected_temperature - Temperature::new(self.config.temperature_drop_wait()) } } else { false } } pub fn get_value_to_change_to(&self, last_state: &PinState, zone: &Zone, current_temperature: &Temperature, now: &DateTime<Local>) -> Option<PinValue> { let zone_should_be_on = self.should_be_on(last_state, zone, current_temperature, now); if last_state.is_on() && !zone_should_be_on { return Some(PinValue::Analog(0u16)); } if !last_state.is_on() && zone_should_be_on { return Some(self.temp_decider.get_expected_value(current_temperature, zone, now)); } None } } #[derive(new)] pub struct TemperatureStateDecider<'a> { config: &'a Settings } impl TemperatureStateDecider<'_> { pub fn get_expected_value(&self, current_temperature: &Temperature, zone: &Zone, now: &DateTime<Local>) -> PinValue { let expected_temperature = match zone.get_expected_temperature(&now.time()) { Some(t) => t, _ => return PinValue::Analog(0) }; if *current_temperature >= expected_temperature { return PinValue::Analog(0); } let diff = (expected_temperature - current_temperature.clone()).abs(); let value = if diff <= Temperature::new(self.config.min_temperature_diff_for_pwm()) { percent_to_analog(self.config.min_pwm_state()) } else if diff < Temperature::new(1f32) { percent_to_analog((diff.value * 100f32) as u8) } else { percent_to_analog(100) }; PinValue::Analog(value) } } #[derive(new)] pub struct HeaterDecider<'a> { repository: &'a PinStateRepository<'a>, config: &'a Settings } impl HeaterDecider<'_> { pub fn should_be_on(&self, nodes: &ControlNodes, now: &DateTime<Local>) -> bool { if let Some(first_zone_on) = self.repository.get_first_zone_on_dt(nodes, &(*now - Duration::hours(24))) { return *now - first_zone_on > Duration::seconds(self.config.acctuator_warmup_time() as i64); } false } pub fn can_turn_zones_off(&self, state: &PinState, now: &DateTime<Local>) -> bool { !state.is_on() && *now - state.dt > Duration::seconds(self.config.heater_pump_stop_time() as i64) } } #[cfg(test)] mod test_deciders { use super::*; use chrono::{TimeZone, NaiveTime}; use crate::repository::test_repository::{create_nodes, create_repository}; use crate::zone::{Interval}; use crate::config::{Config}; use diesel::{SqliteConnection, Connection}; use crate::embedded_migrations; fn create_zone() -> (Zone, Settings) { let config = Settings::new(Config::new(String::from("test"), String::from("host"), String::from("main"), 3)); let intervals = vec![ Interval::new(NaiveTime::from_hms(8, 0, 0), NaiveTime::from_hms(9, 0, 0), Temperature::new(20.0)), Interval::new(NaiveTime::from_hms(23, 1, 0), NaiveTime::from_hms(23, 3, 3), Temperature::new(30.5)) ]; (Zone::new(String::from("zone1"), 1, intervals, 2), config) } speculate! { describe "zone temperature" { before { let (zone, config) = create_zone(); let decider = TemperatureStateDecider::new(&config); } it "should match value" { for (expected, temp, hour) in vec![ (1023, 19.0, 8), (306, 19.8, 8), (716, 19.3, 8), (1023, 2.3, 8), (0, 20.0, 8), (0, 20.0, 9), ] { assert_eq!( decider.get_expected_value( &Temperature::new(temp), &zone, &Local.ymd(2019, 8, 1).and_hms(hour, 0, 0) ).as_u16(), expected ); } } } describe "zone states" { before { let (zone, config) = create_zone(); let temp_decider = TemperatureStateDecider::new(&config); let zone_decider = ZoneStateDecider::new(&temp_decider, &config); } it "should provide zone state" { for (expected, value, temp, hour) in vec![ (true, 1023, 19.0, 8), (true, 0, 19.0, 8), (true, 306, 19.8, 8), (true, 716, 19.3, 8), (true, 0, 19.25, 8), (false, 0, 19.4, 8), (false, 716, 20.0, 8), (false, 716, 19.0, 9), (false, 0, 19.0, 9), ] { assert_eq!( zone_decider.should_be_on( &PinState::new(1, PinValue::Analog(value), Local.ymd(2019, 8, 1).and_hms(8, 0, 0), None), &zone, &Temperature::new(temp), &Local.ymd(2019, 8, 1).and_hms(hour, 0, 0) ), expected, "test with {} {}", value, temp ); } } } describe "heater state" { before { let connection = SqliteConnection::establish(":memory:").unwrap(); embedded_migrations::run(&connection); let config = Settings::new(Config::new("test".to_owned(), "host".to_owned(), "main".to_owned(), 34)); let repository = create_repository(&connection); let heater_decider = HeaterDecider::new(&repository, &config); } it "should be on" { let expected = Local.ymd(2019, 8, 2).and_hms(8, 0, 0); let nodes = create_nodes(); assert!(heater_decider.should_be_on(&nodes, &Local.ymd(2019, 8, 3).and_hms(7, 0, 0)), "{:?}", nodes); assert!(heater_decider.should_be_on(&nodes, &Local.ymd(2019, 8, 2).and_hms(8, 5, 1)), "{:?}", nodes); assert!(!heater_decider.should_be_on(&nodes, &Local.ymd(2019, 8, 2).and_hms(8, 5, 0)), "{:?}", nodes); assert!(!heater_decider.should_be_on(&nodes, &Local.ymd(2019, 8, 4).and_hms(7, 0, 0)), "{:?}", nodes); } it "can turn zones off" { let state = PinState::new(34, PinValue::Analog(0), Local.ymd(2019, 8, 1).and_hms(8, 0, 0), None); assert!(!heater_decider.can_turn_zones_off(&state, &Local.ymd(2019, 8, 1).and_hms(8, 0, 0))); assert!(!heater_decider.can_turn_zones_off(&state, &Local.ymd(2019, 8, 1).and_hms(8, 10, 0))); assert!(heater_decider.can_turn_zones_off(&state, &Local.ymd(2019, 8, 1).and_hms(8, 10, 1))); } } } }
use parquet_format_async_temp::DataPageHeaderV2; use crate::compression::{create_codec, Codec}; use crate::error::Result; use super::{PageIterator, StreamingIterator}; use crate::page::{CompressedDataPage, DataPage, DataPageHeader}; fn decompress_v1(compressed: &[u8], decompressor: &mut dyn Codec, buffer: &mut [u8]) -> Result<()> { decompressor.decompress(compressed, buffer) } fn decompress_v2( compressed: &[u8], page_header: &DataPageHeaderV2, decompressor: &mut dyn Codec, buffer: &mut [u8], ) -> Result<()> { // When processing data page v2, depending on enabled compression for the // page, we should account for uncompressed data ('offset') of // repetition and definition levels. // // We always use 0 offset for other pages other than v2, `true` flag means // that compression will be applied if decompressor is defined let offset = (page_header.definition_levels_byte_length + page_header.repetition_levels_byte_length) as usize; // When is_compressed flag is missing the page is considered compressed let can_decompress = page_header.is_compressed.unwrap_or(true); if can_decompress { (&mut buffer[..offset]).copy_from_slice(&compressed[..offset]); decompressor.decompress(&compressed[offset..], &mut buffer[offset..])?; } else { buffer.copy_from_slice(compressed); } Ok(()) } /// decompresses a page. /// If `page.buffer.len() == 0`, there was no decompression and the buffer was moved. /// Else, decompression took place. pub fn decompress_buffer( compressed_page: &mut CompressedDataPage, buffer: &mut Vec<u8>, ) -> Result<bool> { let codec = create_codec(&compressed_page.compression())?; if let Some(mut codec) = codec { // the buffer must be decompressed; do it so now, writing the decompressed data into `buffer` let compressed_buffer = &compressed_page.buffer; buffer.resize(compressed_page.uncompressed_size(), 0); match compressed_page.header() { DataPageHeader::V1(_) => decompress_v1(compressed_buffer, codec.as_mut(), buffer)?, DataPageHeader::V2(header) => { decompress_v2(compressed_buffer, header, codec.as_mut(), buffer)? } } Ok(true) } else { // page.buffer is already decompressed => swap it with `buffer`, making `page.buffer` the // decompression buffer and `buffer` the decompressed buffer std::mem::swap(&mut compressed_page.buffer, buffer); Ok(false) } } /// Decompresses the page, using `buffer` for decompression. /// If `page.buffer.len() == 0`, there was no decompression and the buffer was moved. /// Else, decompression took place. pub fn decompress( mut compressed_page: CompressedDataPage, buffer: &mut Vec<u8>, ) -> Result<DataPage> { decompress_buffer(&mut compressed_page, buffer)?; Ok(DataPage::new( compressed_page.header, std::mem::take(buffer), compressed_page.dictionary_page, compressed_page.descriptor, )) } fn decompress_reuse<R: std::io::Read>( mut compressed_page: CompressedDataPage, iterator: &mut PageIterator<R>, buffer: &mut Vec<u8>, decompressions: &mut usize, ) -> Result<DataPage> { let was_decompressed = decompress_buffer(&mut compressed_page, buffer)?; let new_page = DataPage::new( compressed_page.header, std::mem::take(buffer), compressed_page.dictionary_page, compressed_page.descriptor, ); if was_decompressed { *decompressions += 1; } else { iterator.reuse_buffer(compressed_page.buffer) } Ok(new_page) } /// Decompressor that allows re-using the page buffer of [`PageIterator`] pub struct Decompressor<'a, R: std::io::Read> { iter: PageIterator<'a, R>, buffer: Vec<u8>, current: Option<Result<DataPage>>, decompressions: usize, } impl<'a, R: std::io::Read> Decompressor<'a, R> { pub fn new(iter: PageIterator<'a, R>, buffer: Vec<u8>) -> Self { Self { iter, buffer, current: None, decompressions: 0, } } pub fn into_buffers(mut self) -> (Vec<u8>, Vec<u8>) { let mut a = self .current .map(|x| x.map(|x| x.buffer).unwrap_or_else(|_| Vec::new())) .unwrap_or(self.iter.buffer); if self.decompressions % 2 == 0 { std::mem::swap(&mut a, &mut self.buffer) }; (a, self.buffer) } } impl<'a, R: std::io::Read> StreamingIterator for Decompressor<'a, R> { type Item = Result<DataPage>; fn advance(&mut self) { if let Some(Ok(page)) = self.current.as_mut() { self.buffer = std::mem::take(&mut page.buffer); } let next = self.iter.next().map(|x| { x.and_then(|x| { decompress_reuse( x, &mut self.iter, &mut self.buffer, &mut self.decompressions, ) }) }); self.current = next; } fn get(&self) -> Option<&Self::Item> { self.current.as_ref() } }
use std::collections::{HashMap, HashSet}; use Index; use Retriever; pub struct BM25 { index: Index, avdl: f64, // Term to number of documents containing that term doc_freq: HashMap<String, usize>, // Document id to length cache doc_len: HashMap<String, usize>, corpus_size: f64, } impl BM25 { pub fn new(index: Index) -> BM25 { let mut doc_lengths = HashMap::new(); let mut doc_f = HashMap::new(); let mut doc_ids = HashSet::new(); for(term, i_list) in index.iter() { for (doc, freq) in i_list.iter() { let len = doc_lengths.entry(doc.clone()).or_insert(0); *len += freq; let f = doc_f.entry(term.clone()).or_insert(0); *f += 1; doc_ids.insert(doc.clone()); } } let total_len_all: usize = doc_lengths.values().sum(); BM25 { avdl: (total_len_all as f64) / (doc_lengths.len() as f64), doc_freq: doc_f, doc_len: doc_lengths, index: index, corpus_size: doc_ids.len() as f64, } } } impl Retriever for BM25 { fn rank(&mut self, query: Vec<String>) -> Vec<(String, f64)> { let mut documents = HashSet::new(); for qt in query.iter() { if let Some(il) = self.index.get(qt) { for doc in il.keys() { documents.insert(doc.clone()); } } } let mut results: Vec<(String, f64)> = Vec::new(); for doc in documents.iter() { let mut sum = 0.0; for term in query.iter() { let ni: f64 = *self.doc_freq.get(term).unwrap_or(&0) as f64; let n = self.corpus_size; let term_il = match self.index.get(term) { Some(e) => e.clone(), None => HashMap::new(), }; let fi: f64 = *term_il.get(doc).unwrap_or(&0) as f64; let ni_o_n_ni: f64 = (ni + 0.5) / (n - ni + 0.5); let k1_fi: f64 = (1.2 + 1.0) * fi; let dl: f64 = *self.doc_len.get(doc).unwrap() as f64; let k: f64 = 1.2 * ((1.0 - 0.75) + (0.75 * (dl / self.avdl))); let matching_query_terms: Vec<&String> = query.iter() .filter(|s| s.to_string() == term.to_string()) .collect(); let qfi: usize = matching_query_terms.len(); let t_1: f64 = 1.0 / ni_o_n_ni; let t_2: f64 = k1_fi / (k + fi); let t_3: f64 = (101 * qfi) as f64 / (100 + qfi) as f64; sum += t_1.log2() * t_2 * t_3; } results.push((doc.clone(), sum)); } results.sort_by(|a, b| (b.1).partial_cmp(&a.1).unwrap()); results } }
/* Copyright 2016 Robert Lathrop 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.*/ /// This module declares the player object. /// The player defines attributes such as the tile to represent the character, /// the health, mana pool, character name and speed. ///Player implements Controllable so that it can be updated from the gameloop extern crate mio; use game::characters::Controllable; use game::characters::Direction; use game::characters::ControllableType; use game::gamemap::GameMap; use std::collections::HashMap; use std::collections::HashSet; ///Defines the Player struct. #[derive(Clone)] pub struct Player{ id: i64, token: mio::Token, pub tile: String, pub hp: i32, max_hp: i32, pub name: String, pub speed: u8, pub index: u32, pub viewport_x: u8, pub viewport_y: u8, //Coordinates (x, y). This is where the char is currently trying to move to. It has to be interpereted by the Map, and converted to an x, y relative to the actual map, not the user. movement: Option<u32>, movement_ticks: u8, direction: Direction, commands: Vec<String>, } /// This defines the custom functions for player. This handles things like getting commands & mouse movement impl Player { pub fn new(tile: String, token: mio::Token) -> Player { Player { id: 0, token: token, tile: format!("players/{}.",tile), hp: 500, max_hp: 500, name: "empty".to_string(), speed: 10, viewport_x: 13, viewport_y: 13, commands: vec![], direction: Direction::South, index: 0, movement: None, movement_ticks: 0, } } ///This is an assisting function for moveable and the A* algorithm. It basically just tries to ///find the lowest value in the open tiles in the A* algorithm fn lowest_estimate(open: &HashSet<u32>, estimates: &mut HashMap<u32, u32>) -> u32{ let mut min = 9999; let mut index_min = 0; for node in open.iter() { let val = estimates.entry(*node).or_insert(255); if *val < min { min = val.clone(); index_min = node.clone(); } } index_min } ///Given a map of tiles to the tile that led to it and the ending tile, it will go back through ///the map, finding the first move on the path fn find_move(path: &HashMap<u32, u32>, end: u32) -> u32 { let mut current = end; loop { let temp = match path.get(&current) { Some(previous) => { previous.clone() }, None => { break; } }; if !path.contains_key(&temp) { break; } current = temp.clone(); } current } ///Computes the shortest path according to the A* algorithm. Gives the next step in the found path fn path_next(width: u8, height: u8, blocked: &Vec<bool>, start: u32, end: u32) -> Option<u32> { //println!("Path!"); //A* algorithm let mut closed = HashSet::new(); //This should be a priority queue (or min-heap) let mut open = HashSet::new(); //This is a map where each node records the node that came before it. //Why not use a doubly linked list? let mut path = HashMap::new(); open.insert(start.clone()); let mut score_from:HashMap<u32, u32> = HashMap::new(); score_from.insert(start.clone(), 0); let mut estimate_to: HashMap<u32, u32> = HashMap::new(); estimate_to.insert(start.clone(), Player::hueristic(width.clone(), start.clone(), end.clone())); while open.len() > 0 { //Grab start with the smallest estimate let current = Player::lowest_estimate(&open, &mut estimate_to); if current == end { //return the index of the first move //println!("Finished! {} {}", current, end); return Some(Player::find_move(&path, end.clone())); } open.remove(&current); closed.insert(current.clone()); //Need to figure out how to get all neighbors let neighbors = Player::find_neighbors(current, width, height, blocked); for neighbor in neighbors.iter() { //println!("Neighbor {}", neighbor); if closed.contains(neighbor) { continue; } //println!("current {}", current); //This should always have a value... let possible_score = score_from.get(&current).unwrap() + 1 as u32; if !open.contains(neighbor) { path.insert(neighbor.clone(), current); open.insert(neighbor.clone()); score_from.insert(neighbor.clone(), possible_score.clone()); //println!("possible score {}", possible_score); estimate_to.insert(neighbor.clone(), possible_score + Player::hueristic(width.clone(), neighbor.clone(), end.clone())); } else { match score_from.clone().get_mut(neighbor) { Some(ref mut value) => { if value.clone() > possible_score { continue; } else { let mut n = path.entry(neighbor.clone()).or_insert(current.clone()); *n = current.clone(); score_from.insert(neighbor.clone(), possible_score.clone()); estimate_to.insert(neighbor.clone(), possible_score + Player::hueristic(width.clone(), neighbor.clone(), end.clone())); } }, None => { path.insert(neighbor.clone(), current); score_from.insert(neighbor.clone(), possible_score.clone()); estimate_to.insert(neighbor.clone(),possible_score + Player::hueristic(width.clone(), neighbor.clone(), end.clone())); }, } } } } None } ///Gives a hueristic estimate by just doing the pythagorean theorem. fn hueristic(width: u8, start: u32, end: u32) -> u32{ //Just using pythagorean theorem to compute the shortest path. let dx = ((start % width as u32) as i32 - (end % width as u32) as i32).abs(); let dy = ((start / width as u32) as i32 - (end / width as u32) as i32).abs(); if dy == 0 { dx as u32 } else if dx == 0 { dy as u32 } else { //println!("heuristic vals {} {}", dx, dy); ((dx * dx + dy * dy) as f64).sqrt() as u32 } } ///Returns the found neighbors to a given index. Does one up, down, left and right. fn find_neighbors(index: u32, width: u8, height: u8, blocked: &Vec<bool>) -> Vec<u32> { let x = index % width as u32; let y = index / width as u32; let mut neighbors = vec![]; for dx in 0..3 { for dy in 0..3 { //if dy == dx || (dx == 0 && dy == 2) || (dx == 2 && dy == 0) { // continue; //} let current_x = (x as i32) + (dx as i32) -1; let current_y = (y as i32) + (dy as i32) -1; if current_x >=0 && current_y >=0 { if current_x as u32 >= width as u32 || current_y as u32 >= height as u32 { continue; } let i = (current_y as u32) * width as u32 + (current_x as u32); //println!("neighbor {}", i); //if not blocked, add to neighbors if !blocked[i as usize] { neighbors.push(i.clone()); } } } } neighbors } ///Checks the end index against the movement goal index. If they are the same, /// it wipes out the movement goalt. fn clear_movement_if_at_destination(&mut self, end: u32) { let replacement: Option<u32> = match self.movement { Some(e) => { if e == end { None } else { Some(e) } }, None => {None}, }; self.movement = replacement; } ///Grabs an available command from the queue. Manages movement by counting the number of cycles ///since last movment. This prefers movement over the top of the queue. SO basically /// /// This checks the number of ticks, against a threshold. If it is greater or equal, and there is a ///movement goal set, it will always do movement. Otherwise, it will increment ticks, and grab ///the top command from the queue. fn get_command(&mut self) -> Option<String> { let has_movement = match self.movement{ Some(_) => {true}, None => {false}, }; if has_movement && self.movement_ticks >= self.speed /* *self.slow */ { //The command returns the absolute location where the user wants to end up. The map knows it can only move 1 space towards that destination let end = self.movement.unwrap(); self.movement_ticks = 0; //println!("got command {}", end); Some(format!("end {}", end)) } else if self.commands.len() > 0 { self.movement_ticks = if self.movement_ticks == 255 { self.movement_ticks } else { self.movement_ticks + 1 }; self.commands.pop() } else { self.movement_ticks = if self.movement_ticks == 255 { self.movement_ticks } else { self.movement_ticks + 1 }; None } } } ///Implements the controllable trait for the player impl Controllable for Player { fn update(&mut self, width: u8, height: u8, blocked: &Vec<bool>) -> Option<Vec<(mio::Token, u8, String)>> { let c = self.get_command(); match c { Some(command) => { println!("{}", command); if command.starts_with("end") { let parts: Vec<&str> = command.split_whitespace().collect(); let end = parts[1].parse::<u32>().unwrap(); println!("Execute path: {} {}", self.index, end); let e = Player::path_next(width.clone(), height.clone(), &blocked, self.index.clone(), end); match e { Some(user_end) => { let x = self.index % width as u32; let y = self.index / width as u32; let dx = user_end % width as u32; let dy = user_end / width as u32; // Since the primary objective is east/west I will lean towards e/w when moving diagonally let mut dir = Direction::South; if dx > x as u32 { dir = Direction::East; } else if dx < x as u32 { dir = Direction::West; } else if dy < y as u32 { dir = Direction::North; } if blocked[user_end as usize] { return Some(vec![(self.token.clone(), 5, "Path Blocked".to_string()); 1]); } self.index = user_end; self.direction = dir; self.clear_movement_if_at_destination(user_end); None }, None => { Some(vec![(self.token.clone(), 5, "No Path Found".to_string()); 1]) }, } } else if command.starts_with("numpad-") { let parts: Vec<&str> = command.split("-").collect(); if parts.len() > 1 { match parts[1].parse::<u32>() { Ok(numpad) => { let mut x: u32 = self.index % width as u32; let mut y: u32 = self.index / width as u32; match numpad { 1 => { x -= 1; y += 1; }, 2 => { y += 1; }, 3 => { x += 1; y += 1; }, 4 => { x -= 1; }, 6 => { x += 1; }, 7 => { x -= 1; y -= 1; }, 8 => { y -= 1; }, 9 => { x += 1; y -= 1; }, _ => {}, }; self.movement = Some(y * width as u32 + x); }, Err(_) => {}, }; } None } else if command.starts_with("skin "){ let parts: Vec<&str> = command.split(" ").collect(); if parts.len() > 1 { if parts[1].starts_with("/") { self.tile = format!("{}.", parts[1].to_string()[1..].to_string()); } else { self.tile = format!("players/{}.", parts[1]); } Some(vec![(self.token.clone(), 3, "Skin Changed".to_string()); 1]) } else { None } } else if command.starts_with("#view ") { let parts: Vec<&str> = command.split(" ").collect(); if parts.len() > 2 { self.viewport_x = parts[1].parse::<u8>().unwrap(); self.viewport_y = parts[2].parse::<u8>().unwrap(); Some(vec![(self.token.clone(), 3, format!("View Changed {} {}", self.viewport_x, self.viewport_y).to_string()); 1]) } else { None } }else { //System message println!("{}", command); Some(vec![(self.token.clone(), 5, "Bad command".to_string()); 1]) } }, None => { None }, } } ///Used when drawing the screen fn get_location(&self) -> u32 { self.index } ///Gets the artwork fn get_tile(&self) -> String { let direction = match self.direction { Direction::South => {"S"}, Direction::North => {"N"}, Direction::East => {"E"}, Direction::West => {"W"}, _ => {"S"}, }; format!("{}{}",self.tile, direction) } ///Gets the Item size fn get_size(&self) -> (u32, u32) { (1, 1) } ///Get the token fn get_token(&self) -> Option<mio::Token> { Some(self.token.clone()) } fn get_hp(&self) -> Option<i32> { Some(self.hp) } fn set_location(&mut self, index: u32) { self.index = index; } fn does_block_index(&self, index: u32) -> bool { self.index == index } fn is_visible(&self, _: &GameMap) -> bool { true } fn hurt(&mut self, damage: i32) { self.hp = if self.hp > damage {self.hp - damage} else {self.max_hp}; } fn push_command(&mut self, command: String) { self.commands.insert(0, command); } fn set_movement(&mut self, end: u32) { self.movement = Some(end); } fn modify_connected_tiles(&mut self, _: u8, _: u8, _: &Vec<bool>) {} fn get_type(&self) -> ControllableType { ControllableType::Player } fn get_viewport(&self) -> (u8, u8) { (self.viewport_x, self.viewport_y) } }
use parameterized_macro::parameterized; // a trailing comma after v and w's arguments (multiple inputs) and after every attribute list #[parameterized( v = { 1, 2, 3, }, w = { 1, 2, 3, }, )] fn my_test(v: u32, w: u32) {} fn main() {}
mod bundle; pub mod components; mod resource; mod system; pub mod traits; pub use crate::bundle::DebugSystemBundle;
use crate::node; use std::any::Any; pub trait NodeBuilderResolver { fn get_pattern(&self) -> &str; fn resolve(&self, indents: usize, line: String) -> Box<dyn NodeBuilder>; } pub trait NodeBuilder { fn append_or_throwback(&mut self, line: String) -> Option<String>; fn build(self: Box<Self>) -> node::Node; } pub fn downcast_ref<T: Any>(builder: &Box<dyn NodeBuilder>) -> Option<&T> { as_any(builder).downcast_ref::<T>() } fn as_any(builder: &Box<dyn NodeBuilder>) -> &dyn Any { builder }
extern crate image; extern crate line_drawing; use line_drawing::*; use image::{DynamicImage, ImageBuffer, Rgb}; type Image = ImageBuffer<Rgb<u8>, Vec<u8>>; // Draw a line of pixels onto the image with a specific colour fn draw_line<T>(image: &mut Image, line: T, colour: [u8; 3]) where T: Iterator<Item = Point<i32>>, { for point in line { image.put_pixel(point.0 as u32, point.1 as u32, Rgb(colour)); } } // Draw an anti-aliased line of pixels fn draw_xiaolin_wu(image: &mut Image, line: XiaolinWu<f32, i32>) { for (point, value) in line { image.put_pixel( point.0 as u32, point.1 as u32, Rgb([(255.0 * value).round() as u8; 3]), ); } } fn main() { let mut image = DynamicImage::new_rgb8(300, 300).to_rgb8(); // Draw each of the different line types draw_line(&mut image, WalkGrid::new((10, 230), (50, 290)), [255, 0, 0]); draw_line( &mut image, Supercover::new((10, 210), (90, 290)), [255, 128, 0], ); draw_line( &mut image, Midpoint::new((10.0, 187.5), (122.22, 290.0)), [128, 255, 0], ); draw_line( &mut image, Bresenham::new((10, 165), (170, 290)), [0, 255, 0], ); // Draw two lines on top of each other to show how bresenham isn't symetrical let a = (10, 10); let b = (200, 290); draw_line(&mut image, Bresenham::new(a, b), [255, 0, 0]); draw_line(&mut image, Bresenham::new(b, a), [0, 128, 255]); // Draw a triangle made out of xiaolin wi lines let a = (275.0, 150.0); let b = (210.0, 285.0); let c = (290.0, 290.0); draw_xiaolin_wu(&mut image, XiaolinWu::new(a, b)); draw_xiaolin_wu(&mut image, XiaolinWu::new(b, c)); draw_xiaolin_wu(&mut image, XiaolinWu::new(c, a)); for point in BresenhamCircle::new(200, 100, 50) { image.put_pixel(point.0 as u32, point.1 as u32, Rgb([255, 0, 0])); } // Save the image image.save("example.png").unwrap(); }
//! Configuration utilities for game engine and your game. use semver::Version; /// This struct represents general configuration of game engine. #[derive(Debug, Clone)] pub struct Config { name: String, version: Version, enable_validation: bool, } pub const ENGINE_NAME: &str = env!("CARGO_CRATE_NAME", "library must be compiled by Cargo"); const ENGINE_VERSION_STR: &str = env!("CARGO_PKG_VERSION", "library must be compiled by Cargo"); lazy_static::lazy_static! { pub static ref ENGINE_VERSION: Version = ENGINE_VERSION_STR.parse().unwrap(); } impl Config { /// Creates new configuration with given name, version and validation usage. pub const fn new(name: String, version: Version, enable_validation: bool) -> Self { Self { name, version, enable_validation, } } /// Name of your game. pub fn name(&self) -> &str { &self.name } /// Semver version of your game. pub fn version(&self) -> &Version { &self.version } /// If game will use validation (useful for debugging). pub fn enable_validation(&self) -> bool { self.enable_validation } } impl Default for Config { fn default() -> Self { Self::new( "Hello World".to_string(), Version::new(0, 0, 0), cfg!(debug_assertions), ) } }
use crate::cell; use crate::cell::{Cell, Event, Merge}; use crate::propagator; use crate::propagator::{Propagator}; //use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::collections::HashSet; use std::fmt::Debug; pub struct Network<A> { cells: Vec<Cell<A>>, cell_neighbours: HashMap<cell::ID, Vec<propagator::ID>>, propagators: Vec<Propagator<A>>, propagator_neighbours: HashMap<propagator::ID, Vec<cell::ID>>, alerted: HashSet<propagator::ID> } impl<A> Network<A> where A: Debug + Merge + Clone + PartialEq { pub fn new() -> Self { Self { cells: Vec::new(), cell_neighbours: HashMap::new(), propagators: Vec::new(), propagator_neighbours: HashMap::new(), alerted: HashSet::new() } } pub fn label_cell(&mut self, id: cell::ID, label: &str) { self.cells[id].set_label(label); } pub fn label_propagator(&mut self, id: cell::ID, label: &str) { //TODO } pub fn make_cell(&mut self) -> cell::ID { self.cells.push(Cell::new()); self.cells.len() - 1 } pub fn alert_all_propagators(&mut self) { for id in 0..self.propagators.len() - 1 { self.alerted.insert(id); } } pub fn make_propagator(&mut self, propagator: Propagator<A>, cell_ids: &[cell::ID]) -> propagator::ID { self.propagators.push(propagator); let id = self.propagators.len() - 1; self.alerted.insert(id); self.propagator_neighbours.insert(id, cell_ids.into()); for &cell_id in cell_ids { match self.cell_neighbours.get_mut(&cell_id) { Some(neighbours) => neighbours.push(id), None => { let mut neighbours = Vec::new(); neighbours.push(id); self.cell_neighbours.insert(cell_id, neighbours); } } } id } pub fn read_cell(&self, id: cell::ID) -> Option<A> { self.cells[id].to_option() } pub fn write_cell(&mut self, id: cell::ID, value: A) { let cell = &mut self.cells[id]; match cell.merge(&value) { Event::Unchanged => {} Event::Contradiction => { panic!("Contradiction!"); } Event::Changed => { match self.cell_neighbours.get(&id) { Some(neighbours) => { for &prop_id in neighbours.iter() { self.alerted.insert(prop_id); } } None => {} }; } } } pub fn num_cells(&self) -> usize { self.cells.len() } pub fn run(&mut self) { while self.alerted.len() > 0 { let mut writes : Vec<(cell::ID, A)>= Vec::new(); for &prop_id in self.alerted.iter() { let propagator = &self.propagators[prop_id]; let cell_ids = self.propagator_neighbours.get(&prop_id).unwrap(); let input_cells : Vec<&Cell<A>> = cell_ids .iter() .take(cell_ids.len() - 1) .map(|&cell_id| { &self.cells[cell_id] }) .collect(); let &output_id = cell_ids.last().unwrap(); let is_ready = input_cells.iter().all(|&cell| !cell.is_empty()); if is_ready { let values : Vec<A> = input_cells .iter() .map(|&cell| cell.unwrap()) .collect(); let value = propagator.run(&values); writes.push((output_id, value)); } } self.alerted.clear(); for (output_id, output) in writes.iter() { self.write_cell(*output_id, output.clone()); } } } }
use {Linkage, ValueRef, TypeRef, ModuleRef}; use libc; cpp! { #include "ffi_helpers.h" #include "llvm/IR/Module.h" pub fn LLVMRustFunctionCreate(ty: TypeRef as "llvm::Type*", linkage: Linkage as "unsigned", name: *const libc::c_char as "const char*", module: ModuleRef as "llvm::Module*") -> ValueRef as "llvm::Value*" { return llvm::Function::Create(support::cast<llvm::FunctionType>(ty), (llvm::GlobalValue::LinkageTypes)linkage, name, module); } pub fn LLVMRustFunctionAddBlock(func: ValueRef as "llvm::Value*", block: ValueRef as "llvm::Value*") { support::cast<llvm::Function>(func)->getBasicBlockList().addNodeToList( support::cast<llvm::BasicBlock>(block)); } }
use ::structs::*; pub fn tick(event: Coordinate) { println!("Data is sinking in: {:?}", &event); }
use std::net::Ipv4Addr; use dhcp; /// DHCP message length pub const MESSAGE_LEN: usize = 548; const MAGIC_COOKIE: [u8; 4] = [99, 130, 83, 99]; pub struct Message { pub op: u8, pub htype: u8, pub hlen: u8, pub hops: u8, pub xid: u32, pub secs: u16, pub flags: u16, pub ciaddr: Ipv4Addr, pub yiaddr: Ipv4Addr, pub siaddr: Ipv4Addr, pub giaddr: Ipv4Addr, pub chaddr: Vec<u8>, // TODO replace with std::ffi::CString when available pub sname: Vec<u8>, // TODO replace with std::ffi::CString when available pub file: Vec<u8>, pub options: Vec<dhcp::Option>, } impl Message { pub fn new() -> Self { Message { op: 1, // BOOTREQUEST htype: 1, // Ethernet (10Mb) hlen: 6, hops: 0, xid: 0, secs: 0, flags: 0, ciaddr: Ipv4Addr::new(0, 0, 0, 0), yiaddr: Ipv4Addr::new(0, 0, 0, 0), siaddr: Ipv4Addr::new(0, 0, 0, 0), giaddr: Ipv4Addr::new(0, 0, 0, 0), chaddr: vec![0, 0, 0, 0, 0, 0], sname: Vec::new(), file: Vec::new(), options: Vec::new(), } } pub fn from_bytes(bytes: &[u8]) -> Message { assert!(bytes.len() == MESSAGE_LEN); let mut msg = Message::new(); msg.op = bytes[0]; msg.htype = bytes[1]; msg.hlen = bytes[2]; msg.hops = bytes[3]; msg.xid = bytes_to_num_be!(&bytes[4..8], 4, u32); msg.secs = bytes_to_num_be!(&bytes[8..10], 2, u16); msg.flags = bytes_to_num_be!(&bytes[10..12], 2, u16); msg.ciaddr = bytes_to_ipv4_addr!(&bytes[12..16]); msg.yiaddr = bytes_to_ipv4_addr!(&bytes[16..20]); msg.siaddr = bytes_to_ipv4_addr!(&bytes[20..24]); msg.giaddr = bytes_to_ipv4_addr!(&bytes[24..28]); msg.chaddr = bytes[28..(28 + msg.hlen as usize)].to_vec(); msg.sname = bytes[44..108].to_vec(); msg.file = bytes[108..236].to_vec(); msg.options = dhcp::parse_options(&bytes[240..]); msg } pub fn to_bytes(&self) -> Vec<u8> { assert!(self.hlen as usize == self.chaddr.len()); assert!(self.chaddr.len() <= 16); assert!(self.sname.len() <= 64); assert!(self.file.len() <= 128); let mut bytes = [0; MESSAGE_LEN]; bytes[0] = self.op; bytes[1] = self.htype; bytes[2] = self.hlen; bytes[3] = self.hops; bytes[4..8].copy_from_slice(&num_to_bytes_be!(self.xid, 4)); bytes[8..10].copy_from_slice(&num_to_bytes_be!(self.secs, 2)); bytes[10..12].copy_from_slice(&num_to_bytes_be!(self.flags, 2)); bytes[12..16].copy_from_slice(&self.ciaddr.octets()); bytes[16..20].copy_from_slice(&self.yiaddr.octets()); bytes[20..24].copy_from_slice(&self.siaddr.octets()); bytes[24..28].copy_from_slice(&self.giaddr.octets()); bytes[28..(28 + self.hlen as usize)].copy_from_slice(&self.chaddr); bytes[44..(44 + self.sname.len())].copy_from_slice(&self.sname); bytes[44..(44 + self.file.len())].copy_from_slice(&self.file); bytes[236..240].copy_from_slice(&MAGIC_COOKIE); dhcp::serialize_options(&self.options, &mut bytes[240..]); bytes.to_vec() } }
use dwdemo::*; fn main() { let _b = Bsim4Model::default(); println!("main ran! "); }
use std::sync::Arc; use eyre::Report; use rosu_v2::prelude::{GameMode, OsuError, Score, Username}; use twilight_model::{ application::interaction::{ application_command::{CommandDataOption, CommandOptionValue}, ApplicationCommand, }, id::{marker::UserMarker, Id}, }; use crate::{ commands::{check_user_mention, parse_discord, parse_mode_option, DoubleResultCow}, database::UserConfig, embeds::{EmbedData, LeaderboardEmbed}, error::Error, pagination::{LeaderboardPagination, Pagination}, util::{ constants::{ common_literals::{DISCORD, INDEX, MODE, MODS, MODS_PARSE_FAIL, NAME}, AVATAR_URL, GENERAL_ISSUE, OSU_API_ISSUE, OSU_WEB_ISSUE, }, matcher, numbers, osu::ModSelection, InteractionExt, MessageExt, }, Args, BotResult, CommandData, Context, MessageBuilder, }; pub(super) async fn _recentleaderboard( ctx: Arc<Context>, data: CommandData<'_>, args: RecentLeaderboardArgs, national: bool, ) -> BotResult<()> { let RecentLeaderboardArgs { config, name, index, mods, } = args; let mode = config.mode.unwrap_or(GameMode::STD); let author_name = config.into_username(); let name = match name.as_ref().or_else(|| author_name.as_ref()) { Some(name) => name.as_str(), None => return super::require_link(&ctx, &data).await, }; let limit = index.map_or(1, |n| n + (n == 0) as usize); if limit > 100 { let content = "Recent history goes only 100 scores back."; return data.error(&ctx, content).await; } // Retrieve the recent scores let scores_fut = ctx .osu() .user_scores(name) .recent() .include_fails(true) .mode(mode) .limit(limit); let (map, mapset, user) = match scores_fut.await { Ok(scores) if scores.len() < limit => { let content = format!( "There are only {} many scores in `{}`'{} recent history.", scores.len(), name, if name.ends_with('s') { "" } else { "s" } ); return data.error(&ctx, content).await; } Ok(mut scores) => match scores.pop() { Some(score) => { let Score { map, mapset, user, .. } = score; (map.unwrap(), mapset.unwrap(), user.unwrap()) } None => { let content = format!( "No recent {}plays found for user `{}`", match mode { GameMode::STD => "", GameMode::TKO => "taiko ", GameMode::CTB => "ctb ", GameMode::MNA => "mania ", }, name ); return data.error(&ctx, content).await; } }, Err(OsuError::NotFound) => { let content = format!("User `{name}` was not found"); return data.error(&ctx, content).await; } Err(why) => { let _ = data.error(&ctx, OSU_API_ISSUE).await; return Err(why.into()); } }; // Retrieve the map's leaderboard let scores_fut = ctx.clients.custom.get_leaderboard( map.map_id, national, match mods { Some(ModSelection::Exclude(_)) | None => None, Some(ModSelection::Include(m)) | Some(ModSelection::Exact(m)) => Some(m), }, mode, ); let scores = match scores_fut.await { Ok(scores) => scores, Err(why) => { let _ = data.error(&ctx, OSU_WEB_ISSUE).await; return Err(why.into()); } }; let amount = scores.len(); // Accumulate all necessary data let first_place_icon = scores .first() .map(|_| format!("{}{}", AVATAR_URL, user.user_id)); let pages = numbers::div_euclid(10, scores.len()); let data_fut = LeaderboardEmbed::new( author_name.as_deref(), &map, Some(&mapset), (!scores.is_empty()).then(|| scores.iter().take(10)), &first_place_icon, 0, &ctx, (1, pages), ); let embed_data = match data_fut.await { Ok(data) => data, Err(why) => { let _ = data.error(&ctx, GENERAL_ISSUE).await; return Err(why); } }; // Sending the embed let content = format!("I found {amount} scores with the specified mods on the map's leaderboard"); let embed = embed_data.into_builder().build(); let builder = MessageBuilder::new().content(content).embed(embed); let response_raw = data.create_message(&ctx, builder).await?; // Set map on garbage collection list if unranked let gb = ctx.map_garbage_collector(&map); // Skip pagination if too few entries if scores.len() <= 10 { return Ok(()); } let response = response_raw.model().await?; // Pagination let pagination = LeaderboardPagination::new( response, map, Some(mapset), scores, author_name, first_place_icon, Arc::clone(&ctx), ); gb.execute(&ctx); let owner = data.author()?.id; tokio::spawn(async move { if let Err(err) = pagination.start(&ctx, owner, 60).await { warn!("{:?}", Report::new(err)); } }); Ok(()) } #[command] #[short_desc("Belgian leaderboard of a map that a user recently played")] #[long_desc( "Display the belgian leaderboard of a map that a user recently played.\n\ Mods can be specified.\n\ To get a previous recent map, you can add a number right after the command,\n\ e.g. `rblb42 badewanne3` to get the 42nd most recent map." )] #[usage("[username] [+mods]")] #[example("badewanne3 +hdhr")] #[aliases("rblb")] pub async fn recentbelgianleaderboard(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match RecentLeaderboardArgs::args(&ctx, &mut args, msg.author.id, num).await { Ok(Ok(mut recent_args)) => { recent_args.config.mode.get_or_insert(GameMode::STD); let data = CommandData::Message { msg, args, num }; _recentleaderboard(ctx, data, recent_args, true).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_recent(ctx, *command).await, } } #[command] #[short_desc("Belgian leaderboard of a map that a user recently played")] #[long_desc( "Display the belgian leaderboard of a mania map that a user recently played.\n\ Mods can be specified.\n\ To get a previous recent map, you can add a number right after the command,\n\ e.g. `rmblb42 badewanne3` to get the 42nd most recent map." )] #[usage("[username] [+mods]")] #[example("badewanne3 +hdhr")] #[aliases("rmblb")] pub async fn recentmaniabelgianleaderboard(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match RecentLeaderboardArgs::args(&ctx, &mut args, msg.author.id, num).await { Ok(Ok(mut recent_args)) => { recent_args.config.mode = Some(GameMode::MNA); let data = CommandData::Message { msg, args, num }; _recentleaderboard(ctx, data, recent_args, true).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_recent(ctx, *command).await, } } #[command] #[short_desc("Belgian leaderboard of a map that a user recently played")] #[long_desc( "Display the belgian leaderboard of a taiko map that a user recently played.\n\ Mods can be specified.\n\ To get a previous recent map, you can add a number right after the command,\n\ e.g. `rtblb42 badewanne3` to get the 42nd most recent map." )] #[usage("[username] [+mods]")] #[example("badewanne3 +hdhr")] #[aliases("rtblb")] pub async fn recenttaikobelgianleaderboard(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match RecentLeaderboardArgs::args(&ctx, &mut args, msg.author.id, num).await { Ok(Ok(mut recent_args)) => { recent_args.config.mode = Some(GameMode::TKO); let data = CommandData::Message { msg, args, num }; _recentleaderboard(ctx, data, recent_args, true).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_recent(ctx, *command).await, } } #[command] #[short_desc("Belgian leaderboard of a map that a user recently played")] #[long_desc( "Display the belgian leaderboard of a ctb map that a user recently played.\n\ Mods can be specified.\n\ To get a previous recent map, you can add a number right after the command,\n\ e.g. `rcblb42 badewanne3` to get the 42nd most recent map." )] #[usage("[username] [+mods]")] #[example("badewanne3 +hdhr")] #[aliases("rcblb")] pub async fn recentctbbelgianleaderboard(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match RecentLeaderboardArgs::args(&ctx, &mut args, msg.author.id, num).await { Ok(Ok(mut recent_args)) => { recent_args.config.mode = Some(GameMode::CTB); let data = CommandData::Message { msg, args, num }; _recentleaderboard(ctx, data, recent_args, true).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_recent(ctx, *command).await, } } #[command] #[short_desc("Global leaderboard of a map that a user recently played")] #[long_desc( "Display the global leaderboard of a map that a user recently played.\n\ Mods can be specified.\n\ To get a previous recent map, you can add a number right after the command,\n\ e.g. `rlb42 badewanne3` to get the 42nd most recent map." )] #[usage("[username] [+mods]")] #[example("badewanne3 +hdhr")] #[aliases("rlb", "rglb", "recentgloballeaderboard")] pub async fn recentleaderboard(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match RecentLeaderboardArgs::args(&ctx, &mut args, msg.author.id, num).await { Ok(Ok(mut recent_args)) => { recent_args.config.mode.get_or_insert(GameMode::STD); let data = CommandData::Message { msg, args, num }; _recentleaderboard(ctx, data, recent_args, false).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_recent(ctx, *command).await, } } #[command] #[short_desc("Global leaderboard of a map that a user recently played")] #[long_desc( "Display the global leaderboard of a mania map that a user recently played.\n\ Mods can be specified.\n\ To get a previous recent map, you can add a number right after the command,\n\ e.g. `rmlb42 badewanne3` to get the 42nd most recent map." )] #[usage("[username] [+mods]")] #[example("badewanne3 +hdhr")] #[aliases("rmlb", "rmglb", "recentmaniagloballeaderboard")] pub async fn recentmanialeaderboard(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match RecentLeaderboardArgs::args(&ctx, &mut args, msg.author.id, num).await { Ok(Ok(mut recent_args)) => { recent_args.config.mode = Some(GameMode::MNA); let data = CommandData::Message { msg, args, num }; _recentleaderboard(ctx, data, recent_args, false).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_recent(ctx, *command).await, } } #[command] #[short_desc("Global leaderboard of a map that a user recently played")] #[long_desc( "Display the global leaderboard of a taiko map that a user recently played.\n\ Mods can be specified.\n\ To get a previous recent map, you can add a number right after the command,\n\ e.g. `rtlb42 badewanne3` to get the 42nd most recent map." )] #[usage("[username] [+mods]")] #[example("badewanne3 +hdhr")] #[aliases("rtlb", "rtglb", "recenttaikogloballeaderboard")] pub async fn recenttaikoleaderboard(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match RecentLeaderboardArgs::args(&ctx, &mut args, msg.author.id, num).await { Ok(Ok(mut recent_args)) => { recent_args.config.mode = Some(GameMode::TKO); let data = CommandData::Message { msg, args, num }; _recentleaderboard(ctx, data, recent_args, false).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_recent(ctx, *command).await, } } #[command] #[short_desc("Global leaderboard of a map that a user recently played")] #[long_desc( "Display the global leaderboard of a ctb map that a user recently played.\n\ Mods can be specified.\n\ To get a previous recent map, you can add a number right after the command,\n\ e.g. `rclb42 badewanne3` to get the 42nd most recent map." )] #[usage("[username] [+mods]")] #[example("badewanne3 +hdhr")] #[aliases("rclb", "rcglb", "recentctbgloballeaderboard")] pub async fn recentctbleaderboard(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match RecentLeaderboardArgs::args(&ctx, &mut args, msg.author.id, num).await { Ok(Ok(mut recent_args)) => { recent_args.config.mode = Some(GameMode::CTB); let data = CommandData::Message { msg, args, num }; _recentleaderboard(ctx, data, recent_args, false).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_recent(ctx, *command).await, } } pub(super) struct RecentLeaderboardArgs { pub config: UserConfig, pub name: Option<Username>, pub index: Option<usize>, pub mods: Option<ModSelection>, } impl RecentLeaderboardArgs { async fn args( ctx: &Context, args: &mut Args<'_>, author_id: Id<UserMarker>, index: Option<usize>, ) -> DoubleResultCow<Self> { let config = ctx.user_config(author_id).await?; let mut name = None; let mut mods = None; for arg in args { if let Some(mods_) = matcher::get_mods(arg) { mods.replace(mods_); } else { match check_user_mention(ctx, arg).await? { Ok(osu) => name = Some(osu.into_username()), Err(content) => return Ok(Err(content)), } } } let args = Self { config, name, index, mods, }; Ok(Ok(args)) } pub(super) async fn slash( ctx: &Context, command: &ApplicationCommand, options: Vec<CommandDataOption>, ) -> DoubleResultCow<Self> { let mut config = ctx.user_config(command.user_id()?).await?; let mut username = None; let mut mods = None; let mut index = None; for option in options { match option.value { CommandOptionValue::String(value) => match option.name.as_str() { NAME => username = Some(value.into()), MODS => match matcher::get_mods(&value) { Some(mods_) => mods = Some(mods_), None => match value.parse() { Ok(mods_) => mods = Some(ModSelection::Exact(mods_)), Err(_) => return Ok(Err(MODS_PARSE_FAIL.into())), }, }, MODE => config.mode = parse_mode_option(&value), _ => return Err(Error::InvalidCommandOptions), }, CommandOptionValue::Integer(value) => { let number = (option.name == INDEX) .then(|| value) .ok_or(Error::InvalidCommandOptions)?; index = Some(number.max(1).min(50) as usize); } CommandOptionValue::User(value) => match option.name.as_str() { DISCORD => match parse_discord(ctx, value).await? { Ok(osu) => username = Some(osu.into_username()), Err(content) => return Ok(Err(content)), }, _ => return Err(Error::InvalidCommandOptions), }, _ => return Err(Error::InvalidCommandOptions), } } let args = Self { config, name: username, mods, index, }; Ok(Ok(args)) } }
use context::Context; use discovery::{Discovery, ServiceDiscovery}; use net::listener::Listener; use std::io::{Error, ErrorKind, Result}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use stream::io::copy_bidirectional; use tokio::spawn; use tokio::sync::mpsc::{self, Sender}; use tokio::time::{interval_at, Instant}; use protocol::Protocols; //vhcq dhwjsq hdjws kqa //qvdhjd3ehj #[tokio::main] async fn main() -> Result<()> { let ctx = Context::from_os_args(); ctx.check()?; let _l = listener_for_supervisor(ctx.port()).await?; log::init(ctx.log_dir())?; metrics::init(&ctx.metrics_url()); let discovery = Arc::from(Discovery::from_url(ctx.discovery())); let mut listeners = ctx.listeners(); let mut tick = interval_at( Instant::now() + Duration::from_secs(1), Duration::from_secs(3), ); let session_id = Arc::new(AtomicUsize::new(0)); let (tx, mut rx) = mpsc::channel(1); loop { let quards = listeners.scan().await; if let Err(e) = quards { log::info!("scan listener failed:{:?}", e); tick.tick().await; continue; } for quard in quards.unwrap().iter() { let quard = quard.clone(); let quard_ = quard.clone(); let discovery = Arc::clone(&discovery); let tx = tx.clone(); let session_id = session_id.clone(); spawn(async move { let _tx = tx.clone(); let session_id = session_id.clone(); match process_one_service(tx, &quard, discovery, session_id).await { Ok(_) => log::info!("service listener complete address:{}", quard.address()), Err(e) => { let _ = _tx.send(false).await; log::warn!("service listener error:{:?} {}", e, quard.address()) } }; }); if let Some(success) = rx.recv().await { if success { if let Err(e) = listeners.on_listened(quard_).await { log::warn!("on_listened failed:{:?} ", e); } } } } tick.tick().await; } } //aaxxbasnkxpmswervcexdwszq async fn process_one_service( tx: Sender<bool>, quard: &context::Quadruple, discovery: Arc<discovery::Discovery>, session_id: Arc<AtomicUsize>, ) -> Result<()> { let parser = Protocols::from(&quard.protocol()).ok_or(Error::new( ErrorKind::InvalidData, format!("'{}' is not a valid protocol", quard.protocol()), ))?; let top = endpoint::Topology::from(parser.clone(), quard.endpoint()).ok_or(Error::new( ErrorKind::InvalidData, format!("'{}' is not a valid endpoint", quard.endpoint()), ))?; let l = Listener::bind(&quard.family(), &quard.address()).await?; log::info!("starting to serve {}", quard.address()); let _ = tx.send(true).await; let sd = Arc::new(ServiceDiscovery::new( discovery, quard.service(), quard.snapshot(), quard.tick(), top, )); let (biz, r_type, _d_type) = discovery::UnixSocketPath::parse(&quard.address()).expect("valid path"); let metric_id = metrics::register_name(r_type + "." + &metrics::encode_addr(&biz)); loop { let sd = sd.clone(); let (client, _addr) = l.accept().await?; let endpoint = quard.endpoint().to_owned(); let parser = parser.clone(); let session_id = session_id.fetch_add(1, Ordering::AcqRel); spawn(async move { if let Err(e) = process_one_connection(client, sd, endpoint, parser, session_id, metric_id).await { log::warn!("connection disconnected:{:?}", e); } }); } } async fn process_one_connection( client: net::Stream, sd: Arc<ServiceDiscovery<endpoint::Topology<Protocols>>>, endpoint: String, parser: Protocols, session_id: usize, metric_id: usize, ) -> Result<()> { use endpoint::Endpoint; let agent = Endpoint::from_discovery(&endpoint, parser.clone(), sd) .await? .ok_or_else(|| { Error::new( ErrorKind::NotFound, format!("'{}' is not a valid endpoint type", endpoint), ) })?; copy_bidirectional(agent, client, parser, session_id, metric_id).await?; Ok(()) } use tokio::net::TcpListener; // 监控一个端口,主要用于进程监控 async fn listener_for_supervisor(port: u16) -> Result<TcpListener> { let addr = format!("127.0.0.1:{}", port); let l = TcpListener::bind(&addr).await?; Ok(l) }
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. //! Runtime debugging and logging utilities. //! //! This module contains macros and functions that will allow //! you to print logs out of the runtime code. //! //! First and foremost be aware that adding regular logging code to //! your runtime will have a negative effect on the performance //! and size of the blob. Luckily there are some ways to mitigate //! this that are described below. //! //! First component to utilize debug-printing and logging is actually //! located in `primitives` crate: `sp_core::RuntimeDebug`. //! This custom-derive generates `core::fmt::Debug` implementation, //! just like regular `derive(Debug)`, however it does not generate //! any code when the code is compiled to WASM. This means that //! you can safely sprinkle `RuntimeDebug` in your runtime codebase, //! without affecting the size. This also allows you to print/log //! both when the code is running natively or in WASM, but note //! that WASM debug formatting of structs will be empty. //! //! ```rust,no_run //! use frame_support::debug; //! //! #[derive(sp_core::RuntimeDebug)] //! struct MyStruct { //! a: u64, //! } //! //! // First initialize the logger. //! // //! // This is only required when you want the logs to be printed //! // also during non-native run. //! // Note that enabling the logger has performance impact on //! // WASM runtime execution and should be used sparingly. //! debug::RuntimeLogger::init(); //! //! let x = MyStruct { a: 5 }; //! // will log an info line `"My struct: MyStruct{a:5}"` when running //! // natively, but will only print `"My struct: "` when running WASM. //! debug::info!("My struct: {:?}", x); //! //! // same output here, although this will print to stdout //! // (and without log format) //! debug::print!("My struct: {:?}", x); //! ``` //! //! If you want to avoid extra overhead in WASM, but still be able //! to print / log when the code is executed natively you can use //! macros coming from `native` sub-module. This module enables //! logs conditionally and strips out logs in WASM. //! //! ```rust,no_run //! use frame_support::debug::native; //! //! #[derive(sp_core::RuntimeDebug)] //! struct MyStruct { //! a: u64, //! } //! //! // We don't initialize the logger, since //! // we are not printing anything out in WASM. //! // debug::RuntimeLogger::init(); //! //! let x = MyStruct { a: 5 }; //! //! // Displays an info log when running natively, nothing when WASM. //! native::info!("My struct: {:?}", x); //! //! // same output to stdout, no overhead on WASM. //! native::print!("My struct: {:?}", x); //! ``` use sp_std::fmt::{self, Debug}; pub use crate::runtime_print as print; pub use log::{debug, error, info, trace, warn}; pub use sp_std::Writer; /// Native-only logging. /// /// Using any functions from this module will have any effect /// only if the runtime is running natively (i.e. not via WASM) #[cfg(feature = "std")] pub mod native { pub use super::{debug, error, info, print, trace, warn}; } /// Native-only logging. /// /// Using any functions from this module will have any effect /// only if the runtime is running natively (i.e. not via WASM) #[cfg(not(feature = "std"))] pub mod native { #[macro_export] macro_rules! noop { ($($arg:tt)+) => {}; } pub use noop as info; pub use noop as debug; pub use noop as error; pub use noop as trace; pub use noop as warn; pub use noop as print; } /// Print out a formatted message. /// /// # Example /// /// ``` /// frame_support::runtime_print!("my value is {}", 3); /// ``` #[macro_export] macro_rules! runtime_print { ($($arg:tt)+) => { { use core::fmt::Write; let mut w = $crate::sp_std::Writer::default(); let _ = core::write!(&mut w, $($arg)+); sp_io::misc::print_utf8(&w.inner()) } } } /// Print out the debuggable type. pub fn debug(data: &impl Debug) { runtime_print!("{:?}", data); } /// Runtime logger implementation - `log` crate backend. /// /// The logger should be initialized if you want to display /// logs inside the runtime that is not necessarily running natively. /// /// When runtime is executed natively any log statements are displayed /// even if this logger is NOT initialized. /// /// Note that even though the logs are not displayed in WASM, they /// may still affect the size and performance of the generated runtime. /// To lower the footprint make sure to only use macros from `native` /// sub-module. pub struct RuntimeLogger; impl RuntimeLogger { /// Initialize the logger. /// /// This is a no-op when running natively (`std`). #[cfg(feature = "std")] pub fn init() {} /// Initialize the logger. /// /// This is a no-op when running natively (`std`). #[cfg(not(feature = "std"))] pub fn init() { static LOGGER: RuntimeLogger = RuntimeLogger;; let _ = log::set_logger(&LOGGER); } } impl log::Log for RuntimeLogger { fn enabled(&self, _metadata: &log::Metadata) -> bool { // to avoid calling to host twice, we pass everything // and let the host decide what to print. // If someone is initializing the logger they should // know what they are doing. true } fn log(&self, record: &log::Record) { use fmt::Write; let mut w = sp_std::Writer::default(); let _ = core::write!(&mut w, "{}", record.args()); sp_io::logging::log(record.level().into(), record.target(), w.inner()); } fn flush(&self) {} }
#[macro_use] extern crate quote; extern crate syn; use syn::{Attribute, Item, ItemFn, ItemMod, Lit, Meta, MetaNameValue}; use std::env; use std::io::{Read, Write}; use std::fs::File; use std::path::{Path, PathBuf}; /// Look for a simple attribute matching a string fn any_attr_is(attrs: &[Attribute], ident: &str) -> bool { attrs.iter().any(|a| match a.interpret_meta() { Some(Meta::Word(i)) if i == ident => true, _ => false }) } /// Parse a list of items for #[register]ed functions (recurses into modules) /// /// mod_path: parent dir of the mod we are parsing /// items: list of items in the current mod /// /// Returns a list of item paths (relative to the current module) fn parse(mod_path: PathBuf, items: Vec<Item>) -> Vec<syn::Path> { let mut names = vec![]; for item in items { match item { // handle a registered function Item::Fn(ItemFn { ref attrs, ident, .. }) if any_attr_is(attrs, "register") => { names.push(ident.into()); } // handle a module Item::Mod(module) => { let (the_path, the_items, the_ident); // what kind of module is it? match module { // inline module! ItemMod { content: Some((_, items)), ident, .. } => { the_items = items; the_ident = ident; the_path = mod_path.clone(); } // non-inline module! ItemMod { attrs, ident, .. } => { // read the #[path] attr if present let mut path = None; for attr in attrs { match attr.interpret_meta() { Some(Meta::NameValue(MetaNameValue { ident, lit: Lit::Str(ref s), .. })) if ident == "path" => { path = Some(s.value()); } _ => {} } } // read in the module contents from file, wherever it is let mut content = String::new(); let mut file = match path { // from a path attribute Some(p) => { the_path = Path::new(&p).parent().unwrap().to_owned(); File::open(&p).expect(&p) } // no path attribute -- try $name.rs and $name/mod.rs None => { match File::open(mod_path.join(format!("{}.rs", ident))) { Ok(file) => { the_path = mod_path.clone(); file } Err(_) => { the_path = mod_path.join(ident.as_ref()); File::open(mod_path.join(ident.as_ref()).join("mod.rs")).expect(&format!("{}/{}/mod.rs", mod_path.display(), ident)) } } } }; file.read_to_string(&mut content).unwrap(); the_items = syn::parse_file(&content).unwrap().items; the_ident = ident; } } // recurse to find registered functions within the new module names.extend( parse(the_path, the_items) .into_iter() .map(|mut p| { // prepend the module path to the found items p.segments.insert(0, the_ident.into()); p }) ); } _ => {} } } names } /// Find registered functions in the given crate. Call this in your build script! /// /// root: path to the crate root (e.g. src/main.rs or src/lib.rs) pub fn go<P: AsRef<Path>>(root: P) { let root = root.as_ref(); let outfile = Path::new(&env::var("OUT_DIR").unwrap()).join("macbuild.rs"); // Exfiltrate the name of the generated file so that macbuild!() can include it println!("cargo:rustc-env=MACBUILD={}", outfile.display()); // Get registered functions from the crate let mut content = String::new(); File::open(root).unwrap().read_to_string(&mut content).unwrap(); let ast = syn::parse_file(&content).unwrap(); let names = parse(root.parent().unwrap().to_owned(), ast.items); // Generate bootstrap function let mut out = File::create(outfile).unwrap(); writeln!(out, "{}", quote! { pub fn bootstrap() { #(::#names();)* } }).unwrap(); }
use super::rand_string; use crate::db::DBConnection; use crate::prelude::*; impl Users { /// It creates a `Users` instance by connecting it to a redis database. /// If the database does not yet exist it will be created. By default, /// sessions will be stored on a concurrent HashMap. In order to have persistent sessions see /// the method [`open_redis`](User::open_redis). /// ```rust, no_run /// # use rocket_auth::{Error, Users}; /// # #[tokio::main] /// # async fn main() -> Result <(), Error> { /// let users = Users::open_sqlite("database.db").await?; /// /// rocket::build() /// .manage(users) /// .launch() /// .await; /// # Ok(()) } /// ``` pub async fn open_sqlite(path: &str) -> Result<Self> { use tokio::sync::Mutex; let conn = rusqlite::Connection::open(path)?; let users: Users = Mutex::new(conn).into(); users.conn.init().await?; Ok(users) } /// It querys a user by their email. /// ``` /// # use rocket::{State, get}; /// # use rocket_auth::{Error, Users}; /// #[get("/user-information/<email>")] /// async fn user_information(email: String, users: &State<Users>) -> Result<String, Error> { /// /// let user = users.get_by_email(&email).await?; /// Ok(format!("{:?}", user)) /// } /// # fn main() {} /// ``` pub async fn get_by_email(&self, email: &str) -> Result<User> { self.conn.get_user_by_email(email).await } /// It querys a user by their email. /// ``` /// # use rocket::{State, get}; /// # use rocket_auth::{Error, Users}; /// # #[get("/user-information/<email>")] /// # async fn user_information(email: String, users: &State<Users>) -> Result<(), Error> { /// let user = users.get_by_id(3).await?; /// format!("{:?}", user); /// # Ok(()) /// # } /// # fn main() {} /// ``` pub async fn get_by_id(&self, user_id: i32) -> Result<User> { self.conn.get_user_by_id(user_id).await } /// Inserts a new user in the database. It will fail if the user already exists. /// ```rust /// # use rocket::{State, get}; /// # use rocket_auth::{Error, Users}; /// #[get("/create_admin/<email>/<password>")] /// async fn create_admin(email: String, password: String, users: &State<Users>) -> Result<String, Error> { /// users.create_user(&email, &password, true).await?; /// Ok("User created successfully".into()) /// } /// # fn main() {} /// ``` pub async fn create_user(&self, email: &str, password: &str, is_admin: bool) -> Result<()> { let password = password.as_bytes(); let salt = rand_string(30); let config = argon2::Config::default(); let hash = argon2::hash_encoded(password, &salt.as_bytes(), &config).unwrap(); self.conn.create_user(email, &hash, is_admin).await?; Ok(()) } /// Deletes a user from de database. Note that this method won't delete the session. /// To do that use [`Auth::delete`](crate::Auth::delete). /// #[get("/delete_user/<id>")] /// fn delete_user(id: i32, users: State<Users>) -> Result<String> { /// users.delete(id)?; /// Ok("The user has been deleted.") /// } pub async fn delete(&self, id: i32) -> Result<()> { self.sess.remove(id)?; self.conn.delete_user_by_id(id).await?; Ok(()) } /// Modifies a user in the database. /// ``` /// # use rocket_auth::{Users, Error}; /// # async fn func(users: Users) -> Result<(), Error> { /// let mut user = users.get_by_id(4).await?; /// user.set_email("new@email.com"); /// user.set_password("new password"); /// users.modify(&user).await?; /// # Ok(())} /// ``` pub async fn modify(&self, user: &User) -> Result<()> { self.conn.update_user(user).await?; Ok(()) } } /// A `Users` instance can also be created from a database connection. /// ``` /// # use rocket_auth::{Users, Error}; /// # use tokio_postgres::NoTls; /// # async fn func() -> Result<(), Error> { /// let (client, connection) = tokio_postgres::connect("host=localhost user=postgres", NoTls).await?; /// let users: Users = client.into(); /// # Ok(())} /// ``` impl<Conn: 'static + DBConnection> From<Conn> for Users { fn from(db: Conn) -> Users { Users { conn: Box::from(db), sess: Box::new(chashmap::CHashMap::new()), } } } /// Additionally, `Users` can be created from a tuple, /// where the first element is a database connection, and the second is a redis connection. /// ``` /// # use rocket_auth::{Users, Error}; /// # extern crate tokio_postgres; /// # use tokio_postgres::NoTls; /// # extern crate redis; /// # async fn func(postgres_path: &str, redis_path: &str) -> Result<(), Error> { /// let (db_client, connection) = tokio_postgres::connect(postgres_path, NoTls).await?; /// let redis_client = redis::Client::open(redis_path)?; /// /// let users: Users = (db_client, redis_client).into(); /// # Ok(())} /// ``` impl<T0: 'static + DBConnection, T1: 'static + SessionManager> From<(T0, T1)> for Users { fn from((db, ss): (T0, T1)) -> Users { Users { conn: Box::from(db), sess: Box::new(ss), } } }
// q0007_reverse_integer struct Solution; impl Solution { pub fn reverse(x: i32) -> i32 { let mut n: i32 = 0; let mut x = x; loop { let b = x % 10; if x == 0 && b == 0 { break; } if let Some(t1) = n.checked_mul(10) { if let Some(t2) = t1.checked_add(b) { n = t2; } else { return 0; } } else { return 0; } x /= 10; } n } } #[cfg(test)] mod tests { use super::Solution; #[test] fn it_works() { assert_eq!(Solution::reverse(123), 321); } }
#[cfg(target_arch = "x86_64")] #[path = "arch/x86_64/arch.rs"] pub mod arch;