text stringlengths 8 4.13M |
|---|
use std::ops::{Deref, DerefMut, Range, Add, AddAssign};
use std::borrow::Borrow;
use std::mem::{self, MaybeUninit};
use std::fmt;
use std::error::Error;
use std::path::PathBuf;
use std::sync::Arc;
use std::hash::{Hash, Hasher, BuildHasher};
use std::collections::{HashMap, hash_map::{Entry, OccupiedEntry}};
use lsp_types::Url;
pub type BoxError = Box<dyn Error + Send + Sync>;
pub trait HashMapExt<K, V> {
fn try_insert(&mut self, k: K, v: V) -> Option<(V, OccupiedEntry<K, V>)>;
}
impl<K: Hash + Eq, V, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
fn try_insert(&mut self, k: K, v: V) -> Option<(V, OccupiedEntry<K, V>)> {
match self.entry(k) {
Entry::Vacant(e) => { e.insert(v); None }
Entry::Occupied(e) => Some((v, e))
}
}
}
#[derive(Clone, Hash, PartialEq, Eq)] pub struct ArcString(pub Arc<String>);
impl Borrow<str> for ArcString {
fn borrow(&self) -> &str { &*self.0 }
}
impl Deref for ArcString {
type Target = str;
fn deref(&self) -> &str { &*self.0 }
}
impl ArcString {
pub fn new(s: String) -> ArcString { ArcString(Arc::new(s)) }
}
impl fmt::Display for ArcString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) }
}
impl fmt::Debug for ArcString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) }
}
impl From<&str> for ArcString {
fn from(s: &str) -> ArcString { ArcString::new(s.to_owned()) }
}
pub struct VecUninit<T>(Vec<MaybeUninit<T>>);
impl<T> VecUninit<T> {
pub fn new(size: usize) -> Self {
let mut res = Vec::with_capacity(size);
unsafe { res.set_len(size) };
VecUninit(res)
}
pub fn set(&mut self, i: usize, val: T) {
self.0[i] = MaybeUninit::new(val);
}
pub unsafe fn assume_init(self) -> Vec<T> {
mem::transmute(self.0)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Span {
pub start: usize,
pub end: usize,
}
impl From<Range<usize>> for Span {
#[inline] fn from(r: Range<usize>) -> Self { Span {start: r.start, end: r.end} }
}
impl From<usize> for Span {
#[inline] fn from(n: usize) -> Self { Span {start: n, end: n} }
}
impl From<Span> for Range<usize> {
#[inline] fn from(s: Span) -> Self { s.start..s.end }
}
impl Add<usize> for Span {
type Output = Self;
fn add(self, i: usize) -> Self {
Span {start: self.start + i, end: self.start + i}
}
}
impl AddAssign<usize> for Span {
fn add_assign(&mut self, i: usize) { *self = *self + i }
}
impl Deref for Span {
type Target = Range<usize>;
fn deref(&self) -> &Range<usize> {
unsafe { mem::transmute(self) }
}
}
impl DerefMut for Span {
fn deref_mut(&mut self) -> &mut Range<usize> {
unsafe { mem::transmute(self) }
}
}
impl Iterator for Span {
type Item = usize;
fn next(&mut self) -> Option<usize> { self.deref_mut().next() }
}
impl DoubleEndedIterator for Span {
fn next_back(&mut self) -> Option<usize> { self.deref_mut().next_back() }
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}..{}", self.start, self.end)
}
}
lazy_static! {
static ref CURRENT_DIR: PathBuf =
std::fs::canonicalize(".").expect("failed to find current directory");
}
fn make_relative(buf: &PathBuf) -> String {
pathdiff::diff_paths(buf, &CURRENT_DIR).as_ref().unwrap_or(buf)
.to_str().unwrap().to_owned()
}
#[derive(Clone)]
pub struct FileRef(Arc<(PathBuf, String, Url)>);
impl FileRef {
pub fn new(buf: PathBuf) -> FileRef {
let u = Url::from_file_path(&buf).expect("bad file path");
let rel = make_relative(&buf);
FileRef(Arc::new((buf, rel, u)))
}
pub fn from_url(url: Url) -> FileRef {
let buf = url.to_file_path().expect("bad URL");
let rel = make_relative(&buf);
FileRef(Arc::new((buf, rel, url)))
}
pub fn path(&self) -> &PathBuf { &self.0 .0 }
pub fn rel(&self) -> &str { &self.0 .1 }
pub fn url(&self) -> &Url { &self.0 .2 }
pub fn ptr(&self) -> *const PathBuf { self.path() }
pub fn ptr_eq(&self, other: &FileRef) -> bool { Arc::ptr_eq(&self.0, &other.0) }
pub fn has_extension(&self, ext: &str) -> bool {
self.path().extension().map_or(false, |s| s == ext)
}
}
impl PartialEq for FileRef {
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl Eq for FileRef {}
impl Hash for FileRef {
fn hash<H: Hasher>(&self, state: &mut H) { self.0.hash(state) }
}
impl fmt::Display for FileRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0 .0.file_name().unwrap_or(self.0 .0.as_os_str()).to_str().unwrap().fmt(f)
}
}
impl fmt::Debug for FileRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct FileSpan {
pub file: FileRef,
pub span: Span,
}
impl fmt::Debug for FileSpan {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{:?}", self.file, self.span)
}
}
|
pub use self::death::Dead;
pub use self::explored::Explored;
pub use self::fighter::Fighter;
pub use self::health::Health;
pub use self::init::Init;
pub use self::intent::{Direction, Action, Intent};
pub use self::mob::Mob;
pub use self::name::Name;
pub use self::player::Player;
pub use self::tile::Tile;
mod death;
mod explored;
mod fighter;
mod health;
mod init;
mod intent;
mod mob;
mod name;
mod player;
mod tile;
|
use diesel::{Connection, SqliteConnection};
pub mod models;
pub mod schema;
pub fn establish_connection() -> SqliteConnection {
let database_url = "data.sqlite";
SqliteConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
} |
#[doc = "Register `SECCFGR3` reader"]
pub type R = crate::R<SECCFGR3_SPEC>;
#[doc = "Register `SECCFGR3` writer"]
pub type W = crate::W<SECCFGR3_SPEC>;
#[doc = "Field `LPTIM6SEC` reader - secure access mode for LPTIM6"]
pub type LPTIM6SEC_R = crate::BitReader;
#[doc = "Field `LPTIM6SEC` writer - secure access mode for LPTIM6"]
pub type LPTIM6SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `VREFBUFSEC` reader - secure access mode for VREFBUF"]
pub type VREFBUFSEC_R = crate::BitReader;
#[doc = "Field `VREFBUFSEC` writer - secure access mode for VREFBUF"]
pub type VREFBUFSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRCSEC` reader - secure access mode for CRC"]
pub type CRCSEC_R = crate::BitReader;
#[doc = "Field `CRCSEC` writer - secure access mode for CRC"]
pub type CRCSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CORDICSEC` reader - secure access mode for CORDIC"]
pub type CORDICSEC_R = crate::BitReader;
#[doc = "Field `CORDICSEC` writer - secure access mode for CORDIC"]
pub type CORDICSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FMACSEC` reader - secure access mode for FMAC"]
pub type FMACSEC_R = crate::BitReader;
#[doc = "Field `FMACSEC` writer - secure access mode for FMAC"]
pub type FMACSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ICACHESEC` reader - secure access mode for ICACHE"]
pub type ICACHESEC_R = crate::BitReader;
#[doc = "Field `ICACHESEC` writer - secure access mode for ICACHE"]
pub type ICACHESEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DCACHESEC` reader - secure access mode for DCACHE"]
pub type DCACHESEC_R = crate::BitReader;
#[doc = "Field `DCACHESEC` writer - secure access mode for DCACHE"]
pub type DCACHESEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ADC12SEC` reader - secure access mode for ADC1 and ADC2"]
pub type ADC12SEC_R = crate::BitReader;
#[doc = "Field `ADC12SEC` writer - secure access mode for ADC1 and ADC2"]
pub type ADC12SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DCMISEC` reader - secure access mode for DCMI"]
pub type DCMISEC_R = crate::BitReader;
#[doc = "Field `DCMISEC` writer - secure access mode for DCMI"]
pub type DCMISEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HASHSEC` reader - secure access mode for HASH"]
pub type HASHSEC_R = crate::BitReader;
#[doc = "Field `HASHSEC` writer - secure access mode for HASH"]
pub type HASHSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RNGSEC` reader - secure access mode for RNG"]
pub type RNGSEC_R = crate::BitReader;
#[doc = "Field `RNGSEC` writer - secure access mode for RNG"]
pub type RNGSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SDMMC1SEC` reader - secure access mode for SDMMC1"]
pub type SDMMC1SEC_R = crate::BitReader;
#[doc = "Field `SDMMC1SEC` writer - secure access mode for SDMMC1"]
pub type SDMMC1SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FMCSEC` reader - secure access mode for FMC"]
pub type FMCSEC_R = crate::BitReader;
#[doc = "Field `FMCSEC` writer - secure access mode for FMC"]
pub type FMCSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OCTOSPI1SEC` reader - secure access mode for OCTOSPI1"]
pub type OCTOSPI1SEC_R = crate::BitReader;
#[doc = "Field `OCTOSPI1SEC` writer - secure access mode for OCTOSPI1"]
pub type OCTOSPI1SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RAMCFGSEC` reader - secure access mode for RAMSCFG"]
pub type RAMCFGSEC_R = crate::BitReader;
#[doc = "Field `RAMCFGSEC` writer - secure access mode for RAMSCFG"]
pub type RAMCFGSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - secure access mode for LPTIM6"]
#[inline(always)]
pub fn lptim6sec(&self) -> LPTIM6SEC_R {
LPTIM6SEC_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - secure access mode for VREFBUF"]
#[inline(always)]
pub fn vrefbufsec(&self) -> VREFBUFSEC_R {
VREFBUFSEC_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 8 - secure access mode for CRC"]
#[inline(always)]
pub fn crcsec(&self) -> CRCSEC_R {
CRCSEC_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - secure access mode for CORDIC"]
#[inline(always)]
pub fn cordicsec(&self) -> CORDICSEC_R {
CORDICSEC_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - secure access mode for FMAC"]
#[inline(always)]
pub fn fmacsec(&self) -> FMACSEC_R {
FMACSEC_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 12 - secure access mode for ICACHE"]
#[inline(always)]
pub fn icachesec(&self) -> ICACHESEC_R {
ICACHESEC_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - secure access mode for DCACHE"]
#[inline(always)]
pub fn dcachesec(&self) -> DCACHESEC_R {
DCACHESEC_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - secure access mode for ADC1 and ADC2"]
#[inline(always)]
pub fn adc12sec(&self) -> ADC12SEC_R {
ADC12SEC_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - secure access mode for DCMI"]
#[inline(always)]
pub fn dcmisec(&self) -> DCMISEC_R {
DCMISEC_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 17 - secure access mode for HASH"]
#[inline(always)]
pub fn hashsec(&self) -> HASHSEC_R {
HASHSEC_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - secure access mode for RNG"]
#[inline(always)]
pub fn rngsec(&self) -> RNGSEC_R {
RNGSEC_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 22 - secure access mode for SDMMC1"]
#[inline(always)]
pub fn sdmmc1sec(&self) -> SDMMC1SEC_R {
SDMMC1SEC_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - secure access mode for FMC"]
#[inline(always)]
pub fn fmcsec(&self) -> FMCSEC_R {
FMCSEC_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - secure access mode for OCTOSPI1"]
#[inline(always)]
pub fn octospi1sec(&self) -> OCTOSPI1SEC_R {
OCTOSPI1SEC_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 26 - secure access mode for RAMSCFG"]
#[inline(always)]
pub fn ramcfgsec(&self) -> RAMCFGSEC_R {
RAMCFGSEC_R::new(((self.bits >> 26) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - secure access mode for LPTIM6"]
#[inline(always)]
#[must_use]
pub fn lptim6sec(&mut self) -> LPTIM6SEC_W<SECCFGR3_SPEC, 0> {
LPTIM6SEC_W::new(self)
}
#[doc = "Bit 1 - secure access mode for VREFBUF"]
#[inline(always)]
#[must_use]
pub fn vrefbufsec(&mut self) -> VREFBUFSEC_W<SECCFGR3_SPEC, 1> {
VREFBUFSEC_W::new(self)
}
#[doc = "Bit 8 - secure access mode for CRC"]
#[inline(always)]
#[must_use]
pub fn crcsec(&mut self) -> CRCSEC_W<SECCFGR3_SPEC, 8> {
CRCSEC_W::new(self)
}
#[doc = "Bit 9 - secure access mode for CORDIC"]
#[inline(always)]
#[must_use]
pub fn cordicsec(&mut self) -> CORDICSEC_W<SECCFGR3_SPEC, 9> {
CORDICSEC_W::new(self)
}
#[doc = "Bit 10 - secure access mode for FMAC"]
#[inline(always)]
#[must_use]
pub fn fmacsec(&mut self) -> FMACSEC_W<SECCFGR3_SPEC, 10> {
FMACSEC_W::new(self)
}
#[doc = "Bit 12 - secure access mode for ICACHE"]
#[inline(always)]
#[must_use]
pub fn icachesec(&mut self) -> ICACHESEC_W<SECCFGR3_SPEC, 12> {
ICACHESEC_W::new(self)
}
#[doc = "Bit 13 - secure access mode for DCACHE"]
#[inline(always)]
#[must_use]
pub fn dcachesec(&mut self) -> DCACHESEC_W<SECCFGR3_SPEC, 13> {
DCACHESEC_W::new(self)
}
#[doc = "Bit 14 - secure access mode for ADC1 and ADC2"]
#[inline(always)]
#[must_use]
pub fn adc12sec(&mut self) -> ADC12SEC_W<SECCFGR3_SPEC, 14> {
ADC12SEC_W::new(self)
}
#[doc = "Bit 15 - secure access mode for DCMI"]
#[inline(always)]
#[must_use]
pub fn dcmisec(&mut self) -> DCMISEC_W<SECCFGR3_SPEC, 15> {
DCMISEC_W::new(self)
}
#[doc = "Bit 17 - secure access mode for HASH"]
#[inline(always)]
#[must_use]
pub fn hashsec(&mut self) -> HASHSEC_W<SECCFGR3_SPEC, 17> {
HASHSEC_W::new(self)
}
#[doc = "Bit 18 - secure access mode for RNG"]
#[inline(always)]
#[must_use]
pub fn rngsec(&mut self) -> RNGSEC_W<SECCFGR3_SPEC, 18> {
RNGSEC_W::new(self)
}
#[doc = "Bit 22 - secure access mode for SDMMC1"]
#[inline(always)]
#[must_use]
pub fn sdmmc1sec(&mut self) -> SDMMC1SEC_W<SECCFGR3_SPEC, 22> {
SDMMC1SEC_W::new(self)
}
#[doc = "Bit 23 - secure access mode for FMC"]
#[inline(always)]
#[must_use]
pub fn fmcsec(&mut self) -> FMCSEC_W<SECCFGR3_SPEC, 23> {
FMCSEC_W::new(self)
}
#[doc = "Bit 24 - secure access mode for OCTOSPI1"]
#[inline(always)]
#[must_use]
pub fn octospi1sec(&mut self) -> OCTOSPI1SEC_W<SECCFGR3_SPEC, 24> {
OCTOSPI1SEC_W::new(self)
}
#[doc = "Bit 26 - secure access mode for RAMSCFG"]
#[inline(always)]
#[must_use]
pub fn ramcfgsec(&mut self) -> RAMCFGSEC_W<SECCFGR3_SPEC, 26> {
RAMCFGSEC_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 = "GTZC1 TZSC secure configuration register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`seccfgr3::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 [`seccfgr3::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SECCFGR3_SPEC;
impl crate::RegisterSpec for SECCFGR3_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`seccfgr3::R`](R) reader structure"]
impl crate::Readable for SECCFGR3_SPEC {}
#[doc = "`write(|w| ..)` method takes [`seccfgr3::W`](W) writer structure"]
impl crate::Writable for SECCFGR3_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SECCFGR3 to value 0"]
impl crate::Resettable for SECCFGR3_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Register `AHB1ENR` reader"]
pub type R = crate::R<AHB1ENR_SPEC>;
#[doc = "Register `AHB1ENR` writer"]
pub type W = crate::W<AHB1ENR_SPEC>;
#[doc = "Field `GPDMA1EN` reader - GPDMA1 clock enable Set and reset by software."]
pub type GPDMA1EN_R = crate::BitReader;
#[doc = "Field `GPDMA1EN` writer - GPDMA1 clock enable Set and reset by software."]
pub type GPDMA1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPDMA2EN` reader - GPDMA2 clock enable Set and reset by software."]
pub type GPDMA2EN_R = crate::BitReader;
#[doc = "Field `GPDMA2EN` writer - GPDMA2 clock enable Set and reset by software."]
pub type GPDMA2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FLITFEN` reader - Flash interface clock enable Set and reset by software."]
pub type FLITFEN_R = crate::BitReader;
#[doc = "Field `FLITFEN` writer - Flash interface clock enable Set and reset by software."]
pub type FLITFEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRCEN` reader - CRC clock enable Set and reset by software."]
pub type CRCEN_R = crate::BitReader;
#[doc = "Field `CRCEN` writer - CRC clock enable Set and reset by software."]
pub type CRCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CORDICEN` reader - CORDIC clock enable Set and reset by software."]
pub type CORDICEN_R = crate::BitReader;
#[doc = "Field `CORDICEN` writer - CORDIC clock enable Set and reset by software."]
pub type CORDICEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FMACEN` reader - FMAC clock enable Set and reset by software."]
pub type FMACEN_R = crate::BitReader;
#[doc = "Field `FMACEN` writer - FMAC clock enable Set and reset by software."]
pub type FMACEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RAMCFGEN` reader - RAMCFG clock enable Set and reset by software."]
pub type RAMCFGEN_R = crate::BitReader;
#[doc = "Field `RAMCFGEN` writer - RAMCFG clock enable Set and reset by software."]
pub type RAMCFGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ETHEN` reader - ETH clock enable Set and reset by software"]
pub type ETHEN_R = crate::BitReader;
#[doc = "Field `ETHEN` writer - ETH clock enable Set and reset by software"]
pub type ETHEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ETHTXEN` reader - ETHTX clock enable Set and reset by software"]
pub type ETHTXEN_R = crate::BitReader;
#[doc = "Field `ETHTXEN` writer - ETHTX clock enable Set and reset by software"]
pub type ETHTXEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ETHRXEN` reader - ETHRX clock enable Set and reset by software"]
pub type ETHRXEN_R = crate::BitReader;
#[doc = "Field `ETHRXEN` writer - ETHRX clock enable Set and reset by software"]
pub type ETHRXEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TZSC1EN` reader - TZSC1 clock enable Set and reset by software"]
pub type TZSC1EN_R = crate::BitReader;
#[doc = "Field `TZSC1EN` writer - TZSC1 clock enable Set and reset by software"]
pub type TZSC1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `BKPRAMEN` reader - BKPRAM clock enable Set and reset by software"]
pub type BKPRAMEN_R = crate::BitReader;
#[doc = "Field `BKPRAMEN` writer - BKPRAM clock enable Set and reset by software"]
pub type BKPRAMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DCACHEEN` reader - DCACHE clock enable Set and reset by software"]
pub type DCACHEEN_R = crate::BitReader;
#[doc = "Field `DCACHEEN` writer - DCACHE clock enable Set and reset by software"]
pub type DCACHEEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM1EN` reader - SRAM1 clock enable Set and reset by software."]
pub type SRAM1EN_R = crate::BitReader;
#[doc = "Field `SRAM1EN` writer - SRAM1 clock enable Set and reset by software."]
pub type SRAM1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - GPDMA1 clock enable Set and reset by software."]
#[inline(always)]
pub fn gpdma1en(&self) -> GPDMA1EN_R {
GPDMA1EN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - GPDMA2 clock enable Set and reset by software."]
#[inline(always)]
pub fn gpdma2en(&self) -> GPDMA2EN_R {
GPDMA2EN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 8 - Flash interface clock enable Set and reset by software."]
#[inline(always)]
pub fn flitfen(&self) -> FLITFEN_R {
FLITFEN_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 12 - CRC clock enable Set and reset by software."]
#[inline(always)]
pub fn crcen(&self) -> CRCEN_R {
CRCEN_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 14 - CORDIC clock enable Set and reset by software."]
#[inline(always)]
pub fn cordicen(&self) -> CORDICEN_R {
CORDICEN_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - FMAC clock enable Set and reset by software."]
#[inline(always)]
pub fn fmacen(&self) -> FMACEN_R {
FMACEN_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 17 - RAMCFG clock enable Set and reset by software."]
#[inline(always)]
pub fn ramcfgen(&self) -> RAMCFGEN_R {
RAMCFGEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 19 - ETH clock enable Set and reset by software"]
#[inline(always)]
pub fn ethen(&self) -> ETHEN_R {
ETHEN_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - ETHTX clock enable Set and reset by software"]
#[inline(always)]
pub fn ethtxen(&self) -> ETHTXEN_R {
ETHTXEN_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - ETHRX clock enable Set and reset by software"]
#[inline(always)]
pub fn ethrxen(&self) -> ETHRXEN_R {
ETHRXEN_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 24 - TZSC1 clock enable Set and reset by software"]
#[inline(always)]
pub fn tzsc1en(&self) -> TZSC1EN_R {
TZSC1EN_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 28 - BKPRAM clock enable Set and reset by software"]
#[inline(always)]
pub fn bkpramen(&self) -> BKPRAMEN_R {
BKPRAMEN_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 30 - DCACHE clock enable Set and reset by software"]
#[inline(always)]
pub fn dcacheen(&self) -> DCACHEEN_R {
DCACHEEN_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - SRAM1 clock enable Set and reset by software."]
#[inline(always)]
pub fn sram1en(&self) -> SRAM1EN_R {
SRAM1EN_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - GPDMA1 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn gpdma1en(&mut self) -> GPDMA1EN_W<AHB1ENR_SPEC, 0> {
GPDMA1EN_W::new(self)
}
#[doc = "Bit 1 - GPDMA2 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn gpdma2en(&mut self) -> GPDMA2EN_W<AHB1ENR_SPEC, 1> {
GPDMA2EN_W::new(self)
}
#[doc = "Bit 8 - Flash interface clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn flitfen(&mut self) -> FLITFEN_W<AHB1ENR_SPEC, 8> {
FLITFEN_W::new(self)
}
#[doc = "Bit 12 - CRC clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn crcen(&mut self) -> CRCEN_W<AHB1ENR_SPEC, 12> {
CRCEN_W::new(self)
}
#[doc = "Bit 14 - CORDIC clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn cordicen(&mut self) -> CORDICEN_W<AHB1ENR_SPEC, 14> {
CORDICEN_W::new(self)
}
#[doc = "Bit 15 - FMAC clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn fmacen(&mut self) -> FMACEN_W<AHB1ENR_SPEC, 15> {
FMACEN_W::new(self)
}
#[doc = "Bit 17 - RAMCFG clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn ramcfgen(&mut self) -> RAMCFGEN_W<AHB1ENR_SPEC, 17> {
RAMCFGEN_W::new(self)
}
#[doc = "Bit 19 - ETH clock enable Set and reset by software"]
#[inline(always)]
#[must_use]
pub fn ethen(&mut self) -> ETHEN_W<AHB1ENR_SPEC, 19> {
ETHEN_W::new(self)
}
#[doc = "Bit 20 - ETHTX clock enable Set and reset by software"]
#[inline(always)]
#[must_use]
pub fn ethtxen(&mut self) -> ETHTXEN_W<AHB1ENR_SPEC, 20> {
ETHTXEN_W::new(self)
}
#[doc = "Bit 21 - ETHRX clock enable Set and reset by software"]
#[inline(always)]
#[must_use]
pub fn ethrxen(&mut self) -> ETHRXEN_W<AHB1ENR_SPEC, 21> {
ETHRXEN_W::new(self)
}
#[doc = "Bit 24 - TZSC1 clock enable Set and reset by software"]
#[inline(always)]
#[must_use]
pub fn tzsc1en(&mut self) -> TZSC1EN_W<AHB1ENR_SPEC, 24> {
TZSC1EN_W::new(self)
}
#[doc = "Bit 28 - BKPRAM clock enable Set and reset by software"]
#[inline(always)]
#[must_use]
pub fn bkpramen(&mut self) -> BKPRAMEN_W<AHB1ENR_SPEC, 28> {
BKPRAMEN_W::new(self)
}
#[doc = "Bit 30 - DCACHE clock enable Set and reset by software"]
#[inline(always)]
#[must_use]
pub fn dcacheen(&mut self) -> DCACHEEN_W<AHB1ENR_SPEC, 30> {
DCACHEEN_W::new(self)
}
#[doc = "Bit 31 - SRAM1 clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn sram1en(&mut self) -> SRAM1EN_W<AHB1ENR_SPEC, 31> {
SRAM1EN_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 = "RCC AHB1 peripherals clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb1enr::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 [`ahb1enr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB1ENR_SPEC;
impl crate::RegisterSpec for AHB1ENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb1enr::R`](R) reader structure"]
impl crate::Readable for AHB1ENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb1enr::W`](W) writer structure"]
impl crate::Writable for AHB1ENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB1ENR to value 0xd000_0100"]
impl crate::Resettable for AHB1ENR_SPEC {
const RESET_VALUE: Self::Ux = 0xd000_0100;
}
|
//! Example to demonstrate how to use the `keep_default_for` attribute.
//!
//! The generated `impl` blocks generate an item for each trait item by
//! default. This means that default methods in traits are also implemented via
//! the proxy type. Sometimes, this is not what you want. One special case is
//! when the default method has where bounds that don't apply to the proxy
//! type.
use auto_impl::auto_impl;
#[auto_impl(&, Box)]
trait Foo {
fn required(&self) -> String;
// The generated impl for `&T` will not override this method.
#[auto_impl(keep_default_for(&))]
fn provided(&self) {
println!("Hello {}", self.required());
}
}
impl Foo for String {
fn required(&self) -> String {
self.clone()
}
fn provided(&self) {
println!("привет {}", self);
}
}
fn test_foo(x: impl Foo) {
x.provided();
}
fn main() {
let s = String::from("Peter");
// Output: "привет Peter", because `String` has overwritten the default
// method.
test_foo(s.clone());
// Output: "Hello Peter", because the method is not overwritten for the
// `&T` impl block.
test_foo(&s);
// Output: "привет Peter", because the `Box<T>` impl overwrites the method
// by default, if you don't specify `keep_default_for`.
test_foo(Box::new(s));
}
|
/*
* Knuth-Morris-Pratt string matcher (Rust)
*
* Copyright (c) 2021 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/knuth-morris-pratt-string-matching
*
* 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.
*/
// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise None is returned.
fn kmp_search(pattern: &str, text: &str) -> Option<usize> {
if pattern.is_empty() {
return Some(0); // Immediate match
}
// Compute longest suffix-prefix table
let pattbytes: &[u8] = pattern.as_bytes();
let mut lsp = Vec::<usize>::with_capacity(pattbytes.len());
lsp.push(0);
for &b in &pattbytes[1 .. ] {
// Start by assuming we're extending the previous LSP
let mut j: usize = *lsp.last().unwrap();
while j > 0 && b != pattbytes[j] {
j = lsp[j - 1];
}
if b == pattbytes[j] {
j += 1;
}
lsp.push(j);
}
// Walk through text string
let mut j: usize = 0; // The number of chars matched in pattern
for (i, &b) in text.as_bytes().iter().enumerate() {
while j > 0 && b != pattbytes[j] {
j = lsp[j - 1]; // Fall back in the pattern
}
if b == pattbytes[j] {
j += 1; // Next char matched, increment position
if j == pattbytes.len() {
return Some(i - (j - 1));
}
}
}
None // Not found
}
|
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
use asynchronous_codec::{Decoder, Encoder};
use bytes::BytesMut;
use prost::Message;
use std::io::Cursor;
use std::marker::PhantomData;
use unsigned_varint::codec::UviBytes;
/// [`Codec`] implements [`Encoder`] and [`Decoder`], uses [`unsigned_varint`]
/// to prefix messages with their length and uses [`prost`] and a provided
/// `struct` implementing [`Message`] to do the encoding.
pub struct Codec<In, Out = In> {
uvi: UviBytes,
phantom: PhantomData<(In, Out)>,
}
impl<In, Out> Codec<In, Out> {
/// Create new [`Codec`].
///
/// Parameter `max_message_len_bytes` determines the maximum length of the
/// Protobuf message. The limit does not include the bytes needed for the
/// [`unsigned_varint`].
pub fn new(max_message_len_bytes: usize) -> Self {
let mut uvi = UviBytes::default();
uvi.set_max_len(max_message_len_bytes);
Self {
uvi,
phantom: PhantomData::default(),
}
}
}
impl<In: Message, Out> Encoder for Codec<In, Out> {
type Item = In;
type Error = Error;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
let mut encoded_msg = BytesMut::new();
item.encode(&mut encoded_msg)
.expect("BytesMut to have sufficient capacity.");
self.uvi.encode(encoded_msg.freeze(), dst)?;
Ok(())
}
}
impl<In, Out: Message + Default> Decoder for Codec<In, Out> {
type Item = Out;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let msg = match self.uvi.decode(src)? {
None => return Ok(None),
Some(msg) => msg,
};
let message = Message::decode(Cursor::new(msg))
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
Ok(Some(message))
}
}
#[derive(thiserror::Error, Debug)]
#[error("Failed to encode/decode message")]
pub struct Error(#[from] std::io::Error);
impl From<Error> for std::io::Error {
fn from(e: Error) -> Self {
e.0
}
}
|
use crate::file::FileWriter;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{Error, Read, Write};
use std::path::PathBuf;
use std::ptr::hash;
use std::sync::{Arc, Mutex, RwLock};
pub struct Storage {
child_count: Arc<Mutex<usize>>,
storage_file: Arc<Mutex<StorageFiles>>,
hashes: Arc<RwLock<HashMap<String, (usize, usize)>>>,
}
pub struct StorageFiles {
pub storage_file: File,
pub meta: File,
}
impl Storage {
pub const BLOCK_SIZE: usize = 1024 * 1024;
pub fn new<P>(path: P) -> Self
where
P: Into<PathBuf>,
{
let path = path.into();
std::fs::DirBuilder::new().create(&path);
let storage_file_path = &path.join("storage");
let storage_meta_path = &path.join("meta");
let storage_file = OpenOptions::new()
.append(true)
.create(true)
.open(storage_file_path)
.expect("couldn't open storage file");
let mut buf = String::new();
{
OpenOptions::new()
.create(true)
.write(true)
.open(&storage_meta_path)
.expect("could not create file");
let mut storage_meta_file_read = OpenOptions::new()
.read(true)
.open(&storage_meta_path)
.expect("couldn't open storage file");
storage_meta_file_read
.read_to_string(&mut buf)
.expect("???");
}
let mut hash_list = HashMap::new();
let mut prev_size = 0;
for line in buf.split('\n').filter(|s| s.len() != 0) {
let v: Vec<String> = line.split(' ').map(|s| s.to_string()).collect();
let size = v[1].parse().unwrap();
hash_list.insert(v[0].clone(), (prev_size, size));
prev_size = size;
}
//dbg!(&hash_list);
let storage_meta_file = OpenOptions::new()
.write(true)
.create(true)
.open(&storage_meta_path)
.expect("???");
Self {
storage_file: Arc::new(Mutex::new(StorageFiles {
storage_file,
meta: storage_meta_file,
})),
child_count: Arc::new(Mutex::new(0)),
hashes: Arc::new(RwLock::new(hash_list)),
}
}
pub fn new_file_writer(&self) -> FileWriter {
FileWriter::new(&self)
}
pub fn get_new_id(&self) -> usize {
let mut count = self.child_count.lock().expect("mutex broke");
*count += 1;
*count
}
pub fn get_storage_file(&self) -> Arc<Mutex<StorageFiles>> {
self.storage_file.clone()
}
pub fn get_hashes(&self) -> Arc<RwLock<HashMap<String, (usize, usize)>>> {
self.hashes.clone()
}
}
|
extern crate gio;
extern crate gtk;
use crate::xml_test::*;
use gtk::{prelude::*, Widget, Container, Builder};
use std::collections::{HashMap};
use std::iter::FromIterator;
macro_rules! class(
{ $type: ty, $class: literal } => {
impl ComponentT for $type {
fn class() -> &'static str { $class }
}
}
);
pub trait ComponentT {
fn class() -> &'static str;
}
pub fn new_comp<T: ComponentT>(id: &'static str) -> Component {
Component { class: T::class().to_string(), id: id.to_string(), ..Component::empty() }
}
class!(gtk::Box, "GtkBox");
class!(gtk::Button, "GtkButton");
class!(gtk::Frame, "GtkFrame");
pub struct Component {
pub class: String,
pub id: String,
pub properties: HashMap<String, String>,
pub children: Children
}
pub struct Children {
pub v: Vec<String>,
pub m: HashMap<String, Component>
}
impl Children {
fn new() -> Children {
Children { v: Vec::new(), m: HashMap::new() }
}
}
pub fn add_child_maybe(widget: &Widget, container: &Container) {
if container.upcast_ref::<Widget>() != widget.get_parent().as_ref().unwrap_or(widget) {
container.add(widget);
}
if !widget.is_visible() {
widget.show_all();
}
}
struct CompIter<'a> {
stack: Vec<&'a Component>
}
impl<'a> CompIter<'a> {
fn new(comp: &'a Component) -> CompIter<'a> {
CompIter { stack: vec![comp] }
}
}
impl<'a> Iterator for CompIter<'a> {
type Item = &'a Component;
fn next(&mut self) -> Option<&'a Component> {
match self.stack.pop() {
None => None,
Some(comp) => {
for c in comp.children.v.iter() {
self.stack.push(&comp.children.m[c]);
}
Some(comp)
}
}
}
}
impl Component {
pub fn empty() -> Component {
Component {
class: String::new(),
id: String::new(),
properties: HashMap::new(),
children: Children::new()
}
}
fn iter(&self) -> CompIter {
CompIter::new(self)
}
pub fn with_props(mut self, props: HashMap<&str, &str>) -> Component {
self.properties = HashMap::from_iter(props.iter().map(|(k,v)| (k.to_string(), v.to_string())));
self
}
pub fn with_children(mut self, children: Vec<Component>) -> Component {
children.into_iter().for_each(|c| {
self.children.v.push(c.id.clone());
self.children.m.insert(c.id.clone(), c);
});
self
}
pub fn build(&self, app: &AppPtr) {
let xml_str = self.to_xml_string().expect("Error serializing to xml");
let builder = Builder::new_from_string(&xml_str[..]);
for c in self.iter() {
app.widget_map.borrow_mut().insert(c.id.clone(), builder.get_object(&c.id).
expect(&format!("Could not get widget {} from xml", c.id)[..]));
}
}
pub fn remove_self_widget(&self, wmap: &mut WidgetMap) {
println!("Removing widget {}", self.id);
let widget = &wmap[&self.id];
if let Some(parent) = widget.get_parent() {
parent.downcast_ref::<Container>().unwrap().remove(widget);
}
for c in self.iter() {
wmap.remove(&c.id);
}
}
pub fn add_child_widget(&self, id: &String, app: &AppPtr) {
self.children.m[id].build(app);
let parent = &app.widget_map.borrow()[&self.id];
let child = &app.widget_map.borrow()[id];
add_child_maybe(&child, parent.downcast_ref::<Container>().unwrap());
}
pub fn render_diff(&self, comp_old: &Component, app: &AppPtr)
{
println!("Comparing {:?} to {:?}", self.id, comp_old.id);
comp_old.children.v.iter().for_each(|old_id| {
let old_child = &comp_old.children.m[old_id];
if let Some(new_child) = self.children.m.get(old_id) {
new_child.render_diff(old_child, app);
}
else {
old_child.remove_self_widget(&mut app.widget_map.borrow_mut());
}
});
self.children.v.iter().for_each(|id| {
if !comp_old.children.m.contains_key(id) {
self.add_child_widget(id, app);
}
});
}
}
|
extern crate cryptopals_lib;
extern crate rusty_aes;
use std::cmp::Ordering;
use crate::cryptopals_lib::utils::file_io_utils;
use crate::rusty_aes::decrypt::Decrypt;
use crate::cryptopals_lib::hex;
pub fn main() {
let file_name = "challenge_files/8.txt";
//read file to string
let input = file_io_utils::read_file_by_lines_to_vec_str(&file_name);
let mut t_input: Vec<Vec<u8>> = Vec::new();
for i in input {
t_input.push(hex::encoders::str_to_hex_u8_buf(&i));
}
// let key = "YELLOW SUBMARINE".as_bytes().to_vec();
//instantiate our aes decryptor
// for (i, t) in t_input.iter().enumerate() {
// println!("index: {} count: {}", i, pattern_match(t, 4));
// }
let collected = collect_chunks(&t_input);
let mut collected = chunk_match(collected, &t_input);
collected.sort_by(|a, b| b.count.partial_cmp(&a.count).unwrap_or(Ordering::Equal));
for c in collected {
if c.count > 1 {
dbg!(c);
}
}
}
#[derive(Debug)]
pub struct Chunk {
line_pos: usize,
count: usize,
chunk: Vec<u8>,
}
fn chunk_match(mut chunks: Vec<Chunk>, input: &Vec<Vec<u8>>) -> Vec<Chunk> {
for mut c in chunks.iter_mut() {
for i in input {
let mut pos = 0;
while pos < i.len() {
if c.chunk.iter().zip(i[pos..pos + 15].to_vec()).all(|(a,b)| eq_with_nan_eq(*a, b)) {
c.count += 1;
}
pos += 16;
}
}
}
chunks
}
fn collect_chunks(input: &Vec<Vec<u8>>) -> Vec<Chunk> {
let mut collected: Vec<Chunk> = Vec::new();
for (i, v) in input.iter().enumerate() {
let mut pos = 0;
while pos < v.len() {
collected.push(Chunk {line_pos: i + 1, count: 0, chunk: v[pos..pos + 15].to_vec()});
pos += 16;
}
}
collected
}
fn eq_with_nan_eq(a: u8, b: u8) -> bool {
a == b
}
fn pattern_match(line: &Vec<u8>, check_size: usize) -> usize {
assert_eq!(line.len() % 16, 0);
let runs = line.len() / check_size;
let mut count = 0;
let mut index = 0;
for _x in 0..runs {
let index_val: Vec<u8> = line[index..index + check_size].to_vec();
// for y in (0..line.len()).step_by(check_size) {
for y in 0..line.len() {
if y + check_size <= line.len() {
if index_val.iter().zip(line[y..y + check_size].to_vec()).all(|(a,b)| eq_with_nan_eq(*a, b)) {
count += 1;
}
}
}
index += check_size;
}
count
} |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - RAMCFG memory 1 control register"]
pub m1cr: M1CR,
_reserved1: [u8; 0x04],
#[doc = "0x08 - RAMCFG memory interrupt status register"]
pub m1isr: M1ISR,
_reserved2: [u8; 0x1c],
#[doc = "0x28 - RAMCFG memory 1 erase key register"]
pub m1erkeyr: M1ERKEYR,
_reserved3: [u8; 0x14],
#[doc = "0x40 - RAMCFG memory 2 control register"]
pub m2cr: M2CR,
#[doc = "0x44 - RAMCFG memory 2 interrupt enable register"]
pub m2ier: M2IER,
#[doc = "0x48 - RAMCFG memory interrupt status register"]
pub m2isr: M2ISR,
#[doc = "0x4c - RAMCFG memory 2 ECC single error address register"]
pub m2sear: M2SEAR,
#[doc = "0x50 - RAMCFG memory 2 ECC double error address register"]
pub m2dear: M2DEAR,
#[doc = "0x54 - RAMCFG memory 2 interrupt clear register 2"]
pub m2icr: M2ICR,
#[doc = "0x58 - RAMCFG memory 2 write protection register 1"]
pub m2wpr1: M2WPR1,
#[doc = "0x5c - RAMCFG memory 2 write protection register 2"]
pub m2wpr2: M2WPR2,
_reserved11: [u8; 0x04],
#[doc = "0x64 - RAMCFG memory 2 ECC key register"]
pub m2ecckeyr: M2ECCKEYR,
#[doc = "0x68 - RAMCFG memory 2 erase key register"]
pub m2erkeyr: M2ERKEYR,
_reserved13: [u8; 0x14],
#[doc = "0x80 - RAMCFG memory 3 control register"]
pub m3cr: M3CR,
#[doc = "0x84 - RAMCFG memory 3 interrupt enable register"]
pub m3ier: M3IER,
#[doc = "0x88 - RAMCFG memory interrupt status register"]
pub m3isr: M3ISR,
#[doc = "0x8c - RAMCFG memory 3 ECC single error address register"]
pub m3sear: M3SEAR,
#[doc = "0x90 - RAMCFG memory 3 ECC double error address register"]
pub m3dear: M3DEAR,
#[doc = "0x94 - RAMCFG memory 3 interrupt clear register 3"]
pub m3icr: M3ICR,
_reserved19: [u8; 0x0c],
#[doc = "0xa4 - RAMCFG memory 3 ECC key register"]
pub m3ecckeyr: M3ECCKEYR,
#[doc = "0xa8 - RAMCFG memory 3 erase key register"]
pub m3erkeyr: M3ERKEYR,
_reserved21: [u8; 0x3c],
#[doc = "0xe8 - RAMCFG memory 4 erase key register"]
pub m4erkeyr: M4ERKEYR,
_reserved22: [u8; 0x14],
#[doc = "0x100 - RAMCFG memory 5 control register"]
pub m5cr: M5CR,
#[doc = "0x104 - RAMCFG memory 5 interrupt enable register"]
pub m5ier: M5IER,
#[doc = "0x108 - RAMCFG memory interrupt status register"]
pub m5isr: M5ISR,
#[doc = "0x10c - RAMCFG memory 5 ECC single error address register"]
pub m5sear: M5SEAR,
#[doc = "0x110 - RAMCFG memory 5 ECC double error address register"]
pub m5dear: M5DEAR,
#[doc = "0x114 - RAMCFG memory 5 interrupt clear register 5"]
pub m5icr: M5ICR,
_reserved28: [u8; 0x0c],
#[doc = "0x124 - RAMCFG memory 5 ECC key register"]
pub m5ecckeyr: M5ECCKEYR,
#[doc = "0x128 - RAMCFG memory 5 erase key register"]
pub m5erkeyr: M5ERKEYR,
}
#[doc = "M1CR (rw) register accessor: RAMCFG memory 1 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m1cr::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 [`m1cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m1cr`]
module"]
pub type M1CR = crate::Reg<m1cr::M1CR_SPEC>;
#[doc = "RAMCFG memory 1 control register"]
pub mod m1cr;
#[doc = "M1ISR (r) register accessor: RAMCFG memory interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m1isr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m1isr`]
module"]
pub type M1ISR = crate::Reg<m1isr::M1ISR_SPEC>;
#[doc = "RAMCFG memory interrupt status register"]
pub mod m1isr;
#[doc = "M1ERKEYR (w) register accessor: RAMCFG memory 1 erase key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`m1erkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m1erkeyr`]
module"]
pub type M1ERKEYR = crate::Reg<m1erkeyr::M1ERKEYR_SPEC>;
#[doc = "RAMCFG memory 1 erase key register"]
pub mod m1erkeyr;
#[doc = "M2CR (rw) register accessor: RAMCFG memory 2 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m2cr::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 [`m2cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2cr`]
module"]
pub type M2CR = crate::Reg<m2cr::M2CR_SPEC>;
#[doc = "RAMCFG memory 2 control register"]
pub mod m2cr;
#[doc = "M2IER (rw) register accessor: RAMCFG memory 2 interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m2ier::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 [`m2ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2ier`]
module"]
pub type M2IER = crate::Reg<m2ier::M2IER_SPEC>;
#[doc = "RAMCFG memory 2 interrupt enable register"]
pub mod m2ier;
#[doc = "M2ISR (r) register accessor: RAMCFG memory interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m2isr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2isr`]
module"]
pub type M2ISR = crate::Reg<m2isr::M2ISR_SPEC>;
#[doc = "RAMCFG memory interrupt status register"]
pub mod m2isr;
#[doc = "M2SEAR (r) register accessor: RAMCFG memory 2 ECC single error address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m2sear::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2sear`]
module"]
pub type M2SEAR = crate::Reg<m2sear::M2SEAR_SPEC>;
#[doc = "RAMCFG memory 2 ECC single error address register"]
pub mod m2sear;
#[doc = "M2DEAR (r) register accessor: RAMCFG memory 2 ECC double error address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m2dear::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2dear`]
module"]
pub type M2DEAR = crate::Reg<m2dear::M2DEAR_SPEC>;
#[doc = "RAMCFG memory 2 ECC double error address register"]
pub mod m2dear;
#[doc = "M2ICR (rw) register accessor: RAMCFG memory 2 interrupt clear register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m2icr::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 [`m2icr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2icr`]
module"]
pub type M2ICR = crate::Reg<m2icr::M2ICR_SPEC>;
#[doc = "RAMCFG memory 2 interrupt clear register 2"]
pub mod m2icr;
#[doc = "M2WPR1 (rw) register accessor: RAMCFG memory 2 write protection register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m2wpr1::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 [`m2wpr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2wpr1`]
module"]
pub type M2WPR1 = crate::Reg<m2wpr1::M2WPR1_SPEC>;
#[doc = "RAMCFG memory 2 write protection register 1"]
pub mod m2wpr1;
#[doc = "M2WPR2 (rw) register accessor: RAMCFG memory 2 write protection register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m2wpr2::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 [`m2wpr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2wpr2`]
module"]
pub type M2WPR2 = crate::Reg<m2wpr2::M2WPR2_SPEC>;
#[doc = "RAMCFG memory 2 write protection register 2"]
pub mod m2wpr2;
#[doc = "M2ECCKEYR (w) register accessor: RAMCFG memory 2 ECC key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`m2ecckeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2ecckeyr`]
module"]
pub type M2ECCKEYR = crate::Reg<m2ecckeyr::M2ECCKEYR_SPEC>;
#[doc = "RAMCFG memory 2 ECC key register"]
pub mod m2ecckeyr;
#[doc = "M2ERKEYR (w) register accessor: RAMCFG memory 2 erase key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`m2erkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m2erkeyr`]
module"]
pub type M2ERKEYR = crate::Reg<m2erkeyr::M2ERKEYR_SPEC>;
#[doc = "RAMCFG memory 2 erase key register"]
pub mod m2erkeyr;
#[doc = "M3CR (rw) register accessor: RAMCFG memory 3 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m3cr::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 [`m3cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m3cr`]
module"]
pub type M3CR = crate::Reg<m3cr::M3CR_SPEC>;
#[doc = "RAMCFG memory 3 control register"]
pub mod m3cr;
#[doc = "M3IER (rw) register accessor: RAMCFG memory 3 interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m3ier::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 [`m3ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m3ier`]
module"]
pub type M3IER = crate::Reg<m3ier::M3IER_SPEC>;
#[doc = "RAMCFG memory 3 interrupt enable register"]
pub mod m3ier;
#[doc = "M3ISR (r) register accessor: RAMCFG memory interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m3isr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m3isr`]
module"]
pub type M3ISR = crate::Reg<m3isr::M3ISR_SPEC>;
#[doc = "RAMCFG memory interrupt status register"]
pub mod m3isr;
#[doc = "M3SEAR (r) register accessor: RAMCFG memory 3 ECC single error address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m3sear::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m3sear`]
module"]
pub type M3SEAR = crate::Reg<m3sear::M3SEAR_SPEC>;
#[doc = "RAMCFG memory 3 ECC single error address register"]
pub mod m3sear;
#[doc = "M3DEAR (r) register accessor: RAMCFG memory 3 ECC double error address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m3dear::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m3dear`]
module"]
pub type M3DEAR = crate::Reg<m3dear::M3DEAR_SPEC>;
#[doc = "RAMCFG memory 3 ECC double error address register"]
pub mod m3dear;
#[doc = "M3ICR (rw) register accessor: RAMCFG memory 3 interrupt clear register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m3icr::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 [`m3icr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m3icr`]
module"]
pub type M3ICR = crate::Reg<m3icr::M3ICR_SPEC>;
#[doc = "RAMCFG memory 3 interrupt clear register 3"]
pub mod m3icr;
#[doc = "M3ECCKEYR (w) register accessor: RAMCFG memory 3 ECC key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`m3ecckeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m3ecckeyr`]
module"]
pub type M3ECCKEYR = crate::Reg<m3ecckeyr::M3ECCKEYR_SPEC>;
#[doc = "RAMCFG memory 3 ECC key register"]
pub mod m3ecckeyr;
#[doc = "M3ERKEYR (w) register accessor: RAMCFG memory 3 erase key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`m3erkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m3erkeyr`]
module"]
pub type M3ERKEYR = crate::Reg<m3erkeyr::M3ERKEYR_SPEC>;
#[doc = "RAMCFG memory 3 erase key register"]
pub mod m3erkeyr;
#[doc = "M4ERKEYR (w) register accessor: RAMCFG memory 4 erase key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`m4erkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m4erkeyr`]
module"]
pub type M4ERKEYR = crate::Reg<m4erkeyr::M4ERKEYR_SPEC>;
#[doc = "RAMCFG memory 4 erase key register"]
pub mod m4erkeyr;
#[doc = "M5CR (rw) register accessor: RAMCFG memory 5 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m5cr::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 [`m5cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m5cr`]
module"]
pub type M5CR = crate::Reg<m5cr::M5CR_SPEC>;
#[doc = "RAMCFG memory 5 control register"]
pub mod m5cr;
#[doc = "M5IER (rw) register accessor: RAMCFG memory 5 interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m5ier::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 [`m5ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m5ier`]
module"]
pub type M5IER = crate::Reg<m5ier::M5IER_SPEC>;
#[doc = "RAMCFG memory 5 interrupt enable register"]
pub mod m5ier;
#[doc = "M5ISR (r) register accessor: RAMCFG memory interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m5isr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m5isr`]
module"]
pub type M5ISR = crate::Reg<m5isr::M5ISR_SPEC>;
#[doc = "RAMCFG memory interrupt status register"]
pub mod m5isr;
#[doc = "M5SEAR (r) register accessor: RAMCFG memory 5 ECC single error address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m5sear::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m5sear`]
module"]
pub type M5SEAR = crate::Reg<m5sear::M5SEAR_SPEC>;
#[doc = "RAMCFG memory 5 ECC single error address register"]
pub mod m5sear;
#[doc = "M5DEAR (r) register accessor: RAMCFG memory 5 ECC double error address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m5dear::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m5dear`]
module"]
pub type M5DEAR = crate::Reg<m5dear::M5DEAR_SPEC>;
#[doc = "RAMCFG memory 5 ECC double error address register"]
pub mod m5dear;
#[doc = "M5ICR (rw) register accessor: RAMCFG memory 5 interrupt clear register 5\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m5icr::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 [`m5icr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m5icr`]
module"]
pub type M5ICR = crate::Reg<m5icr::M5ICR_SPEC>;
#[doc = "RAMCFG memory 5 interrupt clear register 5"]
pub mod m5icr;
#[doc = "M5ECCKEYR (w) register accessor: RAMCFG memory 5 ECC key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`m5ecckeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m5ecckeyr`]
module"]
pub type M5ECCKEYR = crate::Reg<m5ecckeyr::M5ECCKEYR_SPEC>;
#[doc = "RAMCFG memory 5 ECC key register"]
pub mod m5ecckeyr;
#[doc = "M5ERKEYR (w) register accessor: RAMCFG memory 5 erase key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`m5erkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m5erkeyr`]
module"]
pub type M5ERKEYR = crate::Reg<m5erkeyr::M5ERKEYR_SPEC>;
#[doc = "RAMCFG memory 5 erase key register"]
pub mod m5erkeyr;
|
// https://docs.rs/structopt/0.3.21/structopt/index.html
// https://blog.logrocket.com/json-and-rust-why-serde_json-is-the-top-choice/
// https://github.com/serde-rs/json
// ✅ ❌ 🚧 🦀
use std::io::BufReader; // Read, Error
use std::path::Path;
use serde::{Deserialize, Serialize};
use serde_json::Result;
// use std::path::PathBuf;
// use structopt::StructOpt;
use std::fs::{ File, write };
use std::env::args;
#[derive(Deserialize, Serialize, Debug)]
struct ItemList {
items: Vec<Item>,
}
#[derive(Deserialize, Serialize, Debug)]
struct Item {
title: String,
content: String,
status: String,
}
fn create_item(title: String, content: String) -> Item {
Item {
title: title,
content: content,
status: String::from("❌"),
}
}
fn remove_item(mut itemlist: ItemList, title: String) -> ItemList {
for i in 0..itemlist.items.len() {
if itemlist.items[i].title == title {
itemlist.items.remove(i);
}
}
itemlist
}
fn read_itemlist_from_file<P: AsRef<Path>>(path: P) -> Result<ItemList> {
// Open the file in read-only mode with buffer.
let file = File::open(path).expect("bad word");
let reader = BufReader::new(file);
// Read the JSON contents of the file as an instance of `ItemList`.
let u = serde_json::from_reader(reader)?;
// Return the `ItemList`.
Ok(u)
}
fn display(itemlist: &ItemList) {
for i in 0..itemlist.items.len() {
println!("{}: Title: {} \t|{}|\n{}\n", i, itemlist.items[i].title, itemlist.items[i].status, itemlist.items[i].content);
}
}
fn change_status(mut itemlist: ItemList, title: String ,mark: String) -> ItemList {
for i in 0..itemlist.items.len() {
if itemlist.items[i].title == title {
itemlist.items[i].status = mark.clone();
}
}
itemlist
}
fn main() {
let action = args().nth(1).expect("Please specify an action");
let mut itemlist = read_itemlist_from_file("foo.json").unwrap();
let checked = "✅".to_string();
let crossed = "❌".to_string();
let occupied = "🚧".to_string();
if action == "add" {
let item_title = args().nth(2).expect("Please specify item title");
let item_content = args().nth(3).expect("Please specify item content");
let item = create_item(item_title, item_content);
itemlist.items.push(item);
} else if action == "remove" {
let item_title = args().nth(2).expect("Please specify item title");
itemlist = remove_item(itemlist, item_title);
} else if action == "set-status" {
let item_title = args().nth(2).expect("Please specify item title");
let status = args().nth(3).expect("Please specify item status");
if status == "done" {
itemlist = change_status(itemlist, item_title, checked.clone());
} else if status == "undone" {
itemlist = change_status(itemlist, item_title, crossed.clone());
} else if status == "occupied" {
itemlist = change_status(itemlist, item_title, occupied.clone());
}
} else if action == "display" {
display(&itemlist);
} else {
println!("HELP");
}
let j = serde_json::to_string_pretty(&itemlist).expect("bad word");
write("foo.json", j).expect("bad word");
}
// ???: 1. You should loop over the contents of the array by doing for item in itemlist.items.
// 2. You don't need to do .to_string() on "10", String can be compared against a &str.
// ???: I think this will make it nicer :)
// ???: @??? status = checker.clone() did not solve the problem?
// for i in 0..itemlist.items.len() {
// if itemlist.items[i].title == "10".to_string(){
// itemlist.items[i].status = crossed.clone();
// }
// }
// itemlist.items[0].status = checker;
|
use std::{borrow::Cow, marker};
use chrono_tz::Tz;
use either::Either;
use crate::{
errors::{Error, FromSqlError, Result},
types::{
block::ColumnIdx,
column::{ArcColumnWrapper, ColumnData},
Column, ColumnType, Value,
},
Block,
};
pub trait RowBuilder {
fn apply<K: ColumnType>(self, block: &mut Block<K>) -> Result<()>;
}
pub struct RNil;
pub struct RCons<T>
where
T: RowBuilder,
{
key: Cow<'static, str>,
value: Value,
tail: T,
}
impl RNil {
pub fn put(self, key: Cow<'static, str>, value: Value) -> RCons<Self> {
RCons {
key,
value,
tail: RNil,
}
}
}
impl<T> RCons<T>
where
T: RowBuilder,
{
pub fn put(self, key: Cow<'static, str>, value: Value) -> RCons<Self> {
RCons {
key,
value,
tail: self,
}
}
}
impl RowBuilder for RNil {
#[inline(always)]
fn apply<K: ColumnType>(self, _block: &mut Block<K>) -> Result<()> {
Ok(())
}
}
impl<T> RowBuilder for RCons<T>
where
T: RowBuilder,
{
#[inline(always)]
fn apply<K: ColumnType>(self, block: &mut Block<K>) -> Result<()> {
put_param(self.key, self.value, block)?;
self.tail.apply(block)
}
}
impl RowBuilder for Vec<(String, Value)> {
fn apply<K: ColumnType>(self, block: &mut Block<K>) -> Result<()> {
for (k, v) in self {
put_param(k.into(), v, block)?;
}
Ok(())
}
}
fn put_param<K: ColumnType>(
key: Cow<'static, str>,
value: Value,
block: &mut Block<K>,
) -> Result<()> {
let col_index = match key.as_ref().get_index(&block.columns) {
Ok(col_index) => col_index,
Err(Error::FromSql(FromSqlError::OutOfRange)) => {
if block.row_count() <= 1 {
let sql_type = From::from(value.clone());
let timezone = extract_timezone(&value);
let column = Column {
name: key.clone().into(),
data: <dyn ColumnData>::from_type::<ArcColumnWrapper>(
sql_type,
timezone,
block.capacity,
)?,
_marker: marker::PhantomData,
};
block.columns.push(column);
return put_param(key, value, block);
} else {
return Err(Error::FromSql(FromSqlError::OutOfRange));
}
}
Err(err) => return Err(err),
};
block.columns[col_index].push(value);
Ok(())
}
fn extract_timezone(value: &Value) -> Tz {
match value {
Value::Date(_, tz) => *tz,
Value::DateTime(_, tz) => *tz,
Value::Nullable(Either::Right(d)) => extract_timezone(d),
Value::Array(_, data) => {
if let Some(v) = data.first() {
extract_timezone(v)
} else {
Tz::Zulu
}
}
_ => Tz::Zulu,
}
}
#[cfg(test)]
mod test {
use chrono::prelude::*;
use chrono_tz::Tz::{self, UTC};
use crate::{
row,
types::{DateTimeType, Decimal, Simple, SqlType},
};
use super::*;
#[test]
fn test_push_row() {
let date_value: Date<Tz> = UTC.ymd(2016, 10, 22);
let date_time_value: DateTime<Tz> = UTC.ymd(2014, 7, 8).and_hms(14, 0, 0);
let decimal = Decimal::of(2.0_f64, 4);
let mut block = Block::<Simple>::new();
block
.push(row! {
i8_field: 1_i8,
i16_field: 1_i16,
i32_field: 1_i32,
i64_field: 1_i64,
u8_field: 1_u8,
u16_field: 1_u16,
u32_field: 1_u32,
u64_field: 1_u64,
f32_field: 4.66_f32,
f64_field: 2.71_f64,
str_field: "text",
opt_filed: Some("text"),
nil_filed: Option::<&str>::None,
date_field: date_value,
date_time_field: date_time_value,
decimal_field: decimal
})
.unwrap();
assert_eq!(block.row_count(), 1);
assert_eq!(block.columns[0].sql_type(), SqlType::Int8);
assert_eq!(block.columns[1].sql_type(), SqlType::Int16);
assert_eq!(block.columns[2].sql_type(), SqlType::Int32);
assert_eq!(block.columns[3].sql_type(), SqlType::Int64);
assert_eq!(block.columns[4].sql_type(), SqlType::UInt8);
assert_eq!(block.columns[5].sql_type(), SqlType::UInt16);
assert_eq!(block.columns[6].sql_type(), SqlType::UInt32);
assert_eq!(block.columns[7].sql_type(), SqlType::UInt64);
assert_eq!(block.columns[8].sql_type(), SqlType::Float32);
assert_eq!(block.columns[9].sql_type(), SqlType::Float64);
assert_eq!(block.columns[10].sql_type(), SqlType::String);
assert_eq!(
block.columns[11].sql_type(),
SqlType::Nullable(SqlType::String.into())
);
assert_eq!(
block.columns[12].sql_type(),
SqlType::Nullable(SqlType::String.into())
);
assert_eq!(block.columns[13].sql_type(), SqlType::Date);
assert_eq!(
block.columns[14].sql_type(),
SqlType::DateTime(DateTimeType::Chrono)
);
assert_eq!(block.columns[15].sql_type(), SqlType::Decimal(18, 4));
}
}
|
mod logic;
#[cfg(not(target_family = "wasm"))]
mod nif;
#[cfg(target_family = "wasm")]
mod wasm;
|
use std::ops::{Add, AddAssign, BitAnd, Mul, Sub, BitXor};
use std::cmp::{min, max};
use std::hint::unreachable_unchecked;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Pt(i32, i32);
impl Pt {
fn mag(&self) -> i32 {
self.0 + self.1
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Wire {
start: Pt,
end: Pt,
}
impl Add for Pt {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Pt(self.0 + rhs.0, self.1 + rhs.1)
}
}
impl AddAssign for Pt {
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0;
self.1 += rhs.1;
}
}
impl Sub for Pt {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Pt(self.0 - rhs.0, self.1 - rhs.1)
}
}
/// cross product
impl Mul for Pt {
type Output = i32;
fn mul(self, rhs: Self) -> Self::Output {
self.0 * rhs.1 + self.1 * rhs.0 // 2d cross product sort of
}
}
/// dot product
impl BitXor for Pt {
type Output = i32;
fn bitxor(self, rhs: Self) -> Self::Output {
self.0 * rhs.0 + self.1 * rhs.1
}
}
impl<N> Mul<N> for Pt
where N: Into<f64> {
type Output = Pt;
fn mul(self, rhs: N) -> Self::Output {
let n = rhs.into();
Pt(self.0 * n as i32, self.1 * n as i32)
}
}
impl Wire {
fn is_vert(&self) -> bool {
self.start.0 == self.end.0
}
fn len(&self) -> i32 {
(self.start - self.end).mag().abs()
}
fn bottom(&self) -> i32 {
min(self.start.1, self.end.1)
}
fn top(&self) -> i32 {
max(self.start.1, self.end.1)
}
fn left(&self) -> i32 {
min(self.start.0, self.end.0)
}
fn right(&self) -> i32 {
max(self.start.0, self.end.0)
}
fn dist_to(&self, Pt(x, y): &Pt) -> Result<u32, u32> {
if self.left() <= *x && self.right() >= *x &&
self.bottom() <= *y && self.top() >= *y {
Ok(((*x - self.start.0).abs() + (*y - self.start.1).abs()) as u32)
} else {
Err(self.len() as u32)
}
}
}
impl BitAnd for Wire {
type Output = Option<Pt>;
fn bitand(self, rhs: Self) -> Self::Output {
let (slx, srx) = (self.left(), self.right());
let (sdy, suy) = (self.bottom(), self.top());
let (rlx, rrx) = (rhs.left(), rhs.right());
let (rdy, ruy) = (rhs.bottom(), rhs.top());
if self.is_vert() == rhs.is_vert() {
None // lol who needs to implement this
} else {
if self.is_vert() {
if (rlx..rrx).contains(&slx) && (sdy..suy).contains(&rdy) {
Some(Pt(slx, ruy))
} else { None }
} else {
if (slx..srx).contains(&rlx) && (rdy..ruy).contains(&sdy) {
Some(Pt(rlx, suy))
} else { None }
}
}
}
}
#[aoc_generator(day3)]
fn gen(input: &str) -> (Wires, Wires) {
let mut lines: Vec<Wires> = input.lines()
.map(|line| {
let mut curr = Pt(0, 0);
line.split(",")
.map(|s: &str| {
let (dir, num_str) = s.split_at(1);
let num: i32 = num_str.parse().unwrap();
let mv = match dir {
"L" => Pt(-num, 0),
"R" => Pt(num, 0),
"U" => Pt(0, num),
"D" => Pt(0, -num),
// _ => unreachable!(),
_ => unsafe { unreachable_unchecked() },
};
let wire = Wire {
start: curr,
end: curr + mv,
};
curr += mv;
wire
})
.collect()
})
.collect();
(lines.remove(0), lines.remove(0))
}
#[aoc(day3, part1)]
fn part1(input: &(Wires, Wires)) -> i32 {
let (w1, w2) = input;
w1.iter()
.copied()
.flat_map(|wire1| {
w2.iter()
.copied()
.filter_map(move |wire2| wire1 & wire2)
})
.filter(|&pt| pt != Pt(0, 0))
.map(|Pt(x, y)| x.abs() + y.abs())
.min()
.unwrap()
}
#[aoc(day3, part2)]
fn part2(input: &(Wires, Wires)) -> u32 {
let (w1, w2) = input;
w1.iter()
.copied()
.flat_map(|wire1| {
w2.iter()
.copied()
.filter_map(move |wire2| wire1 & wire2)
})
.filter(|&pt| pt != Pt(0, 0))
.map(|pt| w1.dist_to(&pt) + w2.dist_to(&pt))
.min()
.unwrap()
}
type Wires = Vec<Wire>;
trait WiresExt {
fn dist_to(&self, pt: &Pt) -> u32;
}
impl WiresExt for Wires {
fn dist_to(&self, pt: &Pt) -> u32 {
let mut dist = 0;
for wire in self {
match wire.dist_to(pt) {
Ok(d) => return dist + d,
Err(d) => dist += d,
}
}
unsafe { unreachable_unchecked() }
}
}
|
#[macro_use]
extern crate chai;
mod state;
mod test_layer;
fn main() {
let state = state::State {};
let mut app = chai::Application::new(480, 480, "the big gay", state);
let layer = test_layer::TestLayer::new();
app.push_layer(layer);
app.start();
}
|
use nalgebra::core::DMatrix as DMatrix;
use linear::miscelanous::*;
use std;
#[no_mangle]
pub unsafe extern fn regress_point(weights: *mut [f64; 3], point: [f64; 2]) -> f64 {
point[0] * (*weights)[1] + point[1] * (*weights)[2] + (*weights)[0]
}
#[no_mangle]
pub extern fn linear_regression(raw_points : *mut std::os::raw::c_void,
raw_results : *mut std::os::raw::c_void,
dim: u64,
nb_elements: u64) -> *mut [f64; 3] {
let results = import_external(raw_results, nb_elements as usize);
let points : &[f64] = import_external(raw_points, (dim * nb_elements) as usize);
let mut weights : Vec<f64> = Vec::new();
let matrix_data = prepare_matrix_data(points, nb_elements as usize);
let matrix = DMatrix::from_row_slice(dim as usize, nb_elements as usize, matrix_data.as_slice());
let result_matrix = DMatrix::from_row_slice(1 as usize, nb_elements as usize, results);
let transposed_matrix = matrix.transpose();
let square_matrix = matrix.clone() * transposed_matrix.clone();
let inverted_matrix = square_matrix.pseudo_inverse(1e-19);
let verification_matrix = transposed_matrix * inverted_matrix;
let result = result_matrix * verification_matrix;
let calculated_weights = result.data.data();
for i in 0..calculated_weights.len() {
weights.push(calculated_weights[i]);
}
let w: [f64; 3] = [weights[0], weights[1], weights[2]];
Box::into_raw(Box::new(w))
}
fn prepare_matrix_data(points: &[f64], nb_elements: usize) -> Vec<f64> {
let mut points_vector = vec![];
for _ in 0..nb_elements {
points_vector.push(1.0);
}
for i in 0..nb_elements {
points_vector.push(points[i*3]);
}
for i in 0..nb_elements {
points_vector.push(points[i*3+2]);
}
points_vector
}
|
use chomp::ascii::{is_horizontal_space, is_whitespace};
use chomp::prelude::*;
use std::io::Read;
use std::iter::FromIterator;
use std::collections::HashMap;
use std::str;
#[derive(Debug, PartialEq)]
pub struct Header {
name: String,
value: String,
}
struct EOLMatcher {
found_carriage_return: bool,
}
impl EOLMatcher {
fn new() -> Self {
EOLMatcher {
found_carriage_return: false
}
}
fn at_eol<I: U8Input<Token=u8>>(&mut self, token: I::Token) -> bool {
if token == b'\r' {
self.found_carriage_return = true;
false
} else if token == b'\n' && self.found_carriage_return {
self.found_carriage_return = false;
true
} else {
self.found_carriage_return = false;
false
}
}
}
fn header<'a, I: U8Input<Buffer=&'a [u8]>>(i: I) -> SimpleResult<I, Option<HeaderType>> {
let mut eol_matcher = EOLMatcher::new();
parse!{i;
skip_while(is_whitespace);
let name = take_while(|c| c != b':');
token(b':');
skip_while(is_horizontal_space);
let value = take_while(|token| token != b'\r');
string(b"\r\n");
ret {
if let (Ok(name_str), Ok(value_str)) = (str::from_utf8(name), str::from_utf8(value)) {
HeaderType::from_raw(name_str, value_str)
} else {
None
}
}
}
}
fn headers<'a, I: U8Input<Buffer=&'a [u8]>>(i: I) -> SimpleResult<I, Headers> {
many1(i, header)
.bind::<_, _, Error<u8>>(|i, headers: Vec<Option<HeaderType>>| {
i.ret(headers.iter().filter_map(|v| {
match v {
&Some(ref header_type) => Some((header_type.as_key(), Box::new(header_type.clone()))),
&None => None
}
}).collect::<Headers>())
})
}
fn read_content<R: Read>(reader: &mut R, size: usize) -> String {
let mut buf = Vec::with_capacity(size);
reader.read_exact(&mut buf).unwrap();
String::from_utf8(buf).unwrap()
}
fn content<I: U8Input<Token=u8>>(i: I, size: usize) -> SimpleResult<I, String> {
take(i, size).bind(|i, bytes| i.ret(String::from_utf8(bytes.to_vec()).unwrap()))
}
struct IMessage {
headers: Vec<Header>,
content: String,
}
// fn message<I: U8Input>(i: I) -> SimpleResult<I, IMessage> {
// parse!{i;
// let my_headers = headers;
// ret Message {
// headers: headers,
// content: "".to_string()
// }
// }
// }
type ContentLength = usize;
type ContentType = String;
#[derive(Clone, Debug, PartialEq)]
enum HeaderType {
ContentLengthHeader(ContentLength),
ContentTypeHeader(ContentType),
}
impl HeaderType {
fn from_raw(name: &str, value: &str) -> Option<HeaderType> {
match name {
"Content-Type" => Some(HeaderType::ContentTypeHeader(value.to_string())),
"Content-Length" => Some(HeaderType::ContentLengthHeader(value.parse::<usize>().unwrap())),
_ => None
}
}
fn as_key(&self) -> &'static str {
match *self {
HeaderType::ContentLengthHeader(_) => "Content-Length",
HeaderType::ContentTypeHeader(_) => "Content-Type",
}
}
}
type Headers = HashMap<&'static str, Box<HeaderType>>;
struct Content;
/// Per the spec, calls can be batched and sent in one message as an array
pub struct Message;
#[cfg(test)]
mod test {
use chomp::prelude::*;
use super::{Message, Headers, Header, HeaderType, header, headers, content};
use std::io::Read;
use std::str;
#[test]
fn header_parser_works() {
let expected = HeaderType::ContentLengthHeader(9000);
let actual = parse_only(header, b"Content-Length: 9000\r\n").unwrap();
assert_eq!(expected, actual.unwrap());
}
fn valid_headers() -> &'static [u8] {
"
Content-Length: 1\r
Content-Type: application/vscode-jsonrpc; charset=utf8\r
\r\n
".as_bytes()
}
#[test]
fn headers_parse_works() {
let headers = parse_only(headers, valid_headers()).unwrap();
if let Some(&HeaderType::ContentLengthHeader(length)) = headers.get("Content-Length") {
assert_eq!(length, 1);
} else {
panic!();
}
}
fn valid_message() -> &'static [u8] {
"
Content-Length: 4\r
Content-Type: application/vscode-jsonrpc; charset=utf8\r
\r
{\"foo\": true}
".as_bytes()
}
#[test]
fn content_parser_works() {
let data = b"It's over 9000!!!";
let expected = "It's over".to_string();
let result = parse_only(|i| content(i, 9), data).unwrap();
assert_eq!(result, expected);
}
#[test]
fn content_can_read_to_exhaustion() {
let data = b"It's over 9000!!!";
let result = parse_only(|i| content(i, 17), data).unwrap();
assert_eq!(result, str::from_utf8(data).unwrap().to_string());
}
#[test]
fn content_works_with_multibyte_characters() {
let data = "ワンパタン";
let result = parse_only(|i| content(i, 15), data.as_bytes()).unwrap();
assert_eq!(result, data.to_string());
}
#[test]
fn message_can_parse_a_whole_message() {
panic!();
}
#[test]
fn messages_can_parse_an_arbitrary_number_of_messages() {
panic!();
}
}
|
use rusqlite::{Connection, Result, Row};
use sea_query::{ColumnDef, Expr, Func, Iden, Order, Query, SqliteQueryBuilder, Table};
sea_query::sea_query_driver_rusqlite!();
use sea_query_driver_rusqlite::RusqliteValues;
fn main() -> Result<()> {
let conn = Connection::open_in_memory()?;
// Schema
let sql = [
Table::drop()
.table(Character::Table)
.if_exists()
.build(SqliteQueryBuilder),
Table::create()
.table(Character::Table)
.if_not_exists()
.col(
ColumnDef::new(Character::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Character::FontSize).integer())
.col(ColumnDef::new(Character::Character).string())
.build(SqliteQueryBuilder),
]
.join("; ");
conn.execute_batch(&sql)?;
println!("Create table character: Ok()");
println!();
// Create
let (sql, values) = Query::insert()
.into_table(Character::Table)
.columns(vec![Character::Character, Character::FontSize])
.values_panic(vec!["A".into(), 12.into()])
.build(SqliteQueryBuilder);
let result = conn.execute(
sql.as_str(),
RusqliteValues::from(values).as_params().as_slice(),
);
println!("Insert into character: {:?}\n", result);
let id = conn.last_insert_rowid();
// Read
let (sql, values) = Query::select()
.columns(vec![
Character::Id,
Character::Character,
Character::FontSize,
])
.from(Character::Table)
.order_by(Character::Id, Order::Desc)
.limit(1)
.build(SqliteQueryBuilder);
println!("Select one from character:");
let mut stmt = conn.prepare(sql.as_str())?;
let mut rows = stmt.query(RusqliteValues::from(values).as_params().as_slice())?;
while let Some(row) = rows.next()? {
let item = CharacterStruct::from(row);
println!("{:?}", item);
}
println!();
// Update
let (sql, values) = Query::update()
.table(Character::Table)
.values(vec![(Character::FontSize, 24.into())])
.and_where(Expr::col(Character::Id).eq(id))
.build(SqliteQueryBuilder);
let result = conn.execute(
sql.as_str(),
RusqliteValues::from(values).as_params().as_slice(),
);
println!("Update character: {:?}\n", result);
// Read
let (sql, values) = Query::select()
.columns(vec![
Character::Id,
Character::Character,
Character::FontSize,
])
.from(Character::Table)
.order_by(Character::Id, Order::Desc)
.limit(1)
.build(SqliteQueryBuilder);
println!("Select one from character:");
let mut stmt = conn.prepare(sql.as_str())?;
let mut rows = stmt.query(RusqliteValues::from(values).as_params().as_slice())?;
while let Some(row) = rows.next()? {
let item = CharacterStruct::from(row);
println!("{:?}", item);
}
println!();
// Count
let (sql, values) = Query::select()
.from(Character::Table)
.expr(Func::count(Expr::col(Character::Id)))
.build(SqliteQueryBuilder);
print!("Count character: ");
let mut stmt = conn.prepare(sql.as_str())?;
let mut rows = stmt.query(RusqliteValues::from(values).as_params().as_slice())?;
let count: i64 = if let Some(row) = rows.next()? {
row.get_unwrap(0)
} else {
0
};
println!("{}", count);
println!();
// Delete
let (sql, values) = Query::delete()
.from_table(Character::Table)
.and_where(Expr::col(Character::Id).eq(id))
.build(SqliteQueryBuilder);
let result = conn.execute(
sql.as_str(),
RusqliteValues::from(values).as_params().as_slice(),
);
println!("Delete character: {:?}", result);
Ok(())
}
#[derive(Iden)]
enum Character {
Table,
Id,
Character,
FontSize,
}
#[derive(Debug)]
struct CharacterStruct {
id: i32,
character: String,
font_size: i32,
}
impl From<&Row<'_>> for CharacterStruct {
fn from(row: &Row) -> Self {
Self {
id: row.get_unwrap("id"),
character: row.get_unwrap("character"),
font_size: row.get_unwrap("font_size"),
}
}
}
|
use crate::{
custom_client::{OsuStatsScore, ScraperScore},
util::{numbers::round, osu::grade_emote},
};
use rosu_v2::prelude::{GameMode, GameMods, Grade, MatchScore, Score};
use std::fmt::Write;
pub trait ScoreExt: Send + Sync {
// Required to implement
fn count_miss(&self) -> u32;
fn count_50(&self) -> u32;
fn count_100(&self) -> u32;
fn count_300(&self) -> u32;
fn count_geki(&self) -> u32;
fn count_katu(&self) -> u32;
fn max_combo(&self) -> u32;
fn mods(&self) -> GameMods;
fn score(&self) -> u32;
fn pp(&self) -> Option<f32>;
fn acc(&self, mode: GameMode) -> f32;
// Optional to implement
fn grade(&self, mode: GameMode) -> Grade {
match mode {
GameMode::STD => self.osu_grade(),
GameMode::MNA => self.mania_grade(Some(self.acc(GameMode::MNA))),
GameMode::CTB => self.ctb_grade(Some(self.acc(GameMode::CTB))),
GameMode::TKO => self.taiko_grade(),
}
}
fn hits(&self, mode: u8) -> u32 {
let mut amount = self.count_300() + self.count_100() + self.count_miss();
if mode != 1 {
// TKO
amount += self.count_50();
if mode != 0 {
// STD
amount += self.count_katu();
// CTB
amount += (mode != 2) as u32 * self.count_geki();
}
}
amount
}
// Processing to strings
fn grade_emote(&self, mode: GameMode) -> &'static str {
grade_emote(self.grade(mode))
}
fn hits_string(&self, mode: GameMode) -> String {
let mut hits = String::from("{");
if mode == GameMode::MNA {
let _ = write!(hits, "{}/", self.count_geki());
}
let _ = write!(hits, "{}/", self.count_300());
if mode == GameMode::MNA {
let _ = write!(hits, "{}/", self.count_katu());
}
let _ = write!(hits, "{}/", self.count_100());
if mode != GameMode::TKO {
let _ = write!(hits, "{}/", self.count_50());
}
let _ = write!(hits, "{}}}", self.count_miss());
hits
}
// #########################
// ## Auxiliary functions ##
// #########################
fn osu_grade(&self) -> Grade {
let passed_objects = self.hits(GameMode::STD as u8);
let mods = self.mods();
if self.count_300() == passed_objects {
return if mods.contains(GameMods::Hidden) || mods.contains(GameMods::Flashlight) {
Grade::XH
} else {
Grade::X
};
}
let ratio300 = self.count_300() as f32 / passed_objects as f32;
let ratio50 = self.count_50() as f32 / passed_objects as f32;
if ratio300 > 0.9 && ratio50 < 0.01 && self.count_miss() == 0 {
if mods.contains(GameMods::Hidden) || mods.contains(GameMods::Flashlight) {
Grade::SH
} else {
Grade::S
}
} else if ratio300 > 0.9 || (ratio300 > 0.8 && self.count_miss() == 0) {
Grade::A
} else if ratio300 > 0.8 || (ratio300 > 0.7 && self.count_miss() == 0) {
Grade::B
} else if ratio300 > 0.6 {
Grade::C
} else {
Grade::D
}
}
fn mania_grade(&self, acc: Option<f32>) -> Grade {
let passed_objects = self.hits(GameMode::MNA as u8);
let mods = self.mods();
if self.count_geki() == passed_objects {
return if mods.contains(GameMods::Hidden) || mods.contains(GameMods::Flashlight) {
Grade::XH
} else {
Grade::X
};
}
let acc = acc.unwrap_or_else(|| self.acc(GameMode::MNA));
if acc > 95.0 {
if mods.contains(GameMods::Hidden) || mods.contains(GameMods::Flashlight) {
Grade::SH
} else {
Grade::S
}
} else if acc > 90.0 {
Grade::A
} else if acc > 80.0 {
Grade::B
} else if acc > 70.0 {
Grade::C
} else {
Grade::D
}
}
fn taiko_grade(&self) -> Grade {
let mods = self.mods();
let passed_objects = self.hits(GameMode::TKO as u8);
let count_300 = self.count_300();
if count_300 == passed_objects {
return if mods.intersects(GameMods::Hidden | GameMods::Flashlight) {
Grade::XH
} else {
Grade::X
};
}
let ratio300 = count_300 as f32 / passed_objects as f32;
let count_miss = self.count_miss();
if ratio300 > 0.9 && count_miss == 0 {
if mods.intersects(GameMods::Hidden | GameMods::Flashlight) {
Grade::SH
} else {
Grade::S
}
} else if ratio300 > 0.9 || (ratio300 > 0.8 && count_miss == 0) {
Grade::A
} else if ratio300 > 0.8 || (ratio300 > 0.7 && count_miss == 0) {
Grade::B
} else if ratio300 > 0.6 {
Grade::C
} else {
Grade::D
}
}
fn ctb_grade(&self, acc: Option<f32>) -> Grade {
let mods = self.mods();
let acc = acc.unwrap_or_else(|| self.acc(GameMode::CTB));
if (100.0 - acc).abs() <= std::f32::EPSILON {
if mods.contains(GameMods::Hidden) || mods.contains(GameMods::Flashlight) {
Grade::XH
} else {
Grade::X
}
} else if acc > 98.0 {
if mods.contains(GameMods::Hidden) || mods.contains(GameMods::Flashlight) {
Grade::SH
} else {
Grade::S
}
} else if acc > 94.0 {
Grade::A
} else if acc > 90.0 {
Grade::B
} else if acc > 85.0 {
Grade::C
} else {
Grade::D
}
}
}
// #####################
// ## Implementations ##
// #####################
impl ScoreExt for Score {
fn count_miss(&self) -> u32 {
self.statistics.count_miss
}
fn count_50(&self) -> u32 {
self.statistics.count_50
}
fn count_100(&self) -> u32 {
self.statistics.count_100
}
fn count_300(&self) -> u32 {
self.statistics.count_300
}
fn count_geki(&self) -> u32 {
self.statistics.count_geki
}
fn count_katu(&self) -> u32 {
self.statistics.count_katu
}
fn max_combo(&self) -> u32 {
self.max_combo
}
fn mods(&self) -> GameMods {
self.mods
}
fn grade(&self, _mode: GameMode) -> Grade {
self.grade
}
fn score(&self) -> u32 {
self.score
}
fn pp(&self) -> Option<f32> {
self.pp
}
fn acc(&self, _: GameMode) -> f32 {
round(self.accuracy)
}
}
impl ScoreExt for OsuStatsScore {
fn count_miss(&self) -> u32 {
self.count_miss
}
fn count_50(&self) -> u32 {
self.count50
}
fn count_100(&self) -> u32 {
self.count100
}
fn count_300(&self) -> u32 {
self.count300
}
fn count_geki(&self) -> u32 {
self.count_geki
}
fn count_katu(&self) -> u32 {
self.count_katu
}
fn max_combo(&self) -> u32 {
self.max_combo
}
fn mods(&self) -> GameMods {
self.enabled_mods
}
fn hits(&self, _mode: u8) -> u32 {
let mut amount = self.count300 + self.count100 + self.count_miss;
let mode = self.map.mode;
if mode != GameMode::TKO {
amount += self.count50;
if mode != GameMode::STD {
amount += self.count_katu;
amount += (mode != GameMode::CTB) as u32 * self.count_geki;
}
}
amount
}
fn grade(&self, _: GameMode) -> Grade {
self.grade
}
fn score(&self) -> u32 {
self.score
}
fn pp(&self) -> Option<f32> {
self.pp
}
fn acc(&self, _: GameMode) -> f32 {
self.accuracy
}
}
impl ScoreExt for ScraperScore {
fn count_miss(&self) -> u32 {
self.count_miss
}
fn count_50(&self) -> u32 {
self.count50
}
fn count_100(&self) -> u32 {
self.count100
}
fn count_300(&self) -> u32 {
self.count300
}
fn count_geki(&self) -> u32 {
self.count_geki
}
fn count_katu(&self) -> u32 {
self.count_katu
}
fn max_combo(&self) -> u32 {
self.max_combo
}
fn mods(&self) -> GameMods {
self.mods
}
fn hits(&self, _: u8) -> u32 {
let mut amount = self.count300 + self.count100 + self.count_miss;
if self.mode != GameMode::TKO {
amount += self.count50;
if self.mode != GameMode::STD {
amount += self.count_katu;
amount += (self.mode != GameMode::CTB) as u32 * self.count_geki;
}
}
amount
}
fn grade(&self, _: GameMode) -> Grade {
self.grade
}
fn score(&self) -> u32 {
self.score
}
fn pp(&self) -> Option<f32> {
self.pp
}
fn acc(&self, _: GameMode) -> f32 {
self.accuracy
}
}
impl ScoreExt for MatchScore {
fn count_miss(&self) -> u32 {
self.statistics.count_miss
}
fn count_50(&self) -> u32 {
self.statistics.count_50
}
fn count_100(&self) -> u32 {
self.statistics.count_100
}
fn count_300(&self) -> u32 {
self.statistics.count_300
}
fn count_geki(&self) -> u32 {
self.statistics.count_geki
}
fn count_katu(&self) -> u32 {
self.statistics.count_katu
}
fn max_combo(&self) -> u32 {
self.max_combo
}
fn mods(&self) -> GameMods {
self.mods
}
fn score(&self) -> u32 {
self.score
}
fn pp(&self) -> Option<f32> {
None
}
fn acc(&self, _: GameMode) -> f32 {
self.accuracy
}
}
|
#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(glade::test_runner)]
#![reexport_test_harness_main = "test_main"]
extern crate alloc;
use alloc::boxed::Box;
// namespacing
use bootloader::{entry_point, BootInfo};
use core::panic::PanicInfo;
use glade::{print, println};
#[cfg(test)]
use glade::{sprint, sprintln};
// entry point
entry_point!(kmain);
fn kmain(boot_info: &'static BootInfo) -> ! {
use glade::allocator;
use glade::memory::{self, BootInfoFrameAllocator};
use x86_64::VirtAddr;
glade::init();
println!("gladeOS");
let phys_mem_offset = VirtAddr::new(boot_info.physical_memory_offset);
let mut mapper = unsafe { memory::init(phys_mem_offset) };
let mut frame_allocator = unsafe { BootInfoFrameAllocator::init(&boot_info.memory_map) };
allocator::init_heap(&mut mapper, &mut frame_allocator).expect("heap initialization failed");
let x = Box::new(42);
#[cfg(test)]
test_main();
println!("still running");
glade::hlt_loop();
}
// panic handler
#[cfg(not(test))]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("{}", info);
glade::hlt_loop();
}
// test panic handler
#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
glade::test_panic_handler(info);
}
// just to make sure it's running ok
#[test_case]
fn trivial_assertion() {
sprint!("trivial_assertion... ");
assert_eq!(1, 1);
sprintln!("[Ok!]");
}
|
pub mod cache;
pub mod event;
|
mod blog;
mod camera;
mod category;
mod exposure_mode;
mod location;
mod photo;
mod post;
mod size;
mod tag;
pub use blog::Blog;
pub use camera::Camera;
pub use category::{Category, CategoryKind};
pub use exposure_mode::ExposureMode;
pub use location::Location;
pub use photo::{Photo, PhotoFile, PhotoPath};
pub use post::{Post, PostSeries};
pub use size::{suffix, Size, SizeCollection};
pub use tag::{collate_tags, TagPhotos};
|
use texture::Texture;
pub use self::image_importer::ImageImporter;
mod image_importer;
pub type ImportResult<T> = Result<T, String>;
pub trait Importer<I> {
type Texture: Texture;
fn import(input: I) -> ImportResult<Self::Texture>;
}
|
pub mod model;
pub mod routes;
mod controller;
mod service; |
use crate::block::Block;
use crate::crypto::hash::{Hashable, H256};
use std::collections::{HashMap, HashSet};
pub struct BlockBuffer {
/// All blocks that have been received but not processed.
blocks: HashMap<H256, Block>,
// TODO: we could use a sorted vector for better performance
/// Mapping between all blocks that have been received and not processed, and their
/// dependencies
dependency: HashMap<H256, HashSet<H256>>,
/// Mapping between all blocks that have not been processed (but either received or
/// not), and their dependents
dependent: HashMap<H256, HashSet<H256>>,
}
impl BlockBuffer {
pub fn new() -> Self {
Self {
blocks: HashMap::new(),
dependency: HashMap::new(),
dependent: HashMap::new(),
}
}
/// Buffer a block whose parent and/or references are missing.
pub fn insert(&mut self, block: Block, dependencies: &[H256]) {
// Potential race condition here: if X depends on A. Suppose X is received first and
// validation finds that we miss block A. Then we need to insert X. However, at this moment
// A comes. Unaware of X, we just process A without marking X's deps as satisfied. Then X
// finally gets inserted, and is never popped out of the buffer. The core reason is that
// validation and buffer insert are not one atomic operation (and we probably don't want
// to do so). Conclusion: for now we make validation and buffer an atomic operation.
let hash = block.hash();
self.blocks.insert(hash, block);
let mut dependency = HashSet::new();
for dep_hash in dependencies {
dependency.insert(*dep_hash);
if !self.dependent.contains_key(&dep_hash) {
let dependent = HashSet::new();
self.dependent.insert(*dep_hash, dependent);
}
let dependent = self.dependent.get_mut(&dep_hash).unwrap();
dependent.insert(hash);
}
self.dependency.insert(hash, dependency);
}
/// Mark that the given block has been processed.
pub fn satisfy(&mut self, hash: H256) -> Vec<Block> {
let mut resolved_blocks: Vec<Block> = vec![];
// get what blocks are blocked by the block being satisfied
if let Some(dependents) = self.dependent.remove(&hash) {
for node in &dependents {
let dependency = self.dependency.get_mut(&node).unwrap();
dependency.remove(&hash);
if dependency.is_empty() {
self.dependency.remove(&node).unwrap();
resolved_blocks.push(self.blocks.remove(&node).unwrap());
}
}
}
resolved_blocks
}
}
|
use std::collections::VecDeque;
fn main() {
use std::io::BufRead;
let rule = Rule::new();
let stdin = std::io::stdin();
for problem in stdin.lock().lines().filter_map(|r| r.ok()) {
println!("{}", Sudoku::solve(problem, &rule));
}
}
struct Rule {
size: usize,
digits: String,
n_coord: usize,
n_block: usize,
parents: Vec<Vec<Block>>,
children: Vec<Vec<Coord>>,
}
type Block = usize;
type Coord = usize;
impl Rule {
fn new() -> Self {
let unit = 3;
let size = unit * unit;
let digits = "123456789".to_string();
assert_eq!(size, digits.len());
let n_coord = size * size * size;
let n_block = 4 * size * size;
let mut parents = Vec::with_capacity(n_coord);
for i in 0..size {
for j in 0..size {
let p = i / unit * unit + j / unit;
for k in 0..size {
parents.push(vec![
(0 * size + i) * size + j,
(1 * size + i) * size + k,
(2 * size + j) * size + k,
(3 * size + p) * size + k,
]);
}
}
}
let mut children = vec![Vec::with_capacity(size); n_block];
for c in 0..n_coord {
for &b in &parents[c] {
children[b].push(c);
}
}
Rule {
size,
digits,
n_coord,
n_block,
parents,
children,
}
}
}
#[derive(Clone)]
struct Sudoku<'a> {
state: Vec<State>,
count: Vec<Count>,
queue: VecDeque<Coord>,
rule: &'a Rule,
}
#[derive(Clone, PartialEq)]
enum State {
Vague,
False,
True,
}
type Count = usize;
const COUNT_DONE: Count = std::usize::MAX;
impl<'a> Sudoku<'a> {
fn solve(problem: String, rule: &'a Rule) -> String {
let mut s = Sudoku::new(rule);
s.feed(problem);
if let Some(s) = s.search() {
s.display()
} else {
"NO SOLUTION".to_string()
}
}
fn new(rule: &'a Rule) -> Self {
Sudoku {
state: vec![State::Vague; rule.n_coord],
count: vec![rule.size; rule.n_block],
queue: VecDeque::new(),
rule,
}
}
fn feed(&mut self, problem: String) {
let size = self.rule.size;
for (ij, ch) in problem.chars().take(size * size).enumerate() {
let i = ij / size;
let j = ij % size;
if let Some(k) = self.rule.digits.find(ch) {
self.queue.push_back((i * size + j) * size + k);
}
}
}
fn display(&self) -> String {
let size = self.rule.size;
let mut res = String::with_capacity(size * size);
for i in 0..size {
for j in 0..size {
res.push(
(0..size)
.find(|&k| self.state[(i * size + j) * size + k] == State::True)
.map_or('.', |k| self.rule.digits.chars().nth(k).unwrap()),
);
}
}
res
}
fn search(mut self) -> Option<Self> {
while let Some(c) = self.queue.pop_front() {
if !self.assign(c) {
return None;
}
}
let mut b_min = 0;
let mut min = self.count[b_min];
for b in 1..self.rule.n_block {
if self.count[b] < min {
b_min = b;
min = self.count[b_min];
}
}
if min == COUNT_DONE {
return Some(self);
}
self.rule.children[b_min].iter().find_map(|&c| {
let mut s = self.clone();
s.queue.push_back(c);
s.search()
})
}
fn assign(&mut self, c: Coord) -> bool {
match self.state[c] {
State::Vague => {
self.state[c] = State::True;
self.rule.parents[c].iter().all(|&b| self.mark(b))
}
State::False => false,
State::True => true,
}
}
fn mark(&mut self, b: Block) -> bool {
self.count[b] = COUNT_DONE;
self.rule.children[b].iter().all(|&c| self.ban(c))
}
fn ban(&mut self, c: Coord) -> bool {
match self.state[c] {
State::Vague => {
self.state[c] = State::False;
self.rule.parents[c].iter().all(|&b| self.countdown(b))
}
_ => true,
}
}
fn countdown(&mut self, b: Block) -> bool {
if self.count[b] == COUNT_DONE {
return true;
}
self.count[b] -= 1;
if self.count[b] == 0 {
return false;
}
if self.count[b] == 1 {
for &c in &self.rule.children[b] {
if self.state[c] == State::Vague {
self.queue.push_back(c);
}
}
}
return true;
}
}
|
use super::{frame::DeipProposal, runtime, RuntimeT};
use node_template_runtime::Call;
use serde::{ser::Serializer, Serialize};
impl Serialize for runtime::WrappedCall<<RuntimeT as DeipProposal>::Call> {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
match &self.0 {
Call::Deip(deip_call) => Self::serialize_deip_call(deip_call, serializer),
Call::DeipProposal(deip_proposal_call) => {
Self::serialize_deip_proposal_call(deip_proposal_call, serializer)
}
Call::DeipOrg(deip_org_call) => {
Self::serialize_deip_org_call(deip_org_call, serializer)
}
Call::DeipAssets(deip_assets_call) => {
Self::serialize_deip_assets_call(deip_assets_call, serializer)
}
Call::System(_)
| Call::Utility(_)
| Call::RandomnessCollectiveFlip(_)
| Call::Timestamp(_)
| Call::Grandpa(_)
| Call::Balances(_)
| Call::Sudo(_)
| Call::TemplateModule(_)
| Call::Multisig(_) => CallObject {
module: "unsupported_module",
call: "unsupported_call",
args: &UnsupportedCallArgs {},
}.serialize(serializer),
}
}
}
impl runtime::WrappedCall<<RuntimeT as DeipProposal>::Call> {
fn serialize_deip_call<S>(
deip_call: &pallet_deip::Call<node_template_runtime::Runtime>,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
use pallet_deip::Call::*;
match deip_call {
create_project(is_private, external_id, team_id, description, domains) => CallObject {
module: "deip",
call: "create_project",
args: &DeipCreateProjectCallArgs {
is_private,
external_id,
team_id,
description,
domains,
},
}
.serialize(serializer),
create_investment_opportunity(external_id, creator, shares, funding_model) => {
CallObject {
module: "deip",
call: "create_investment_opportunity",
args: &DeipCreateInvestmentOpportunityCallArgs {
external_id,
creator,
shares,
funding_model,
},
}
.serialize(serializer)
}
activate_crowdfunding(sale_id) => CallObject {
module: "deip",
call: "activate_crowdfunding",
args: &DeipActivateCrowdfundingCallArgs { sale_id },
}
.serialize(serializer),
expire_crowdfunding(sale_id) => CallObject {
module: "deip",
call: "expire_crowdfunding",
args: &DeipExpireCrowdfundingCallArgs { sale_id },
}
.serialize(serializer),
finish_crowdfunding(sale_id) => CallObject {
module: "deip",
call: "finish_crowdfunding",
args: &DeipFinishCrowdfundingCallArgs { sale_id },
}
.serialize(serializer),
invest(id, amount) => CallObject {
module: "deip",
call: "invest",
args: &DeipInvestCallArgs { id, amount },
}
.serialize(serializer),
update_project(project_id, description, is_private) => CallObject {
module: "deip",
call: "update_project",
args: &DeipUpdateProjectCallArgs {
project_id,
description,
is_private,
},
}
.serialize(serializer),
create_project_content(
external_id,
project_external_id,
team_id,
content_type,
description,
content,
authors,
references,
) => CallObject {
module: "deip",
call: "create_project_content",
args: &DeipCreateProjectContentCallArgs {
external_id,
project_external_id,
team_id,
content_type,
description,
content,
authors,
references,
},
}
.serialize(serializer),
create_project_nda(
external_id,
end_date,
contract_hash,
maybe_start_date,
parties,
projects,
) => CallObject {
module: "deip",
call: "create_project_nda",
args: &DeipCreateProjectNdaCallArgs {
external_id,
end_date,
contract_hash,
maybe_start_date,
parties,
projects,
},
}
.serialize(serializer),
create_nda_content_access_request(
external_id,
nda_external_id,
encrypted_payload_hash,
encrypted_payload_iv,
) => CallObject {
module: "deip",
call: "create_nda_content_access_request",
args: &DeipCreateProjectNdaAccessRequestCallArgs {
external_id,
nda_external_id,
encrypted_payload_hash,
encrypted_payload_iv,
},
}
.serialize(serializer),
fulfill_nda_content_access_request(
external_id,
encrypted_payload_encryption_key,
proof_of_encrypted_payload_encryption_key,
) => CallObject {
module: "deip",
call: "fulfill_nda_content_access_request",
args: &DeipFulfillNdaAccessRequestCallArgs {
external_id,
encrypted_payload_encryption_key,
proof_of_encrypted_payload_encryption_key,
},
}
.serialize(serializer),
reject_nda_content_access_request(external_id) => CallObject {
module: "deip",
call: "reject_nda_content_access_request",
args: &DeipRejectNdaAccessRequestCallArgs { external_id },
}
.serialize(serializer),
create_review(
external_id,
author,
content,
domains,
assessment_model,
weight,
project_content_external_id,
) => CallObject {
module: "deip",
call: "create_review",
args: &DeipCreateReviewCallArgs {
external_id,
author,
content,
domains,
assessment_model,
weight,
project_content_external_id,
},
}
.serialize(serializer),
upvote_review(review_id, domain_id) => CallObject {
module: "deip",
call: "upvote_review",
args: &DeipUpvoteReviewCallArgs {
review_id,
domain_id,
},
}
.serialize(serializer),
add_domain(domain) => CallObject {
module: "deip",
call: "add_domain",
args: &DeipAddDomainCallArgs { domain },
}
.serialize(serializer),
__PhantomItem(..) => unreachable!(),
}
}
fn serialize_deip_proposal_call<S>(
deip_proposal_call: &pallet_deip_proposal::Call<node_template_runtime::Runtime>,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
use pallet_deip_proposal::Call::*;
match deip_proposal_call {
propose(batch, external_id) => CallObject {
module: "deip_proposal",
call: "propose",
args: &DeipProposalProposeCallArgs {
batch: &RuntimeT::wrap_input_batch(batch),
external_id,
},
}
.serialize(serializer),
decide(proposal_id, decision) => CallObject {
module: "deip_proposal",
call: "decide",
args: &DeipProposalDecideCallArgs {
proposal_id,
decision,
},
}
.serialize(serializer),
expire(proposal_id) => CallObject {
module: "deip_proposal",
call: "expire",
args: &DeipProposalExpireCallArgs { proposal_id },
}
.serialize(serializer),
__Ignore(..) => unreachable!(),
}
}
fn serialize_deip_org_call<S>(
deip_org_call: &pallet_deip_org::Call<node_template_runtime::Runtime>,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
use pallet_deip_org::Call::*;
match deip_org_call {
create(name, key_source) => CallObject {
module: "deip_org",
call: "create",
args: &DeipOrgCreateCallArgs { name, key_source },
}
.serialize(serializer),
transfer_ownership(transfer_to, key_source) => CallObject {
module: "deip_org",
call: "transfer_ownership",
args: &DeipOrgTransferOwnershipCallArgs {
transfer_to,
key_source,
},
}
.serialize(serializer),
on_behalf(name, call) => CallObject {
module: "deip_org",
call: "on_behalf",
args: &DeipOrgOnBehalfCallArgs {
name,
call: &RuntimeT::wrap_call(call),
},
}
.serialize(serializer),
__Ignore(..) => unreachable!(),
}
}
fn serialize_deip_assets_call<S>(
deip_assets_call: &pallet_deip_assets::Call<node_template_runtime::Runtime>,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
use pallet_deip_assets::Call::*;
match deip_assets_call {
create_asset(id, admin, max_zombies, min_balance, project_id) => CallObject {
module: "deip_assets",
call: "create_asset",
args: &DeipAssetsCreateAssetCallArgs {
id,
admin,
max_zombies,
min_balance,
project_id,
},
}
.serialize(serializer),
destroy(id, zombies_witness) => CallObject {
module: "deip_assets",
call: "destroy",
args: &DeipAssetsDestroyCallArgs {
id,
zombies_witness,
},
}
.serialize(serializer),
issue_asset(id, beneficiary, amount) => CallObject {
module: "deip_assets",
call: "issue_asset",
args: &DeipAssetsIssueAssetCallArgs {
id,
beneficiary,
amount,
},
}
.serialize(serializer),
burn(id, who, amount) => CallObject {
module: "deip_assets",
call: "burn",
args: &DeipAssetsBurnCallArgs { id, who, amount },
}
.serialize(serializer),
transfer(id, target, amount) => CallObject {
module: "deip_assets",
call: "transfer",
args: &DeipAssetsTransferCallArgs { id, target, amount },
}
.serialize(serializer),
freeze(id, who) => CallObject {
module: "deip_assets",
call: "freeze",
args: &DeipAssetsFreezeCallArgs { id, who },
}
.serialize(serializer),
thaw(id, who) => CallObject {
module: "deip_assets",
call: "thaw",
args: &DeipAssetsThawCallArgs { id, who },
}
.serialize(serializer),
freeze_asset(id) => CallObject {
module: "deip_assets",
call: "freeze_asset",
args: &DeipAssetsFreezeAssetCallArgs { id },
}
.serialize(serializer),
thaw_asset(id) => CallObject {
module: "deip_assets",
call: "thaw_asset",
args: &DeipAssetsThawAssetCallArgs { id },
}
.serialize(serializer),
transfer_ownership(id, owner) => CallObject {
module: "deip_assets",
call: "transfer_ownership",
args: &DeipAssetsTransferOwnershipCallArgs { id, owner },
}
.serialize(serializer),
set_team(id, issuer, admin, freezer) => CallObject {
module: "deip_assets",
call: "set_team",
args: &DeipAssetsSetTeamCallArgs {
id,
issuer,
admin,
freezer,
},
}
.serialize(serializer),
set_max_zombies(id, max_zombies) => CallObject {
module: "deip_assets",
call: "set_max_zombies",
args: &DeipAssetsSetMaxZombiesCallArgs { id, max_zombies },
}
.serialize(serializer),
set_metadata(id, name, symbol, decimals) => CallObject {
module: "deip_assets",
call: "set_metadata",
args: &DeipAssetsSetMetadataCallArgs {
id,
name,
symbol,
decimals,
},
}
.serialize(serializer),
__Ignore(..) => unreachable!(),
}
}
}
#[derive(Serialize)]
struct UnsupportedCallArgs {}
#[derive(Serialize)]
struct DeipAssetsSetMetadataCallArgs<A, B, C, D> {
id: A,
name: B,
symbol: C,
decimals: D,
}
#[derive(Serialize)]
struct DeipAssetsSetMaxZombiesCallArgs<A, B> {
id: A,
max_zombies: B,
}
#[derive(Serialize)]
struct DeipAssetsSetTeamCallArgs<A, B, C, D> {
id: A,
issuer: B,
admin: C,
freezer: D,
}
#[derive(Serialize)]
struct DeipAssetsTransferOwnershipCallArgs<A, B> {
id: A,
owner: B,
}
#[derive(Serialize)]
struct DeipAssetsThawAssetCallArgs<A> {
id: A,
}
#[derive(Serialize)]
struct DeipAssetsFreezeAssetCallArgs<A> {
id: A,
}
#[derive(Serialize)]
struct DeipAssetsThawCallArgs<A, B> {
id: A,
who: B,
}
#[derive(Serialize)]
struct DeipAssetsFreezeCallArgs<A, B> {
id: A,
who: B,
}
#[derive(Serialize)]
struct DeipAssetsTransferCallArgs<A, B, C> {
id: A,
target: B,
amount: C,
}
#[derive(Serialize)]
struct DeipAssetsBurnCallArgs<A, B, C> {
id: A,
who: B,
amount: C,
}
#[derive(Serialize)]
struct DeipAssetsIssueAssetCallArgs<A, B, C> {
id: A,
beneficiary: B,
amount: C,
}
#[derive(Serialize)]
struct DeipAssetsDestroyCallArgs<A, B> {
id: A,
zombies_witness: B,
}
#[derive(Serialize)]
struct DeipAssetsCreateAssetCallArgs<A, B, C, D, E> {
id: A,
admin: B,
max_zombies: C,
min_balance: D,
project_id: E,
}
#[derive(Serialize)]
struct DeipOrgOnBehalfCallArgs<A, B> {
name: A,
call: B,
}
#[derive(Serialize)]
struct DeipOrgTransferOwnershipCallArgs<A, B> {
transfer_to: A,
key_source: B,
}
#[derive(Serialize)]
struct DeipOrgCreateCallArgs<A, B> {
name: A,
key_source: B,
}
#[derive(Serialize)]
struct DeipProposalDecideCallArgs<A, B> {
proposal_id: A,
decision: B,
}
#[derive(Serialize)]
struct DeipProposalExpireCallArgs<A> {
proposal_id: A,
}
#[derive(Serialize)]
struct DeipProposalProposeCallArgs<A, B> {
batch: A,
external_id: B,
}
#[derive(Serialize)]
struct DeipAddDomainCallArgs<A> {
domain: A,
}
#[derive(Serialize)]
struct DeipCreateReviewCallArgs<A, B, C, D, E, F, G> {
external_id: A,
author: B,
content: C,
domains: D,
assessment_model: E,
weight: F,
project_content_external_id: G,
}
#[derive(Serialize)]
struct DeipUpvoteReviewCallArgs<A, B> {
review_id: A,
domain_id: B,
}
#[derive(Serialize)]
struct DeipRejectNdaAccessRequestCallArgs<A> {
external_id: A,
}
#[derive(Serialize)]
struct DeipFulfillNdaAccessRequestCallArgs<A, B, C> {
external_id: A,
encrypted_payload_encryption_key: B,
proof_of_encrypted_payload_encryption_key: C,
}
#[derive(Serialize)]
struct DeipCreateProjectNdaAccessRequestCallArgs<A, B, C, D> {
external_id: A,
nda_external_id: B,
encrypted_payload_hash: C,
encrypted_payload_iv: D,
}
#[derive(Serialize)]
struct DeipCreateProjectNdaCallArgs<A, B, C, D, E, F> {
external_id: A,
end_date: B,
contract_hash: C,
maybe_start_date: D,
parties: E,
projects: F,
}
#[derive(Serialize)]
struct DeipCreateProjectContentCallArgs<A, B, C, D, E, F, G, H> {
external_id: A,
project_external_id: B,
team_id: C,
content_type: D,
description: E,
content: F,
authors: G,
references: H,
}
#[derive(Serialize)]
struct DeipInvestCallArgs<A, B> {
id: A,
amount: B,
}
#[derive(Serialize)]
struct DeipUpdateProjectCallArgs<A, B, C> {
project_id: A,
description: B,
is_private: C,
}
#[derive(Serialize)]
struct DeipFinishCrowdfundingCallArgs<A> {
sale_id: A,
}
#[derive(Serialize)]
struct DeipExpireCrowdfundingCallArgs<A> {
sale_id: A,
}
#[derive(Serialize)]
struct DeipActivateCrowdfundingCallArgs<A> {
sale_id: A,
}
#[derive(Serialize)]
struct DeipCreateInvestmentOpportunityCallArgs<A, B, C, D> {
external_id: A,
creator: B,
shares: C,
funding_model: D,
}
#[derive(Serialize)]
struct DeipCreateProjectCallArgs<A, B, C, D, E> {
is_private: A,
external_id: B,
team_id: C,
description: D,
domains: E,
}
#[derive(Serialize)]
struct CallObject<A, B, C> {
module: A,
call: B,
args: C,
}
|
use crate::construction::constraints::{ConstraintPipeline, TOTAL_DISTANCE_KEY, TOTAL_DURATION_KEY};
use crate::construction::heuristics::{InsertionContext, RegistryContext, SolutionContext};
use crate::helpers::models::problem::*;
use crate::helpers::models::solution::create_route_context_with_activities;
use crate::models::common::IdDimension;
use crate::models::examples::create_example_problem;
use crate::models::problem::{Fleet, Job, Jobs, ObjectiveCost};
use crate::models::solution::Registry;
use crate::models::{Problem, Solution};
use crate::utils::{DefaultRandom, Environment, Random};
use std::sync::Arc;
pub fn test_random() -> Arc<dyn Random + Send + Sync> {
Arc::new(DefaultRandom::default())
}
pub fn create_empty_problem_with_constraint(constraint: ConstraintPipeline) -> Arc<Problem> {
create_problem_with_constraint_jobs_and_fleet(constraint, vec![], test_fleet())
}
pub fn create_empty_problem() -> Arc<Problem> {
create_empty_problem_with_constraint(ConstraintPipeline::default())
}
pub fn create_problem_with_constraint_jobs_and_fleet(
constraint: ConstraintPipeline,
jobs: Vec<Job>,
fleet: Fleet,
) -> Arc<Problem> {
let transport = TestTransportCost::new_shared();
let fleet = Arc::new(fleet);
let jobs = Arc::new(Jobs::new(fleet.as_ref(), jobs, &transport));
Arc::new(Problem {
fleet,
jobs,
locks: vec![],
constraint: Arc::new(constraint),
activity: Arc::new(TestActivityCost::default()),
transport,
objective: Arc::new(ObjectiveCost::default()),
extras: Arc::new(Default::default()),
})
}
pub fn create_empty_solution() -> Solution {
Solution {
registry: Registry::new(&test_fleet(), test_random()),
routes: vec![],
unassigned: Default::default(),
extras: Arc::new(Default::default()),
}
}
pub fn create_empty_solution_context() -> SolutionContext {
SolutionContext {
required: vec![],
ignored: vec![],
unassigned: Default::default(),
locked: Default::default(),
routes: vec![],
registry: RegistryContext::new(Registry::new(&test_fleet(), test_random())),
state: Default::default(),
}
}
pub fn create_empty_insertion_context() -> InsertionContext {
InsertionContext {
problem: create_empty_problem(),
solution: create_empty_solution_context(),
environment: Arc::new(Environment::default()),
}
}
/// Creates a simple insertion context with given distance and amount of unassigned jobs.
pub fn create_simple_insertion_ctx(distance: f64, unassigned: usize) -> InsertionContext {
let problem = create_example_problem();
let mut insertion_ctx = create_empty_insertion_context();
let mut route_ctx = create_route_context_with_activities(problem.fleet.as_ref(), "v1", vec![]);
route_ctx.state_mut().put_route_state(TOTAL_DISTANCE_KEY, distance);
route_ctx.state_mut().put_route_state(TOTAL_DURATION_KEY, 0.);
insertion_ctx.solution.routes.push(route_ctx);
(0..unassigned).for_each(|_| {
insertion_ctx
.solution
.unassigned
.insert(problem.jobs.all().next().clone().expect("at least one job expected"), 0);
});
insertion_ctx
}
pub fn get_customer_ids_from_routes_sorted(insertion_ctx: &InsertionContext) -> Vec<Vec<String>> {
let mut result = get_customer_ids_from_routes(insertion_ctx);
result.sort();
result
}
pub fn get_sorted_customer_ids_from_jobs(jobs: &[Job]) -> Vec<String> {
let mut ids = jobs.iter().map(|job| get_customer_id(&job)).collect::<Vec<String>>();
ids.sort();
ids
}
pub fn get_customer_ids_from_routes(insertion_ctx: &InsertionContext) -> Vec<Vec<String>> {
insertion_ctx
.solution
.routes
.iter()
.map(|rc| {
rc.route
.tour
.all_activities()
.filter(|a| a.job.is_some())
.map(|a| a.retrieve_job().unwrap())
.map(|job| get_customer_id(&job))
.collect::<Vec<String>>()
})
.collect()
}
pub fn get_customer_id(job: &Job) -> String {
job.dimens().get_id().unwrap().clone()
}
|
use super::ignore;
use super::options::Options;
use super::Error;
use lazy_static::lazy_static;
use regex::Regex;
use rsass::output::Format;
use rsass::{parse_scss_data, FileContext, GlobalScope};
use std::io::Write;
pub struct TestFixture {
fn_name: String,
input: String,
expectation: TestExpectation,
options: Options,
}
enum TestExpectation {
ExpectedCSS(String),
ExpectedError(String),
}
use TestExpectation::{ExpectedCSS, ExpectedError};
impl TestFixture {
pub fn new_ok(
fn_name: String,
input: String,
expected_css: &str,
options: Options,
) -> Self {
TestFixture {
fn_name,
input: input,
options: options,
expectation: ExpectedCSS(normalize_output_css(expected_css)),
}
}
pub fn new_err(
fn_name: String,
input: String,
error: String,
options: Options,
) -> Self {
TestFixture {
fn_name,
input: input,
expectation: ExpectedError(error),
options: options,
}
}
pub fn write_test(&self, rs: &mut dyn Write) -> Result<(), Error> {
if let Some(ref reason) = self.options.should_skip {
ignore(rs, &self.fn_name, reason)?;
return Ok(());
}
match self.expectation {
ExpectedError(_) => {
// TODO: Support error tests;
ignore(
rs,
&self.fn_name,
"error tests are not supported yet",
)?;
}
ExpectedCSS(ref expected) => {
rs.write_all(b"#[test]\n")?;
if let Some(reason) = self.is_failure() {
writeln!(rs, "#[ignore] // {}", reason)?;
}
writeln!(rs, "fn {}() {{", self.fn_name)?;
let precision = self.options.precision;
if let Some(precision) = precision {
writeln!(
rs,
" let format = rsass::output::Format {{ \
style: rsass::output::Style::Expanded, \
precision: {} \
}};",
precision,
)?;
}
let input = format!("{:?}", self.input)
.replace(escaped_newline(), "\n \\n");
let expected = format!("{:?}", expected)
.replace(escaped_newline(), "\n \\n");
writeln!(
rs,
" assert_eq!(\
\n {}\
\n {}\
\n )\
\n .unwrap(),\
\n {}\
\n );",
if precision.is_none() {
"rsass("
} else {
"crate::rsass_fmt(format,"
},
input,
expected,
)?;
rs.write_all(b"}\n")?;
}
}
Ok(())
}
/// Execute the test here and now, return None for success or Some
/// reason to fail.
fn is_failure(&self) -> Option<&'static str> {
match &self.expectation {
ExpectedError(_) => Some("Error tests not supported yet"),
ExpectedCSS(ref expected) => {
let mut format = Format::default();
if let Some(precision) = self.options.precision {
format.precision = precision as usize;
}
match rsass(&self.input, format) {
Ok(ref actual) => {
if expected == actual {
None // Yes!
} else {
Some("wrong result")
}
}
Err(_) => Some("unexepected error"),
}
}
}
}
}
/// Return a pattern function matching the 'n' in \n, unless the
/// backslash is also escaped.
fn escaped_newline() -> impl FnMut(char) -> bool {
let mut n = 0;
move |c: char| {
let next_n = if c == '\\' { n + 1 } else { 0 };
let result = n % 2 == 1 && c == 'n';
n = next_n;
result
}
}
fn rsass(input: &str, format: Format) -> Result<String, String> {
compile_scss(input.as_bytes(), format)
.map_err(|e| format!("rsass failed: {}", e))
.and_then(|s| {
String::from_utf8(s)
.map(|s| normalize_output_css(s.as_str()))
.map_err(|e| format!("{:?}", e))
})
}
pub fn compile_scss(
input: &[u8],
format: Format,
) -> Result<Vec<u8>, rsass::Error> {
let mut file_context = FileContext::new();
file_context.push_path("tests/spec".as_ref());
let items = parse_scss_data(input)?;
format.write_root(&items, &mut GlobalScope::new(format), &file_context)
}
fn normalize_output_css(css: &str) -> String {
// Normalizes the whitespace in the given CSS to make it easier to compare. Based on:
// https://github.com/sass/sass-spec/blob/0f59164aabb3273645fda068d0fb1b879aa3f1dc/lib/sass_spec/util.rb#L5-L7
// NOTE: This is done on input and expected output.
// The actual result is normalized in a simler way in the rsass function in generated tests.
lazy_static! {
static ref RE: Regex = Regex::new("(?:\r?\n)+").unwrap();
}
RE.replace_all(&css, "\n").to_string()
}
|
struct Callbacks<T> {
callbacks: Vec<Box<FnMut(&T)>>,
}
impl<T> Callbacks<T> {
pub fn new() -> Self {
Callbacks { callbacks: Vec::new() }
}
pub fn register<F: FnMut(&T) + 'static>(&mut self, c: F) {
self.callbacks.push(Box::new(c));
}
pub fn call(&mut self, val: &T) {
for c in self.callbacks.iter_mut() {
c(val);
}
}
}
#[cfg(test)]
mod tests {
use super::Callbacks;
#[test]
fn basic_cb() {
let mut callbacks = Callbacks::new();
callbacks.register(|num| assert_eq!(num, &55));
callbacks.call(&55);
}
#[test]
fn vec_cb() {
let mut callbacks: Callbacks<Vec<f32>> = Callbacks::new();
let test_vec = vec![4.5, 5.5, 6.6];
let mut sum = 1.0;
callbacks.register(move |vec| {
for v in vec.iter() {
sum = sum + v;
}
assert_eq!(sum, 1.0 + 4.5 + 5.5 + 6.6);
});
assert_eq!(sum, 1.0);
callbacks.call(&test_vec);
}
}
|
mod expr;
mod program;
mod stmt;
pub use expr::Expression;
pub use program::Program;
pub use stmt::Statement;
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
pub type QueryParam = String;
pub type TimespanParam = String;
pub type WorkspacesParam = Vec<String>;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryBody {
pub query: QueryParam,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timespan: Option<TimespanParam>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspaces: Option<WorkspacesParam>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryResults {
pub tables: Vec<Table>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Table {
pub name: String,
pub columns: Vec<Column>,
pub rows: Vec<Vec<String>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Column {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataResults {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub categories: Vec<MetadataCategory>,
#[serde(rename = "resourceTypes", default, skip_serializing_if = "Vec::is_empty")]
pub resource_types: Vec<MetadataResourceType>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub solutions: Vec<MetadataSolution>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tables: Vec<MetadataTable>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<MetadataFunction>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub queries: Vec<MetadataQuery>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub applications: Vec<MetadataApplication>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub workspaces: Vec<MetadataWorkspace>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<MetadataResource>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub permissions: Vec<MetadataPermissions>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataCategory {
pub id: String,
#[serde(rename = "displayName")]
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related: Option<metadata_category::Related>,
}
pub mod metadata_category {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Related {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tables: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<String>,
#[serde(rename = "resourceTypes", default, skip_serializing_if = "Vec::is_empty")]
pub resource_types: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub queries: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub solutions: Vec<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataSolution {
pub id: String,
pub name: String,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
pub related: metadata_solution::Related,
}
pub mod metadata_solution {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Related {
pub tables: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub categories: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub queries: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub workspaces: Vec<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataResourceType {
pub id: String,
#[serde(rename = "type")]
pub type_: String,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related: Option<metadata_resource_type::Related>,
}
pub mod metadata_resource_type {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Related {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tables: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub categories: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub queries: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub workspaces: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataTable {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "timespanColumn", default, skip_serializing_if = "Option::is_none")]
pub timespan_column: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub columns: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related: Option<metadata_table::Related>,
}
pub mod metadata_table {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Related {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub categories: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub solutions: Vec<String>,
#[serde(rename = "resourceTypes", default, skip_serializing_if = "Vec::is_empty")]
pub resource_types: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub workspaces: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub queries: Vec<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataFunction {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub body: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related: Option<metadata_function::Related>,
}
pub mod metadata_function {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Related {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tables: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub solutions: Vec<String>,
#[serde(rename = "resourceTypes", default, skip_serializing_if = "Vec::is_empty")]
pub resource_types: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub categories: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub workspaces: Vec<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataQuery {
pub id: String,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub body: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related: Option<metadata_query::Related>,
}
pub mod metadata_query {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Related {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub categories: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub solutions: Vec<String>,
#[serde(rename = "resourceTypes", default, skip_serializing_if = "Vec::is_empty")]
pub resource_types: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tables: Vec<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataApplication {
pub id: String,
#[serde(rename = "resourceId")]
pub resource_id: String,
pub name: String,
pub region: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related: Option<metadata_application::Related>,
}
pub mod metadata_application {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Related {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tables: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataWorkspace {
pub id: String,
#[serde(rename = "resourceId")]
pub resource_id: String,
pub name: String,
pub region: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related: Option<metadata_workspace::Related>,
}
pub mod metadata_workspace {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Related {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tables: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub solutions: Vec<String>,
#[serde(rename = "resourceTypes", default, skip_serializing_if = "Vec::is_empty")]
pub resource_types: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataResource {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataPermissions {
pub workspaces: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub applications: Vec<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tags {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetail {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<String>,
#[serde(rename = "additionalProperties", default, skip_serializing_if = "Option::is_none")]
pub additional_properties: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorInfo {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorDetail>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub innererror: Box<Option<ErrorInfo>>,
#[serde(rename = "additionalProperties", default, skip_serializing_if = "Option::is_none")]
pub additional_properties: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
pub error: ErrorInfo,
}
|
struct Solution;
use crate::shared::tree_node::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
/// https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
impl Solution {
pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
// Solution::bfs_iterative(root)
Solution::dfs_recursive(root)
}
/// 0 ms 2.2 MB
fn bfs_iterative(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
if root.is_none() {
return vec![];
}
let root = root.unwrap();
let mut result = vec![];
let mut current_nodes = vec![];
current_nodes.push(root);
while !current_nodes.is_empty() {
let values = current_nodes
.iter()
.map(|x| x.borrow().val)
.collect::<Vec<_>>();
result.push(values);
let mut next_nodes = vec![];
for node in current_nodes {
let node = (*node).replace(TreeNode::new(0));
if let Some(left) = node.left {
next_nodes.push(left);
}
if let Some(right) = node.right {
next_nodes.push(right);
}
}
current_nodes = next_nodes;
}
result.reverse();
result
}
/// 0 ms 2.3 MB
fn dfs_recursive(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
fn helper(node: Option<Rc<RefCell<TreeNode>>>, level: usize, result: &mut Vec<Vec<i32>>) {
if node.is_none() {
return;
}
let node = (*node.unwrap()).replace(TreeNode::new(0));
if let Some(vec) = result.get_mut(level - 1) {
vec.push(node.val)
} else {
let vec = vec![node.val];
result.push(vec);
}
let next = level + 1;
helper(node.left, next, result);
helper(node.right, next, result);
}
let mut result = vec![];
helper(root, 1, &mut result);
result.reverse();
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[rstest(root, expected,
case(
"[]",
vec![]
),
case(
"[3,9,20,null,null,15,7]",
vec![
vec![15,7],
vec![9,20],
vec![3]
]),
)]
fn bfs_iterative(root: &str, expected: Vec<Vec<i32>>) {
assert_eq!(
Solution::bfs_iterative(TreeNode::from_str_and_wrap(root)),
expected
);
}
#[rstest(root, expected,
case(
"[]",
vec![]
),
case(
"[3,9,20,null,null,15,7]",
vec![
vec![15,7],
vec![9,20],
vec![3]
]),
)]
fn dfs_recursive(root: &str, expected: Vec<Vec<i32>>) {
assert_eq!(
Solution::dfs_recursive(TreeNode::from_str_and_wrap(root)),
expected
);
}
}
|
const INPUT: &str = include_str!("../input.txt");
fn get_seat(char_iter: &mut impl Iterator<Item = char>) -> u64 {
char_iter.fold(0, |acc, c| {
let half = match c {
'R' | 'B' => 1,
_ => 0,
};
(acc << 1) | half
})
}
fn part1() -> u64 {
INPUT
.lines()
.map(|line| get_seat(&mut line.chars()))
.max()
.unwrap()
}
fn part2() -> u64 {
let mut seat_ids: Vec<_> = INPUT
.lines()
.map(|line| get_seat(&mut line.chars()))
.collect();
seat_ids.sort_unstable();
seat_ids
.windows(2)
.find(|tup| tup[0] + 1 != tup[1])
.unwrap()[0]
+ 1
}
fn main() {
println!("part 1: {}", part1());
println!("part 2: {}", part2());
}
#[cfg(test)]
mod tests {
use super::{part1, part2};
#[test]
fn test_part1() {
assert_eq!(part1(), 989);
}
#[test]
fn test_part2() {
assert_eq!(part2(), 548);
}
}
|
use crate::hittable::*;
use crate::ray::*;
use crate::vec3::*;
pub trait Material {
fn scatter(r_in: &Ray, rec: &HitRecord, attenuation: &Color, scattered: &Ray) -> bool;
}
pub struct Lambertian {
pub albedo: Color,
}
impl Lambertian {
pub fn from(a: &Color) -> Self {
Self { albedo: a }
}
}
impl Material for Lambertian {
fn scatter(
&self,
r_in: &Ray,
rec: &HitRecord,
attenuation: &mut Color,
scattered: &mut Ray,
) -> bool {
let scatter_direction: Vec3 = rec.normal + Vec3::random_unit_vector();
scattered = Ray::from(rec.p, scatter_direction);
attenuation = self.albedo;
true
}
}
|
#![deny(clippy::all, clippy::pedantic)]
pub fn primes_up_to(upper_bound: usize) -> Vec<usize> {
let mut marked = (0..=upper_bound).map(|_| true).collect::<Vec<bool>>();
(2..=upper_bound)
.filter(|num| {
if !marked[*num] {
return false;
}
let mut multiple = *num;
while multiple <= upper_bound {
marked[multiple] = false;
multiple += num;
}
true
})
.collect::<Vec<usize>>()
}
|
//! 中断模块 (的函数封装)-> 初始化
//!
//!
mod context;
mod handler;
mod timer;
// 2021-3-10
// ? pub use context::Context;
/// 初始化中断相关的子模块
///
/// - [`handler::init`]
/// - [`timer::init`]
pub fn init() {
handler::init();
// 2021-3-10
timer::init();
println!("mod interrupt initialized");
}
|
use std::ops::{Add, AddAssign, Sub, SubAssign};
fn main() {
let num = add(4, 6);
println!("num = {}", num);
let num1 = sub(4, 6);
println!("num = {}", num);
let mut p = Point { x: 30, y: 50 };
println!("Point({}, {})", p.x, p.y);
p.add(5, 5);
println!("Point({}, {})", p.x, p.y);
p.sub(1000, 1000);
println!("Point({}, {})", p.x, p.y);
}
fn sub<T>(x: T, y: T) -> T
where
T: Sub<Output = T>,
{
x - y
}
fn add<T: Add<Output = T>>(x: T, y: T) -> T {
x + y
}
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn add(&mut self, x: T, y: T)
where
T: AddAssign,
{
self.x += x;
self.y += y;
}
fn sub(&mut self, x: T, y: T)
where
T: SubAssign,
{
self.x -= x;
self.y -= y;
}
}
|
use super::BackendTypes;
use rustc_middle::mir::coverage::*;
use rustc_middle::ty::Instance;
pub trait CoverageInfoMethods: BackendTypes {
fn coverageinfo_finalize(&self);
}
pub trait CoverageInfoBuilderMethods<'tcx>: BackendTypes {
fn create_pgo_func_name_var(&self, instance: Instance<'tcx>) -> Self::Value;
/// Returns true if the function source hash was added to the coverage map (even if it had
/// already been added, for this instance). Returns false *only* if `-Z instrument-coverage` is
/// not enabled (a coverage map is not being generated).
fn set_function_source_hash(
&mut self,
instance: Instance<'tcx>,
function_source_hash: u64,
) -> bool;
/// Returns true if the counter was added to the coverage map; false if `-Z instrument-coverage`
/// is not enabled (a coverage map is not being generated).
fn add_coverage_counter(
&mut self,
instance: Instance<'tcx>,
index: CounterValueReference,
region: CodeRegion,
) -> bool;
/// Returns true if the expression was added to the coverage map; false if
/// `-Z instrument-coverage` is not enabled (a coverage map is not being generated).
fn add_coverage_counter_expression(
&mut self,
instance: Instance<'tcx>,
id: InjectedExpressionId,
lhs: ExpressionOperandId,
op: Op,
rhs: ExpressionOperandId,
region: Option<CodeRegion>,
) -> bool;
/// Returns true if the region was added to the coverage map; false if `-Z instrument-coverage`
/// is not enabled (a coverage map is not being generated).
fn add_coverage_unreachable(&mut self, instance: Instance<'tcx>, region: CodeRegion) -> bool;
}
|
/*!
Data stores that store the result of partial word lookups
to prevent repeated work.
*/
use std::hash::{Hash, Hasher};
use rustc_hash::{FxHashMap, FxHasher};
use crate::trie::Trie;
#[derive(Clone)]
pub struct CachedWords {
words_cache: FxHashMap<u64, Vec<String>>,
}
impl CachedWords {
pub fn default() -> CachedWords {
CachedWords {
words_cache: FxHashMap::default(),
}
}
pub fn words<T: Iterator<Item = char> + Clone>(
&mut self,
iter: T,
trie: &Trie,
) -> &Vec<String> {
let mut hasher = FxHasher::default();
for c in iter.clone() {
c.hash(&mut hasher);
}
let key = hasher.finish();
self.words_cache
.entry(key)
.or_insert_with(|| trie.words(iter))
}
}
#[derive(Clone)]
pub struct CachedIsViable {
is_viable_cache: FxHashMap<u64, bool>,
}
impl CachedIsViable {
pub fn default() -> CachedIsViable {
CachedIsViable {
is_viable_cache: FxHashMap::default(),
}
}
pub fn is_viable<T: Iterator<Item = char> + Clone>(&mut self, iter: T, trie: &Trie) -> bool {
let mut hasher = FxHasher::default();
for c in iter.clone() {
c.hash(&mut hasher);
}
let key = hasher.finish();
*self
.is_viable_cache
.entry(key)
.or_insert_with(|| trie.is_viable(iter))
}
}
|
#[doc = "Register `ITLINE31` reader"]
pub type R = crate::R<ITLINE31_SPEC>;
#[doc = "Field `RNG` reader - RNG"]
pub type RNG_R = crate::BitReader;
#[doc = "Field `AES` reader - AES"]
pub type AES_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - RNG"]
#[inline(always)]
pub fn rng(&self) -> RNG_R {
RNG_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - AES"]
#[inline(always)]
pub fn aes(&self) -> AES_R {
AES_R::new(((self.bits >> 1) & 1) != 0)
}
}
#[doc = "interrupt line 31 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`itline31::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ITLINE31_SPEC;
impl crate::RegisterSpec for ITLINE31_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`itline31::R`](R) reader structure"]
impl crate::Readable for ITLINE31_SPEC {}
#[doc = "`reset()` method sets ITLINE31 to value 0"]
impl crate::Resettable for ITLINE31_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use SafeWrapper;
use ir::{User, Instruction, TerminatorInst, CatchPadInst, Block};
use sys;
pub struct CatchReturnInst<'ctx>(TerminatorInst<'ctx>);
impl<'ctx> CatchReturnInst<'ctx>
{
/// Creates a new catch return instruction.
pub fn new(catch_pad: &CatchPadInst,
block: &Block) -> Self {
unsafe {
let inner = sys::LLVMRustCreateCatchReturnInst(catch_pad.inner(), block.inner());
wrap_value!(inner => User => Instruction => TerminatorInst => CatchReturnInst)
}
}
}
impl_subtype!(CatchReturnInst => TerminatorInst);
|
use futures::Stream;
use crate::netlink_packet_route::{link::LinkMessage, RtnlMessage};
use netlink_packet_core::{
header::flags::{NLM_F_DUMP, NLM_F_REQUEST},
NetlinkFlags, NetlinkMessage, NetlinkPayload,
};
use crate::{Error, ErrorKind, Handle};
lazy_static! {
// Flags for `ip link get`
static ref GET_FLAGS: NetlinkFlags = NetlinkFlags::from(NLM_F_REQUEST | NLM_F_DUMP);
}
pub struct LinkGetRequest {
handle: Handle,
message: LinkMessage,
}
impl LinkGetRequest {
pub(crate) fn new(handle: Handle) -> Self {
let message = LinkMessage::new();
LinkGetRequest { handle, message }
}
/// Execute the request
pub fn execute(self) -> impl Stream<Item = LinkMessage, Error = Error> {
let LinkGetRequest {
mut handle,
message,
} = self;
let mut req = NetlinkMessage::from(RtnlMessage::GetLink(message));
req.header.flags = *GET_FLAGS;
handle.request(req).and_then(move |msg| {
let (header, payload) = msg.into_parts();
match payload {
NetlinkPayload::InnerMessage(RtnlMessage::NewLink(msg)) => Ok(msg),
NetlinkPayload::Error(err) => Err(ErrorKind::NetlinkError(err).into()),
_ => Err(ErrorKind::UnexpectedMessage(NetlinkMessage::new(header, payload)).into()),
}
})
}
/// Return a mutable reference to the request
pub fn message_mut(&mut self) -> &mut LinkMessage {
&mut self.message
}
}
|
use crate::rtb_type;
rtb_type! {
OperatingSystem,
500,
OtherNotListed=0;
Nintendo3DSSystemSoftware=1;
Android=2;
AppleTVSoftware=3;
Asha=4;
Bada=5;
BlackBerry=6;
BREW=7;
ChromeOS=8;
Darwin=9;
FireOS=10;
FirefoxOS=11;
HelenOS=12;
Ios=13;
Linux=14;
MacOS=15;
MeeGo=16;
MorphOS=17;
NetBSD=18;
NucleusPLUS=19;
PSVitaSystemSoftware=20;
PS3SystemSoftware=21;
PS4Software=22;
PSPSystemSoftware=23;
Symbian=24;
Tizen=25;
WatchOS=26;
WebOS=27;
Windows=28
}
|
use anyhow::Result;
/// Trait describing interface for available operations on repositories
pub trait RepoOperations {
/// Executing custom git command on a repository
///
/// # Arguments
///
/// * `cmd` - command to execute, e.g. status --porcelain
fn custom_cmd(&self, cmd: String) -> Result<()>;
/// Executing `git status --porcelain` on the repository and displaying result if it's not clean.
/// It doesn't display anything on a clean repository.
fn porcelain(&self) -> Result<()>;
/// Finds repositories which have cherry-picks in history
fn find_cherry_picks(&self) -> Result<Option<String>>;
/// Prints all cherry picks found in history
fn print_cherry_picks(&self) -> Result<()>;
/// Print repository and commits with author if there is one in last `number` of commits
///
/// # Arguments
///
/// * `number` - last number of commits to look into
/// * `author` - author to look for
fn print_commits_with_author(&self, number: u32, author: &str) -> Result<()>;
}
|
#[link(name = "glfw",
vers = "0.1",
uuid = "6199FAD3-6D03-4E29-87E7-7DC1B1B65C2C",
author = "Brendan Zabarauskas",
url = "https://github.com/bjz/glfw3-rs")];
#[comment = "Bindings and wrapper functions for glfw3."];
#[crate_type = "lib"];
use core::libc::*;
use support::event;
pub use support::consts::*;
/// Low-level bindings
pub mod ll;
/// Mid-level wrapper functions
pub mod ml;
pub mod support {
pub mod consts;
pub mod event;
pub mod types;
}
/**
* A struct containing a low-level monitor handle
*/
pub struct Monitor { ptr: *::ml::GLFWmonitor }
/**
* A struct containing a low-level window handle
*/
pub struct Window { ptr: *::ml::GLFWwindow }
pub type ErrorFun = @fn(error: c_int, format: ~str);
pub type WindowPosFun = @fn(window: &Window, width: int, height: int);
pub type WindowSizeFun = @fn(window: &Window, width: int, height: int);
pub type WindowCloseFun = @fn(window: &Window);
pub type WindowRefreshFun = @fn(window: &Window);
pub type WindowFocusFun = @fn(window: &Window, activated: bool);
pub type WindowIconifyFun = @fn(window: &Window, iconified: bool);
pub type MouseButtonFun = @fn(window: &Window, button: c_int, action: c_int);
pub type CursorPosFun = @fn(window: &Window, xpos: float, ypos: float);
pub type CursorEnterFun = @fn(window: &Window, entered: bool);
pub type ScrollFun = @fn(window: &Window, xpos: float, ypos: float);
pub type KeyFun = @fn(window: &Window, key: c_int, action: c_int);
pub type CharFun = @fn(window: &Window, character: char);
pub type MonitorFun = @fn(monitor: &Monitor, event: c_int);
pub struct VidMode {
width: c_int,
height: c_int,
redBits: c_int,
greenBits: c_int,
blueBits: c_int,
}
pub struct GammaRamp {
red: [c_ushort, ..GAMMA_RAMP_SIZE],
green: [c_ushort, ..GAMMA_RAMP_SIZE],
blue: [c_ushort, ..GAMMA_RAMP_SIZE],
}
pub type GLProc = ::ml::GLFWglproc;
/**
* Initialises GLFW on the main platform thread. `glfw::terminate` is
* automatically called on the success or failure of `f`
*/
pub fn spawn(f: ~fn()) {
do task::spawn_sched(task::PlatformThread) {
use core::unstable::finally::Finally;
match ml::init() {
FALSE => fail!(~"Failed to initialize GLFW"),
_ => f.finally(ml::terminate),
}
}
}
pub struct Version {
major: int,
minor: int,
rev: int,
}
/**
* Returns a struct containing the GLFW version numbers.
*/
pub fn get_version() -> Version {
match ml::get_version() {
(major, minor, rev) => Version {
major: major as int,
minor: minor as int,
rev: rev as int,
}
}
}
pub fn get_version_string() -> ~str {
ml::get_version_string()
}
pub fn set_error_callback(cbfun: ErrorFun) {
do event::error::set_callback(cbfun) |ext_cb| {
ml::set_error_callback(ext_cb);
}
}
pub fn get_monitors() -> ~[Monitor] {
ml::get_monitors().map(|&m| Monitor { ptr: m })
}
pub fn get_primary_monitor() -> Monitor {
Monitor { ptr: ml::get_primary_monitor() }
}
pub impl Monitor {
fn get_pos(&self) -> (int, int) {
match ml::get_monitor_pos(self.ptr) {
(xpos, ypos) => (xpos as int, ypos as int)
}
}
fn get_physical_size(&self) -> (int, int) {
match ml::get_monitor_physical_size(self.ptr) {
(width, height) => (width as int, height as int)
}
}
fn get_name(&self) -> ~str {
ml::get_monitor_name(self.ptr)
}
fn get_video_modes(&self) -> ~[VidMode] {
ml::get_video_modes(self.ptr)
}
fn get_video_mode(&self) -> VidMode {
ml::get_video_mode(self.ptr)
}
/* Gamma ramp functions */
pub fn set_gamma(&self, gamma: float) {
ml::set_gamma(self.ptr, gamma as c_float);
}
pub fn get_gamma_ramp(&self) -> GammaRamp {
ml::get_gamma_ramp(self.ptr)
}
pub fn set_gamma_ramp(&self, ramp: &GammaRamp) {
ml::set_gamma_ramp(self.ptr, ramp);
}
}
fn set_monitor_callback(cbfun: MonitorFun) {
do event::monitor::set_callback(cbfun) |ext_cb| {
ml::set_monitor_callback(ext_cb);
}
}
impl ToStr for VidMode {
fn to_str(&self) -> ~str {
fmt!("%? x %? %? (%? %? %?)",
self.width, self.height,
(self.redBits + self.blueBits + self.greenBits),
self.redBits, self.blueBits, self.greenBits)
}
}
/* Window handling */
macro_rules! hint(
($name:ident $(($arg_name:ident: $arg_ty:ty) => ($hint:expr, $arg_conv:expr))+) => (
pub fn $name($($arg_name: $arg_ty),+) {
$(::ml::window_hint($hint, $arg_conv);)+
}
)
)
pub mod window_hint {
use core::libc::c_int;
pub fn default() {
::ml::default_window_hints();
}
hint!(red_bits (bits: uint) => (::RED_BITS, bits as c_int))
hint!(green_bits (bits: uint) => (::GREEN_BITS, bits as c_int))
hint!(blue_bits (bits: uint) => (::BLUE_BITS, bits as c_int))
hint!(alpha_bits (bits: uint) => (::ALPHA_BITS, bits as c_int))
hint!(depth_bits (bits: uint) => (::DEPTH_BITS, bits as c_int))
hint!(stencil_bits (bits: uint) => (::STENCIL_BITS, bits as c_int))
hint!(accum_red_bits (bits: uint) => (::ACCUM_RED_BITS, bits as c_int))
hint!(accum_green_bits (bits: uint) => (::ACCUM_GREEN_BITS, bits as c_int))
hint!(accum_blue_bits (bits: uint) => (::ACCUM_BLUE_BITS, bits as c_int))
hint!(accum_alpha_bits (bits: uint) => (::ACCUM_ALPHA_BITS, bits as c_int))
hint!(aux_buffers (buffers: uint) => (::AUX_BUFFERS, buffers as c_int))
hint!(stereo (value: bool) => (::STEREO, value as c_int))
hint!(samples (samples: uint) => (::SAMPLES, samples as c_int))
hint!(srgb_capable (value: bool) => (::SRGB_CAPABLE, value as c_int))
hint!(client_api (api: c_int) => (::CLIENT_API, api))
hint!(context_version_major (major: uint) => (::CONTEXT_VERSION_MAJOR, major as c_int))
hint!(context_version_minor (minor: uint) => (::CONTEXT_VERSION_MINOR, minor as c_int))
hint!(context_version (major: uint) => (::CONTEXT_VERSION_MAJOR, major as c_int)
(minor: uint) => (::CONTEXT_VERSION_MINOR, minor as c_int))
hint!(context_robustness (value: bool) => (::CONTEXT_ROBUSTNESS, value as c_int))
hint!(opengl_forward_compat (value: bool) => (::OPENGL_FORWARD_COMPAT, value as c_int))
hint!(opengl_debug_context (value: bool) => (::OPENGL_DEBUG_CONTEXT, value as c_int))
hint!(opengl_profile (profile: c_int) => (::OPENGL_PROFILE, profile))
hint!(resizable (value: bool) => (::RESIZABLE, value as c_int))
hint!(visible (value: bool) => (::VISIBLE, value as c_int))
hint!(undecorated (value: bool) => (::UNDECORATED, value as c_int))
}
pub enum WindowMode {
FullScreen(Monitor),
Windowed,
}
pub impl Window {
fn create(width: uint, height: uint, title: &str, mode: WindowMode) -> Result<Window,~str> {
Window::create_shared(width, height, title, mode, &Window { ptr: ptr::null() })
}
fn create_shared(width: uint, height: uint, title: &str,
mode: WindowMode, share: &Window) -> Result<Window,~str> {
match ml::create_window(
width as c_int,
height as c_int,
title,
match mode {
FullScreen(m) => m.ptr,
Windowed => ptr::null()
},
share.ptr
) {
w if !w.is_null() => Ok(Window { ptr: w }),
_ => Err(~"Failed to open GLFW window"),
}
}
fn destroy(&self) {
ml::destroy_window(self.ptr);
}
fn should_close(&self) -> bool {
ml::window_should_close(self.ptr) as bool
}
fn set_should_close(&self, value: bool) {
ml::set_window_should_close(self.ptr, value as c_int)
}
fn set_title(&self, title: &str) {
ml::set_window_title(self.ptr, title)
}
fn get_pos(&self) -> (int, int) {
match ml::get_window_pos(self.ptr) {
(xpos, ypos) => (xpos as int, ypos as int)
}
}
fn set_pos(&self, xpos: int, ypos: int) {
ml::set_window_pos(self.ptr, xpos as c_int, ypos as c_int);
}
fn get_size(&self) -> (int, int) {
match ml::get_window_size(self.ptr) {
(width, height) => (width as int, height as int)
}
}
fn set_size(&self, width: int, height: int) {
ml::set_window_size(self.ptr, width as c_int, height as c_int);
}
fn iconify(&self) {
ml::iconify_window(self.ptr);
}
fn restore(&self) {
ml::restore_window(self.ptr);
}
fn show(&self) {
ml::show_window(self.ptr);
}
fn hide(&self) {
ml::hide_window(self.ptr);
}
fn get_monitor(&self) -> WindowMode {
match ml::get_window_monitor(self.ptr) {
m if m.is_null() => Windowed,
m => FullScreen(Monitor { ptr: m }),
}
}
fn get_param(&self, param: c_int) -> c_int {
ml::get_window_param(self.ptr, param)
}
fn set_user_pointer(&self, pointer: *c_void) {
ml::set_window_user_pointer(self.ptr, pointer);
}
fn get_user_pointer(&self) -> *c_void {
ml::get_window_user_pointer(self.ptr)
}
fn set_pos_callback(&self, cbfun: WindowSizeFun) {
do event::windowpos::set_callback(cbfun) |ext_cb| {
ml::set_window_pos_callback(self.ptr, ext_cb);
}
}
fn set_size_callback(&self, cbfun: WindowSizeFun) {
do event::windowsize::set_callback(cbfun) |ext_cb| {
ml::set_window_size_callback(self.ptr, ext_cb);
}
}
fn set_close_callback(&self, cbfun: WindowCloseFun) {
do event::windowclose::set_callback(cbfun) |ext_cb| {
ml::set_window_close_callback(self.ptr, ext_cb);
}
}
fn set_refresh_callback(&self, cbfun: WindowRefreshFun) {
do event::windowrefresh::set_callback(cbfun) |ext_cb| {
ml::set_window_refresh_callback(self.ptr, ext_cb);
}
}
fn set_focus_callback(&self, cbfun: WindowFocusFun) {
do event::windowfocus::set_callback(cbfun) |ext_cb| {
ml::set_window_focus_callback(self.ptr, ext_cb);
}
}
fn set_iconify_callback(&self, cbfun: WindowIconifyFun) {
do event::windowiconify::set_callback(cbfun) |ext_cb| {
ml::set_window_iconify_callback(self.ptr, ext_cb);
}
}
fn get_input_mode(&self, mode: c_int) -> int {
ml::get_input_mode(self.ptr, mode) as int
}
fn set_input_mode(&self, mode: c_int, value: int) {
ml::set_input_mode(self.ptr, mode, value as c_int);
}
fn get_key(&self, key: c_int) -> c_int {
ml::get_key(self.ptr, key)
}
fn get_mouse_button(&self, button: c_int) -> c_int {
ml::get_mouse_button(self.ptr, button)
}
fn get_cursor_pos(&self) -> (float, float) {
match ml::get_cursor_pos(self.ptr) {
(xpos, ypos) => (xpos as float, ypos as float)
}
}
fn set_cursor_pos(&self, xpos: float, ypos: float) {
ml::set_cursor_pos(self.ptr, xpos as c_double, ypos as c_double);
}
fn set_key_callback(&self, cbfun: KeyFun) {
do event::key::set_callback(cbfun) |ext_cb| {
ml::set_key_callback(self.ptr, ext_cb);
}
}
fn set_char_callback(&self, cbfun: CharFun) {
do event::char::set_callback(cbfun) |ext_cb| {
ml::set_char_callback(self.ptr, ext_cb);
}
}
fn set_mouse_button_callback(&self, cbfun: MouseButtonFun) {
do event::mousebutton::set_callback(cbfun) |ext_cb| {
ml::set_mouse_button_callback(self.ptr, ext_cb);
}
}
fn set_cursor_pos_callback(&self, cbfun: CursorPosFun) {
do event::cursorpos::set_callback(cbfun) |ext_cb| {
ml::set_cursor_pos_callback(self.ptr, ext_cb);
}
}
fn set_cursor_enter_callback(&self, cbfun: CursorEnterFun) {
do event::cursorenter::set_callback(cbfun) |ext_cb| {
ml::set_cursor_enter_callback(self.ptr, ext_cb);
}
}
fn set_scroll_callback(&self, cbfun: ScrollFun) {
do event::scroll::set_callback(cbfun) |ext_cb| {
ml::set_scroll_callback(self.ptr, ext_cb);
}
}
fn set_clipboard_string(&self, string: &str) {
ml::set_clipboard_string(self.ptr, string);
}
fn get_clipboard_string(&self) -> ~str {
ml::get_clipboard_string(self.ptr)
}
fn make_context_current(&self) {
ml::make_context_current(self.ptr);
}
fn swap_buffers(&self) {
ml::swap_buffers(self.ptr);
}
}
pub fn poll_events() {
ml::poll_events();
}
pub fn wait_events() {
ml::wait_events();
}
pub mod joystick {
use core::libc::*;
pub fn is_present(joy: c_int) -> bool {
::ml::get_joystick_param(joy, ::ml::PRESENT) as bool
}
pub fn num_axes(joy: c_int) -> Option<uint> {
let axes = ::ml::get_joystick_param(joy, ::ml::AXES);
if axes > 0 { Some(axes as uint) } else { None }
}
pub fn num_buttons(joy: c_int) -> Option<uint> {
let buttons = ::ml::get_joystick_param(joy, ::ml::BUTTONS);
if buttons > 0 { Some(buttons as uint) } else { None }
}
pub fn get_axes(joy: c_int) -> Result<~[float],()> {
do num_axes(joy).map_default(Err(())) |&num| {
unsafe {
let mut axes = ~[];
vec::grow(&mut axes, num, &0.0);
vec::raw::set_len(&mut axes, num);
if ::ll::glfwGetJoystickAxes(joy, &axes[0], num as c_int) > 0 {
Ok(axes.map(|&a| a as float))
} else {
Err(())
}
}
}
}
pub fn get_buttons(joy: c_int) -> Result<~[int],()> {
do num_axes(joy).map_default(Err(())) |&num| {
unsafe {
let mut buttons = ~[];
vec::grow(&mut buttons, num, &0);
vec::raw::set_len(&mut buttons, num);
if ::ll::glfwGetJoystickButtons(joy, &buttons[0], num as c_int) > 0 {
Ok(buttons.map(|&a| a as int))
} else {
Err(())
}
}
}
}
pub fn get_name(joy: c_int) -> ~str {
::ml::get_joystick_name(joy)
}
}
pub fn get_time() -> f64 {
ml::get_time() as f64
}
pub fn set_time(time: f64) {
ml::set_time(time as c_double);
}
pub fn get_current_context() -> Window {
Window { ptr: ml::get_current_context() }
}
pub fn set_swap_interval(interval: int) {
ml::set_swap_interval(interval as c_int);
}
pub fn extension_supported(extension: &str) -> bool {
ml::extension_supported(extension) as bool
}
pub fn get_proc_address(procname: &str) -> GLProc {
ml::get_proc_address(procname)
} |
use strum::EnumIter;
#[derive(Clone, Copy, EnumIter, PartialEq, Eq, Hash, Debug)]
pub enum Color {
Red,
Blue,
Green,
White,
Yellow,
All,
Black,
}
impl Color {
pub fn to_string(&self) -> &str {
match self {
Color::Red => ":red_square:",
Color::Blue => ":blue_square:",
Color::Green => ":green_square:",
Color::White => ":white_square:",
Color::Yellow => ":yellow_square:",
Color::All => ":rainbow_flag:",
Color::Black => ":black_square:",
}
}
}
#[derive(Clone, Copy)]
pub enum Hint {
Color(Color),
Value(u8),
}
impl Hint {
// Returns true if the hint applies to a given card
pub fn applies_to(&self, card: &Card) -> bool {
match self {
Hint::Color(c) if *c == card.color => true,
Hint::Value(v) if *v == card.value => true,
_ => false,
}
}
}
#[derive(Clone, Copy)]
pub struct Card {
pub value: u8,
pub color: Color,
pub hints: (Option<Hint>, Option<Hint>),
}
impl Card {
// Add an hint to the card
pub fn add_hint(&mut self, hint: Hint) {
match hint {
Hint::Color(c) => match self.hints.0 {
Some(Hint::Color(c2)) if c2 == c => {
self.hints.0 = Some(Hint::Color(Color::All));
}
_ => (),
},
Hint::Value(v) => {
self.hints.1 = Some(Hint::Value(v));
}
}
}
pub fn value_to_string(&self) -> &str {
match self.value {
1 => ":one:",
2 => ":two:",
3 => ":three:",
4 => ":four:",
5 => ":five:",
_ => ":construction:",
}
}
}
|
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
use rocket::fairing::AdHoc;
use auth::authsettings::AuthSettings;
mod api;
mod protected;
mod auth;
mod routes;
fn main() {
let routes_vec = routes::get_routes();
rocket::ignite()
.mount("/", routes_vec)
.attach(AdHoc::on_attach("authsettings", |rocket: rocket::Rocket| {
let settings = AuthSettings::from_env().expect("Auth0 settings must be configured in env variables!");
Ok(rocket.manage(settings))
}))
.launch();
}
|
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum MemoryError {
OutOfBounds,
InvalidAccess,
ReadOnly,
Overflow,
Underflow,
Overlap,
}
pub mod address;
pub mod address_space;
pub mod sparse;
pub mod zero;
pub mod rom; |
use super::role::RoleEntity;
use crate::{
repository::{GetEntityFuture, ListEntitiesFuture, Repository},
utils, Backend, Entity,
};
use twilight_model::{
guild::Member,
gateway::payload::MemberUpdate,
id::{GuildId, RoleId, UserId},
};
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MemberEntity {
pub deaf: bool,
pub guild_id: GuildId,
pub hoisted_role_id: Option<RoleId>,
pub joined_at: Option<String>,
pub mute: bool,
pub nick: Option<String>,
pub pending: bool,
pub premium_since: Option<String>,
pub role_ids: Vec<RoleId>,
pub user_id: UserId,
}
impl From<Member> for MemberEntity {
fn from(member: Member) -> Self {
Self {
deaf: member.deaf,
guild_id: member.guild_id,
hoisted_role_id: member.hoisted_role,
joined_at: member.joined_at,
mute: member.mute,
nick: member.nick,
pending: member.pending,
premium_since: member.premium_since,
role_ids: member.roles,
user_id: member.user.id,
}
}
}
impl MemberEntity {
pub fn update(self, update: MemberUpdate) -> Self {
Self {
guild_id: update.guild_id,
joined_at: Some(update.joined_at),
nick: update.nick.or(self.nick),
premium_since: update.premium_since.or(self.premium_since),
role_ids: update.roles,
user_id: update.user.id,
..self
}
}
}
impl Entity for MemberEntity {
type Id = (GuildId, UserId);
/// Return an ID consisting of a tuple of the guild ID and user ID.
fn id(&self) -> Self::Id {
(self.guild_id, self.user_id)
}
}
pub trait MemberRepository<B: Backend>: Repository<MemberEntity, B> {
/// Retrieve the hoisted role associated with a role.
fn hoisted_role(
&self,
guild_id: GuildId,
user_id: UserId,
) -> GetEntityFuture<'_, RoleEntity, B::Error> {
utils::relation_and_then(
self.backend().members(),
self.backend().roles(),
(guild_id, user_id),
|member| member.hoisted_role_id,
)
}
/// Retrieve a stream of roles associated with a member.
///
/// Backend implementations aren't obligated to return roles in any
/// particular order.
fn roles(
&self,
guild_id: GuildId,
user_id: UserId,
) -> ListEntitiesFuture<'_, RoleEntity, B::Error> {
utils::stream(
self.backend().members(),
self.backend().roles(),
(guild_id, user_id),
|member| member.role_ids.into_iter(),
)
}
}
|
extern crate watchexec;
use watchexec::{cli, run};
fn main() {
run(cli::get_args());
}
|
#![allow(dead_code)]
#![allow(unused_imports)]
use std::fmt;
use std::mem;
#[derive(Debug)]
pub struct List<T> {
head: ListEnum<T>
}
#[derive(Debug)]
pub struct IntoIter<T> (List<T>);
pub struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
pub struct IterMut<'a, T> {
next: Option<&'a mut Node<T>>,
}
#[derive(Debug)]
pub struct Node<T> {
value: T,
next: ListEnum<T>
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
}
pub fn into_iter(self) -> IntoIter<T> {
IntoIter(self)
}
pub fn push(&mut self, elem: T) {
let new_node = Box::new(Node {
value: elem,
next: self.head.take(),
});
self.head = Some(new_node);
}
pub fn pop(&mut self) -> Option<T> {
match self.head.take() {
None => {
None
},
Some(node) => {
self.head = node.next;
Some(node.value)
}
}
}
pub fn peek(&mut self) -> Option<T> {
self.head.take().map(|node| {
node.value
})
}
pub fn peek_with_ref(&mut self) -> Option<&T> {
self.head.as_ref().map(|node| {
&node.value
})
}
pub fn peek_with_ref_mut(&mut self) -> Option<&mut T> {
self.head.as_mut().map(|node| {
&mut node.value
})
}
}
impl<T> List<T> {
pub fn iter(&self) -> Iter<'_, T> {
Iter {
next: self.head.as_ref().map(|node| &**node)
}
}
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
IterMut {
next: self.head.as_mut().map(|node| &mut **node)
}
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_ref().map(|node| &**node);
&node.value
})
}
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|node| {
self.next = node.next.as_mut().map(|node| &mut **node);
&mut node.value
})
}
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.0.pop()
}
}
impl<T> Drop for List<T> {
fn drop(&mut self) {
let mut cur_link = self.head.take();
while let Some(mut boxed_node) = cur_link {
cur_link = boxed_node.next.take();
}
}
}
impl<T: std::fmt::Display> fmt::Display for Node<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}) ->", self.value)
}
}
type ListEnum<T> = Option<Box<Node<T>>>;
mod test {
use super::List;
use super::Node;
use super::ListEnum;
#[test]
fn ll_take2_test_empty_list_pop() {
let mut empty_list: List<f32> = List::new();
assert_eq!(empty_list.pop(), None);
}
#[test]
fn ll_take2_test_insert_pop_list() {
let mut l: List<f32> = List::new();
l.push(100.0);
assert_eq!(l.pop(), Some(100.0));
}
#[test]
fn ll_take2_insert_peek_list() {
let mut l: List<f32> = List::new();
l.push(100.0);
assert_eq!(l.peek(), Some(100.0));
l.push(300.0);
assert_eq!(l.peek(), Some(300.0));
}
#[test]
fn ll_take2_insert_peek_ref_list() {
let mut l: List<f32> = List::new();
l.push(100.0);
assert_eq!(l.peek_with_ref(), Some(&100.0));
l.push(300.0);
assert_eq!(l.peek(), Some(300.0));
}
#[test]
fn peek() {
let mut list = List::new();
assert_eq!(list.peek_with_ref(), None);
assert_eq!(list.peek_with_ref_mut(), None);
list.push(1); list.push(2); list.push(3);
assert_eq!(list.peek_with_ref(), Some(&3));
assert_eq!(list.peek_with_ref_mut(), Some(&mut 3));
list.peek_with_ref_mut().map(|value| {
*value = 42
});
assert_eq!(list.peek_with_ref(), Some(&42));
assert_eq!(list.pop(), Some(42));
}
#[test]
fn ll_take2_into_iter() {
let mut list = List::new();
list.push(1); list.push(2); list.push(3);
let mut iter = list.into_iter();
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), None);
}
#[test]
fn ll_take2_test() {
let mut list: List<f32> = List::new();
list.push(10.0);
list.push(11.0);
list.pop();
assert_eq!(list.peek_with_ref(), Some(&10.0));
list.push(11.0);
let opt = list.peek_with_ref_mut();
opt.map(|value| {
*value = 200.0;
});
assert_eq!(list.peek_with_ref(), Some(&200.0));
}
#[test]
fn ll_take2_iter() {
let mut list = List::new();
list.push(1); list.push(2); list.push(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));
}
#[test]
fn ll_take2_iter_mut() {
let mut list = List::new();
list.push(1); list.push(2); list.push(3);
let mut iter = list.iter_mut();
assert_eq!(iter.next(), Some(&mut 3));
assert_eq!(iter.next(), Some(&mut 2));
assert_eq!(iter.next(), Some(&mut 1));
}
}
|
#[macro_use]
extern crate diesel;
pub mod domain;
pub mod controller;
pub mod response;
pub mod request;
pub mod repository;
pub mod service;
pub mod driver;
pub mod model;
pub mod schema;
#[cfg(test)]
mod tests; |
use super::{GoalSpecific, InvisibleGoal, ResponseContextEntry, VisibleGoal};
use crate::base::{Cohesion, ComputeMode, Hiding, Relevance};
use crate::pos::InteractionPoint;
use crate::resp::OutputForm;
use serde::Deserialize;
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Default, Debug, Eq, PartialEq)]
pub struct CommandState {
pub interaction_points: Vec<InteractionPoint>,
pub current_file: String,
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct InferredType {
pub command_state: CommandState,
pub time: String,
pub expr: String,
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct NormalForm {
pub compute_mode: ComputeMode,
pub command_state: CommandState,
pub time: String,
pub expr: String,
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct Context {
pub interaction_point: InteractionPoint,
pub context: Vec<ResponseContextEntry>,
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct AgdaError {
pub message: Option<String>,
}
impl Into<String> for AgdaError {
fn into(self) -> String {
self.message.unwrap_or_else(|| "Unknown error".to_owned())
}
}
impl<Ok> Into<Result<Ok, String>> for AgdaError {
fn into(self) -> Result<Ok, String> {
Err(self.into())
}
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct NamedPrettyTCM {
pub name: String,
pub term: String,
}
/// One item in the `telToList` telescope list.
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct TelescopicItem {
pub dom: String,
pub name: Option<String>,
pub finite: bool,
pub cohesion: Cohesion,
pub relevance: Relevance,
pub hiding: Hiding,
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct ModuleContents {
pub names: Vec<String>,
pub contents: Vec<NamedPrettyTCM>,
pub telescope: Vec<TelescopicItem>,
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct AllGoalsWarnings {
pub visible_goals: Vec<VisibleGoal>,
pub invisible_goals: Vec<InvisibleGoal>,
pub warnings: String,
pub errors: String,
}
/// Something that is displayed in the Emacs mode,
/// serialized with more details.
#[serde(tag = "kind")]
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub enum DisplayInfo {
CompilationOk {
warnings: String,
errors: String,
},
Constraints {
constraints: Vec<OutputForm>,
},
AllGoalsWarnings(AllGoalsWarnings),
Time {
time: String,
},
Error(AgdaError),
IntroNotFound,
IntroConstructorUnknown {
/// Available constructors
constructors: Vec<String>,
},
Auto {
info: String,
},
ModuleContents(ModuleContents),
SearchAbout {
search: String,
results: Vec<NamedPrettyTCM>,
},
WhyInScope {
thing: String,
filepath: String,
message: String,
},
NormalForm(NormalForm),
InferredType(InferredType),
Context(Context),
Version {
version: String,
},
GoalSpecific(GoalSpecific),
}
|
mod candidate_uncles;
use crate::component::entry::TxEntry;
use crate::config::BlockAssemblerConfig;
use crate::error::BlockAssemblerError as Error;
pub use candidate_uncles::CandidateUncles;
use ckb_chain_spec::consensus::Consensus;
use ckb_jsonrpc_types::{BlockTemplate, CellbaseTemplate, TransactionTemplate, UncleTemplate};
use ckb_reward_calculator::RewardCalculator;
use ckb_snapshot::Snapshot;
use ckb_store::ChainStore;
use ckb_types::{
bytes::Bytes,
core::{
BlockNumber, Capacity, Cycle, EpochExt, HeaderView, TransactionBuilder, TransactionView,
UncleBlockView, Version,
},
packed::{self, Byte32, CellInput, CellOutput, CellbaseWitness, ProposalShortId, Transaction},
prelude::*,
};
use failure::Error as FailureError;
use lru_cache::LruCache;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::{atomic::AtomicU64, atomic::AtomicUsize};
use tokio::sync::lock::Lock;
const BLOCK_TEMPLATE_TIMEOUT: u64 = 3000;
const TEMPLATE_CACHE_SIZE: usize = 10;
pub struct TemplateCache {
pub time: u64,
pub uncles_updated_at: u64,
pub txs_updated_at: u64,
pub template: BlockTemplate,
}
impl TemplateCache {
pub fn is_outdate(&self, current_time: u64) -> bool {
current_time.saturating_sub(self.time) > BLOCK_TEMPLATE_TIMEOUT
}
pub fn is_modified(&self, last_uncles_updated_at: u64, last_txs_updated_at: u64) -> bool {
last_uncles_updated_at != self.uncles_updated_at
|| last_txs_updated_at != self.txs_updated_at
}
}
pub type BlockTemplateCacheKey = (Byte32, Cycle, u64, Version);
#[derive(Clone)]
pub struct BlockAssembler {
pub(crate) config: Arc<BlockAssemblerConfig>,
pub(crate) work_id: Arc<AtomicUsize>,
pub(crate) last_uncles_updated_at: Arc<AtomicU64>,
pub(crate) template_caches: Lock<LruCache<BlockTemplateCacheKey, TemplateCache>>,
pub(crate) candidate_uncles: Lock<CandidateUncles>,
}
impl BlockAssembler {
pub fn new(config: BlockAssemblerConfig) -> Self {
Self {
config: Arc::new(config),
work_id: Arc::new(AtomicUsize::new(0)),
last_uncles_updated_at: Arc::new(AtomicU64::new(0)),
template_caches: Lock::new(LruCache::new(TEMPLATE_CACHE_SIZE)),
candidate_uncles: Lock::new(CandidateUncles::new()),
}
}
pub(crate) fn transform_params(
consensus: &Consensus,
bytes_limit: Option<u64>,
proposals_limit: Option<u64>,
max_version: Option<Version>,
) -> (u64, u64, Version) {
let bytes_limit = bytes_limit
.min(Some(consensus.max_block_bytes()))
.unwrap_or_else(|| consensus.max_block_bytes());
let proposals_limit = proposals_limit
.min(Some(consensus.max_block_proposals_limit()))
.unwrap_or_else(|| consensus.max_block_proposals_limit());
let version = max_version
.min(Some(consensus.block_version()))
.unwrap_or_else(|| consensus.block_version());
(bytes_limit, proposals_limit, version)
}
pub(crate) fn transform_uncle(uncle: &UncleBlockView) -> UncleTemplate {
UncleTemplate {
hash: uncle.hash().unpack(),
required: false,
proposals: uncle
.data()
.proposals()
.into_iter()
.map(Into::into)
.collect(),
header: uncle.data().header().into(),
}
}
pub(crate) fn transform_cellbase(
tx: &TransactionView,
cycles: Option<Cycle>,
) -> CellbaseTemplate {
CellbaseTemplate {
hash: tx.hash().unpack(),
cycles: cycles.map(Into::into),
data: tx.data().into(),
}
}
pub(crate) fn transform_tx(
tx: &TxEntry,
required: bool,
depends: Option<Vec<u32>>,
) -> TransactionTemplate {
TransactionTemplate {
hash: tx.transaction.hash().unpack(),
required,
cycles: Some(tx.cycles.into()),
depends: depends.map(|deps| deps.into_iter().map(|x| u64::from(x).into()).collect()),
data: tx.transaction.data().into(),
}
}
pub(crate) fn calculate_txs_size_limit(
bytes_limit: u64,
cellbase: Transaction,
uncles: &[UncleBlockView],
proposals: &HashSet<ProposalShortId>,
) -> Result<usize, FailureError> {
let empty_dao = packed::Byte32::default();
let raw_header = packed::RawHeader::new_builder().dao(empty_dao).build();
let header = packed::Header::new_builder().raw(raw_header).build();
let block = packed::Block::new_builder()
.header(header)
.transactions(vec![cellbase].pack())
.uncles(uncles.iter().map(|u| u.data()).pack())
.proposals(
proposals
.iter()
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
.pack(),
)
.build();
let serialized_size = block.serialized_size_without_uncle_proposals();
let bytes_limit = bytes_limit as usize;
bytes_limit
.checked_sub(serialized_size)
.ok_or_else(|| Error::InvalidParams(format!("bytes_limit {}", bytes_limit)).into())
}
/// Miner mined block H(c), the block reward will be finalized at H(c + w_far + 1).
/// Miner specify own lock in cellbase witness.
/// The cellbase have only one output,
/// miner should collect the block reward for finalize target H(max(0, c - w_far - 1))
pub(crate) fn build_cellbase(
snapshot: &Snapshot,
tip: &HeaderView,
cellbase_witness: CellbaseWitness,
) -> Result<TransactionView, FailureError> {
let candidate_number = tip.number() + 1;
let tx = {
let (target_lock, block_reward) =
RewardCalculator::new(snapshot.consensus(), snapshot).block_reward(tip)?;
let input = CellInput::new_cellbase_input(candidate_number);
let output = CellOutput::new_builder()
.capacity(block_reward.total.pack())
.lock(target_lock)
.build();
let witness = cellbase_witness.as_bytes().pack();
let no_finalization_target =
candidate_number <= snapshot.consensus().finalization_delay_length();
let tx_builder = TransactionBuilder::default().input(input).witness(witness);
let insufficient_reward_to_create_cell = output.is_lack_of_capacity(Capacity::zero())?;
if no_finalization_target || insufficient_reward_to_create_cell {
tx_builder.build()
} else {
tx_builder
.output(output)
.output_data(Bytes::default().pack())
.build()
}
};
Ok(tx)
}
// A block B1 is considered to be the uncle of another block B2 if all of the following conditions are met:
// (1) they are in the same epoch, sharing the same difficulty;
// (2) height(B2) > height(B1);
// (3) B1's parent is either B2's ancestor or embedded in B2 or its ancestors as an uncle;
// and (4) B2 is the first block in its chain to refer to B1.
pub(crate) fn prepare_uncles(
snapshot: &Snapshot,
candidate_number: BlockNumber,
current_epoch_ext: &EpochExt,
candidate_uncles: &mut CandidateUncles,
) -> Vec<UncleBlockView> {
let epoch_number = current_epoch_ext.number();
let max_uncles_num = snapshot.consensus().max_uncles_num();
let mut uncles: Vec<UncleBlockView> = Vec::with_capacity(max_uncles_num);
let mut removed = Vec::new();
for uncle in candidate_uncles.values() {
if uncles.len() == max_uncles_num {
break;
}
let parent_hash = uncle.header().parent_hash();
if uncle.compact_target() != current_epoch_ext.compact_target()
|| uncle.epoch().number() != epoch_number
|| snapshot.get_block_number(&uncle.hash()).is_some()
|| snapshot.is_uncle(&uncle.hash())
|| !(uncles.iter().any(|u| u.hash() == parent_hash)
|| snapshot.get_block_number(&parent_hash).is_some()
|| snapshot.is_uncle(&parent_hash))
|| uncle.number() >= candidate_number
{
removed.push(uncle.clone());
} else {
uncles.push(uncle.clone());
}
}
for r in removed {
candidate_uncles.remove(&r);
}
uncles
}
}
|
fn main() {
// Comments
// this is an example of a line comment
// rugular comments which are ignored by the compiler
// println!("Hello Rust!")
/*
* This is another type of comment, a block comment. In general,
* line comments are the recommended comment style. But
* block comments are extremely useful for temporarily disabling
* chunks of code. /* Block comments can be /* nested, */ */
* so it takes only a few keystrokes to comment out everything
* in this main() function. /*/*/* Try it yourself! */*/*/
*/
/*
Note: The previous column of `*` was entirely for style. There's
no actual need for it.
*/
/*
Note: The previous column of `*` was entirely for style. There's
no actual need for it.
*/
// You can manipulate expressions more easily with block comments
// than with line comments. Try deleting the comment delimiters
// to change the result:
let x = 5 + /* 90 + */ 5;
println!("Is `x` 10 or 100? x = {}", x); // Is `x` 10 or 100? x = 10
println!("Hello, world!");
// format!: 格式化文本
// print!: 和format类似,但是文字内容会在控制台打印出来
// println!: 和print!类似,但是会从新的一行开始
// eprint!: 和format类似,但是文字从标准错误中打印
// eprintln!: 和eprint!类似,但是会从新的一行开始
println!("{} days", 31);
println!("{0}, this is {1}, {1}, this is {0}", "Rust", "lang");
println!(
"{subject}, {verb}, {object}",
subject = "the quick brown fox",
verb = "jumps over",
object = "the lazy dog",
);
println!("{} of {:b} people know binary, the other half doesn't,", 1, 2);
println!("{number:>width$}",
number = 1,
width = 10,
);
println!("{number:>0width$}",
number = 1,
width = 10,
);
}
|
use anyhow::Result;
use std::time::Duration;
use crossterm::event::{poll, read, Event, KeyCode, KeyEvent};
use super::result_list::ResultList;
use crate::ig::Ig;
#[derive(Default)]
pub(crate) struct InputHandler {
input_buffer: String,
}
impl InputHandler {
pub(crate) fn handle_input(&mut self, result_list: &mut ResultList, ig: &mut Ig) -> Result<()> {
let poll_timeout = if ig.is_searching() {
Duration::from_millis(1)
} else {
Duration::from_millis(100)
};
if poll(poll_timeout)? {
let read_event = read()?;
if let Event::Key(key_event) = read_event {
if matches!(
key_event,
KeyEvent {
code: KeyCode::Char(_),
..
}
) {
self.handle_char_input(key_event.code, result_list, ig);
} else {
self.handle_non_char_input(key_event.code, result_list, ig);
}
}
}
Ok(())
}
fn handle_char_input(&mut self, key_code: KeyCode, result_list: &mut ResultList, ig: &mut Ig) {
if let KeyCode::Char(c) = key_code {
self.input_buffer.push(c);
}
let consume_buffer_and_execute = |buffer: &mut String, op: &mut dyn FnMut()| {
buffer.clear();
op();
};
match self.input_buffer.as_str() {
"j" => {
consume_buffer_and_execute(&mut self.input_buffer, &mut || result_list.next_match())
}
"k" => consume_buffer_and_execute(&mut self.input_buffer, &mut || {
result_list.previous_match()
}),
"l" => {
consume_buffer_and_execute(&mut self.input_buffer, &mut || result_list.next_file())
}
"h" => consume_buffer_and_execute(&mut self.input_buffer, &mut || {
result_list.previous_file()
}),
"gg" => consume_buffer_and_execute(&mut self.input_buffer, &mut || result_list.top()),
"G" => consume_buffer_and_execute(&mut self.input_buffer, &mut || result_list.bottom()),
"dd" => consume_buffer_and_execute(&mut self.input_buffer, &mut || {
result_list.remove_current_entry()
}),
"dw" => consume_buffer_and_execute(&mut self.input_buffer, &mut || {
result_list.remove_current_file()
}),
"q" => consume_buffer_and_execute(&mut self.input_buffer, &mut || ig.exit()),
"g" | "d" => (),
_ => self.input_buffer.clear(),
}
}
fn handle_non_char_input(
&mut self,
key_code: KeyCode,
result_list: &mut ResultList,
ig: &mut Ig,
) {
self.input_buffer.clear();
match key_code {
KeyCode::Down => result_list.next_match(),
KeyCode::Up => result_list.previous_match(),
KeyCode::Right | KeyCode::PageDown => result_list.next_file(),
KeyCode::Left | KeyCode::PageUp => result_list.previous_file(),
KeyCode::Home => result_list.top(),
KeyCode::End => result_list.bottom(),
KeyCode::Delete => result_list.remove_current_entry(),
KeyCode::Enter => ig.open_file(),
KeyCode::F(5) => ig.search(result_list),
KeyCode::Esc => ig.exit(),
_ => (),
}
}
}
|
extern crate dmbc;
extern crate exonum;
extern crate exonum_testkit;
extern crate hyper;
extern crate iron;
extern crate iron_test;
extern crate mount;
extern crate serde_json;
pub mod dmbc_testkit;
use dmbc_testkit::{DmbcTestApiBuilder, DmbcTestKitApi};
use exonum::crypto;
use hyper::status::StatusCode;
use dmbc::currency::api::asset::AssetResponse;
use dmbc::currency::api::error::ApiError;
#[test]
fn asset_is_in_blockchain() {
let meta_data = "asset";
let units = 2;
let fixed = 10;
let (public_key, _) = crypto::gen_keypair();
let (asset, info) = dmbc_testkit::create_asset(
meta_data,
units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&public_key,
);
let testkit = DmbcTestApiBuilder::new()
.add_asset_info(&asset.id(), info.clone())
.create();
let api = testkit.api();
let (status, response): (StatusCode, AssetResponse) =
api.get_with_status(&format!("/v1/assets/{}", asset.id().to_string()));
assert_eq!(status, StatusCode::Ok);
assert_eq!(response, Ok(Some(info)));
}
#[test]
fn asset_isnt_in_blockchain() {
let meta_data = "asset";
let units = 2;
let fixed = 10;
let (public_key, _) = crypto::gen_keypair();
let (asset, _) = dmbc_testkit::create_asset(
meta_data,
units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&public_key,
);
let testkit = DmbcTestApiBuilder::new().create();
let api = testkit.api();
let (status, response): (StatusCode, AssetResponse) =
api.get_with_status(&format!("/v1/assets/{}", asset.id().to_string()));
assert_eq!(status, StatusCode::Ok);
assert_eq!(response, Ok(None));
}
#[test]
fn asset_invalid_id() {
let testkit = DmbcTestApiBuilder::new().create();
let api = testkit.api();
let (status, response): (StatusCode, AssetResponse) =
api.get_with_status("/v1/assets/badassetid");
assert_eq!(status, StatusCode::BadRequest);
assert_eq!(response, Err(ApiError::AssetIdInvalid));
}
|
use std::fs;
#[derive(Debug)]
struct Instruction {
op_code: i64,
step: usize,
modes: Vec<i64>
}
fn parse_instruction(mut instruction: i64) -> Instruction {
let mut parameters = vec![];
while instruction > 0 {
parameters.push(instruction % 10);
instruction /= 10;
}
let op_code;
if parameters.len() > 1 {
op_code = parameters[0] + 10 * parameters[1];
} else {
op_code = parameters[0];
}
let step: usize;
match op_code {
1 | 2 | 7 | 8 => step = 4,
3 | 4 => step = 2,
5 | 6 => step = 3,
99 => step = 2, // Program ends, no step
_ => panic!("Unknown command")
}
let mut modes: Vec<i64> = vec![0; step - 1];
if parameters.len() > 2 {
for (i, mode) in parameters[2..].iter().enumerate() {
modes[i] = *mode;
}
}
Instruction { op_code, step, modes }
}
fn run_intcode_program(mut program: Vec<i64>, input: i64) -> i64{
let mut output: i64 = 0;
let mut i = 0;
while i < program.len() {
// Identify parameter modes and op code
let instruction = parse_instruction(program[i]);
if instruction.op_code == 99 {
break;
}
let mut parameters = vec![];
for (j, mode) in instruction.modes.iter().enumerate() {
if *mode == 0 {
parameters.push(program[program[i + j + 1 as usize] as usize]);
} else {
parameters.push(program[i + j + 1 as usize]);
}
}
let pos = program[i + instruction.step - 1] as usize;
match instruction.op_code {
1 => program[pos] = parameters[0] + parameters[1],
2 => program[pos] = parameters[0] * parameters[1],
3 => program[pos] = input,
4 => output = parameters[0],
5 => if parameters[0] != 0 { i = parameters[1] as usize; continue; },
6 => if parameters[0] == 0 { i = parameters[1] as usize; continue; },
7 => if parameters[0] < parameters[1] { program[pos] = 1; } else { program[pos] = 0; },
8 => if parameters[0] == parameters[1] { program[pos] = 1; } else { program[pos] = 0; },
_ => panic!("Unknown command")
}
i += instruction.step;
}
output
}
fn main() {
let program1:Vec<i64> = fs::read_to_string("input_1.txt")
.unwrap()
.split(",")
.map(|l| l.parse().unwrap())
.collect();
println!("Result 1: {}", run_intcode_program(program1, 1));
let program2:Vec<i64> = fs::read_to_string("input_2.txt")
.unwrap()
.split(",")
.map(|l| l.parse().unwrap())
.collect();
println!("Result 2: {}", run_intcode_program(program2, 5));
} |
#[doc = "Register `IR` reader"]
pub type R = crate::R<IR_SPEC>;
#[doc = "Register `IR` writer"]
pub type W = crate::W<IR_SPEC>;
#[doc = "Field `RF0N` reader - Rx FIFO 0 New Message"]
pub type RF0N_R = crate::BitReader;
#[doc = "Field `RF0N` writer - Rx FIFO 0 New Message"]
pub type RF0N_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF0W` reader - Rx FIFO 0 Full"]
pub type RF0W_R = crate::BitReader;
#[doc = "Field `RF0W` writer - Rx FIFO 0 Full"]
pub type RF0W_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF0F` reader - Rx FIFO 0 Full"]
pub type RF0F_R = crate::BitReader;
#[doc = "Field `RF0F` writer - Rx FIFO 0 Full"]
pub type RF0F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF0L` reader - Rx FIFO 0 Message Lost"]
pub type RF0L_R = crate::BitReader;
#[doc = "Field `RF0L` writer - Rx FIFO 0 Message Lost"]
pub type RF0L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF1N` reader - Rx FIFO 1 New Message"]
pub type RF1N_R = crate::BitReader;
#[doc = "Field `RF1N` writer - Rx FIFO 1 New Message"]
pub type RF1N_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF1W` reader - Rx FIFO 1 Watermark Reached"]
pub type RF1W_R = crate::BitReader;
#[doc = "Field `RF1W` writer - Rx FIFO 1 Watermark Reached"]
pub type RF1W_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF1F` reader - Rx FIFO 1 Watermark Reached"]
pub type RF1F_R = crate::BitReader;
#[doc = "Field `RF1F` writer - Rx FIFO 1 Watermark Reached"]
pub type RF1F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF1L` reader - Rx FIFO 1 Message Lost"]
pub type RF1L_R = crate::BitReader;
#[doc = "Field `RF1L` writer - Rx FIFO 1 Message Lost"]
pub type RF1L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HPM` reader - High Priority Message"]
pub type HPM_R = crate::BitReader;
#[doc = "Field `HPM` writer - High Priority Message"]
pub type HPM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TC` reader - Transmission Completed"]
pub type TC_R = crate::BitReader;
#[doc = "Field `TC` writer - Transmission Completed"]
pub type TC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TCF` reader - Transmission Cancellation Finished"]
pub type TCF_R = crate::BitReader;
#[doc = "Field `TCF` writer - Transmission Cancellation Finished"]
pub type TCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEF` reader - Tx FIFO Empty"]
pub type TEF_R = crate::BitReader;
#[doc = "Field `TEF` writer - Tx FIFO Empty"]
pub type TEF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFN` reader - Tx Event FIFO New Entry"]
pub type TEFN_R = crate::BitReader;
#[doc = "Field `TEFN` writer - Tx Event FIFO New Entry"]
pub type TEFN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFW` reader - Tx Event FIFO Watermark Reached"]
pub type TEFW_R = crate::BitReader;
#[doc = "Field `TEFW` writer - Tx Event FIFO Watermark Reached"]
pub type TEFW_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFF` reader - Tx Event FIFO Full"]
pub type TEFF_R = crate::BitReader;
#[doc = "Field `TEFF` writer - Tx Event FIFO Full"]
pub type TEFF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFL` reader - Tx Event FIFO Element Lost"]
pub type TEFL_R = crate::BitReader;
#[doc = "Field `TEFL` writer - Tx Event FIFO Element Lost"]
pub type TEFL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TSW` reader - Timestamp Wraparound"]
pub type TSW_R = crate::BitReader;
#[doc = "Field `TSW` writer - Timestamp Wraparound"]
pub type TSW_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MRAF` reader - Message RAM Access Failure"]
pub type MRAF_R = crate::BitReader;
#[doc = "Field `MRAF` writer - Message RAM Access Failure"]
pub type MRAF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TOO` reader - Timeout Occurred"]
pub type TOO_R = crate::BitReader;
#[doc = "Field `TOO` writer - Timeout Occurred"]
pub type TOO_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DRX` reader - Message stored to Dedicated Rx Buffer"]
pub type DRX_R = crate::BitReader;
#[doc = "Field `DRX` writer - Message stored to Dedicated Rx Buffer"]
pub type DRX_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ELO` reader - Error Logging Overflow"]
pub type ELO_R = crate::BitReader;
#[doc = "Field `ELO` writer - Error Logging Overflow"]
pub type ELO_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EP` reader - Error Passive"]
pub type EP_R = crate::BitReader;
#[doc = "Field `EP` writer - Error Passive"]
pub type EP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EW` reader - Warning Status"]
pub type EW_R = crate::BitReader;
#[doc = "Field `EW` writer - Warning Status"]
pub type EW_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `BO` reader - Bus_Off Status"]
pub type BO_R = crate::BitReader;
#[doc = "Field `BO` writer - Bus_Off Status"]
pub type BO_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WDI` reader - Watchdog Interrupt"]
pub type WDI_R = crate::BitReader;
#[doc = "Field `WDI` writer - Watchdog Interrupt"]
pub type WDI_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PEA` reader - Protocol Error in Arbitration Phase (Nominal Bit Time is used)"]
pub type PEA_R = crate::BitReader;
#[doc = "Field `PEA` writer - Protocol Error in Arbitration Phase (Nominal Bit Time is used)"]
pub type PEA_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PED` reader - Protocol Error in Data Phase (Data Bit Time is used)"]
pub type PED_R = crate::BitReader;
#[doc = "Field `PED` writer - Protocol Error in Data Phase (Data Bit Time is used)"]
pub type PED_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ARA` reader - Access to Reserved Address"]
pub type ARA_R = crate::BitReader;
#[doc = "Field `ARA` writer - Access to Reserved Address"]
pub type ARA_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Rx FIFO 0 New Message"]
#[inline(always)]
pub fn rf0n(&self) -> RF0N_R {
RF0N_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Rx FIFO 0 Full"]
#[inline(always)]
pub fn rf0w(&self) -> RF0W_R {
RF0W_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Rx FIFO 0 Full"]
#[inline(always)]
pub fn rf0f(&self) -> RF0F_R {
RF0F_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Rx FIFO 0 Message Lost"]
#[inline(always)]
pub fn rf0l(&self) -> RF0L_R {
RF0L_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Rx FIFO 1 New Message"]
#[inline(always)]
pub fn rf1n(&self) -> RF1N_R {
RF1N_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Rx FIFO 1 Watermark Reached"]
#[inline(always)]
pub fn rf1w(&self) -> RF1W_R {
RF1W_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Rx FIFO 1 Watermark Reached"]
#[inline(always)]
pub fn rf1f(&self) -> RF1F_R {
RF1F_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Rx FIFO 1 Message Lost"]
#[inline(always)]
pub fn rf1l(&self) -> RF1L_R {
RF1L_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - High Priority Message"]
#[inline(always)]
pub fn hpm(&self) -> HPM_R {
HPM_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Transmission Completed"]
#[inline(always)]
pub fn tc(&self) -> TC_R {
TC_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Transmission Cancellation Finished"]
#[inline(always)]
pub fn tcf(&self) -> TCF_R {
TCF_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Tx FIFO Empty"]
#[inline(always)]
pub fn tef(&self) -> TEF_R {
TEF_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - Tx Event FIFO New Entry"]
#[inline(always)]
pub fn tefn(&self) -> TEFN_R {
TEFN_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - Tx Event FIFO Watermark Reached"]
#[inline(always)]
pub fn tefw(&self) -> TEFW_R {
TEFW_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - Tx Event FIFO Full"]
#[inline(always)]
pub fn teff(&self) -> TEFF_R {
TEFF_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - Tx Event FIFO Element Lost"]
#[inline(always)]
pub fn tefl(&self) -> TEFL_R {
TEFL_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - Timestamp Wraparound"]
#[inline(always)]
pub fn tsw(&self) -> TSW_R {
TSW_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - Message RAM Access Failure"]
#[inline(always)]
pub fn mraf(&self) -> MRAF_R {
MRAF_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - Timeout Occurred"]
#[inline(always)]
pub fn too(&self) -> TOO_R {
TOO_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - Message stored to Dedicated Rx Buffer"]
#[inline(always)]
pub fn drx(&self) -> DRX_R {
DRX_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 22 - Error Logging Overflow"]
#[inline(always)]
pub fn elo(&self) -> ELO_R {
ELO_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - Error Passive"]
#[inline(always)]
pub fn ep(&self) -> EP_R {
EP_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - Warning Status"]
#[inline(always)]
pub fn ew(&self) -> EW_R {
EW_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Bus_Off Status"]
#[inline(always)]
pub fn bo(&self) -> BO_R {
BO_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - Watchdog Interrupt"]
#[inline(always)]
pub fn wdi(&self) -> WDI_R {
WDI_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - Protocol Error in Arbitration Phase (Nominal Bit Time is used)"]
#[inline(always)]
pub fn pea(&self) -> PEA_R {
PEA_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - Protocol Error in Data Phase (Data Bit Time is used)"]
#[inline(always)]
pub fn ped(&self) -> PED_R {
PED_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - Access to Reserved Address"]
#[inline(always)]
pub fn ara(&self) -> ARA_R {
ARA_R::new(((self.bits >> 29) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Rx FIFO 0 New Message"]
#[inline(always)]
#[must_use]
pub fn rf0n(&mut self) -> RF0N_W<IR_SPEC, 0> {
RF0N_W::new(self)
}
#[doc = "Bit 1 - Rx FIFO 0 Full"]
#[inline(always)]
#[must_use]
pub fn rf0w(&mut self) -> RF0W_W<IR_SPEC, 1> {
RF0W_W::new(self)
}
#[doc = "Bit 2 - Rx FIFO 0 Full"]
#[inline(always)]
#[must_use]
pub fn rf0f(&mut self) -> RF0F_W<IR_SPEC, 2> {
RF0F_W::new(self)
}
#[doc = "Bit 3 - Rx FIFO 0 Message Lost"]
#[inline(always)]
#[must_use]
pub fn rf0l(&mut self) -> RF0L_W<IR_SPEC, 3> {
RF0L_W::new(self)
}
#[doc = "Bit 4 - Rx FIFO 1 New Message"]
#[inline(always)]
#[must_use]
pub fn rf1n(&mut self) -> RF1N_W<IR_SPEC, 4> {
RF1N_W::new(self)
}
#[doc = "Bit 5 - Rx FIFO 1 Watermark Reached"]
#[inline(always)]
#[must_use]
pub fn rf1w(&mut self) -> RF1W_W<IR_SPEC, 5> {
RF1W_W::new(self)
}
#[doc = "Bit 6 - Rx FIFO 1 Watermark Reached"]
#[inline(always)]
#[must_use]
pub fn rf1f(&mut self) -> RF1F_W<IR_SPEC, 6> {
RF1F_W::new(self)
}
#[doc = "Bit 7 - Rx FIFO 1 Message Lost"]
#[inline(always)]
#[must_use]
pub fn rf1l(&mut self) -> RF1L_W<IR_SPEC, 7> {
RF1L_W::new(self)
}
#[doc = "Bit 8 - High Priority Message"]
#[inline(always)]
#[must_use]
pub fn hpm(&mut self) -> HPM_W<IR_SPEC, 8> {
HPM_W::new(self)
}
#[doc = "Bit 9 - Transmission Completed"]
#[inline(always)]
#[must_use]
pub fn tc(&mut self) -> TC_W<IR_SPEC, 9> {
TC_W::new(self)
}
#[doc = "Bit 10 - Transmission Cancellation Finished"]
#[inline(always)]
#[must_use]
pub fn tcf(&mut self) -> TCF_W<IR_SPEC, 10> {
TCF_W::new(self)
}
#[doc = "Bit 11 - Tx FIFO Empty"]
#[inline(always)]
#[must_use]
pub fn tef(&mut self) -> TEF_W<IR_SPEC, 11> {
TEF_W::new(self)
}
#[doc = "Bit 12 - Tx Event FIFO New Entry"]
#[inline(always)]
#[must_use]
pub fn tefn(&mut self) -> TEFN_W<IR_SPEC, 12> {
TEFN_W::new(self)
}
#[doc = "Bit 13 - Tx Event FIFO Watermark Reached"]
#[inline(always)]
#[must_use]
pub fn tefw(&mut self) -> TEFW_W<IR_SPEC, 13> {
TEFW_W::new(self)
}
#[doc = "Bit 14 - Tx Event FIFO Full"]
#[inline(always)]
#[must_use]
pub fn teff(&mut self) -> TEFF_W<IR_SPEC, 14> {
TEFF_W::new(self)
}
#[doc = "Bit 15 - Tx Event FIFO Element Lost"]
#[inline(always)]
#[must_use]
pub fn tefl(&mut self) -> TEFL_W<IR_SPEC, 15> {
TEFL_W::new(self)
}
#[doc = "Bit 16 - Timestamp Wraparound"]
#[inline(always)]
#[must_use]
pub fn tsw(&mut self) -> TSW_W<IR_SPEC, 16> {
TSW_W::new(self)
}
#[doc = "Bit 17 - Message RAM Access Failure"]
#[inline(always)]
#[must_use]
pub fn mraf(&mut self) -> MRAF_W<IR_SPEC, 17> {
MRAF_W::new(self)
}
#[doc = "Bit 18 - Timeout Occurred"]
#[inline(always)]
#[must_use]
pub fn too(&mut self) -> TOO_W<IR_SPEC, 18> {
TOO_W::new(self)
}
#[doc = "Bit 19 - Message stored to Dedicated Rx Buffer"]
#[inline(always)]
#[must_use]
pub fn drx(&mut self) -> DRX_W<IR_SPEC, 19> {
DRX_W::new(self)
}
#[doc = "Bit 22 - Error Logging Overflow"]
#[inline(always)]
#[must_use]
pub fn elo(&mut self) -> ELO_W<IR_SPEC, 22> {
ELO_W::new(self)
}
#[doc = "Bit 23 - Error Passive"]
#[inline(always)]
#[must_use]
pub fn ep(&mut self) -> EP_W<IR_SPEC, 23> {
EP_W::new(self)
}
#[doc = "Bit 24 - Warning Status"]
#[inline(always)]
#[must_use]
pub fn ew(&mut self) -> EW_W<IR_SPEC, 24> {
EW_W::new(self)
}
#[doc = "Bit 25 - Bus_Off Status"]
#[inline(always)]
#[must_use]
pub fn bo(&mut self) -> BO_W<IR_SPEC, 25> {
BO_W::new(self)
}
#[doc = "Bit 26 - Watchdog Interrupt"]
#[inline(always)]
#[must_use]
pub fn wdi(&mut self) -> WDI_W<IR_SPEC, 26> {
WDI_W::new(self)
}
#[doc = "Bit 27 - Protocol Error in Arbitration Phase (Nominal Bit Time is used)"]
#[inline(always)]
#[must_use]
pub fn pea(&mut self) -> PEA_W<IR_SPEC, 27> {
PEA_W::new(self)
}
#[doc = "Bit 28 - Protocol Error in Data Phase (Data Bit Time is used)"]
#[inline(always)]
#[must_use]
pub fn ped(&mut self) -> PED_W<IR_SPEC, 28> {
PED_W::new(self)
}
#[doc = "Bit 29 - Access to Reserved Address"]
#[inline(always)]
#[must_use]
pub fn ara(&mut self) -> ARA_W<IR_SPEC, 29> {
ARA_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "FDCAN Interrupt Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ir::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 [`ir::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IR_SPEC;
impl crate::RegisterSpec for IR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ir::R`](R) reader structure"]
impl crate::Readable for IR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ir::W`](W) writer structure"]
impl crate::Writable for IR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets IR to value 0"]
impl crate::Resettable for IR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::collections::HashMap;
use std::marker::PhantomData;
use analyser::interface::*;
use ndarray::prelude::*;
use ops::prelude::*;
use tensor::Datum;
use Result;
pub fn build(pb: &::tfpb::node_def::NodeDef) -> Result<Box<Op>> {
let begin_mask = pb.get_attr_opt_int("begin_mask")?.unwrap_or(0);
let end_mask = pb.get_attr_opt_int("end_mask")?.unwrap_or(0);
let shrink_axis_mask = pb.get_attr_opt_int("shrink_axis_mask")?.unwrap_or(0);
let datatype = pb.get_attr_datatype("T")?;
Ok(boxed_new!(StridedSlice(datatype)(
begin_mask,
end_mask,
shrink_axis_mask
)))
}
#[derive(Debug, Default, Clone, new)]
pub struct StridedSlice<T: Datum> {
begin_mask: i64,
end_mask: i64,
shrink_axis_mask: i64,
_phantom: PhantomData<T>,
}
#[derive(Debug)]
struct Dim {
begin: i32,
stride: i32,
len: usize,
shrink: bool,
}
impl<T: Datum> StridedSlice<T> {
fn must_shrink(&self, ix: usize) -> bool {
self.shrink_axis_mask & 1 << ix != 0
}
fn prepare_one_dim(
&self,
ix: usize,
dim: usize,
begin: &ArrayView1<i32>,
end: &ArrayView1<i32>,
strides: &ArrayView1<i32>,
) -> Dim {
let dim = dim as i32;
// deal with too small dim begin/end/stride for input rank
if ix >= begin.len() {
return Dim {
begin: 0,
stride: 1,
len: dim as usize,
shrink: false,
};
}
// deal with negative indexing
let b = if begin[ix] >= 0 {
begin[ix]
} else {
dim + begin[ix]
};
let e = if end[ix] >= 0 { end[ix] } else { dim + end[ix] };
// deal with shrinking
if self.must_shrink(ix) {
return Dim {
begin: b,
stride: 1,
len: 1,
shrink: true,
};
}
// deal with begin and end masks
let s = strides[ix];
let b = if (self.begin_mask >> ix) & 1 == 1 {
if s.signum() > 0 {
0
} else {
dim - 1
}
} else {
b
};
let e = if (self.end_mask >> ix) & 1 == 1 {
if s.signum() < 0 {
-1
} else {
dim
}
} else {
e
};
let len = (((s.abs() as i32 - 1) + (e - b).abs()) / s.abs()) as usize;
Dim {
begin: b,
stride: s,
len,
shrink: false,
}
}
fn prepare(
&self,
input_shape: &[usize],
begin: &ArrayView1<i32>,
end: &ArrayView1<i32>,
strides: &ArrayView1<i32>,
) -> (Vec<Dim>, Vec<usize>, Vec<usize>) {
trace!(
"StridedSlice {:?} computing shapes: input_shape:{:?} begin:{:?} end:{:?} strides:{:?}",
self,
input_shape,
begin,
end,
strides
);
let bounds: Vec<Dim> = (0..input_shape.len())
.map(|ix| self.prepare_one_dim(ix, input_shape[ix], begin, end, strides))
.collect();
let mid_shape: Vec<usize> = bounds.iter().map(|d| d.len).collect();
let end_shape: Vec<usize> = bounds.iter().filter(|d| !d.shrink).map(|d| d.len).collect();
(bounds, mid_shape, end_shape)
}
}
impl<T: Datum> Op for StridedSlice<T> {
/// Evaluates the operation given the input tensors.
fn eval(&self, mut inputs: Vec<TensorView>) -> Result<Vec<TensorView>> {
let (input, begin, end, strides) = args_4!(inputs);
let input = T::tensor_to_view(&input)?;
let begin = begin.as_i32s().ok_or("Begin expected as I32")?;
let end = end.as_i32s().ok_or("End expected as I32")?;
let strides = strides.as_i32s().ok_or("Strides expected as I32")?;
let (bounds, mid_shape, end_shape) = self.prepare(
input.shape(),
&begin.view().into_dimensionality()?,
&end.view().into_dimensionality()?,
&strides.view().into_dimensionality()?,
);
let output = Array::from_shape_fn(mid_shape, |coords| {
let coord: Vec<_> = coords
.slice()
.iter()
.enumerate()
.map(|(d, i)| (*i as i32 * bounds[d].stride + bounds[d].begin) as usize)
.collect();
input[&*coord]
});
let output = output.into_shape(end_shape)?;
Ok(vec![T::array_into_tensor(output.into()).into()])
}
/// Returns the attributes of the operation and their values.
fn get_attributes(&self) -> HashMap<&'static str, Attr> {
hashmap!{
"begin_mask" => Attr::I64(self.begin_mask),
"end_mask" => Attr::I64(self.end_mask),
"shrink_axis_mask" => Attr::I64(self.shrink_axis_mask),
}
}
}
impl<T: Datum> InferenceRulesOp for StridedSlice<T> {
fn rules<'r, 'p: 'r, 's: 'r>(
&'s self,
solver: &mut Solver<'r>,
inputs: &'p TensorsProxy,
outputs: &'p TensorsProxy,
) {
solver
.equals(&inputs.len, 4)
.equals(&outputs.len, 1)
.equals(&inputs[1].datatype, DataType::I32)
.equals(&inputs[2].datatype, DataType::I32)
.equals(&inputs[3].datatype, DataType::I32)
.equals(&inputs[0].datatype, &outputs[0].datatype)
.equals(&inputs[1].rank, 1)
.equals(&inputs[2].rank, 1)
.equals(&inputs[3].rank, 1)
.given(&inputs[0].shape, move |solver, input_shape: ShapeFact| {
solver.given(&inputs[1].value, move |solver, begin: Tensor| {
let input_shape = input_shape.clone();
solver.given(&inputs[2].value, move |solver, end: Tensor| {
let input_shape = input_shape.clone();
let begin = begin.clone();
solver.given(&inputs[3].value, move |solver, stride: Tensor| {
let begin = begin
.as_i32s()
.unwrap()
.view()
.into_dimensionality()
.unwrap();
let end = end.as_i32s().unwrap().view().into_dimensionality().unwrap();
let stride = stride
.as_i32s()
.unwrap()
.view()
.into_dimensionality()
.unwrap();
let dims: Vec<IntFact> = input_shape
.dims
.iter()
.enumerate()
.filter_map(|(ix, d)| {
if self.must_shrink(ix) {
None
} else {
match d {
DimFact::Only(d) => Some(IntFact::Only(
self.prepare_one_dim(ix, *d, &begin, &end, &stride)
.len
as _,
)),
DimFact::Streamed => {
Some(IntFact::Special(SpecialKind::Streamed))
}
DimFact::Any => Some(IntFact::Any),
}
}
})
.collect();
solver.equals(&outputs[0].rank, dims.len() as isize);
for (ix, d) in dims.iter().enumerate() {
solver.equals(&outputs[0].shape[ix], *d);
}
});
});
});
});
}
}
#[cfg(test)]
mod tests {
#![allow(non_snake_case)]
use super::*;
use ndarray::*;
use Tensor;
fn eval<I, B, E, S>(op: StridedSlice<i32>, input: I, begin: B, end: E, strides: S) -> Tensor
where
I: Into<Tensor>,
B: Into<Tensor>,
E: Into<Tensor>,
S: Into<Tensor>,
{
op.eval(vec![
input.into().into(),
begin.into().into(),
end.into().into(),
strides.into().into(),
]).unwrap()
.pop()
.unwrap()
.into_tensor()
}
// https://www.tensorflow.org/api_docs/python/tf/strided_slice
#[test]
fn eval_1() {
assert_eq!(
eval(
StridedSlice::default(),
arr3(&[
[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]],
]),
arr1(&[1, 0, 0]),
arr1(&[2, 1, 3]),
arr1(&[1, 1, 1])
),
Tensor::from(arr3(&[[[3, 3, 3]]])),
);
}
#[test]
fn eval_2() {
assert_eq!(
eval(
StridedSlice::default(),
arr3(&[
[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]],
]),
arr1(&[1, 0, 0]),
arr1(&[2, 2, 3]),
arr1(&[1, 1, 1])
),
Tensor::from(arr3(&[[[3, 3, 3], [4, 4, 4]]])),
);
}
#[test]
fn eval_3() {
assert_eq!(
eval(
StridedSlice::default(),
arr3(&[
[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]],
]),
arr1(&[1, -1, 0]),
arr1(&[2, -3, 3]),
arr1(&[1, -1, 1])
),
Tensor::from(arr3(&[[[4, 4, 4], [3, 3, 3]]])),
);
}
#[test]
fn eval_4() {
assert_eq!(
eval(
StridedSlice::default(),
arr3(&[
[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]],
]),
arr1(&[1, 0, 0]),
arr1(&[2, 2, 4]),
arr1(&[1, 1, 2])
),
Tensor::from(arr3(&[[[3, 3], [4, 4]]])),
);
}
#[test]
fn eval_5() {
assert_eq!(
eval(
StridedSlice::default(),
arr1(&[0, 0]),
arr1(&[0]),
arr1(&[-1]),
arr1(&[1])
),
Tensor::from(arr1(&[0]))
)
}
#[test]
fn eval_6() {
assert_eq!(
eval(
StridedSlice::default(),
arr2(&[[1, 0, 0, 0], [3, 0, 0, 0], [0, 0, 0, 0]]),
arr1(&[-3, -4]),
arr1(&[-1, -1]),
arr1(&[1, 2])
),
Tensor::from(arr2(&[[1, 0], [3, 0]]))
)
}
#[test]
fn eval_7() {
assert_eq!(
eval(
StridedSlice::default(),
arr2(&[[0, 6], [0, 0]]),
arr1(&[0]),
arr1(&[2]),
arr1(&[1])
),
Tensor::from(arr2(&[[0, 6], [0, 0]]))
)
}
#[test]
fn eval_begin_mask_1() {
let mut op = StridedSlice::default();
op.begin_mask = 1;
assert_eq!(
eval(op, arr1(&[0, 1]), arr1(&[1]), arr1(&[1]), arr1(&[1])),
Tensor::from(arr1(&[0]))
)
}
#[test]
fn eval_shrink_1() {
let mut op = StridedSlice::default();
op.shrink_axis_mask = 1;
assert_eq!(
eval(
op,
arr2(&[[0]]),
arr1(&[0, 0]),
arr1(&[0, 0]),
arr1(&[1, 1])
),
Tensor::I32(arr1(&[]).into_dyn())
)
}
}
|
use super::*;
pub(crate) fn echo_command(ctx: &Context) -> CommandResult {
for part in ctx.parts {
let output = Output::new().add(*part).build();
ctx.status(output);
}
Ok(Response::Nothing)
}
|
// https://beta.atcoder.jp/contests/abc002/tasks/abc002_4
macro_rules! scan {
($t:ty) => {
{
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim().parse::<$t>().unwrap()
}
};
($($t:ty),*) => {
{
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let mut iter = line.split_whitespace();
(
$(iter.next().unwrap().parse::<$t>().unwrap(),)*
)
}
};
($t:ty; $n:expr) => {
(0..$n).map(|_|
scan!($t)
).collect::<Vec<_>>()
};
($($t:ty),*; $n:expr) => {
(0..$n).map(|_|
scan!($($t),*)
).collect::<Vec<_>>()
};
($t:ty ;;) => {
{
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.split_whitespace()
.map(|t| t.parse::<$t>().unwrap())
.collect::<Vec<_>>()
}
};
($t:ty ;; $n:expr) => {
(0..$n).map(|_| scan!($t ;;)).collect::<Vec<_>>()
};
}
fn main() {
let (n, m) = scan!(usize, usize);
let mut g: Vec<u32> = Vec::new();
for i in 0..n {
g.push(1 << i);
}
for _i in 0..m {
let (x, y) = scan!(usize, usize);
g[x - 1] |= 1 << (y - 1);
g[y - 1] |= 1 << (x - 1);
}
let mut max = 1;
for i in 0..(1 << n) {
let mut found = true;
let mut cnt = 0;
for j in 0..n {
if i & (1 << j) != 0 {
if (i & g[j]) != i {
found = false;
break;
}
cnt += 1;
}
}
if found {
max = std::cmp::max(max, cnt);
}
}
println!("{}", max);
}
|
#![no_std]
#![no_main]
use ruduino::Pin;
use ruduino::cores::current::{port};
#[no_mangle]
pub extern fn main() {
port::B5::set_output();
loop {
port::B5::set_high();
ruduino::delay::delay_ms(1000);
port::B5::set_low();
ruduino::delay::delay_ms(1000);
}
}
|
use anyhow::{anyhow, Result};
use druid::Vec2;
use druid::{
piet::{PietText, Text, TextAttribute, TextLayoutBuilder},
Color, Command, EventCtx, ExtEventSink, Target, UpdateCtx, WidgetId, WindowId,
};
use druid::{Env, PaintCtx};
use git2::Repository;
use language::{new_highlight_config, new_parser, LapceLanguage};
use lsp_types::SemanticTokens;
use lsp_types::SemanticTokensLegend;
use lsp_types::SemanticTokensServerCapabilities;
use lsp_types::{
CodeActionResponse, Position, Range, TextDocumentContentChangeEvent,
};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::{
borrow::Cow,
ffi::OsString,
io::{self, Read, Write},
path::{Path, PathBuf},
sync::Arc,
thread,
};
use std::{collections::HashMap, fs::File};
use std::{fs, str::FromStr};
use tree_sitter::{Parser, Tree};
use tree_sitter_highlight::{
Highlight, HighlightConfiguration, HighlightEvent, Highlighter,
};
use xi_core_lib::selection::InsertDrift;
use xi_rope::{
interval::IntervalBounds, rope::Rope, Cursor, Delta, DeltaBuilder, Interval,
LinesMetric, RopeDelta, RopeInfo, Transformer,
};
use crate::{
command::LapceUICommand,
command::LAPCE_UI_COMMAND,
editor::EditorOperator,
editor::HighlightTextLayout,
find::Find,
language,
movement::{ColPosition, Movement, SelRegion, Selection},
state::LapceTabState,
state::LapceWorkspaceType,
state::Mode,
state::LAPCE_APP_STATE,
theme::LapceTheme,
};
#[derive(Debug, Clone)]
pub struct InvalLines {
pub start_line: usize,
pub inval_count: usize,
pub new_count: usize,
}
#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug, Serialize, Deserialize)]
pub struct BufferId(pub usize);
#[derive(Clone)]
pub struct BufferUIState {
window_id: WindowId,
tab_id: WidgetId,
pub id: BufferId,
pub text_layouts: Vec<Arc<Option<HighlightTextLayout>>>,
pub line_changes: HashMap<usize, char>,
pub max_len_line: usize,
pub max_len: usize,
pub dirty: bool,
}
pub struct Buffer {
window_id: WindowId,
tab_id: WidgetId,
pub id: BufferId,
pub rope: Rope,
highlight_config: Arc<HighlightConfiguration>,
highlight_names: Vec<String>,
pub semantic_tokens: Option<Vec<(usize, usize, String)>>,
pub highlights: Vec<(usize, usize, Highlight)>,
pub line_highlights: HashMap<usize, Vec<(usize, usize, String)>>,
undos: Vec<Vec<(RopeDelta, RopeDelta)>>,
current_undo: usize,
pub path: String,
pub language_id: String,
pub rev: u64,
pub dirty: bool,
pub code_actions: HashMap<usize, CodeActionResponse>,
sender: Sender<(WindowId, WidgetId, BufferId, u64)>,
pub diff: Vec<DiffHunk>,
pub line_changes: HashMap<usize, char>,
pub view_offset: Vec2,
pub offset: usize,
pub tree: Option<Tree>,
}
impl Buffer {
pub fn new(
window_id: WindowId,
tab_id: WidgetId,
buffer_id: BufferId,
path: &str,
event_sink: ExtEventSink,
sender: Sender<(WindowId, WidgetId, BufferId, u64)>,
) -> Buffer {
let state = LAPCE_APP_STATE.get_tab_state(&window_id, &tab_id);
let content = state
.proxy
.lock()
.as_ref()
.unwrap()
.new_buffer(buffer_id, PathBuf::from(path.to_string()))
.unwrap();
let rope = Rope::from_str(&content).unwrap();
// let rope = if let Ok(rope) = load_file(&window_id, &tab_id, path) {
// rope
// } else {
// Rope::from("")
// };
let mut parser = new_parser(LapceLanguage::Rust);
let tree = parser.parse(&rope.to_string(), None).unwrap();
let (highlight_config, highlight_names) =
new_highlight_config(LapceLanguage::Rust);
let path_buf = PathBuf::from_str(path).unwrap();
path_buf.extension().unwrap().to_str().unwrap().to_string();
let mut buffer = Buffer {
window_id: window_id.clone(),
tab_id: tab_id.clone(),
id: buffer_id.clone(),
rope,
highlight_config: Arc::new(highlight_config),
semantic_tokens: None,
highlight_names,
highlights: Vec::new(),
line_highlights: HashMap::new(),
undos: Vec::new(),
current_undo: 0,
code_actions: HashMap::new(),
rev: 0,
dirty: false,
language_id: language_id_from_path(path).unwrap_or("").to_string(),
path: path.to_string(),
diff: Vec::new(),
line_changes: HashMap::new(),
view_offset: Vec2::ZERO,
offset: 0,
tree: None,
sender,
};
let language_id = buffer.language_id.clone();
// state.plugins.lock().new_buffer(&PluginBufferInfo {
// buffer_id: buffer_id.clone(),
// language_id: buffer.language_id.clone(),
// path: path.to_string(),
// nb_lines: buffer.num_lines(),
// buf_size: buffer.len(),
// rev: buffer.rev,
// });
// state.lsp.lock().new_buffer(
// &buffer_id,
// path,
// &buffer.language_id,
// buffer.rope.to_string(),
// );
buffer.update_highlights();
buffer
}
pub fn len(&self) -> usize {
self.rope.len()
}
pub fn highlights_apply_delta(&mut self, delta: &RopeDelta) {
let mut transformer = Transformer::new(delta);
if let Some(semantic_tokens) = self.semantic_tokens.as_mut() {
self.semantic_tokens = Some(
semantic_tokens
.iter()
.map(|h| {
(
transformer.transform(h.0, true),
transformer.transform(h.1, true),
h.2.clone(),
)
})
.collect(),
)
} else {
self.highlights = self
.highlights
.iter()
.map(|h| {
(
transformer.transform(h.0, true),
transformer.transform(h.1, true),
h.2.clone(),
)
})
.collect()
}
}
fn format_semantic_tokens(
&self,
semantic_tokens_provider: Option<SemanticTokensServerCapabilities>,
value: Value,
) -> Option<Vec<(usize, usize, String)>> {
let semantic_tokens: SemanticTokens = serde_json::from_value(value).ok()?;
let semantic_tokens_provider = semantic_tokens_provider.as_ref()?;
let semantic_lengends = semantic_tokens_lengend(semantic_tokens_provider);
let mut highlights = Vec::new();
let mut line = 0;
let mut start = 0;
for semantic_token in &semantic_tokens.data {
if semantic_token.delta_line > 0 {
line += semantic_token.delta_line as usize;
start = self.offset_of_line(line);
}
start += semantic_token.delta_start as usize;
let end = start + semantic_token.length as usize;
let kind = semantic_lengends.token_types
[semantic_token.token_type as usize]
.as_str()
.to_string();
highlights.push((start, end, kind));
}
Some(highlights)
}
pub fn set_semantic_tokens(
&mut self,
semantic_tokens_provider: Option<SemanticTokensServerCapabilities>,
value: Value,
) -> Option<()> {
let semantic_tokens =
self.format_semantic_tokens(semantic_tokens_provider, value)?;
self.semantic_tokens = Some(semantic_tokens);
self.line_highlights = HashMap::new();
let window_id = self.window_id;
let tab_id = self.tab_id;
let buffer_id = self.id;
thread::spawn(move || {
let state = LAPCE_APP_STATE.get_tab_state(&window_id, &tab_id);
for (view_id, editor) in state.editor_split.lock().editors.iter() {
if editor.buffer_id.as_ref() == Some(&buffer_id) {
LAPCE_APP_STATE.submit_ui_command(
LapceUICommand::FillTextLayouts,
view_id.clone(),
);
}
}
});
None
}
pub fn update_highlights(&mut self) {
self.line_highlights = HashMap::new();
self.sender
.send((self.window_id, self.tab_id, self.id, self.rev));
let state = LAPCE_APP_STATE.get_tab_state(&self.window_id, &self.tab_id);
// state.lsp.lock().get_semantic_tokens(&self);
}
pub fn get_line_highligh(
&mut self,
line: usize,
) -> &Vec<(usize, usize, String)> {
if self.line_highlights.get(&line).is_none() {
let mut line_highlight = Vec::new();
if let Some(semantic_tokens) = self.semantic_tokens.as_ref() {
let start_offset = self.offset_of_line(line);
let end_offset = self.offset_of_line(line + 1) - 1;
for (start, end, hl) in semantic_tokens {
if *start > end_offset {
break;
}
if *start >= start_offset && *start <= end_offset {
let end = if *end > end_offset {
end_offset - start_offset
} else {
end - start_offset
};
line_highlight.push((start - start_offset, end, hl.clone()));
}
}
} else {
let start_offset = self.offset_of_line(line);
let end_offset = self.offset_of_line(line + 1) - 1;
for (start, end, hl) in &self.highlights {
if *start > end_offset {
break;
}
if *start >= start_offset && *start <= end_offset {
let end = if *end > end_offset {
end_offset - start_offset
} else {
end - start_offset
};
line_highlight.push((
start - start_offset,
end,
self.highlight_names[hl.0].to_string(),
));
}
}
}
self.line_highlights.insert(line, line_highlight);
}
self.line_highlights.get(&line).unwrap()
}
pub fn correct_offset(&self, selection: &Selection) -> Selection {
let mut result = Selection::new();
for region in selection.regions() {
let (line, col) = self.offset_to_line_col(region.start());
let max_col = self.line_max_col(line, false);
let (start, col) = if col > max_col {
(self.offset_of_line(line) + max_col, max_col)
} else {
(region.start(), col)
};
let (line, col) = self.offset_to_line_col(region.start());
let max_col = self.line_max_col(line, false);
let end = if col > max_col {
self.offset_of_line(line) + max_col
} else {
region.end()
};
let new_region =
SelRegion::new(start, end, region.horiz().map(|h| h.clone()));
result.add_region(new_region);
}
result
}
pub fn fill_horiz(&self, selection: &Selection) -> Selection {
let mut result = Selection::new();
for region in selection.regions() {
let new_region = if region.horiz().is_some() {
region.clone()
} else {
let (_, col) = self.offset_to_line_col(region.min());
SelRegion::new(
region.start(),
region.end(),
Some(ColPosition::Col(col)),
)
};
result.add_region(new_region);
}
result
}
fn update_size(
&mut self,
ui_state: &mut BufferUIState,
inval_lines: &InvalLines,
) {
if ui_state.max_len_line >= inval_lines.start_line
&& ui_state.max_len_line
< inval_lines.start_line + inval_lines.inval_count
{
let (max_len, max_len_line) = self.get_max_line_len();
ui_state.max_len = max_len;
ui_state.max_len_line = max_len_line;
} else {
let mut max_len = 0;
let mut max_len_line = 0;
for line in inval_lines.start_line
..inval_lines.start_line + inval_lines.new_count
{
let line_len = self.line_len(line);
if line_len > max_len {
max_len = line_len;
max_len_line = line;
}
}
if max_len > ui_state.max_len {
ui_state.max_len = max_len;
ui_state.max_len_line = max_len_line;
} else if ui_state.max_len >= inval_lines.start_line {
ui_state.max_len_line = ui_state.max_len_line
+ inval_lines.new_count
- inval_lines.inval_count;
}
}
}
fn inv_delta(&self, delta: &RopeDelta) -> RopeDelta {
let (ins, del) = delta.clone().factor();
let del_rope = del.complement().delete_from(&self.rope);
let ins = ins.inserted_subset();
let del = del.transform_expand(&ins);
Delta::synthesize(&del_rope, &del, &ins)
}
fn add_undo(&mut self, delta: &RopeDelta, new_undo_group: bool) {
let inv_delta = self.inv_delta(delta);
if new_undo_group {
self.undos.truncate(self.current_undo);
self.undos.push(vec![(delta.clone(), inv_delta)]);
self.current_undo += 1;
} else {
if self.undos.is_empty() {
self.undos.push(Vec::new());
self.current_undo += 1;
}
// let mut undos = &self.undos[self.current_undo - 1];
// let last_undo = &undos[undos.len() - 1];
// last_undo.0.is_identity();
self.undos[self.current_undo - 1].push((delta.clone(), inv_delta));
}
}
pub fn redo(
&mut self,
ctx: &mut EventCtx,
ui_state: &mut BufferUIState,
) -> Option<usize> {
if self.current_undo >= self.undos.len() {
return None;
}
let deltas = self.undos[self.current_undo].clone();
self.current_undo += 1;
for (delta, __) in deltas.iter() {
self.apply_delta(ctx, ui_state, &delta);
}
self.update_highlights();
Some(deltas[0].1.summary().0.start())
}
pub fn undo(
&mut self,
ctx: &mut EventCtx,
ui_state: &mut BufferUIState,
) -> Option<usize> {
if self.current_undo < 1 {
return None;
}
self.current_undo -= 1;
let deltas = self.undos[self.current_undo].clone();
for (_, delta) in deltas.iter().rev() {
self.apply_delta(ctx, ui_state, &delta);
}
self.update_highlights();
Some(deltas[0].1.summary().0.start())
}
fn apply_delta(
&mut self,
ctx: &mut EventCtx,
ui_state: &mut BufferUIState,
delta: &RopeDelta,
) {
self.rev += 1;
self.dirty = true;
self.tree = None;
ui_state.dirty = true;
let (iv, newlen) = delta.summary();
let old_logical_end_line = self.rope.line_of_offset(iv.end) + 1;
let old_logical_end_offset = self.rope.offset_of_line(old_logical_end_line);
let content_change = get_document_content_changes(delta, self);
self.rope = delta.apply(&self.rope);
let content_change = match content_change {
Some(content_change) => content_change,
None => TextDocumentContentChangeEvent {
range: None,
range_length: None,
text: self.get_document(),
},
};
let state = LAPCE_APP_STATE.get_tab_state(&self.window_id, &self.tab_id);
// state.plugins.lock().update(
// &self.id,
// delta,
// self.len(),
// self.num_lines(),
// self.rev,
// );
// state.lsp.lock().update(&self, &content_change, self.rev);
state
.proxy
.lock()
.as_ref()
.unwrap()
.update(self.id, delta, self.rev);
let logical_start_line = self.rope.line_of_offset(iv.start);
let new_logical_end_line = self.rope.line_of_offset(iv.start + newlen) + 1;
let old_hard_count = old_logical_end_line - logical_start_line;
let new_hard_count = new_logical_end_line - logical_start_line;
let inval_lines = InvalLines {
start_line: logical_start_line,
inval_count: old_hard_count,
new_count: new_hard_count,
};
self.code_actions = HashMap::new();
self.highlights_apply_delta(delta);
self.update_size(ui_state, &inval_lines);
ui_state.update_text_layouts(&inval_lines);
}
pub fn yank(&self, selection: &Selection) -> Vec<String> {
selection
.regions()
.iter()
.map(|region| {
self.rope
.slice_to_cow(region.min()..region.max())
.to_string()
})
.collect()
}
pub fn do_move(
&mut self,
ctx: &mut EventCtx,
ui_state: &mut BufferUIState,
mode: &Mode,
movement: &Movement,
selection: &Selection,
operator: Option<EditorOperator>,
count: Option<usize>,
) -> Selection {
if let Some(operator) = operator {
let selection = movement.update_selection(
selection,
&self,
count.unwrap_or(1),
true,
true,
);
let mut new_selection = Selection::new();
for region in selection.regions() {
let start_line = self.line_of_offset(region.min());
let end_line = self.line_of_offset(region.max());
let new_region = if movement.is_vertical() {
let region = SelRegion::new(
self.offset_of_line(start_line),
self.offset_of_line(end_line + 1),
Some(ColPosition::Col(0)),
);
region
} else {
if movement.is_inclusive() {
SelRegion::new(
region.min(),
region.max() + 1,
region.horiz().map(|h| h.clone()),
)
} else {
region.clone()
}
};
new_selection.add_region(new_region);
}
match operator {
EditorOperator::Delete(_) => {
let delta = self.edit(ctx, ui_state, "", &new_selection, true);
new_selection.apply_delta(&delta, true, InsertDrift::Default)
}
EditorOperator::Yank(_) => new_selection,
}
} else {
movement.update_selection(
&selection,
&self,
count.unwrap_or(1),
mode == &Mode::Insert,
mode == &Mode::Visual,
)
}
}
pub fn edit_multiple(
&mut self,
ctx: &mut EventCtx,
ui_state: &mut BufferUIState,
edits: Vec<(&Selection, &str)>,
new_undo_group: bool,
) -> RopeDelta {
let mut builder = DeltaBuilder::new(self.len());
for (selection, content) in edits {
let rope = Rope::from(content);
for region in selection.regions() {
builder.replace(region.min()..region.max(), rope.clone());
}
}
let delta = builder.build();
self.add_undo(&delta, new_undo_group);
self.apply_delta(ctx, ui_state, &delta);
self.update_highlights();
delta
}
pub fn edit(
&mut self,
ctx: &mut EventCtx,
ui_state: &mut BufferUIState,
content: &str,
selection: &Selection,
new_undo_group: bool,
) -> RopeDelta {
self.edit_multiple(ctx, ui_state, vec![(selection, content)], new_undo_group)
}
pub fn indent_on_line(&self, line: usize) -> String {
let line_start_offset = self.rope.offset_of_line(line);
let word_boundary =
WordCursor::new(&self.rope, line_start_offset).next_non_blank_char();
let indent = self.rope.slice_to_cow(line_start_offset..word_boundary);
indent.to_string()
}
pub fn line_of_offset(&self, offset: usize) -> usize {
let max = self.len();
let offset = if offset > max { max } else { offset };
self.rope.line_of_offset(offset)
}
pub fn offset_of_line(&self, line: usize) -> usize {
self.rope.offset_of_line(line)
}
pub fn offset_to_line_col(&self, offset: usize) -> (usize, usize) {
let max = self.len();
let offset = if offset > max { max } else { offset };
let line = self.line_of_offset(offset);
(line, offset - self.offset_of_line(line))
}
pub fn offset_to_position(&self, offset: usize) -> Position {
let max = self.len();
let offset = if offset > max { max } else { offset };
let (line, col) = self.offset_to_line_col(offset);
Position {
line: line as u64,
character: col as u64,
}
}
pub fn offset_of_position(&self, position: &Position) -> Option<usize> {
let line = position.line as usize;
if line > self.num_lines() {
return None;
}
let offset = self.offset_of_line(line) + position.character as usize;
if offset > self.len() {
return None;
}
Some(offset)
}
pub fn num_lines(&self) -> usize {
self.line_of_offset(self.rope.len()) + 1
}
pub fn line_len(&self, line: usize) -> usize {
self.offset_of_line(line + 1) - self.offset_of_line(line)
}
pub fn get_max_line_len(&self) -> (usize, usize) {
let mut pre_offset = 0;
let mut max_len = 0;
let mut max_len_line = 0;
for line in 0..self.num_lines() {
let offset = self.rope.offset_of_line(line);
let line_len = offset - pre_offset;
pre_offset = offset;
if line_len > max_len {
max_len = line_len;
max_len_line = line;
}
}
(max_len, max_len_line)
}
pub fn last_line(&self) -> usize {
self.line_of_offset(self.rope.len())
}
pub fn line_max_col(&self, line: usize, include_newline: bool) -> usize {
match self.offset_of_line(line + 1) - self.offset_of_line(line) {
n if n == 0 => 0,
n if n == 1 => 0,
n => match include_newline {
true => n - 1,
false => n - 2,
},
}
}
pub fn line_horiz_col(
&self,
line: usize,
horiz: &ColPosition,
include_newline: bool,
) -> usize {
let max_col = self.line_max_col(line, include_newline);
match horiz {
&ColPosition::Col(n) => match max_col > n {
true => n,
false => max_col,
},
&ColPosition::End => max_col,
_ => 0,
}
}
pub fn line_end(&self, line: usize, include_newline: bool) -> usize {
let line_start_offset = self.offset_of_line(line);
let line_end_offset = self.offset_of_line(line + 1);
let line_end_offset = if line_end_offset - line_start_offset <= 1 {
line_start_offset
} else {
if include_newline {
line_end_offset - 1
} else {
line_end_offset - 2
}
};
line_end_offset
}
pub fn line_end_offset(&self, offset: usize, include_newline: bool) -> usize {
let line = self.line_of_offset(offset);
self.line_end(line, include_newline)
}
pub fn char_at_offset(&self, offset: usize) -> Option<char> {
WordCursor::new(&self.rope, offset)
.inner
.peek_next_codepoint()
}
pub fn first_non_blank_character_on_line(&self, line: usize) -> usize {
let line_start_offset = self.rope.offset_of_line(line);
WordCursor::new(&self.rope, line_start_offset).next_non_blank_char()
}
pub fn word_forward(&self, offset: usize) -> usize {
WordCursor::new(&self.rope, offset).next_boundary().unwrap()
}
pub fn word_end_forward(&self, offset: usize) -> usize {
WordCursor::new(&self.rope, offset).end_boundary().unwrap()
}
pub fn word_backword(&self, offset: usize) -> usize {
WordCursor::new(&self.rope, offset).prev_boundary().unwrap()
}
pub fn match_pairs(&self, offset: usize) -> Option<usize> {
WordCursor::new(&self.rope, offset).match_pairs()
}
pub fn previous_unmmatched(&self, offset: usize, c: char) -> Option<usize> {
WordCursor::new(&self.rope, offset).previous_unmatched(c)
}
pub fn next_unmmatched(&self, offset: usize, c: char) -> Option<usize> {
WordCursor::new(&self.rope, offset).next_unmatched(c)
}
pub fn prev_code_boundary(&self, offset: usize) -> usize {
WordCursor::new(&self.rope, offset).prev_code_boundary()
}
pub fn next_code_boundary(&self, offset: usize) -> usize {
WordCursor::new(&self.rope, offset).next_code_boundary()
}
pub fn select_word(&self, offset: usize) -> (usize, usize) {
WordCursor::new(&self.rope, offset).select_word()
}
pub fn slice_to_cow<T: IntervalBounds>(&self, range: T) -> Cow<str> {
self.rope.slice_to_cow(range)
}
pub fn update_line_layouts(
&mut self,
text: &mut PietText,
line: usize,
env: &Env,
) -> bool {
// if line >= self.num_lines() {
// return false;
// }
// let theme = &LAPCE_STATE.theme;
// let line_hightlight = self.get_line_highligh(line).clone();
// if self.text_layouts[line].is_none()
// || self.text_layouts[line]
// .as_ref()
// .as_ref()
// .unwrap()
// .highlights
// != line_hightlight
// {
// let line_content = self
// .slice_to_cow(
// self.offset_of_line(line)..self.offset_of_line(line + 1),
// )
// .to_string();
// self.text_layouts[line] = Arc::new(Some(self.get_text_layout(
// text,
// theme,
// line,
// line_content,
// env,
// )));
// return true;
// }
false
}
pub fn get_text_layout(
&mut self,
text: &mut PietText,
theme: &HashMap<String, Color>,
line: usize,
line_content: String,
env: &Env,
) -> HighlightTextLayout {
let mut layout_builder = text
.new_text_layout(line_content.clone())
.font(env.get(LapceTheme::EDITOR_FONT).family, 13.0)
.text_color(env.get(LapceTheme::EDITOR_FOREGROUND));
for (start, end, hl) in self.get_line_highligh(line) {
if let Some(color) = theme.get(hl) {
layout_builder = layout_builder.range_attribute(
start..end,
TextAttribute::TextColor(color.clone()),
);
}
}
let layout = layout_builder.build().unwrap();
HighlightTextLayout {
layout,
text: line_content,
highlights: self.get_line_highligh(line).clone(),
}
}
pub fn get_document(&self) -> String {
self.rope.to_string()
}
}
pub struct WordCursor<'a> {
inner: Cursor<'a, RopeInfo>,
}
impl<'a> WordCursor<'a> {
pub fn new(text: &'a Rope, pos: usize) -> WordCursor<'a> {
let inner = Cursor::new(text, pos);
WordCursor { inner }
}
/// Get previous boundary, and set the cursor at the boundary found.
pub fn prev_boundary(&mut self) -> Option<usize> {
if let Some(ch) = self.inner.prev_codepoint() {
let mut prop = get_word_property(ch);
let mut candidate = self.inner.pos();
while let Some(prev) = self.inner.prev_codepoint() {
let prop_prev = get_word_property(prev);
if classify_boundary(prop_prev, prop).is_start() {
break;
}
prop = prop_prev;
candidate = self.inner.pos();
}
self.inner.set(candidate);
return Some(candidate);
}
None
}
pub fn next_non_blank_char(&mut self) -> usize {
let mut candidate = self.inner.pos();
while let Some(next) = self.inner.next_codepoint() {
let prop = get_word_property(next);
if prop != WordProperty::Space {
break;
}
candidate = self.inner.pos();
}
self.inner.set(candidate);
candidate
}
/// Get next boundary, and set the cursor at the boundary found.
pub fn next_boundary(&mut self) -> Option<usize> {
if let Some(ch) = self.inner.next_codepoint() {
let mut prop = get_word_property(ch);
let mut candidate = self.inner.pos();
while let Some(next) = self.inner.next_codepoint() {
let prop_next = get_word_property(next);
if classify_boundary(prop, prop_next).is_start() {
break;
}
prop = prop_next;
candidate = self.inner.pos();
}
self.inner.set(candidate);
return Some(candidate);
}
None
}
pub fn end_boundary(&mut self) -> Option<usize> {
self.inner.next_codepoint();
if let Some(ch) = self.inner.next_codepoint() {
let mut prop = get_word_property(ch);
let mut candidate = self.inner.pos();
while let Some(next) = self.inner.next_codepoint() {
let prop_next = get_word_property(next);
if classify_boundary(prop, prop_next).is_end() {
break;
}
prop = prop_next;
candidate = self.inner.pos();
}
self.inner.set(candidate);
return Some(candidate - 1);
}
None
}
pub fn prev_code_boundary(&mut self) -> usize {
let mut candidate = self.inner.pos();
while let Some(prev) = self.inner.prev_codepoint() {
let prop_prev = get_word_property(prev);
if prop_prev != WordProperty::Other {
break;
}
candidate = self.inner.pos();
}
return candidate;
}
pub fn next_code_boundary(&mut self) -> usize {
let mut candidate = self.inner.pos();
while let Some(prev) = self.inner.next_codepoint() {
let prop_prev = get_word_property(prev);
if prop_prev != WordProperty::Other {
break;
}
candidate = self.inner.pos();
}
return candidate;
}
pub fn match_pairs(&mut self) -> Option<usize> {
let c = self.inner.peek_next_codepoint()?;
let other = matching_char(c)?;
let left = matching_pair_direction(other)?;
if left {
self.previous_unmatched(other)
} else {
self.inner.next_codepoint();
let offset = self.next_unmatched(other)?;
Some(offset - 1)
}
}
pub fn next_unmatched(&mut self, c: char) -> Option<usize> {
let other = matching_char(c)?;
let mut n = 0;
while let Some(current) = self.inner.next_codepoint() {
if current == c && n == 0 {
return Some(self.inner.pos());
}
if current == other {
n += 1;
} else if current == c {
n -= 1;
}
}
None
}
pub fn previous_unmatched(&mut self, c: char) -> Option<usize> {
let other = matching_char(c)?;
let mut n = 0;
while let Some(current) = self.inner.prev_codepoint() {
if current == c {
if n == 0 {
return Some(self.inner.pos());
}
}
if current == other {
n += 1;
} else if current == c {
n -= 1;
}
}
None
}
pub fn select_word(&mut self) -> (usize, usize) {
let initial = self.inner.pos();
let end = self.next_code_boundary();
self.inner.set(initial);
let start = self.prev_code_boundary();
(start, end)
}
/// Return the selection for the word containing the current cursor. The
/// cursor is moved to the end of that selection.
pub fn select_word_old(&mut self) -> (usize, usize) {
let initial = self.inner.pos();
let init_prop_after = self.inner.next_codepoint().map(get_word_property);
self.inner.set(initial);
let init_prop_before = self.inner.prev_codepoint().map(get_word_property);
let mut start = initial;
let init_boundary =
if let (Some(pb), Some(pa)) = (init_prop_before, init_prop_after) {
classify_boundary_initial(pb, pa)
} else {
WordBoundary::Both
};
let mut prop_after = init_prop_after;
let mut prop_before = init_prop_before;
if prop_after.is_none() {
start = self.inner.pos();
prop_after = prop_before;
prop_before = self.inner.prev_codepoint().map(get_word_property);
}
while let (Some(pb), Some(pa)) = (prop_before, prop_after) {
if start == initial {
if init_boundary.is_start() {
break;
}
} else if !init_boundary.is_boundary() {
if classify_boundary(pb, pa).is_boundary() {
break;
}
} else if classify_boundary(pb, pa).is_start() {
break;
}
start = self.inner.pos();
prop_after = prop_before;
prop_before = self.inner.prev_codepoint().map(get_word_property);
}
self.inner.set(initial);
let mut end = initial;
prop_after = init_prop_after;
prop_before = init_prop_before;
if prop_before.is_none() {
prop_before = self.inner.next_codepoint().map(get_word_property);
end = self.inner.pos();
prop_after = self.inner.next_codepoint().map(get_word_property);
}
while let (Some(pb), Some(pa)) = (prop_before, prop_after) {
if end == initial {
if init_boundary.is_end() {
break;
}
} else if !init_boundary.is_boundary() {
if classify_boundary(pb, pa).is_boundary() {
break;
}
} else if classify_boundary(pb, pa).is_end() {
break;
}
end = self.inner.pos();
prop_before = prop_after;
prop_after = self.inner.next_codepoint().map(get_word_property);
}
self.inner.set(end);
(start, end)
}
}
#[derive(PartialEq, Eq)]
enum WordBoundary {
Interior,
Start, // a boundary indicating the end of a word
End, // a boundary indicating the start of a word
Both,
}
impl WordBoundary {
fn is_start(&self) -> bool {
*self == WordBoundary::Start || *self == WordBoundary::Both
}
fn is_end(&self) -> bool {
*self == WordBoundary::End || *self == WordBoundary::Both
}
fn is_boundary(&self) -> bool {
*self != WordBoundary::Interior
}
}
fn classify_boundary(prev: WordProperty, next: WordProperty) -> WordBoundary {
use self::WordBoundary::*;
use self::WordProperty::*;
match (prev, next) {
(Lf, Lf) => Start,
(Lf, Space) => Interior,
(_, Lf) => End,
(Lf, _) => Start,
(Space, Space) => Interior,
(_, Space) => End,
(Space, _) => Start,
(Punctuation, Other) => Both,
(Other, Punctuation) => Both,
_ => Interior,
}
}
fn classify_boundary_initial(
prev: WordProperty,
next: WordProperty,
) -> WordBoundary {
use self::WordBoundary::*;
use self::WordProperty::*;
match (prev, next) {
// (Lf, Other) => Start,
// (Other, Lf) => End,
// (Lf, Space) => Interior,
// (Lf, Punctuation) => Interior,
// (Space, Lf) => Interior,
// (Punctuation, Lf) => Interior,
// (Space, Punctuation) => Interior,
// (Punctuation, Space) => Interior,
_ => classify_boundary(prev, next),
}
}
#[derive(Copy, Clone, PartialEq)]
pub enum WordProperty {
Lf,
Space,
Punctuation,
Other, // includes letters and all of non-ascii unicode
}
pub fn get_word_property(codepoint: char) -> WordProperty {
if codepoint <= ' ' {
if codepoint == '\n' {
return WordProperty::Lf;
}
return WordProperty::Space;
} else if codepoint <= '\u{3f}' {
if (0xfc00fffe00000000u64 >> (codepoint as u32)) & 1 != 0 {
return WordProperty::Punctuation;
}
} else if codepoint <= '\u{7f}' {
// Hardcoded: @[\]^`{|}~
if (0x7800000178000001u64 >> ((codepoint as u32) & 0x3f)) & 1 != 0 {
return WordProperty::Punctuation;
}
}
WordProperty::Other
}
impl BufferUIState {
pub fn new(
window_id: WindowId,
tab_id: WidgetId,
buffer_id: BufferId,
lines: usize,
max_len: usize,
max_len_line: usize,
) -> BufferUIState {
BufferUIState {
window_id,
tab_id,
id: buffer_id,
text_layouts: vec![Arc::new(None); lines],
line_changes: HashMap::new(),
max_len,
max_len_line,
dirty: false,
}
}
fn update_text_layouts(&mut self, inval_lines: &InvalLines) {
let mut new_layouts = Vec::new();
if inval_lines.start_line < self.text_layouts.len() {
new_layouts
.extend_from_slice(&self.text_layouts[..inval_lines.start_line]);
}
for _ in 0..inval_lines.new_count {
new_layouts.push(Arc::new(None));
}
if inval_lines.start_line + inval_lines.inval_count < self.text_layouts.len()
{
new_layouts.extend_from_slice(
&self.text_layouts
[inval_lines.start_line + inval_lines.inval_count..],
);
}
self.text_layouts = new_layouts;
}
pub fn update_line_layouts(
&mut self,
text: &mut PietText,
buffer: &mut Buffer,
line: usize,
env: &Env,
) -> bool {
if line >= self.text_layouts.len() {
return false;
}
//let state = LAPCE_APP_STATE.get_tab_state(&self.window_id, &self.tab_id);
let theme = &LAPCE_APP_STATE.theme;
let line_hightlight = buffer.get_line_highligh(line).clone();
if self.text_layouts[line].is_none()
|| self.text_layouts[line]
.as_ref()
.as_ref()
.unwrap()
.highlights
!= line_hightlight
{
let line_content = buffer
.slice_to_cow(
buffer.offset_of_line(line)..buffer.offset_of_line(line + 1),
)
.to_string();
self.text_layouts[line] = Arc::new(Some(self.get_text_layout(
text,
buffer,
theme,
line,
line_content,
env,
)));
return true;
}
false
}
pub fn get_text_layout(
&mut self,
text: &mut PietText,
buffer: &mut Buffer,
theme: &HashMap<String, Color>,
line: usize,
line_content: String,
env: &Env,
) -> HighlightTextLayout {
let mut layout_builder = text
.new_text_layout(line_content.replace('\t', " "))
.font(env.get(LapceTheme::EDITOR_FONT).family, 13.0)
.text_color(env.get(LapceTheme::EDITOR_FOREGROUND));
let highlights = buffer.get_line_highligh(line);
for (start, end, hl) in highlights {
let start = start + &line_content[..*start].matches('\t').count() * 3;
let end = end + &line_content[..*end].matches('\t').count() * 3;
if let Some(color) = theme.get(hl) {
layout_builder = layout_builder.range_attribute(
start..end,
TextAttribute::TextColor(color.clone()),
);
} else {
// println!("no color for {} {}", hl, start);
}
}
let layout = layout_builder.build().unwrap();
HighlightTextLayout {
layout,
text: line_content,
highlights: highlights.clone(),
}
}
}
pub fn previous_has_unmatched_pair(line: &str, col: usize) -> bool {
let mut count = HashMap::new();
let mut pair_first = HashMap::new();
for c in line[..col].chars().rev() {
if let Some(left) = matching_pair_direction(c) {
let key = if left { c } else { matching_char(c).unwrap() };
let pair_count = *count.get(&key).unwrap_or(&0i32);
if !pair_first.contains_key(&key) {
pair_first.insert(key, left);
}
if left {
count.insert(key, pair_count - 1);
} else {
count.insert(key, pair_count + 1);
}
}
}
for (_, pair_count) in count.iter() {
if *pair_count < 0 {
return true;
}
}
for (_, left) in pair_first.iter() {
if *left {
return true;
}
}
false
}
pub fn next_has_unmatched_pair(line: &str, col: usize) -> bool {
let mut count = HashMap::new();
for c in line[col..].chars() {
if let Some(left) = matching_pair_direction(c) {
let key = if left { c } else { matching_char(c).unwrap() };
if !count.contains_key(&key) {
count.insert(key, 0i32);
}
if left {
count.insert(key, count.get(&key).unwrap_or(&0i32) - 1);
} else {
count.insert(key, count.get(&key).unwrap_or(&0i32) + 1);
}
}
}
for (_, pair_count) in count.iter() {
if *pair_count > 0 {
return true;
}
}
false
}
pub fn matching_pair_direction(c: char) -> Option<bool> {
Some(match c {
'{' => true,
'}' => false,
'(' => true,
')' => false,
'[' => true,
']' => false,
_ => return None,
})
}
pub fn matching_char(c: char) -> Option<char> {
Some(match c {
'{' => '}',
'}' => '{',
'(' => ')',
')' => '(',
'[' => ']',
']' => '[',
_ => return None,
})
}
pub fn start_buffer_highlights(
receiver: Receiver<(WindowId, WidgetId, BufferId, u64)>,
event_sink: ExtEventSink,
) -> Result<()> {
let mut highlighter = Highlighter::new();
let mut highlight_configs = HashMap::new();
let mut parsers = HashMap::new();
loop {
let (window_id, tab_id, buffer_id, rev) = receiver.recv()?;
let (workspace_path, language, path, rope_str) = {
let state = LAPCE_APP_STATE.get_tab_state(&window_id, &tab_id);
let editor_split = state.editor_split.lock();
let buffer = editor_split.buffers.get(&buffer_id).unwrap();
let language = match buffer.language_id.as_str() {
"rust" => LapceLanguage::Rust,
// "go" => LapceLanguage::Go,
_ => continue,
};
if buffer.rev != rev {
continue;
} else {
(
state.workspace.lock().path.clone(),
language,
buffer.path.clone(),
buffer.slice_to_cow(..buffer.len()).to_string(),
)
}
};
if let Some((diff, line_changes)) =
get_git_diff(&workspace_path, &PathBuf::from(path), &rope_str)
{
let state = LAPCE_APP_STATE.get_tab_state(&window_id, &tab_id);
let mut editor_split = state.editor_split.lock();
let buffer = editor_split.buffers.get_mut(&buffer_id).unwrap();
if buffer.rev != rev {
continue;
}
let buffer_id = buffer.id;
buffer.diff = diff;
buffer.line_changes = line_changes;
// for (view_id, editor) in editor_split.editors.iter() {
// if editor.buffer_id.as_ref() == Some(&buffer_id) {
event_sink.submit_command(
LAPCE_UI_COMMAND,
LapceUICommand::UpdateLineChanges(buffer_id),
Target::Widget(tab_id),
);
// }
// }
}
if !highlight_configs.contains_key(&language) {
let (highlight_config, highlight_names) = new_highlight_config(language);
highlight_configs.insert(language, highlight_config);
}
let highlight_config = highlight_configs.get(&language).unwrap();
let mut highlights: Vec<(usize, usize, Highlight)> = Vec::new();
let mut current_hl: Option<Highlight> = None;
for hightlight in highlighter
.highlight(highlight_config, &rope_str.as_bytes(), None, |_| None)
.unwrap()
{
if let Ok(highlight) = hightlight {
match highlight {
HighlightEvent::Source { start, end } => {
if let Some(hl) = current_hl {
highlights.push((start, end, hl.clone()));
}
}
HighlightEvent::HighlightStart(hl) => {
current_hl = Some(hl);
}
HighlightEvent::HighlightEnd => current_hl = None,
}
}
}
{
let state = LAPCE_APP_STATE.get_tab_state(&window_id, &tab_id);
let mut editor_split = state.editor_split.lock();
let buffer = editor_split.buffers.get_mut(&buffer_id).unwrap();
if buffer.rev != rev {
continue;
}
buffer.highlights = highlights.to_owned();
buffer.line_highlights = HashMap::new();
for (view_id, editor) in editor_split.editors.iter() {
if editor.buffer_id.as_ref() == Some(&buffer_id) {
event_sink.submit_command(
LAPCE_UI_COMMAND,
LapceUICommand::FillTextLayouts,
Target::Widget(view_id.clone()),
);
}
}
}
if !parsers.contains_key(&language) {
let parser = new_parser(language);
parsers.insert(language, parser);
}
let parser = parsers.get_mut(&language).unwrap();
if let Some(tree) = parser.parse(&rope_str, None) {
let state = LAPCE_APP_STATE.get_tab_state(&window_id, &tab_id);
let mut editor_split = state.editor_split.lock();
let buffer = editor_split.buffers.get_mut(&buffer_id).unwrap();
if buffer.rev != rev {
continue;
}
buffer.tree = Some(tree);
let editor = editor_split.editors.get(&editor_split.active).unwrap();
if editor.buffer_id == Some(buffer_id) {
editor_split.update_signature();
}
}
}
}
#[derive(Clone, Debug)]
pub struct DiffHunk {
pub old_start: u32,
pub old_lines: u32,
pub new_start: u32,
pub new_lines: u32,
pub header: String,
}
fn get_git_diff(
workspace_path: &PathBuf,
path: &PathBuf,
content: &str,
) -> Option<(Vec<DiffHunk>, HashMap<usize, char>)> {
let repo = Repository::open(workspace_path.to_str()?).ok()?;
let head = repo.head().ok()?;
let tree = head.peel_to_tree().ok()?;
let tree_entry = tree
.get_path(path.strip_prefix(workspace_path).ok()?)
.ok()?;
let blob = repo.find_blob(tree_entry.id()).ok()?;
let mut patch = git2::Patch::from_blob_and_buffer(
&blob,
None,
content.as_bytes(),
None,
None,
)
.ok()?;
let mut line_changes = HashMap::new();
Some((
(0..patch.num_hunks())
.into_iter()
.filter_map(|i| {
let hunk = patch.hunk(i).ok()?;
let hunk = DiffHunk {
old_start: hunk.0.old_start(),
old_lines: hunk.0.old_lines(),
new_start: hunk.0.new_start(),
new_lines: hunk.0.new_lines(),
header: String::from_utf8(hunk.0.header().to_vec()).ok()?,
};
let mut line_diff = 0;
for line in 0..hunk.old_lines + hunk.new_lines {
if let Ok(diff_line) = patch.line_in_hunk(i, line as usize) {
match diff_line.origin() {
' ' => {
let new_line = diff_line.new_lineno().unwrap();
let old_line = diff_line.old_lineno().unwrap();
line_diff = new_line as i32 - old_line as i32;
}
'-' => {
let old_line = diff_line.old_lineno().unwrap() - 1;
let new_line =
(old_line as i32 + line_diff) as usize;
line_changes.insert(new_line, '-');
line_diff -= 1;
}
'+' => {
let new_line =
diff_line.new_lineno().unwrap() as usize - 1;
if let Some(c) = line_changes.get(&new_line) {
if c == &'-' {
line_changes.insert(new_line, 'm');
}
} else {
line_changes.insert(new_line, '+');
}
line_diff += 1;
}
_ => continue,
}
diff_line.origin();
}
}
Some(hunk)
})
.collect(),
line_changes,
))
}
//fn highlights_process(
// language_id: String,
// receiver: Receiver<u64>,
// buffer_id: BufferId,
// event_sink: ExtEventSink,
//) -> Result<()> {
// let language = match language_id.as_ref() {
// "rust" => LapceLanguage::Rust,
// "go" => LapceLanguage::Go,
// _ => return Ok(()),
// };
// let mut highlighter = Highlighter::new();
// let (highlight_config, highlight_names) = new_highlight_config(language);
// loop {
// let rev = receiver.recv()?;
// let rope_str = {
// let state = LAPCE_APP_STATE.get_active_state();
// let editor_split = state.editor_split.lock();
// let buffer = editor_split.buffers.get(&buffer_id).unwrap();
// if buffer.rev != rev {
// continue;
// } else {
// buffer.slice_to_cow(..buffer.len()).to_string()
// }
// };
//
// let mut highlights: Vec<(usize, usize, Highlight)> = Vec::new();
// let mut current_hl: Option<Highlight> = None;
// for hightlight in highlighter
// .highlight(&highlight_config, &rope_str.as_bytes(), None, |_| None)
// .unwrap()
// {
// if let Ok(highlight) = hightlight {
// match highlight {
// HighlightEvent::Source { start, end } => {
// if let Some(hl) = current_hl {
// highlights.push((start, end, hl.clone()));
// }
// }
// HighlightEvent::HighlightStart(hl) => {
// current_hl = Some(hl);
// }
// HighlightEvent::HighlightEnd => current_hl = None,
// }
// }
// }
//
// let state = LAPCE_APP_STATE.get_active_state();
// let mut editor_split = state.editor_split.lock();
// let buffer = editor_split.buffers.get_mut(&buffer_id).unwrap();
// if buffer.rev != rev {
// continue;
// }
// buffer.highlights = highlights.to_owned();
// buffer.line_highlights = HashMap::new();
//
// for (view_id, editor) in editor_split.editors.iter() {
// if editor.buffer_id.as_ref() == Some(&buffer_id) {
// event_sink.submit_command(
// LAPCE_UI_COMMAND,
// LapceUICommand::FillTextLayouts,
// Target::Widget(view_id.clone()),
// );
// }
// }
// }
//}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use xi_rope::Delta;
use xi_rope::Rope;
use super::*;
#[test]
fn test_reverse_delta() {
let rope = Rope::from_str("0123456789").unwrap();
let mut builder = DeltaBuilder::new(rope.len());
builder.replace(3..4, Rope::from_str("a").unwrap());
let delta1 = builder.build();
println!("{:?}", delta1);
let middle_rope = delta1.apply(&rope);
let mut builder = DeltaBuilder::new(middle_rope.len());
builder.replace(1..5, Rope::from_str("b").unwrap());
let delta2 = builder.build();
println!("{:?}", delta2);
let new_rope = delta2.apply(&middle_rope);
let (ins1, del1) = delta1.factor();
let in1 = ins1.inserted_subset();
let (ins2, del2) = delta2.factor();
let in2 = ins2.inserted_subset();
ins2.transform_expand(&in1, true)
.inserted_subset()
.transform_union(&in1);
// del1.transform_expand(&in1).transform_expand(&del2);
// let del1 = del1.transform_expand(&in1).transform_expand(&in2);
// let del2 = del2.transform_expand(&in2);
// let del = del1.union(&del2);
let union = ins2.transform_expand(&in1, true).apply(&ins1.apply(&rope));
println!("{}", union);
// if delta1.is_simple_delete()
}
}
fn language_id_from_path(path: &str) -> Option<&str> {
let path_buf = PathBuf::from_str(path).ok()?;
Some(match path_buf.extension()?.to_str()? {
"rs" => "rust",
"go" => "go",
_ => return None,
})
}
pub fn get_document_content_changes(
delta: &RopeDelta,
buffer: &Buffer,
) -> Option<TextDocumentContentChangeEvent> {
let (interval, _) = delta.summary();
let (start, end) = interval.start_end();
// TODO: Handle more trivial cases like typing when there's a selection or transpose
if let Some(node) = delta.as_simple_insert() {
let text = String::from(node);
let (start, end) = interval.start_end();
let text_document_content_change_event = TextDocumentContentChangeEvent {
range: Some(Range {
start: buffer.offset_to_position(start),
end: buffer.offset_to_position(end),
}),
range_length: Some((end - start) as u64),
text,
};
return Some(text_document_content_change_event);
}
// Or a simple delete
else if delta.is_simple_delete() {
let mut end_position = buffer.offset_to_position(end);
let text_document_content_change_event = TextDocumentContentChangeEvent {
range: Some(Range {
start: buffer.offset_to_position(start),
end: end_position,
}),
range_length: Some((end - start) as u64),
text: String::new(),
};
return Some(text_document_content_change_event);
}
None
}
fn semantic_tokens_lengend(
semantic_tokens_provider: &SemanticTokensServerCapabilities,
) -> SemanticTokensLegend {
match semantic_tokens_provider {
SemanticTokensServerCapabilities::SemanticTokensOptions(options) => {
options.legend.clone()
}
SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
options,
) => options.semantic_tokens_options.legend.clone(),
}
}
|
use std::borrow::Cow;
use std::error::Error;
use std::{str, marker};
use heed_traits::{BytesDecode, BytesEncode};
use bytemuck::try_cast_slice;
/// Describes an [`prim@str`].
pub struct Str<'a> {
_phantom: marker::PhantomData<&'a ()>,
}
impl<'a> BytesEncode for Str<'a> {
type EItem = &'a str;
fn bytes_encode(item: &Self::EItem) -> Result<Cow<[u8]>, Box<dyn Error>> {
try_cast_slice(item.as_bytes()).map(Cow::Borrowed).map_err(Into::into)
}
}
impl<'a> BytesDecode<'a> for Str<'_> {
type DItem = &'a str;
fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, Box<dyn Error>> {
str::from_utf8(bytes).map_err(Into::into)
}
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::ADCTRIM {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct ADCRFBUFIBTRIMR {
bits: u8,
}
impl ADCRFBUFIBTRIMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct ADCREFBUFTRIMR {
bits: u8,
}
impl ADCREFBUFTRIMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct ADCREFKEEPIBTRIMR {
bits: u8,
}
impl ADCREFKEEPIBTRIMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _ADCRFBUFIBTRIMW<'a> {
w: &'a mut W,
}
impl<'a> _ADCRFBUFIBTRIMW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ADCREFBUFTRIMW<'a> {
w: &'a mut W,
}
impl<'a> _ADCREFBUFTRIMW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 31;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ADCREFKEEPIBTRIMW<'a> {
w: &'a mut W,
}
impl<'a> _ADCREFKEEPIBTRIMW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 11:12 - ADC reference buffer input bias trim"]
#[inline]
pub fn adcrfbufibtrim(&self) -> ADCRFBUFIBTRIMR {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) as u8
};
ADCRFBUFIBTRIMR { bits }
}
#[doc = "Bits 6:10 - ADC Reference buffer trim"]
#[inline]
pub fn adcrefbuftrim(&self) -> ADCREFBUFTRIMR {
let bits = {
const MASK: u8 = 31;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) as u8
};
ADCREFBUFTRIMR { bits }
}
#[doc = "Bits 0:1 - ADC Reference Ibias trim"]
#[inline]
pub fn adcrefkeepibtrim(&self) -> ADCREFKEEPIBTRIMR {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
ADCREFKEEPIBTRIMR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 512 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 11:12 - ADC reference buffer input bias trim"]
#[inline]
pub fn adcrfbufibtrim(&mut self) -> _ADCRFBUFIBTRIMW {
_ADCRFBUFIBTRIMW { w: self }
}
#[doc = "Bits 6:10 - ADC Reference buffer trim"]
#[inline]
pub fn adcrefbuftrim(&mut self) -> _ADCREFBUFTRIMW {
_ADCREFBUFTRIMW { w: self }
}
#[doc = "Bits 0:1 - ADC Reference Ibias trim"]
#[inline]
pub fn adcrefkeepibtrim(&mut self) -> _ADCREFKEEPIBTRIMW {
_ADCREFKEEPIBTRIMW { w: self }
}
}
|
use crate::uses::*;
use core::sync::atomic::{AtomicU64, Ordering};
use core::time::Duration;
use super::Timer;
const DEFAULT_RESET: Duration = Duration::from_millis(20);
pub static apic_timer: ApicTimer = ApicTimer::new(DEFAULT_RESET);
pub struct ApicTimer {
elapsed_time: AtomicU64,
nano_reset: AtomicU64,
}
impl ApicTimer {
const fn new(reset: Duration) -> Self {
ApicTimer {
elapsed_time: AtomicU64::new(0),
nano_reset: AtomicU64::new(0),
}
}
}
impl Timer for ApicTimer {
fn nsec(&self) -> u64 {
cpud().lapic().nsec()
}
}
|
use super::*;
#[allow(unused_imports)]
use cgmath::SquareMatrix;
type Subject = RayGenerator;
fn subject() -> Subject {
let transform = Transform::new(Matrix4::identity());
let fov = FieldOfView::new(Vector2::new(90.0, 90.0));
let image = Image::new(Vector2::new(20, 10));
Subject::new(&transform, &fov, &image)
}
mod new {
use super::*;
#[test]
fn it_builds_the_generator_from_the_camera_related_components() {
let subject = subject();
assert_eq!(subject.matrix, Matrix4::identity());
assert_eq!(subject.degrees, Vector2::new(90.0, 90.0));
assert_eq!(subject.resolution, Vector2::new(20, 10));
}
#[test]
fn it_sets_vectors_that_span_left_to_right_and_top_to_bottom() {
let subject = subject();
assert_approx_eq!(subject.left_to_right.x, 2.0);
assert_approx_eq!(subject.top_to_bottom.y, -2.0);
}
#[test]
fn it_sets_a_vector_from_the_eye_to_the_center_of_the_image_plane() {
let subject = subject();
assert_eq!(subject.forward, Vector3::new(0.0, 0.0, 1.0));
}
#[test]
fn it_sets_the_origin_of_the_camera() {
let subject = subject();
assert_eq!(subject.origin, Point3::new(0.0, 0.0, 0.0));
}
}
mod generate_ray {
use super::*;
#[test]
fn it_generates_the_expected_ray_that_goes_through_the_top_left_pixel() {
let subject = subject();
let ray = subject.generate_ray(0, 0);
assert_eq!(ray.origin, Point3::new(0.0, 0.0, 0.0));
assert_approx_eq!(ray.direction.x, -0.95);
assert_approx_eq!(ray.direction.y, 0.9);
assert_approx_eq!(ray.direction.z, 1.0);
}
#[test]
fn it_generates_the_expected_ray_for_another_arbitrary_pixel() {
let subject = subject();
let ray = subject.generate_ray(13, 5);
assert_eq!(ray.origin, Point3::new(0.0, 0.0, 0.0));
assert_approx_eq!(ray.direction.x, 0.35);
assert_approx_eq!(ray.direction.y, -0.1);
assert_approx_eq!(ray.direction.z, 1.0);
}
}
mod pixel_ratio {
use super::*;
#[test]
fn it_returns_the_ratio_of_the_pixel_coordinate_to_the_image_resolution() {
let subject = subject();
assert_eq!(subject.pixel_ratio(0, 0), Vector2::new(0.025, 0.05));
assert_eq!(subject.pixel_ratio(2, 4), Vector2::new(0.125, 0.45));
assert_eq!(subject.pixel_ratio(17, 7), Vector2::new(0.875, 0.75));
}
}
mod image_plane_vector {
use super::*;
#[test]
fn it_returns_a_vector_from_the_eye_to_the_pixel_on_the_image_plane() {
let subject = subject();
let result = subject.image_plane_vector(Vector2::new(0.5, 0.5));
assert_eq!(result, Vector3::new(0.0, 0.0, 1.0));
let result = subject.image_plane_vector(Vector2::new(0.1, 0.2));
assert_approx_eq!(result.x, -0.8);
assert_approx_eq!(result.y, 0.6);
let result = subject.image_plane_vector(Vector2::new(0.4, 0.6));
assert_approx_eq!(result.x, -0.2);
assert_approx_eq!(result.y, -0.2);
}
}
mod span {
use super::*;
#[test]
fn it_returns_the_width_or_height_of_the_image_plane_located_a_unit_distance_away() {
assert_approx_eq!(Subject::span(0.0), 0.0);
assert_approx_eq!(Subject::span(90.0), 2.0);
}
}
|
// use std::collections::HashSet;
use amethyst::{core::timing::Time, ecs::prelude::*};
use crate::resources::{Context, Game, MessageChannel, Msg, State};
#[derive(Debug)]
pub struct TickSystem {
last_tick: f64,
}
impl Default for TickSystem {
fn default() -> Self {
TickSystem { last_tick: 0.0 }
}
}
impl<'s> System<'s> for TickSystem {
type SystemData = (
Read<'s, Time>,
ReadExpect<'s, Context>,
Write<'s, MessageChannel>,
ReadExpect<'s, Game>,
);
fn run(&mut self, (time, ctx, mut messages, game): Self::SystemData) {
if &State::Main == game.get_state() {
let now = time.absolute_real_time_seconds();
let tick_duration = ctx.tick_duration;
let new_tick = self.last_tick + tick_duration;
if now > new_tick {
self.last_tick = new_tick;
messages.single_write(Msg::Tick(new_tick));
}
}
}
}
|
use crate::buffering::BufferingBuilder;
use crate::csv;
use crate::storage::error::Error;
use crate::storage::{Entry, SeriesTable, SeriesWriter};
use bytes::buf::Buf;
use futures::{Stream, StreamExt};
use std::sync::Arc;
use warp::reject::Rejection;
use warp::{http::StatusCode, Filter};
enum ImportError {
Parse(String),
Internal(Error),
}
impl From<Error> for ImportError {
fn from(err: Error) -> ImportError {
ImportError::Internal(err)
}
}
impl From<Error> for Rejection {
fn from(err: Error) -> Rejection {
super::error::internal(err)
}
}
impl From<ImportError> for Rejection {
fn from(err: ImportError) -> Rejection {
match err {
ImportError::Parse(reason) => super::error::bad_request(reason),
ImportError::Internal(reason) => super::error::internal(reason),
}
}
}
async fn import_entries<S, B>(body: S, writer: Arc<SeriesWriter>) -> Result<(), ImportError>
where
S: Stream<Item = Result<B, warp::Error>> + Send + 'static + Unpin,
B: Buf + Send,
{
let mut csv = csv::ChunkedReader::new();
let mut body = body.boxed();
let mut entries_count = 0usize;
while let Some(Ok(mut chunk)) = body.next().await {
for batch in csv
.read(&mut chunk)
.buffering::<Result<Vec<Entry>, ()>>(1024 * 1024)
{
let batch = batch.map_err(|_| ImportError::Parse("invalid csv".to_owned()))?;
entries_count += batch.len();
writer.append_with_batch_size_async(10, batch).await?;
log::debug!("Imported {} entries", entries_count);
}
}
log::debug!("Import completed, imported {} entries", entries_count);
Ok(())
}
async fn restore<S, B>(
name: String,
series_table: Arc<SeriesTable>,
body: S,
) -> Result<StatusCode, Rejection>
where
S: Stream<Item = Result<B, warp::Error>> + Send + 'static + Unpin,
B: Buf + Send,
{
let series_name = series_table.create_temp()?;
let writer = series_table.writer(&series_name).ok_or_else(|| {
Error::Other(format!(
"can not open temp series: {}",
&series_name
))
})?;
import_entries(body, writer).await?;
if !series_table.rename(&series_name, &name)? {
#[rustfmt::skip]
log::warn!("can not restore series '{}' -> '{}', conflict", &series_name, &name);
return Err(super::error::conflict(&name));
}
Ok(StatusCode::OK)
}
pub fn filter(series_table: Arc<SeriesTable>) -> warp::filters::BoxedFilter<(impl warp::Reply,)> {
warp::path!("series" / String / "restore")
.and(warp::post())
.and(super::with_series_table(series_table.clone()))
.and(warp::body::stream())
.and_then(self::restore)
.recover(super::error::handle)
.boxed()
}
#[cfg(test)]
mod test {
use super::*;
use crate::failpoints::Failpoints;
use crate::storage::error::Error;
use crate::storage::series_table;
use warp::http::StatusCode;
#[tokio::test]
async fn test_export() -> Result<(), Error> {
let fp = Arc::new(Failpoints::create());
let series_table = series_table::test::create_with_failpoints(fp.clone())?;
let resp = warp::test::request()
.method("POST")
.path("/series/t/restore")
.body("1; 12.3\n3; 13.4\n")
.reply(&super::filter(series_table.series_table.clone()))
.await;
assert_eq!(StatusCode::OK, resp.status());
let entries = series_table
.reader("t")
.unwrap()
.iterator(0)?
.collect::<Result<Vec<Entry>, Error>>()?;
#[rustfmt::skip]
assert_eq!(
vec![
Entry { ts: 1, value: 12.3 },
Entry { ts: 3, value: 13.4 },
],
entries
);
let resp = warp::test::request()
.method("POST")
.path("/series/t/restore")
.body("1xx 12.3\n3; 13.4\n")
.reply(&super::filter(series_table.series_table.clone()))
.await;
assert_eq!(StatusCode::BAD_REQUEST, resp.status());
Ok(())
}
}
|
extern crate elevator;
#[macro_use] extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate floating_duration;
use std::time::Instant;
use std::env;
use std::fs::File;
use std::io::{self, Read, Write, BufRead, BufReader};
use std::io::prelude::*;
use elevator::buildings;
use elevator::buildings::{Building, getCumulativeFloorHeight};
use elevator::physics::{ElevatorState};
#[derive(Clone)]
struct Trip {
dst: u64,
up: f64,
down: f64
}
fn main()
{
let simlog = File::open("simulation.log").expect("read simulation log");
let mut simlog = BufReader::new(&simlog);
let mut jerk = 0.0;
let mut prev_est: Option<ElevatorState> = None;
let mut dst_timing: Vec<Trip> = Vec::new();
let mut start_location = 0.0;
let mut first_line = String::new();
let len = simlog.read_line(&mut first_line).unwrap();
let spec: u64 = serde_json::from_str(&first_line).unwrap();
let esp: Box<Building> = buildings::deserialize(spec);
for line in simlog.lines() {
let l = line.unwrap();
let (est, dst): (ElevatorState,u64) = serde_json::from_str(&l).unwrap();
let dl = dst_timing.len();
if dst_timing.len()==0 || dst_timing[dl-1].dst != dst {
dst_timing.push(Trip { dst:dst, up:0.0, down:0.0 });
}
if let Some(prev_est) = prev_est {
let dt = est.timestamp - prev_est.timestamp;
if est.velocity > 0.0 {
dst_timing[dl-1].up += dt;
} else {
dst_timing[dl-1].down += dt;
}
let da = (est.acceleration - prev_est.acceleration).abs();
jerk = (jerk * (1.0 - dt)) + (da * dt);
if jerk.abs() > 0.22 {
panic!("jerk is outside of acceptable limits: {} {:?}", jerk, est)
}
} else {
start_location = est.location;
}
if est.acceleration.abs() > 2.2 {
panic!("acceleration is outside of acceptable limits: {:?}", est)
}
if est.velocity.abs() > 5.5 {
panic!("velocity is outside of acceptable limits: {:?}", est)
}
prev_est = Some(est);
}
//elevator should not backup
let mut total_time = 0.0;
let mut total_direct = 0.0;
for trip in dst_timing.clone()
{
total_time += (trip.up + trip.down);
if trip.up > trip.down {
total_direct += trip.up;
} else {
total_direct += trip.down;
}
}
if (total_direct / total_time) < 0.9 {
panic!("elevator back up is too common: {}", total_direct / total_time)
}
//trips should finish within 20% of theoretical limit
let MAX_JERK = 0.2;
let MAX_ACCELERATION = 2.0;
let MAX_VELOCITY = 5.0;
let mut trip_start_location = start_location;
let mut theoretical_time = 0.0;
let floor_heights = esp.get_floor_heights();
for trip in dst_timing.clone()
{
let next_floor = getCumulativeFloorHeight(floor_heights.clone(), trip.dst);
let d = (trip_start_location - next_floor).abs();
theoretical_time += (
2.0*(MAX_ACCELERATION / MAX_JERK) +
2.0*(MAX_JERK / MAX_ACCELERATION) +
d / MAX_VELOCITY
);
trip_start_location = next_floor;
}
if total_time > (theoretical_time * 1.2) {
panic!("elevator moves to slow {} {}", total_time, theoretical_time * 1.2)
}
println!("All simulation checks passing.");
}
|
enum Easing {
Linear,
Parabolic,
}
impl Easing {
fn get_scalar(progress: f64, easing: Easing) -> f64 {
match easing {
Easing::Linear => {
progress
},
Easing::Parabolic => {
progress * progress
},
}
}
}
struct PropertyAnimation<T> {
from: T,
to: T,
progress: f64,
duration: f64,
}
impl<T: std::ops::Mul<f64>> PropertyAnimation<T> {
fn step(&mut self, delta: f64) {
}
}
|
use regex::Regex;
use std::env;
use std::ffi::CString;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::os::raw::{c_char, c_int};
mod dimacs;
extern "C" {
fn drat_main(argc: c_int, argv: *const *const c_char) -> c_int;
}
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 4 {
panic!("c Usage: ./sat-verifier file.cnf file.out file.drat");
}
let cnf_file = File::open(&args[1]).unwrap();
let out_file = File::open(&args[2]).unwrap();
let mut cnf_reader = BufReader::new(cnf_file);
let out_reader = BufReader::new(out_file);
let dimacs = dimacs::parse_dimacs_from_buf_reader(&mut cnf_reader);
let mut result = "".to_owned();
let mut model = vec![];
for line in out_reader.lines() {
let line = line.unwrap();
let line = line.trim();
if line.is_empty() {
continue;
}
if line.starts_with('c') {
continue;
} else if line.starts_with('s') {
let re_cnf = Regex::new(r"s\s+([A-Z]+)").unwrap();
if let Some(cap) = re_cnf.captures(&line) {
result = cap[1].parse().unwrap();
}
} else if line.starts_with('v') {
let re = Regex::new(r"(-?\d+)").unwrap();
for (_, cap) in re.captures_iter(&line).enumerate() {
let v = match cap[1].parse::<i64>().unwrap() {
0 => break,
n => n,
};
model.push(v);
}
}
}
if result == "SATISFIABLE" {
if model.len() != dimacs.n_vars {
println!("c Incorrect number of vars");
println!("s UNVERIFIED");
return;
}
for i in 1..=dimacs.n_vars {
if !model.contains(&(i as i64)) && !model.contains(&-(i as i64)) {
println!("c var {} not found", i);
println!("s UNVERIFIED");
return;
}
}
for cl in dimacs.clauses {
let mut sat = false;
for &l in cl.iter() {
if model.contains(&l) {
sat = true;
break;
}
}
if !sat {
println!("c cl {:?} not satisfied", cl);
println!("s UNVERIFIED");
return;
}
}
println!("s VERIFIED");
return;
} else if result == "UNSATISFIABLE" {
unsafe {
drat_main(
3,
[
CString::new("./drat-trim").unwrap().as_ptr(),
CString::new(args[1].as_bytes()).unwrap().as_ptr(),
CString::new(args[3].as_bytes()).unwrap().as_ptr(),
]
.as_ptr(),
);
}
return;
}
println!("c {}", result);
println!("s UNVERIFIED");
}
|
use crate::util::{
Bezier, FollowBezierAnimation, Globals, Group, GroupBoxQuad, GroupMiddleQuad, Maps, MyShader,
SelectedBoxQuad, SelectingBoxQuad, TurnRoundAnimation,
};
use crate::inputs::Action;
use bevy::{
prelude::*,
render::pipeline::{RenderPipeline, RenderPipelines},
};
// There is culling between two transparent quads at the same distance from the camera.
// Is this normal behavior?
// To avoid culling, the quads that can intercept each other in the xy plane need
// to have different z-values
//
//
///////////////////////////////////////////// z positions
// spawn_group_middle_quads: -1000.0
// car: -720.0
// helicopter: -715.0
// heli rotor blades: -710.0
// spawn_group_bounding_box: 0.0
// spawn_selecting_bounding_box: 5.0
// spawn_selection_bounding_box: -10.0
// button_ui: -550.0
// color_ui: -500.0
// buttons: -400.0
// icon: 10.1
// icon2: 20.1
// pos_z in bezier_spawner: -5110.0 to -1110.0
// bezier_bounding_box: -20.0
// start anchor: 30.0 + pos_z
// end anchor: 40.0 + pos_z
// ctrl start: 50 + pos_z
// ctrl end: 60 + pos_z
// middle quads: 110 + pos_z + 10 per quad
// road: -725.0
// light: -700.0
// mesh: -730.0
// helicopter: -715.0
// heli rotor blades: -710.0
// car: -720.0
///////////////////////////////////////////// z positions
pub fn spawn_selection_bounding_box(
mut commands: Commands,
// asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
// mut pipelines: ResMut<Assets<PipelineDescriptor>>,
// mut render_graph: ResMut<RenderGraph>,
globals: ResMut<Globals>,
maps: ResMut<Maps>,
mut my_shader_params: ResMut<Assets<MyShader>>,
clearcolor_struct: Res<ClearColor>,
) {
// Bounding Box for group
let bb_group_size = Vec2::new(10.0, 10.0);
let shader_params_handle_group_bb = my_shader_params.add(MyShader {
color: Color::DARK_GRAY,
t: 0.5,
zoom: 0.15 / globals.scale,
size: bb_group_size / (globals.scale / 0.15),
clearcolor: clearcolor_struct.0.clone(),
..Default::default()
});
let visible_bb_group = Visible {
is_visible: false,
is_transparent: true,
};
let mesh_handle_bb_group = meshes.add(Mesh::from(shape::Quad {
size: bb_group_size,
flip: false,
}));
let bb_group_transform = Transform::from_translation(Vec3::new(0.0, 0.0, -10.0));
let bb_group_pipeline_handle = maps.pipeline_handles["bounding_box"].clone();
commands
.spawn_bundle(MeshBundle {
mesh: mesh_handle_bb_group,
visible: visible_bb_group,
render_pipelines: RenderPipelines::from_pipelines(vec![RenderPipeline::new(
bb_group_pipeline_handle,
)]),
transform: bb_group_transform,
..Default::default()
})
.insert(shader_params_handle_group_bb)
.insert(SelectedBoxQuad);
}
pub fn spawn_selecting_bounding_box(
mut commands: Commands,
// asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
// mut pipelines: ResMut<Assets<PipelineDescriptor>>,
// mut render_graph: ResMut<RenderGraph>,
globals: ResMut<Globals>,
maps: ResMut<Maps>,
mut my_shader_params: ResMut<Assets<MyShader>>,
clearcolor_struct: Res<ClearColor>,
) {
// Bounding Box for group
let bb_group_size = Vec2::new(100.0, 100.0);
let shader_params_handle_group_bb = my_shader_params.add(MyShader {
color: Color::DARK_GRAY,
t: 0.5,
zoom: 0.15 / globals.scale,
size: bb_group_size / (globals.scale / 0.15),
clearcolor: clearcolor_struct.0.clone(),
..Default::default()
});
let visible_bb_group = Visible {
is_visible: false,
is_transparent: true,
};
let mesh_handle_bb_group = meshes.add(Mesh::from(shape::Quad {
size: bb_group_size,
flip: false,
}));
let bb_group_transform = Transform::from_translation(Vec3::new(0.0, 0.0, 5.0));
let bb_group_pipeline_handle = maps.pipeline_handles["selecting"].clone();
commands
.spawn_bundle(MeshBundle {
mesh: mesh_handle_bb_group,
visible: visible_bb_group,
render_pipelines: RenderPipelines::from_pipelines(vec![RenderPipeline::new(
bb_group_pipeline_handle,
)]),
transform: bb_group_transform,
..Default::default()
})
.insert(shader_params_handle_group_bb)
.insert(SelectingBoxQuad);
}
pub fn spawn_group_bounding_box(
mut commands: Commands,
// asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
// mut pipelines: ResMut<Assets<PipelineDescriptor>>,
// mut render_graph: ResMut<RenderGraph>,
globals: ResMut<Globals>,
mut my_shader_params: ResMut<Assets<MyShader>>,
clearcolor_struct: Res<ClearColor>,
mut group_event_reader: EventReader<Handle<Group>>,
maps: ResMut<Maps>,
// group: &Group,
) {
// Bounding Box for group
for group_handle in group_event_reader.iter() {
let bb_group_size = Vec2::new(10.0, 10.0);
let shader_params_handle_group_bb = my_shader_params.add(MyShader {
color: Color::BLACK,
t: 0.5,
zoom: 0.15 / globals.scale,
size: bb_group_size / (globals.scale / 0.15),
clearcolor: clearcolor_struct.0.clone(),
..Default::default()
});
let visible_bb_group = Visible {
is_visible: false,
is_transparent: true,
};
let mesh_handle_bb_group = meshes.add(Mesh::from(shape::Quad {
size: bb_group_size,
flip: false,
}));
let bb_group_transform = Transform::from_translation(Vec3::new(0.0, 0.0, 0.0));
let bb_group_pipeline_handle = maps.pipeline_handles["bounding_box"].clone();
commands
.spawn_bundle(MeshBundle {
mesh: mesh_handle_bb_group,
visible: visible_bb_group,
render_pipelines: RenderPipelines::from_pipelines(vec![RenderPipeline::new(
bb_group_pipeline_handle,
)]),
transform: bb_group_transform,
..Default::default()
})
.insert(shader_params_handle_group_bb)
.insert(GroupBoxQuad)
.insert(group_handle.clone());
}
}
pub fn spawn_group_middle_quads(
mut commands: Commands,
bezier_curves: ResMut<Assets<Bezier>>,
globals: ResMut<Globals>,
mut my_shader_params: ResMut<Assets<MyShader>>,
clearcolor_struct: Res<ClearColor>,
// group_handle: Handle<Group>,
groups: ResMut<Assets<Group>>,
maps: ResMut<Maps>,
// mut group_event_reader: EventReader<Group>,
mut group_event_reader: EventReader<Handle<Group>>,
) {
for group_handle in group_event_reader.iter() {
let visible = Visible {
is_visible: true,
is_transparent: true,
};
let middle_mesh_handle = maps.mesh_handles["middles"].clone();
let pos_z = -1000.0;
let num_mid_quads = 50;
let group = groups.get(group_handle.clone()).unwrap();
let (parent, _handle) = group.group.iter().next().unwrap();
let first_bezier_handle = group.handles.iter().next().unwrap();
let first_bezier = bezier_curves.get(first_bezier_handle).unwrap();
let color = first_bezier.color.unwrap(); //Color::hex("2e003e").unwrap();
let vrange: Vec<f32> = (0..num_mid_quads)
.map(|x| (x as f32) / (num_mid_quads as f32 - 1.0) - 0.0000001)
.collect();
// println!("total length: {:?}", vrange);
let ecm_pipeline_handle = maps.pipeline_handles["mids"].clone();
let render_piplines =
RenderPipelines::from_pipelines(vec![RenderPipeline::new(ecm_pipeline_handle)]);
let mut z = 0.0;
let mut x = -20.0;
// let mut k = 0;
for t in vrange {
// let pos = group.compute_position_with_bezier(&bezier_curves, t as f64);
let pos = group.compute_position_with_lut(t as f32);
let mid_shader_params_handle = my_shader_params.add(MyShader {
color,
t: 0.5,
zoom: 0.15 / globals.scale,
size: Vec2::new(1.0, 1.0),
clearcolor: clearcolor_struct.0.clone(),
..Default::default()
});
x = x + 2.0;
z = z + 5.0;
let child = commands
// // left
.spawn_bundle(MeshBundle {
mesh: middle_mesh_handle.clone(),
visible: visible.clone(),
render_pipelines: render_piplines.clone(),
transform: Transform::from_xyz(pos.x, pos.y, pos_z),
..Default::default()
})
.insert(GroupMiddleQuad(num_mid_quads))
.insert(mid_shader_params_handle.clone())
.insert(group_handle.clone())
.id();
commands.entity(*parent).push_children(&[child]);
}
}
}
pub fn spawn_heli(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<ColorMaterial>>,
mut action_event_reader: EventReader<Action>,
groups: Res<Assets<Group>>,
) {
if action_event_reader.iter().any(|x| x == &Action::SpawnHeli) {
if let Some(_) = groups.iter().next() {
// let rotation = Quat::IDENTITY;
let rotation = Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)
.mul_quat(Quat::from_rotation_x(std::f32::consts::FRAC_PI_2));
commands
.spawn_bundle((
Transform {
translation: Vec3::new(0.0, 0.0, -720.0),
rotation,
scale: Vec3::splat(3.0),
..Default::default()
},
GlobalTransform::identity(),
))
.insert(FollowBezierAnimation {
animation_offset: 0.0,
initial_direction: Vec3::Z,
})
// .insert(TurnRoundAnimation)
.with_children(|cell| {
cell.spawn_scene(asset_server.load("models/car.gltf#Scene0"));
})
.id();
let heli_handle = asset_server.load("textures/heli.png");
let size = Vec2::new(25.0, 25.0);
let heli_sprite = commands
.spawn_bundle(SpriteBundle {
material: materials.add(heli_handle.into()),
// mesh: mesh_handle_button.clone(),
transform: Transform::from_translation(Vec3::new(0.0, 0.0, -710.0)),
sprite: Sprite::new(size),
visible: Visible {
is_visible: true,
is_transparent: true,
},
..Default::default()
})
.insert(FollowBezierAnimation {
animation_offset: -0.1,
initial_direction: Vec3::X,
})
.id();
let copter_handle = asset_server.load("textures/copter.png");
let copter_sprite = commands
.spawn_bundle(SpriteBundle {
material: materials.add(copter_handle.into()),
// mesh: mesh_handle_button.clone(),
transform: Transform::from_translation(Vec3::new(3.0, 1.0, 5.0)),
sprite: Sprite::new(size),
visible: Visible {
is_visible: true,
is_transparent: true,
},
..Default::default()
})
.insert(TurnRoundAnimation)
.id();
commands.entity(heli_sprite).push_children(&[copter_sprite]);
// light
commands
.spawn_bundle(PointLightBundle {
transform: Transform::from_translation(Vec3::new(0.0, 25.0, -700.0)),
point_light: PointLight {
intensity: 50000.,
range: 1000.,
..Default::default()
},
..Default::default()
})
.insert(FollowBezierAnimation {
animation_offset: 0.0,
initial_direction: Vec3::X,
});
}
}
}
|
use std::{
io::Read,
sync::atomic::{AtomicI32, Ordering},
};
use lazy_static::lazy_static;
use tokio::io::{AsyncWrite, AsyncWriteExt};
use crate::error::Result;
/// Closure to obtain a new, unique request ID.
pub(crate) fn next_request_id() -> i32 {
lazy_static! {
static ref REQUEST_ID: AtomicI32 = AtomicI32::new(0);
}
REQUEST_ID.fetch_add(1, Ordering::SeqCst)
}
/// Serializes `string` to bytes and writes them to `writer` with a null terminator appended.
pub(super) async fn write_cstring<W: AsyncWrite + Unpin>(
writer: &mut W,
string: &str,
) -> Result<()> {
// Write the string's UTF-8 bytes.
writer.write_all(string.as_bytes()).await?;
// Write the null terminator.
writer.write_all(&[0]).await?;
Ok(())
}
pub(super) struct SyncCountReader<R> {
reader: R,
bytes_read: usize,
}
impl<R: Read> SyncCountReader<R> {
/// Constructs a new CountReader that wraps `reader`.
pub(super) fn new(reader: R) -> Self {
SyncCountReader {
reader,
bytes_read: 0,
}
}
/// Gets the number of bytes read so far.
pub(super) fn bytes_read(&self) -> usize {
self.bytes_read
}
}
impl<R: Read> Read for SyncCountReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let bytes = self.reader.read(buf)?;
self.bytes_read += bytes;
Ok(bytes)
}
}
|
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct Meta {
pub title: String,
pub context: String,
pub teammates: Vec<String>,
}
|
use std::collections::HashMap;
use std::path::Path;
use std::ffi::OsStr;
use iron::prelude::*;
use iron_sessionstorage::Value as SessionValue;
use iron_sessionstorage::traits::SessionRequestExt;
use rand::*;
use crypto::md5::Md5;
use crypto::digest::Digest; // used for input_str, result_str
use chrono::{Local, NaiveDateTime};
use urlencoded::{UrlEncodedQuery, UrlEncodedBody};
use serde::Serialize;
use serde_json::{self, Value};
use hbs::handlebars::{Helper, Handlebars, RenderContext, RenderError};
use router::{Router, Params};
use pulldown_cmark::{Parser, html};
use toml::value::Value::String as Toml_String;
use common::http::SessionData;
use common::lazy_static::{RECORDS_COUNT_PER_PAGE, ADMINS};
pub fn parse_to_html(text: &str) -> String {
let mut temp = String::new();
let parser = Parser::new(text);
html::push_html(&mut temp, parser);
temp
}
pub fn gen_salt() -> String {
thread_rng()
.gen_ascii_chars()
.take(32)
.collect::<String>()
}
pub fn gen_md5(str: &str) -> String {
let mut sh = Md5::new();
sh.input_str(str);
sh.result_str().to_string()
}
pub fn get_file_ext(filename: &str) -> Option<&str>{
Path::new(filename)
.extension()
.and_then(OsStr::to_str)
}
pub fn gen_gravatar_url(email: &str) -> String {
"http://www.gravatar.com/avatar/".to_string() + &*gen_md5(email) + "?s=150"
}
pub fn gen_datetime() -> NaiveDateTime {
Local::now().naive_utc()
}
pub fn check_and_get_string(value: &Value) -> String {
if value.is_null() {
"".to_string()
} else {
value.as_str().unwrap().to_string()
}
}
pub fn is_login(req: &mut Request) -> bool {
let session_wrapper = req.session().get::<SessionData>().unwrap();
if session_wrapper.is_some() {
true
} else {
false
}
}
pub fn get_session_obj(req: &mut Request) -> Value {
let session_wrapper = req.session().get::<SessionData>().unwrap();
json_parse(&*session_wrapper.unwrap().into_raw())
}
pub fn get_router_params(req: &mut Request) -> Params {
req.extensions.get::<Router>().unwrap().clone()
}
pub fn get_request_body(req: &mut Request) -> HashMap<String, Vec<String>> {
req.get::<UrlEncodedBody>().unwrap()
}
pub fn get_request_query(req: &mut Request) -> HashMap<String, Vec<String>> {
req.get::<UrlEncodedQuery>().unwrap()
}
pub fn has_request_query(req: &mut Request) -> bool {
if req.get::<UrlEncodedQuery>().is_err() {
false
} else {
true
}
}
pub fn get_query_page(req: &mut Request) -> u32 {
let has_query_params = has_request_query(req);
let page: u32;
if has_query_params {
let query = get_request_query(req);
if query.get("page").is_none() {
page = 1;
} else {
let page_wrapper = query.get("page").unwrap()[0].parse::<u32>();
if page_wrapper.is_err() {
page = 1;
} else {
page = page_wrapper.unwrap();
}
}
} else {
page = 1;
}
page
}
pub fn json_stringify<T: Serialize>(data: &T) -> String {
serde_json::to_string(data).unwrap()
}
pub fn json_parse(data: &str) -> Value {
serde_json::from_str(data).unwrap()
}
pub fn mount_template_var(helper: &Helper, _: &Handlebars, context: &mut RenderContext) -> Result<(), RenderError> {
let param_key = helper.param(0);
let param_value = helper.param(1);
if param_key.is_none() || param_value.is_none() {
return Ok(());
}
let key = param_key.unwrap().value().as_str().unwrap().to_string();
let value = param_value.unwrap().value();
let mut view_data = context.context_mut().data_mut().as_object_mut().unwrap();
view_data.insert(key, json!(value));
Ok(())
}
pub fn build_pagination(cur_page: u32, total: u32, base_url: &str) -> Value {
let mut delta = 1;
if total % RECORDS_COUNT_PER_PAGE == 0 {
delta = 0;
}
let page_count = total / RECORDS_COUNT_PER_PAGE + delta;
let mut is_show_prev_ellipsis = true;
let mut is_show_next_ellipsis = true;
let mut is_first_page_disabled = false;
let mut is_last_page_disabled = false;
let mut page_list;
if page_count < 6 {
is_show_prev_ellipsis = false;
is_show_next_ellipsis = false;
} else {
if cur_page < 4 {
is_show_prev_ellipsis = false;
}
if cur_page > page_count - 3 {
is_show_next_ellipsis = false;
}
}
if cur_page == 1 {
is_first_page_disabled = true;
}
if cur_page == page_count {
is_last_page_disabled = true;
}
page_list = vec![];
if page_count < 6 { // 总页数小于等于5时
for i in 1..(page_count + 1) {
if i == cur_page {
page_list.push(json!({
"page": i,
"is_active": true
}));
} else {
page_list.push(json!({
"page": i
}));
}
}
} else if cur_page < 4 { // 总页数大于5,当前页码小于等于3时,隐藏左侧ellipsis
for i in 1..6 {
if i == cur_page {
page_list.push(json!({
"page": i,
"is_active": true
}));
} else {
page_list.push(json!({
"page": i
}));
}
}
} else if cur_page > page_count - 3 { // 总页数大于5,当前页码距离总页数小于等于3时,隐藏右侧ellipsis
for i in (page_count - 4)..(page_count + 1) {
if i == cur_page {
page_list.push(json!({
"page": i,
"is_active": true
}));
} else {
page_list.push(json!({
"page": i
}));
}
}
} else { // 当前页码的左右两侧各放置两个页码
for i in (cur_page - 2)..(cur_page + 3) {
if i == cur_page {
page_list.push(json!({
"page": i,
"is_active": true
}));
} else {
page_list.push(json!({
"page": i
}));
}
}
}
json!({
"base_url": base_url.to_owned(),
"is_show_prev_ellipsis": is_show_prev_ellipsis,
"is_show_next_ellipsis": is_show_next_ellipsis,
"page_list": page_list,
"is_first_page_disabled": is_first_page_disabled,
"is_last_page_disabled": is_last_page_disabled,
"first_page": 1,
"last_page": page_count
})
}
pub fn is_admin(username: &str) -> bool {
if ADMINS.contains(&Toml_String(username.to_string())) {
true
} else {
false
}
}
#[test]
fn test_gen_salt() {
assert_ne!(gen_salt(), "runner".to_owned());
}
#[test]
fn test_gen_md5() {
assert_ne!(gen_md5("runner"), "runner".to_owned());
}
#[test]
fn test_get_file_ext() {
assert_eq!(get_file_ext("abc.txt").unwrap(), "txt");
} |
/// Sort an array using merge sort
///
/// # Parameters
///
/// - `arr`: A vector to sort in-place
///
/// # Type parameters
///
/// - `T`: A type that can be checked for equality and ordering e.g. a `i32`, a
/// `u8`, or a `f32`.
///
/// # Undefined Behavior
///
/// Does not work with `String` vectors.
///
/// # Examples
///
/// ```rust
/// use algorithmplus::sort::merge_sort;
///
/// let mut ls = vec![3, 2, 1];
/// merge_sort(&mut ls);
///
/// assert_eq!(ls, [1, 2, 3]);
/// ```
pub fn merge_sort<T: PartialEq + PartialOrd + Copy>(arr: &mut [T]) {
let mid = arr.len() / 2;
if mid > 0 {
merge_sort(&mut arr[..mid]);
merge_sort(&mut arr[mid..]);
let mut ret = arr.to_vec();
merge(&arr[..mid], &arr[mid..], &mut ret[..]);
arr.copy_from_slice(&ret);
}
}
fn merge<T: PartialEq + PartialOrd + Copy>(arr_one: &[T], arr_two: &[T], result_arr: &mut [T]) {
let mut left = 0;
let mut right = 0;
let mut index = 0;
let arr_one_len = arr_one.len();
let arr_two_len = arr_two.len();
while left < arr_one_len && right < arr_two_len {
if arr_one[left] <= arr_two[right] {
result_arr[index] = arr_one[left];
index += 1;
left += 1;
} else {
result_arr[index] = arr_two[right];
index += 1;
right += 1;
}
}
if left < arr_one_len {
for idx in left..arr_one_len {
result_arr[index] = arr_one[idx];
index += 1;
}
}
if right < arr_two_len {
for idx in right..arr_two_len {
result_arr[index] = arr_two[idx];
index += 1;
}
}
}
|
use super::*;
use rayon::prelude::*;
impl Graph {
/// Return iterator on the node of the graph.
pub fn get_nodes_iter(&self) -> impl Iterator<Item = (NodeT, Option<NodeTypeT>)> + '_ {
(0..self.get_nodes_number())
.map(move |node_id| (node_id, self.get_unchecked_node_type(node_id)))
}
/// Return iterator on the node degrees of the graph.
pub fn get_node_degrees_iter(&self) -> impl Iterator<Item = NodeT> + '_ {
(0..self.get_nodes_number()).map(move |node| self.get_node_degree(node))
}
/// Return iterator on the node degrees of the graph.
pub fn get_node_degrees_par_iter(&self) -> impl ParallelIterator<Item = NodeT> + '_ {
(0..self.get_nodes_number())
.into_par_iter()
.map(move |node| self.get_node_degree(node))
}
/// Return iterator on the node of the graph as Strings.
pub fn get_nodes_names_iter(
&self,
) -> impl Iterator<Item = (NodeT, String, Option<String>)> + '_ {
(0..self.get_nodes_number()).map(move |node_id| {
(
node_id,
self.nodes.translate(node_id).to_owned(),
self.get_node_type_string(node_id),
)
})
}
/// Return iterator on the edges of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_iter(
&self,
directed: bool,
) -> Box<dyn Iterator<Item = (EdgeT, NodeT, NodeT)> + '_> {
if self.sources.is_some() && self.destinations.is_some() {
return Box::new((0..self.get_edges_number()).filter_map(move |edge_id| {
let (src, dst) = self.get_edge_from_edge_id(edge_id);
if !directed && src > dst {
return None;
}
Some((edge_id, src, dst))
}));
}
Box::new(
self.edges
.iter()
.enumerate()
.filter_map(move |(edge_id, edge)| {
let (src, dst) = self.decode_edge(edge);
if !directed && src > dst {
return None;
}
Some((edge_id as EdgeT, src, dst))
}),
)
}
/// Return iterator on the (non unique) source nodes of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_sources_iter(&self, directed: bool) -> impl Iterator<Item = NodeT> + '_ {
self.get_edges_iter(directed).map(move |(_, src, _)| src)
}
/// Return parallel iterator on the (non unique) source nodes of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_sources_par_iter(&self, directed: bool) -> impl ParallelIterator<Item = NodeT> + '_ {
self.get_edges_par_iter(directed)
.map(move |(_, src, _)| src)
}
/// Return iterator on the (non unique) destination nodes of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_destinations_iter(&self, directed: bool) -> impl Iterator<Item = NodeT> + '_ {
self.get_edges_iter(directed).map(move |(_, _, dst)| dst)
}
/// Return parallel iterator on the (non unique) destination nodes of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_destinations_par_iter(
&self,
directed: bool,
) -> impl ParallelIterator<Item = NodeT> + '_ {
self.get_edges_par_iter(directed)
.map(move |(_, _, dst)| dst)
}
/// Return iterator on the edges of the graph with the string name.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_string_iter(
&self,
directed: bool,
) -> impl Iterator<Item = (EdgeT, String, String)> + '_ {
self.get_edges_iter(directed)
.map(move |(edge_id, src, dst)| {
(
edge_id,
self.nodes.translate(src).to_owned(),
self.nodes.translate(dst).to_owned(),
)
})
}
/// Return iterator on the edges of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_par_iter(
&self,
directed: bool,
) -> impl ParallelIterator<Item = (EdgeT, NodeT, NodeT)> + '_ {
self.edges
.par_enumerate()
.filter_map(move |(edge_id, edge)| {
let (src, dst) = self.decode_edge(edge);
if !directed && src > dst {
return None;
}
Some((edge_id as EdgeT, src, dst))
})
}
/// Return iterator on the edges of the graph with the string name.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_par_string_iter(
&self,
directed: bool,
) -> impl ParallelIterator<Item = (EdgeT, String, String)> + '_ {
self.get_edges_par_iter(directed)
.map(move |(edge_id, src, dst)| {
(
edge_id,
self.nodes.translate(src).to_owned(),
self.nodes.translate(dst).to_owned(),
)
})
}
/// Return iterator on the edges of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_triples(
&self,
directed: bool,
) -> impl Iterator<Item = (EdgeT, NodeT, NodeT, Option<EdgeTypeT>)> + '_ {
self.get_edges_iter(directed)
.map(move |(edge_id, src, dst)| {
(edge_id, src, dst, self.get_unchecked_edge_type(edge_id))
})
}
/// Return iterator on the edges of the graph with the string name.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_string_triples(
&self,
directed: bool,
) -> impl Iterator<Item = (EdgeT, String, String, Option<String>)> + '_ {
self.get_edges_string_iter(directed)
.map(move |(edge_id, src, dst)| (edge_id, src, dst, self.get_edge_type_string(edge_id)))
}
/// Return iterator on the edges of the graph with the string name.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_par_string_triples(
&self,
directed: bool,
) -> impl ParallelIterator<Item = (EdgeT, String, String, Option<String>)> + '_ {
self.get_edges_par_string_iter(directed)
.map(move |(edge_id, src, dst)| (edge_id, src, dst, self.get_edge_type_string(edge_id)))
}
/// Return iterator on the edges of the graph with the string name.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_par_string_quadruples(
&self,
directed: bool,
) -> impl ParallelIterator<Item = (EdgeT, String, String, Option<String>, Option<WeightT>)> + '_
{
self.get_edges_par_string_triples(directed)
.map(move |(edge_id, src, dst, edge_type)| {
(edge_id, src, dst, edge_type, self.get_edge_weight(edge_id))
})
}
/// Return iterator on the edges of the graph with the string name.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_string_quadruples(
&self,
directed: bool,
) -> impl Iterator<Item = (EdgeT, String, String, Option<String>, Option<WeightT>)> + '_ {
self.get_edges_string_triples(directed)
.map(move |(edge_id, src, dst, edge_type)| {
(edge_id, src, dst, edge_type, self.get_edge_weight(edge_id))
})
}
/// Return iterator on the edges of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_par_triples(
&self,
directed: bool,
) -> impl ParallelIterator<Item = (EdgeT, NodeT, NodeT, Option<EdgeTypeT>)> + '_ {
self.get_edges_par_iter(directed)
.map(move |(edge_id, src, dst)| {
(edge_id, src, dst, self.get_unchecked_edge_type(edge_id))
})
}
/// Return iterator on the edges of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_quadruples(
&self,
directed: bool,
) -> impl Iterator<Item = (EdgeT, NodeT, NodeT, Option<EdgeTypeT>, Option<WeightT>)> + '_ {
self.get_edges_triples(directed)
.map(move |(edge_id, src, dst, edge_type)| {
(edge_id, src, dst, edge_type, self.get_edge_weight(edge_id))
})
}
/// Return iterator on the edges of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_edges_par_quadruples(
&self,
directed: bool,
) -> impl ParallelIterator<Item = (EdgeT, NodeT, NodeT, Option<EdgeTypeT>, Option<WeightT>)> + '_
{
self.get_edges_par_triples(directed)
.map(move |(edge_id, src, dst, edge_type)| {
(edge_id, src, dst, edge_type, self.get_edge_weight(edge_id))
})
}
/// Return the src, dst, edge type and weight of a given edge id
pub fn get_edge_quadruple(
&self,
edge_id: EdgeT,
) -> (NodeT, NodeT, Option<EdgeTypeT>, Option<WeightT>) {
let (src, dst, edge_type) = self.get_edge_triple(edge_id);
(src, dst, edge_type, self.get_edge_weight(edge_id))
}
/// Return the src, dst, edge type of a given edge id
pub fn get_edge_triple(&self, edge_id: EdgeT) -> (NodeT, NodeT, Option<EdgeTypeT>) {
let (src, dst) = self.get_edge_from_edge_id(edge_id);
(src, dst, self.get_unchecked_edge_type(edge_id))
}
/// Return iterator on the edges of the graph.
///
/// # Arguments
/// * `directed`: bool, wethever to filter out the undirected edges.
pub fn get_unique_edges_iter(
&self,
directed: bool,
) -> Box<dyn Iterator<Item = (NodeT, NodeT)> + '_> {
if self.sources.is_some() && self.destinations.is_some() {
return Box::new((0..self.get_edges_number()).filter_map(move |edge_id| {
let (src, dst) = self.get_edge_from_edge_id(edge_id);
if edge_id > 0 {
let (last_src, last_dst) = self.get_edge_from_edge_id(edge_id - 1);
if last_src == src && last_dst == dst {
return None;
}
}
if !directed && src > dst {
return None;
}
Some((src, dst))
}));
}
Box::new(self.edges.iter_uniques().filter_map(move |edge| {
let (src, dst) = self.decode_edge(edge);
if !directed && src > dst {
return None;
}
Some((src, dst))
}))
}
/// Return iterator on the unique sources of the graph.
pub fn get_unique_sources_iter(&self) -> impl Iterator<Item = NodeT> + '_ {
self.unique_sources.iter().map(|source| source as NodeT)
}
/// Return iterator on the unique sources of the graph.
pub fn get_unique_sources_par_iter(&self) -> impl ParallelIterator<Item = NodeT> + '_ {
self.unique_sources.par_iter().map(|source| source as NodeT)
}
}
|
use num::Num;
use num::pow;
use std::fmt;
use std::ops::{Add, Sub, Mul, Neg};
/// Quaternion represents a three dimensional component (x, y, z) with a definied
/// amount of rotation (w).
///
/// # Remarks
///
/// This struct is implemented to be used with numerical types.
#[derive(Clone, Copy)]
pub struct Quat<N: Copy> {
x: N,
y: N,
z: N,
w: N
}
////////////////////////////////////////////////////////////////////////////////
// Inherent methods
////////////////////////////////////////////////////////////////////////////////
impl<N: Copy + Num> Quat<N> { // implementation of Quat<N>
/// Initializes a Matrix with default values
#[inline]
pub fn new() -> Quat<N> where N: Default {
Quat { x: N::default(),
y: N::default(),
z: N::default(),
w: N::default()}
}
/// Initializes a Quat with defined values
///
/// # Arguments
///
/// * `x`: X dimension value
/// * `y`: Y dimension value
/// * `z`: Z dimension value
/// * `w`: rotation value
#[inline]
pub fn init(x: N, y: N, z: N, w: N) -> Quat<N> {
Quat { x: x,
y: y,
z: z,
w: w }
}
/// Returns X dimension value
#[inline]
pub fn x(&self) -> N {
self.x
}
/// Returns Y dimension value
#[inline]
pub fn y(&self) -> N {
self.y
}
/// Returns Z dimension value
pub fn z(&self) -> N {
self.z
}
/// Returns rotation value
#[inline]
pub fn w(&self) -> N {
self.w
}
/// Modifies X dimension value
///
/// # Arguments
///
/// * `x`: new X dimension value
#[inline]
pub fn set_x(&mut self, x: N) {
self.x = x;
}
/// Modifies Y dimension value
///
/// # Arguments
///
/// * `y`: new Y dimension value
#[inline]
pub fn set_y(&mut self, y: N) {
self.y = y;
}
/// Modifies Z dimension value
///
/// # Arguments
///
/// * `z`: new Z dimension value
#[inline]
pub fn set_z(&mut self, z: N) {
self.z = z;
}
/// Modifies rotation value
///
/// # Arguments
///
/// * `w`: new rotation value
#[inline]
pub fn set_w(&mut self, w: N) {
self.w = w;
}
/// Modify all values at once
///
/// # Arguments
///
/// * `x`: new X dimension value
/// * `y`: new Y dimension value
/// * `z`: new Z dimension value
/// * `w`: new rotation value
#[inline]
pub fn set(&mut self, x: N, y: N, z: N, w: N) {
self.x = x;
self.y = y;
self.z = z;
self.w = w;
}
/// Scale the Quat values
///
/// # Arguments
///
/// * `scalar`: value of the scalation
#[inline]
pub fn scale(&mut self, scalar: N) {
self.x = self.x * scalar;
self.y = self.y * scalar;
self.z = self.z * scalar;
self.w = self.w * scalar;
}
/// Returns the conjugation of a quaternion
#[inline]
pub fn conjugate(&self) -> Quat<N> where N: Neg<Output = N> {
Quat {
x: -self.x,
y: -self.y,
z: -self.z,
w: self.w
}
}
/// Returns the magnitude of a quaternion
#[inline]
pub fn magnitude(&self) -> f64 where N: Into<f64> {
(pow(self.x, 2) + pow(self.y, 2) + pow(self.z, 2) + pow(self.w, 2)).into().sqrt()
}
/// Returns the normalization of a quaternion in decimal values
#[inline]
pub fn norm(&self) -> Quat<f64> where N: Into<f64> {
let m: f64 = self.magnitude();
Quat::<f64> {
x: self.x.into() / m,
y: self.y.into() / m,
z: self.z.into() / m,
w: self.w.into() / m
}
}
/// Returns a quaternion representing the rotation of a three dimensional component
///
/// # Arguments
///
/// * `x`: x dimensional value
/// * `y`: y dimensional value
/// * `z`: z dimensional value
/// * `angle`: angle of the rotation
#[inline]
pub fn rotation(x: N, y: N, z: N, angle: f64) -> Quat<f64>
where N: Into<f64> {
Quat::<f64> {
x: x.into() * (angle * 0.5).sin(),
y: y.into() * (angle * 0.5).sin(),
z: z.into() * (angle * 0.5).sin(),
w: (angle * 0.5).cos()
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Traits
////////////////////////////////////////////////////////////////////////////////
/// Add `+` implementation for Quat
impl<N: Copy + Num> Add for Quat<N> {
type Output = Quat<N>;
fn add(self, other: Quat<N>) -> Quat<N> {
Quat { x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
w: self.w + other.w }
}
}
/// Sub `-` implementation for Quat
impl<N: Copy + Num> Sub for Quat<N> {
type Output = Quat<N>;
fn sub(self, other: Quat<N>) -> Quat<N> {
Quat { x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
w: self.w - other.w }
}
}
/// Negative `-` implementation for Quat
impl<N: Copy + Num + Neg<Output = N>> Neg for Quat<N> {
type Output = Quat<N>;
fn neg(self) -> Quat<N> {
Quat { x: -self.x,
y: -self.y,
z: -self.z,
w: -self.w }
}
}
/// Multiplication `*` implementation for Quat
impl<N: Copy + Num> Mul for Quat<N> {
type Output = Quat<N>;
fn mul(self, other: Quat<N>) -> Quat<N> {
Quat { x: self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y,
y: self.w*other.y - self.x*other.z + self.y*other.w + self.z*other.x,
z: self.w*other.z + self.x*other.y - self.y*other.x + self.z*other.w,
w: self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z }
}
}
/// Display implementation for Quat
impl<N: Copy + Num> fmt::Display for Quat<N> where N: fmt::Display {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "( {x}, {y}, {z}, {w} )", x = self.x, y = self.y, z = self.z, w = self.w)
}
} |
use crate::error::{from_protobuf_error, NiaServerError, NiaServerResult};
use crate::protocol::Serializable;
use protobuf::Message;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ActionKeyPress {
key_code: i32,
}
impl ActionKeyPress {
pub fn new(key_code: i32) -> ActionKeyPress {
ActionKeyPress { key_code }
}
pub fn get_key_code(&self) -> i32 {
self.key_code
}
}
impl Serializable<ActionKeyPress, nia_protocol_rust::ActionKeyPress>
for ActionKeyPress
{
fn to_pb(&self) -> nia_protocol_rust::ActionKeyPress {
let mut action_key_press_pb = nia_protocol_rust::ActionKeyPress::new();
action_key_press_pb.set_key_code(self.get_key_code());
action_key_press_pb
}
fn from_pb(
object_pb: nia_protocol_rust::ActionKeyPress,
) -> NiaServerResult<ActionKeyPress> {
let action_key_press = ActionKeyPress::new(object_pb.get_key_code());
Ok(action_key_press)
}
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[test]
fn serializable_and_deserializable() {
let expected = 123;
let action_key_press = ActionKeyPress::new(expected);
let bytes = action_key_press.to_bytes().unwrap();
let action_key_press = ActionKeyPress::from_bytes(bytes).unwrap();
let result = action_key_press.key_code;
assert_eq!(expected, result)
}
}
|
#[doc = "Register `HYSCR4` reader"]
pub type R = crate::R<HYSCR4_SPEC>;
#[doc = "Register `HYSCR4` writer"]
pub type W = crate::W<HYSCR4_SPEC>;
#[doc = "Field `PG` reader - Port G hysteresis control on/off"]
pub type PG_R = crate::FieldReader<u16>;
#[doc = "Field `PG` writer - Port G hysteresis control on/off"]
pub type PG_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>;
impl R {
#[doc = "Bits 0:15 - Port G hysteresis control on/off"]
#[inline(always)]
pub fn pg(&self) -> PG_R {
PG_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - Port G hysteresis control on/off"]
#[inline(always)]
#[must_use]
pub fn pg(&mut self) -> PG_W<HYSCR4_SPEC, 0> {
PG_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 = "Hysteresis control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hyscr4::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 [`hyscr4::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct HYSCR4_SPEC;
impl crate::RegisterSpec for HYSCR4_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`hyscr4::R`](R) reader structure"]
impl crate::Readable for HYSCR4_SPEC {}
#[doc = "`write(|w| ..)` method takes [`hyscr4::W`](W) writer structure"]
impl crate::Writable for HYSCR4_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets HYSCR4 to value 0"]
impl crate::Resettable for HYSCR4_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use phi::{Phi, View, ViewAction};
use phi::gfx::{CopySprite, Sprite, AnimatedSprite, AnimatedSpriteDescr};
use phi::data::{Rectangle, MaybeAlive};
use views::shared::{Background, BgSet};
use views::panel::{Panel, PanelFactory};
use views::panel;
use views::card::{Card, CardFactory};
use sdl2::pixels::Color;
const DEBUG: bool = false;
enum Possibility {
}
enum CardAction {
NextTurn { yourself: Possibility },
}
pub struct GameView {
bg: BgSet,
panels: Vec<Panel>,
}
impl GameView {
pub fn new(phi: &mut Phi) -> GameView {
let bg = BgSet::new(&mut phi.renderer);
let card_factory = Card::factory(phi);
GameView {
bg: bg,
panels: panel::factory().new_panel(card_factory.new_deck(phi, 5), 5),
}
}
}
impl View for GameView {
fn render(&mut self, phi: &mut Phi) -> ViewAction {
if phi.events.now.quit {
return ViewAction::Quit;
}
// Clear the screen
phi.renderer.set_draw_color(Color::RGB(0, 0, 0));
phi.renderer.clear();
// Render the background
self.bg.back.render(&mut phi.renderer);
// Render Panels
for panel in &self.panels {
panel.render(phi);
}
ViewAction::None
}
fn update(mut self: Box<Self>, phi: &mut Phi, elapsed: f64) -> ViewAction {
if phi.events.now.quit {
return ViewAction::Quit;
}
ViewAction::None
}
}
|
use crate::num_traits::FromPrimitive;
use fmt::Display;
use serde::{de, Deserialize, Deserializer};
use std::{fmt, marker::Copy};
#[derive(Debug, Primitive, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ExposureMode {
Undefined = 0,
Manual = 1,
ProgramAE = 2,
AperturePriority = 3,
ShutterPriority = 4,
Creative = 5,
Action = 6,
Portrait = 7,
Landscape = 8,
Bulb = 9,
}
impl Clone for ExposureMode {
fn clone(&self) -> ExposureMode {
*self
}
}
impl Default for ExposureMode {
fn default() -> Self {
ExposureMode::Undefined
}
}
impl<'de> Deserialize<'de> for ExposureMode {
fn deserialize<D>(deserializer: D) -> Result<ExposureMode, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_u64(ExposureModeVisitor)
}
}
impl Display for ExposureMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ExposureMode::Undefined => f.write_str("Unknown"),
ExposureMode::Manual => f.write_str("Manual"),
ExposureMode::ProgramAE => f.write_str("Program AE"),
ExposureMode::AperturePriority => f.write_str("Aperture Priority"),
ExposureMode::ShutterPriority => f.write_str("Shutter Priority"),
ExposureMode::Creative => f.write_str("Creative Mode"),
ExposureMode::Action => f.write_str("Action Mode"),
ExposureMode::Portrait => f.write_str("Portrait Mode"),
ExposureMode::Landscape => f.write_str("Landscape Mode"),
ExposureMode::Bulb => f.write_str("Bulb Flash"),
}
}
}
struct ExposureModeVisitor;
impl<'de> de::Visitor<'de> for ExposureModeVisitor {
type Value = ExposureMode;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("an integer between 0 and 9")
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(ExposureMode::from_u64(value).unwrap())
}
}
|
#[doc = "Register `CR` reader"]
pub type R = crate::R<CR_SPEC>;
#[doc = "Register `CR` writer"]
pub type W = crate::W<CR_SPEC>;
#[doc = "Field `EN` reader - EN"]
pub type EN_R = crate::BitReader;
#[doc = "Field `EN` writer - EN"]
pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CACHEINV` reader - CACHEINV"]
pub type CACHEINV_R = crate::BitReader;
#[doc = "Field `CACHEINV` writer - CACHEINV"]
pub type CACHEINV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WAYSEL` reader - WAYSEL"]
pub type WAYSEL_R = crate::BitReader;
#[doc = "Field `WAYSEL` writer - WAYSEL"]
pub type WAYSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HITMEN` reader - HITMEN"]
pub type HITMEN_R = crate::BitReader;
#[doc = "Field `HITMEN` writer - HITMEN"]
pub type HITMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MISSMEN` reader - MISSMEN"]
pub type MISSMEN_R = crate::BitReader;
#[doc = "Field `MISSMEN` writer - MISSMEN"]
pub type MISSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HITMRST` reader - HITMRST"]
pub type HITMRST_R = crate::BitReader;
#[doc = "Field `HITMRST` writer - HITMRST"]
pub type HITMRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MISSMRST` reader - MISSMRST"]
pub type MISSMRST_R = crate::BitReader;
#[doc = "Field `MISSMRST` writer - MISSMRST"]
pub type MISSMRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - EN"]
#[inline(always)]
pub fn en(&self) -> EN_R {
EN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - CACHEINV"]
#[inline(always)]
pub fn cacheinv(&self) -> CACHEINV_R {
CACHEINV_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - WAYSEL"]
#[inline(always)]
pub fn waysel(&self) -> WAYSEL_R {
WAYSEL_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 16 - HITMEN"]
#[inline(always)]
pub fn hitmen(&self) -> HITMEN_R {
HITMEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - MISSMEN"]
#[inline(always)]
pub fn missmen(&self) -> MISSMEN_R {
MISSMEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - HITMRST"]
#[inline(always)]
pub fn hitmrst(&self) -> HITMRST_R {
HITMRST_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - MISSMRST"]
#[inline(always)]
pub fn missmrst(&self) -> MISSMRST_R {
MISSMRST_R::new(((self.bits >> 19) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - EN"]
#[inline(always)]
#[must_use]
pub fn en(&mut self) -> EN_W<CR_SPEC, 0> {
EN_W::new(self)
}
#[doc = "Bit 1 - CACHEINV"]
#[inline(always)]
#[must_use]
pub fn cacheinv(&mut self) -> CACHEINV_W<CR_SPEC, 1> {
CACHEINV_W::new(self)
}
#[doc = "Bit 2 - WAYSEL"]
#[inline(always)]
#[must_use]
pub fn waysel(&mut self) -> WAYSEL_W<CR_SPEC, 2> {
WAYSEL_W::new(self)
}
#[doc = "Bit 16 - HITMEN"]
#[inline(always)]
#[must_use]
pub fn hitmen(&mut self) -> HITMEN_W<CR_SPEC, 16> {
HITMEN_W::new(self)
}
#[doc = "Bit 17 - MISSMEN"]
#[inline(always)]
#[must_use]
pub fn missmen(&mut self) -> MISSMEN_W<CR_SPEC, 17> {
MISSMEN_W::new(self)
}
#[doc = "Bit 18 - HITMRST"]
#[inline(always)]
#[must_use]
pub fn hitmrst(&mut self) -> HITMRST_W<CR_SPEC, 18> {
HITMRST_W::new(self)
}
#[doc = "Bit 19 - MISSMRST"]
#[inline(always)]
#[must_use]
pub fn missmrst(&mut self) -> MISSMRST_W<CR_SPEC, 19> {
MISSMRST_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 = "ICACHE control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::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 [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CR_SPEC;
impl crate::RegisterSpec for CR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cr::R`](R) reader structure"]
impl crate::Readable for CR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"]
impl crate::Writable for CR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CR to value 0x04"]
impl crate::Resettable for CR_SPEC {
const RESET_VALUE: Self::Ux = 0x04;
}
|
fn main() {
//defn: The String type, which is provided by Rust’s standard library rather than coded into the core language, is a growable, mutable, owned, UTF-8 encoded string type.
/////////////////
// new strings //
/////////////////
// new empty string
let mut s = String::new();
// pushing (borrowed) slices
s.push_str("foo");
s.push_str(" bar");
// new string from literal
let literal = "some text";
let _s1 = literal.to_string();
let _s2 = "some text".to_string();
let _s3 = String::from("some text");
// pushing chars
let mut s4 = String::from("lo");
s4.push('l');
///////////////////
// concatenation //
///////////////////
// with `+` operator
let s5 = String::from("foo ");
let s6 = String::from("bar");
let _s7 = s5 + &s6; // s5 is moved to s7 and cannot be used anymore
// note: + delegates to fn w/ signature ~=
// fn add(self, s: &str) -> String
// this means that &s6: &String is deref coerced to &str
// upshot: we move s5,
// apend a borrowed copy of s6
// and return ownership of the result
// (more efficient than copying both strings)
// with format! macro
let tic = String::from("tic");
let tac = String::from("tac");
let toe = String::from("toe");
let _s8 = format!("{}-{}-{}", tic, tac, toe); // does not take ownership of any params
/////////////////
// no indexing //
/////////////////
let _s9 = String::from("foo");
// let f = s9[0]; <- BOOM! (cannot index into strings)
// WHY? mainly: UTF-8
// rust respresents strings as vecotrs of bytes
// but it also supports UTF-8 strings, so chars are represented w/ 2 bytes
// -> indexing woudl return only 1 of 2 bytes necessary to represent char
// :. the compiler prevents this error
// also: consider bytes, scalar values (chars), grapheme clusters
// - in non-english languages, there can be multiple bytes per char (aka "scalar value")
// and multiple chars per grapheme cluster ("leter") b/c diacritics each get a char repr
// - note: in the hindu example (below), we have 6 chars, but *18* bytes (ie: 3 chars per byte) why?
// - :. REALLY no 1-to-1 mapping of byte to "letter"
// slicing as workaround..
let hello = "Здравствуйте";
let s10 = &hello[0..4];
assert!(s10 == "Зд");
// let s10 = &hello[0..1]; <-- BOOM! invalid char boundary!
///////////////
// iterating //
///////////////
for c in "नमस्ते".chars() {
println!("{}", c); // prints 6 chars (including diacritics)
}
for b in "नमस्ते".bytes() {
println!("{}", b); // prints 18 bytes
}
}
|
use crate::binds::BindCount;
use crate::binds::{BindsInternal, CollectBinds};
use crate::{Column, WriteSql};
use std::fmt::{self, Write};
#[derive(Debug, Clone)]
pub enum Group {
Col(Column),
And { lhs: Box<Group>, rhs: Box<Group> },
Raw(String),
}
impl Group {
pub fn raw(sql: &str) -> Self {
Group::Raw(sql.to_string())
}
}
impl<T> From<T> for Group
where
T: Into<Column>,
{
fn from(col: T) -> Self {
Group::Col(col.into())
}
}
impl WriteSql for &Group {
fn write_sql<W: Write>(self, f: &mut W, bind_count: &mut BindCount) -> fmt::Result {
match self {
Group::Col(col) => col.write_sql(f, bind_count),
Group::And { lhs, rhs } => {
lhs.write_sql(f, bind_count)?;
write!(f, ", ")?;
rhs.write_sql(f, bind_count)?;
Ok(())
}
Group::Raw(sql) => write!(f, "{}", sql),
}
}
}
impl CollectBinds for Group {
fn collect_binds(&self, _: &mut BindsInternal) {}
}
impl<T> Into<Group> for (T,)
where
T: Into<Group>,
{
fn into(self) -> Group {
self.0.into()
}
}
macro_rules! impl_into_group {
(
$first:ident, $second:ident,
) => {
#[allow(warnings)]
impl<$first, $second> Into<Group> for ($first, $second)
where
$first: Into<Group>,
$second: Into<Group>,
{
fn into(self) -> Group {
let (lhs, rhs) = self;
Group::And {
lhs: Box::new(lhs.into()),
rhs: Box::new(rhs.into()),
}
}
}
};
(
$head:ident, $($tail:ident),*,
) => {
#[allow(warnings)]
impl<$head, $($tail),*> Into<Group> for ($head, $($tail),*)
where
$head: Into<Group>,
$( $tail: Into<Group> ),*
{
fn into(self) -> Group {
let (
$head, $($tail),*
) = self;
let tail_group: Group = ($($tail),*).into();
Group::And {
lhs: Box::new($head.into()),
rhs: Box::new(tail_group),
}
}
}
impl_into_group!($($tail),*,);
};
}
impl_into_group!(
T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21,
T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32,
);
|
use crate::generate::grammars::{LexicalGrammar, Production, ProductionStep, SyntaxGrammar};
use crate::generate::rules::{Associativity, Precedence, Symbol, SymbolType, TokenSet};
use lazy_static::lazy_static;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::u32;
lazy_static! {
static ref START_PRODUCTION: Production = Production {
dynamic_precedence: 0,
steps: vec![ProductionStep {
symbol: Symbol {
index: 0,
kind: SymbolType::NonTerminal,
},
precedence: Precedence::None,
associativity: None,
alias: None,
field_name: None,
}],
};
}
/// A ParseItem represents an in-progress match of a single production in a grammar.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ParseItem<'a> {
/// The index of the parent rule within the grammar.
pub variable_index: u32,
/// The number of symbols that have already been matched.
pub step_index: u32,
/// The production being matched.
pub production: &'a Production,
/// A boolean indicating whether any of the already-matched children were
/// hidden nodes and had fields. Ordinarily, a parse item's behavior is not
/// affected by the symbols of its preceding children; it only needs to
/// keep track of their fields and aliases.
///
/// Take for example these two items:
/// X -> a b • c
/// X -> a g • c
///
/// They can be considered equivalent, for the purposes of parse table
/// generation, because they entail the same actions. But if this flag is
/// true, then the item's set of inherited fields may depend on the specific
/// symbols of its preceding children.
pub has_preceding_inherited_fields: bool,
}
/// A ParseItemSet represents a set of in-progress matches of productions in a
/// grammar, and for each in-progress match, a set of "lookaheads" - tokens that
/// are allowed to *follow* the in-progress rule. This object corresponds directly
/// to a state in the final parse table.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ParseItemSet<'a> {
pub entries: Vec<(ParseItem<'a>, TokenSet)>,
}
/// A ParseItemSetCore is like a ParseItemSet, but without the lookahead
/// information. Parse states with the same core are candidates for merging.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ParseItemSetCore<'a> {
pub entries: Vec<ParseItem<'a>>,
}
pub(crate) struct ParseItemDisplay<'a>(
pub &'a ParseItem<'a>,
pub &'a SyntaxGrammar,
pub &'a LexicalGrammar,
);
pub(crate) struct TokenSetDisplay<'a>(
pub &'a TokenSet,
pub &'a SyntaxGrammar,
pub &'a LexicalGrammar,
);
pub(crate) struct ParseItemSetDisplay<'a>(
pub &'a ParseItemSet<'a>,
pub &'a SyntaxGrammar,
pub &'a LexicalGrammar,
);
impl<'a> ParseItem<'a> {
pub fn start() -> Self {
ParseItem {
variable_index: u32::MAX,
production: &START_PRODUCTION,
step_index: 0,
has_preceding_inherited_fields: false,
}
}
pub fn step(&self) -> Option<&'a ProductionStep> {
self.production.steps.get(self.step_index as usize)
}
pub fn symbol(&self) -> Option<Symbol> {
self.step().map(|step| step.symbol)
}
pub fn associativity(&self) -> Option<Associativity> {
self.prev_step().and_then(|step| step.associativity)
}
pub fn precedence(&self) -> &Precedence {
self.prev_step()
.map_or(&Precedence::None, |step| &step.precedence)
}
pub fn prev_step(&self) -> Option<&'a ProductionStep> {
if self.step_index > 0 {
Some(&self.production.steps[self.step_index as usize - 1])
} else {
None
}
}
pub fn is_done(&self) -> bool {
self.step_index as usize == self.production.steps.len()
}
pub fn is_augmented(&self) -> bool {
self.variable_index == u32::MAX
}
/// Create an item like this one, but advanced by one step.
pub fn successor(&self) -> ParseItem<'a> {
ParseItem {
variable_index: self.variable_index,
production: self.production,
step_index: self.step_index + 1,
has_preceding_inherited_fields: self.has_preceding_inherited_fields,
}
}
/// Create an item identical to this one, but with a different production.
/// This is used when dynamically "inlining" certain symbols in a production.
pub fn substitute_production(&self, production: &'a Production) -> ParseItem<'a> {
let mut result = self.clone();
result.production = production;
result
}
}
impl<'a> ParseItemSet<'a> {
pub fn with(elements: impl IntoIterator<Item = (ParseItem<'a>, TokenSet)>) -> Self {
let mut result = Self::default();
for (item, lookaheads) in elements {
result.insert(item, &lookaheads);
}
result
}
pub fn insert(&mut self, item: ParseItem<'a>, lookaheads: &TokenSet) -> &mut TokenSet {
match self.entries.binary_search_by(|(i, _)| i.cmp(&item)) {
Err(i) => {
self.entries.insert(i, (item, lookaheads.clone()));
&mut self.entries[i].1
}
Ok(i) => {
self.entries[i].1.insert_all(lookaheads);
&mut self.entries[i].1
}
}
}
pub fn core(&self) -> ParseItemSetCore<'a> {
ParseItemSetCore {
entries: self.entries.iter().map(|e| e.0).collect(),
}
}
}
impl<'a> Default for ParseItemSet<'a> {
fn default() -> Self {
Self {
entries: Vec::new(),
}
}
}
impl<'a> fmt::Display for ParseItemDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if self.0.is_augmented() {
write!(f, "START →")?;
} else {
write!(
f,
"{} →",
&self.1.variables[self.0.variable_index as usize].name
)?;
}
for (i, step) in self.0.production.steps.iter().enumerate() {
if i == self.0.step_index as usize {
write!(f, " •")?;
if let Some(associativity) = step.associativity {
if !step.precedence.is_none() {
write!(f, " ({} {:?})", step.precedence, associativity)?;
} else {
write!(f, " ({:?})", associativity)?;
}
} else if !step.precedence.is_none() {
write!(f, " ({})", step.precedence)?;
}
}
write!(f, " ")?;
if step.symbol.is_terminal() {
if let Some(variable) = self.2.variables.get(step.symbol.index) {
write!(f, "{}", &variable.name)?;
} else {
write!(f, "{}-{}", "terminal", step.symbol.index)?;
}
} else if step.symbol.is_external() {
write!(f, "{}", &self.1.external_tokens[step.symbol.index].name)?;
} else {
write!(f, "{}", &self.1.variables[step.symbol.index].name)?;
}
if let Some(alias) = &step.alias {
write!(f, "@{}", alias.value)?;
}
}
if self.0.is_done() {
write!(f, " •")?;
if let Some(step) = self.0.production.steps.last() {
if let Some(associativity) = step.associativity {
if !step.precedence.is_none() {
write!(f, " ({} {:?})", step.precedence, associativity)?;
} else {
write!(f, " ({:?})", associativity)?;
}
} else if !step.precedence.is_none() {
write!(f, " ({})", step.precedence)?;
}
}
}
Ok(())
}
}
impl<'a> fmt::Display for TokenSetDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "[")?;
for (i, symbol) in self.0.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
if symbol.is_terminal() {
if let Some(variable) = self.2.variables.get(symbol.index) {
write!(f, "{}", &variable.name)?;
} else {
write!(f, "{}-{}", "terminal", symbol.index)?;
}
} else if symbol.is_external() {
write!(f, "{}", &self.1.external_tokens[symbol.index].name)?;
} else {
write!(f, "{}", &self.1.variables[symbol.index].name)?;
}
}
write!(f, "]")?;
Ok(())
}
}
impl<'a> fmt::Display for ParseItemSetDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for (item, lookaheads) in self.0.entries.iter() {
writeln!(
f,
"{}\t{}",
ParseItemDisplay(item, self.1, self.2),
TokenSetDisplay(lookaheads, self.1, self.2)
)?;
}
Ok(())
}
}
impl<'a> Hash for ParseItem<'a> {
fn hash<H: Hasher>(&self, hasher: &mut H) {
hasher.write_u32(self.variable_index);
hasher.write_u32(self.step_index);
hasher.write_i32(self.production.dynamic_precedence);
hasher.write_usize(self.production.steps.len());
hasher.write_i32(self.has_preceding_inherited_fields as i32);
self.precedence().hash(hasher);
self.associativity().hash(hasher);
// The already-matched children don't play any role in the parse state for
// this item, unless any of the following are true:
// * the children have fields
// * the children have aliases
// * the children are hidden and
// See the docs for `has_preceding_inherited_fields`.
for step in &self.production.steps[0..self.step_index as usize] {
step.alias.hash(hasher);
step.field_name.hash(hasher);
if self.has_preceding_inherited_fields {
step.symbol.hash(hasher);
}
}
for step in &self.production.steps[self.step_index as usize..] {
step.hash(hasher);
}
}
}
impl<'a> PartialEq for ParseItem<'a> {
fn eq(&self, other: &Self) -> bool {
if self.variable_index != other.variable_index
|| self.step_index != other.step_index
|| self.production.dynamic_precedence != other.production.dynamic_precedence
|| self.production.steps.len() != other.production.steps.len()
|| self.precedence() != other.precedence()
|| self.associativity() != other.associativity()
|| self.has_preceding_inherited_fields != other.has_preceding_inherited_fields
{
return false;
}
for (i, step) in self.production.steps.iter().enumerate() {
// See the previous comment (in the `Hash::hash` impl) regarding comparisons
// of parse items' already-completed steps.
if i < self.step_index as usize {
if step.alias != other.production.steps[i].alias {
return false;
}
if step.field_name != other.production.steps[i].field_name {
return false;
}
if self.has_preceding_inherited_fields
&& step.symbol != other.production.steps[i].symbol
{
return false;
}
} else if *step != other.production.steps[i] {
return false;
}
}
return true;
}
}
impl<'a> Ord for ParseItem<'a> {
fn cmp(&self, other: &Self) -> Ordering {
self.step_index
.cmp(&other.step_index)
.then_with(|| self.variable_index.cmp(&other.variable_index))
.then_with(|| {
self.production
.dynamic_precedence
.cmp(&other.production.dynamic_precedence)
})
.then_with(|| {
self.production
.steps
.len()
.cmp(&other.production.steps.len())
})
.then_with(|| self.precedence().cmp(&other.precedence()))
.then_with(|| self.associativity().cmp(&other.associativity()))
.then_with(|| {
for (i, step) in self.production.steps.iter().enumerate() {
// See the previous comment (in the `Hash::hash` impl) regarding comparisons
// of parse items' already-completed steps.
let o = if i < self.step_index as usize {
step.alias
.cmp(&other.production.steps[i].alias)
.then_with(|| {
step.field_name.cmp(&other.production.steps[i].field_name)
})
} else {
step.cmp(&other.production.steps[i])
};
if o != Ordering::Equal {
return o;
}
}
return Ordering::Equal;
})
}
}
impl<'a> PartialOrd for ParseItem<'a> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Eq for ParseItem<'a> {}
impl<'a> Hash for ParseItemSet<'a> {
fn hash<H: Hasher>(&self, hasher: &mut H) {
hasher.write_usize(self.entries.len());
for (item, lookaheads) in self.entries.iter() {
item.hash(hasher);
lookaheads.hash(hasher);
}
}
}
impl<'a> Hash for ParseItemSetCore<'a> {
fn hash<H: Hasher>(&self, hasher: &mut H) {
hasher.write_usize(self.entries.len());
for item in &self.entries {
item.hash(hasher);
}
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
use std::path::PathBuf;
use bytes::BytesMut;
use nix::sys::stat::FileStat;
use reverie::Pid;
use crate::gdbstub::commands::*;
use crate::gdbstub::hex::*;
/// struct stat defined by gdb host i/o packet. This is *not* the same as
/// libc::stat or nix's FileStat (which is just libc::stat).
// NB: packed is needed to force size_of::<HostioStat> == 0x40. Otherwise
// gdb (client) would complain.
#[repr(packed(4))]
pub struct HostioStat {
st_dev: u32,
st_ino: u32,
st_mode: u32,
st_nlink: u32,
st_uid: u32,
st_gid: u32,
st_rdev: u32,
st_size: u64,
st_blksize: u64,
st_blocks: u64,
st_atime: u32,
st_mtime: u32,
st_ctime: u32,
}
impl From<FileStat> for HostioStat {
fn from(stat: FileStat) -> HostioStat {
HostioStat {
st_dev: stat.st_dev as u32,
st_ino: stat.st_ino as u32,
st_nlink: stat.st_nlink as u32,
st_mode: stat.st_mode as u32,
st_uid: stat.st_uid,
st_gid: stat.st_gid,
st_rdev: stat.st_rdev as u32,
st_size: stat.st_size as u64,
st_blksize: stat.st_blksize as u64,
st_blocks: stat.st_blocks as u64,
st_atime: stat.st_atime as u32,
st_mtime: stat.st_mtime as u32,
st_ctime: stat.st_ctime as u32,
}
}
}
#[derive(PartialEq, Debug)]
pub enum vFile {
Setfs(Option<i32>),
Open(PathBuf, i32, u32),
Close(i32),
Pread(i32, isize, isize),
Pwrite(i32, isize, Vec<u8>),
Fstat(i32),
Unlink(PathBuf),
Readlink(PathBuf),
}
impl ParseCommand for vFile {
fn parse(mut bytes: BytesMut) -> Option<Self> {
if bytes.starts_with(b":setfs:") {
let pid: i32 = decode_hex(&bytes[b":setfs:".len()..]).ok()?;
Some(vFile::Setfs(if pid == 0 { None } else { Some(pid) }))
} else if bytes.starts_with(b":open:") {
let mut iter = bytes[b":open:".len()..].split_mut(|c| *c == b',');
let fname = iter.next().and_then(|s| decode_hex_string(s).ok())?;
let fname = PathBuf::from(OsString::from_vec(fname));
let flags = iter.next().and_then(|s| decode_hex(s).ok())?;
let mode = iter.next().and_then(|s| decode_hex(s).ok())?;
Some(vFile::Open(fname, flags, mode))
} else if bytes.starts_with(b":close:") {
let fd: i32 = decode_hex(&bytes[b":close:".len()..]).ok()?;
Some(vFile::Close(fd))
} else if bytes.starts_with(b":pread:") {
let mut iter = bytes[b":pread:".len()..].split_mut(|c| *c == b',');
let fd = iter.next().and_then(|s| decode_hex(s).ok())?;
let count = iter.next().and_then(|s| decode_hex(s).ok())?;
let offset = iter.next().and_then(|s| decode_hex(s).ok())?;
Some(vFile::Pread(fd, count, offset))
} else if bytes.starts_with(b":pwrite:") {
let mut iter = bytes[b":pwrite:".len()..].split_mut(|c| *c == b',');
let fd = iter.next().and_then(|s| decode_hex(s).ok())?;
let offset = iter.next().and_then(|s| decode_hex(s).ok())?;
let bytes = iter.next().and_then(|s| decode_binary_string(s).ok())?;
Some(vFile::Pwrite(fd, offset, bytes))
} else if bytes.starts_with(b":fstat:") {
let fd: i32 = decode_hex(&bytes[b":fstat:".len()..]).ok()?;
Some(vFile::Fstat(fd))
} else if bytes.starts_with(b":unlink:") {
let fname = bytes.split_off(b":unlink:".len());
let fname = decode_hex_string(&fname).ok()?;
let fname = PathBuf::from(OsString::from_vec(fname));
Some(vFile::Unlink(fname))
} else if bytes.starts_with(b":readlink:") {
let fname = bytes.split_off(b":readlink:".len());
let fname = decode_hex_string(&fname).ok()?;
let fname = PathBuf::from(OsString::from_vec(fname));
Some(vFile::Readlink(fname))
} else {
None
}
}
}
#[cfg(test)]
mod test {
use std::mem;
use super::*;
#[test]
fn hostio_stat_size_check() {
assert_eq!(mem::size_of::<HostioStat>(), 0x40);
}
#[test]
fn hostio_sanity() {
// NB: `vFile` prefix is stripped prior.
assert_eq!(
vFile::parse(BytesMut::from(&b":open:6a7573742070726f62696e67,0,1c0"[..])),
Some(vFile::Open(PathBuf::from("just probing"), 0x0, 0x1c0))
);
assert_eq!(
vFile::parse(BytesMut::from(&b":pread:b,1000,0"[..])),
Some(vFile::Pread(0xb, 0x1000, 0x0))
);
assert_eq!(
vFile::parse(BytesMut::from(&b":unlink:6a7573742070726f62696e67"[..])),
Some(vFile::Unlink(PathBuf::from("just probing")))
);
assert_eq!(
vFile::parse(BytesMut::from(&b":readlink:6a7573742070726f62696e67"[..])),
Some(vFile::Readlink(PathBuf::from("just probing")))
);
}
}
|
use crossterm::{
cursor, queue,
style::{Color, Print, ResetColor, SetBackgroundColor, SetForegroundColor},
terminal::{self, Clear, ClearType},
Result,
};
use std::io::Write;
pub const ENTRY_COLOR: Color = Color::Rgb {
r: 255,
g: 180,
b: 100,
};
const HEADER_COLOR: Color = Color::Black;
const ACTION_COLOR: Color = Color::White;
const HEADER_BG_WAITING_COLOR: Color = Color::Magenta;
const HEADER_BG_WAITING_DARK_COLOR: Color = Color::DarkMagenta;
const HEADER_BG_OK_COLOR: Color = Color::Green;
const HEADER_BG_OK_DARK_COLOR: Color = Color::DarkGreen;
const HEADER_BG_ERROR_COLOR: Color = Color::Red;
const HEADER_BG_ERROR_DARK_COLOR: Color = Color::DarkRed;
const HEADER_BG_CANCELED_COLOR: Color = Color::Yellow;
const HEADER_BG_CANCELED_DARK_COLOR: Color = Color::DarkYellow;
const HEADER_PREFIX: &str = "Verco @ ";
pub enum HeaderKind {
Waiting,
Ok,
Error,
Canceled,
}
pub struct Header<'a> {
pub action_name: &'a str,
pub directory_name: String,
}
impl<'a> Header<'a> {
pub fn length(&self) -> usize {
HEADER_PREFIX.len()
+ self.directory_name.len()
+ 3
+ self.action_name.len()
}
}
pub fn show_header<W>(
write: &mut W,
header: &Header,
kind: HeaderKind,
) -> Result<()>
where
W: Write,
{
let background_color = match kind {
HeaderKind::Waiting => HEADER_BG_WAITING_COLOR,
HeaderKind::Ok => HEADER_BG_OK_COLOR,
HeaderKind::Error => HEADER_BG_ERROR_COLOR,
HeaderKind::Canceled => HEADER_BG_CANCELED_COLOR,
};
let background_dark_color = match kind {
HeaderKind::Waiting => HEADER_BG_WAITING_DARK_COLOR,
HeaderKind::Ok => HEADER_BG_OK_DARK_COLOR,
HeaderKind::Error => HEADER_BG_ERROR_DARK_COLOR,
HeaderKind::Canceled => HEADER_BG_CANCELED_DARK_COLOR,
};
let status = match kind {
HeaderKind::Waiting => "waiting",
HeaderKind::Ok => "ok",
HeaderKind::Error => "error",
HeaderKind::Canceled => "canceled",
};
queue!(
write,
Clear(ClearType::All),
cursor::MoveTo(0, 0),
SetBackgroundColor(background_color),
SetForegroundColor(HEADER_COLOR),
Print(HEADER_PREFIX),
Print(&header.directory_name),
Print(' '),
SetBackgroundColor(background_dark_color),
SetForegroundColor(ACTION_COLOR),
Print(' '),
Print(header.action_name),
Print(' '),
SetBackgroundColor(background_color),
SetForegroundColor(HEADER_COLOR),
Print(" ".repeat(
terminal::size()?.0 as usize - header.length() - status.len() - 2
)),
SetBackgroundColor(background_dark_color),
SetForegroundColor(ACTION_COLOR),
Print(' '),
Print(status),
Print(' '),
ResetColor,
cursor::MoveToNextLine(1),
)
}
|
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - MSPI PIO Transfer Control/Status Register"]
pub ctrl: CTRL,
#[doc = "0x04 - MSPI Transfer Configuration Register"]
pub cfg: CFG,
#[doc = "0x08 - MSPI Transfer Address Register"]
pub addr: ADDR,
#[doc = "0x0c - MSPI Transfer Instruction"]
pub instr: INSTR,
#[doc = "0x10 - TX Data FIFO"]
pub txfifo: TXFIFO,
#[doc = "0x14 - RX Data FIFO"]
pub rxfifo: RXFIFO,
#[doc = "0x18 - TX FIFO Entries"]
pub txentries: TXENTRIES,
#[doc = "0x1c - RX FIFO Entries"]
pub rxentries: RXENTRIES,
#[doc = "0x20 - TX/RX FIFO Threshhold Levels"]
pub threshold: THRESHOLD,
_reserved0: [u8; 220usize],
#[doc = "0x100 - MSPI Module Configuration"]
pub mspicfg: MSPICFG,
#[doc = "0x104 - MSPI Output Pad Configuration"]
pub padcfg: PADCFG,
#[doc = "0x108 - MSPI Output Enable Pad Configuration"]
pub padouten: PADOUTEN,
#[doc = "0x10c - Configuration for XIP/DMA support of SPI flash modules."]
pub flash: FLASH,
_reserved1: [u8; 16usize],
#[doc = "0x120 - External Flash Scrambling Controls"]
pub scrambling: SCRAMBLING,
_reserved2: [u8; 220usize],
#[doc = "0x200 - MSPI Master Interrupts: Enable"]
pub inten: INTEN,
#[doc = "0x204 - MSPI Master Interrupts: Status"]
pub intstat: INTSTAT,
#[doc = "0x208 - MSPI Master Interrupts: Clear"]
pub intclr: INTCLR,
#[doc = "0x20c - MSPI Master Interrupts: Set"]
pub intset: INTSET,
_reserved3: [u8; 64usize],
#[doc = "0x250 - DMA Configuration Register"]
pub dmacfg: DMACFG,
#[doc = "0x254 - DMA Status Register"]
pub dmastat: DMASTAT,
#[doc = "0x258 - DMA Target Address Register"]
pub dmatargaddr: DMATARGADDR,
#[doc = "0x25c - DMA Device Address Register"]
pub dmadevaddr: DMADEVADDR,
#[doc = "0x260 - DMA Total Transfer Count"]
pub dmatotcount: DMATOTCOUNT,
#[doc = "0x264 - DMA BYTE Transfer Count"]
pub dmabcount: DMABCOUNT,
_reserved4: [u8; 16usize],
#[doc = "0x278 - DMA Transmit Trigger Threshhold"]
pub dmathresh: DMATHRESH,
_reserved5: [u8; 36usize],
#[doc = "0x2a0 - Command Queue Configuration Register"]
pub cqcfg: CQCFG,
_reserved6: [u8; 4usize],
#[doc = "0x2a8 - CQ Target Read Address Register"]
pub cqaddr: CQADDR,
#[doc = "0x2ac - Command Queue Status Register"]
pub cqstat: CQSTAT,
#[doc = "0x2b0 - Command Queue Flag Register"]
pub cqflags: CQFLAGS,
#[doc = "0x2b4 - Command Queue Flag Set/Clear Register"]
pub cqsetclear: CQSETCLEAR,
#[doc = "0x2b8 - Command Queue Pause Mask Register"]
pub cqpause: CQPAUSE,
_reserved7: [u8; 4usize],
#[doc = "0x2c0 - Command Queue Current Index"]
pub cqcuridx: CQCURIDX,
#[doc = "0x2c4 - Command Queue End Index"]
pub cqendidx: CQENDIDX,
}
#[doc = "MSPI PIO Transfer Control/Status Register"]
pub struct CTRL {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI PIO Transfer Control/Status Register"]
pub mod ctrl;
#[doc = "MSPI Transfer Configuration Register"]
pub struct CFG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Transfer Configuration Register"]
pub mod cfg;
#[doc = "MSPI Transfer Address Register"]
pub struct ADDR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Transfer Address Register"]
pub mod addr;
#[doc = "MSPI Transfer Instruction"]
pub struct INSTR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Transfer Instruction"]
pub mod instr;
#[doc = "TX Data FIFO"]
pub struct TXFIFO {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "TX Data FIFO"]
pub mod txfifo;
#[doc = "RX Data FIFO"]
pub struct RXFIFO {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "RX Data FIFO"]
pub mod rxfifo;
#[doc = "TX FIFO Entries"]
pub struct TXENTRIES {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "TX FIFO Entries"]
pub mod txentries;
#[doc = "RX FIFO Entries"]
pub struct RXENTRIES {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "RX FIFO Entries"]
pub mod rxentries;
#[doc = "TX/RX FIFO Threshhold Levels"]
pub struct THRESHOLD {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "TX/RX FIFO Threshhold Levels"]
pub mod threshold;
#[doc = "MSPI Module Configuration"]
pub struct MSPICFG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Module Configuration"]
pub mod mspicfg;
#[doc = "MSPI Output Pad Configuration"]
pub struct PADCFG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Output Pad Configuration"]
pub mod padcfg;
#[doc = "MSPI Output Enable Pad Configuration"]
pub struct PADOUTEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Output Enable Pad Configuration"]
pub mod padouten;
#[doc = "Configuration for XIP/DMA support of SPI flash modules."]
pub struct FLASH {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Configuration for XIP/DMA support of SPI flash modules."]
pub mod flash;
#[doc = "External Flash Scrambling Controls"]
pub struct SCRAMBLING {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "External Flash Scrambling Controls"]
pub mod scrambling;
#[doc = "MSPI Master Interrupts: Enable"]
pub struct INTEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Master Interrupts: Enable"]
pub mod inten;
#[doc = "MSPI Master Interrupts: Status"]
pub struct INTSTAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Master Interrupts: Status"]
pub mod intstat;
#[doc = "MSPI Master Interrupts: Clear"]
pub struct INTCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Master Interrupts: Clear"]
pub mod intclr;
#[doc = "MSPI Master Interrupts: Set"]
pub struct INTSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "MSPI Master Interrupts: Set"]
pub mod intset;
#[doc = "DMA Configuration Register"]
pub struct DMACFG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "DMA Configuration Register"]
pub mod dmacfg;
#[doc = "DMA Status Register"]
pub struct DMASTAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "DMA Status Register"]
pub mod dmastat;
#[doc = "DMA Target Address Register"]
pub struct DMATARGADDR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "DMA Target Address Register"]
pub mod dmatargaddr;
#[doc = "DMA Device Address Register"]
pub struct DMADEVADDR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "DMA Device Address Register"]
pub mod dmadevaddr;
#[doc = "DMA Total Transfer Count"]
pub struct DMATOTCOUNT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "DMA Total Transfer Count"]
pub mod dmatotcount;
#[doc = "DMA BYTE Transfer Count"]
pub struct DMABCOUNT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "DMA BYTE Transfer Count"]
pub mod dmabcount;
#[doc = "DMA Transmit Trigger Threshhold"]
pub struct DMATHRESH {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "DMA Transmit Trigger Threshhold"]
pub mod dmathresh;
#[doc = "Command Queue Configuration Register"]
pub struct CQCFG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Command Queue Configuration Register"]
pub mod cqcfg;
#[doc = "CQ Target Read Address Register"]
pub struct CQADDR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "CQ Target Read Address Register"]
pub mod cqaddr;
#[doc = "Command Queue Status Register"]
pub struct CQSTAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Command Queue Status Register"]
pub mod cqstat;
#[doc = "Command Queue Flag Register"]
pub struct CQFLAGS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Command Queue Flag Register"]
pub mod cqflags;
#[doc = "Command Queue Flag Set/Clear Register"]
pub struct CQSETCLEAR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Command Queue Flag Set/Clear Register"]
pub mod cqsetclear;
#[doc = "Command Queue Pause Mask Register"]
pub struct CQPAUSE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Command Queue Pause Mask Register"]
pub mod cqpause;
#[doc = "Command Queue Current Index"]
pub struct CQCURIDX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Command Queue Current Index"]
pub mod cqcuridx;
#[doc = "Command Queue End Index"]
pub struct CQENDIDX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Command Queue End Index"]
pub mod cqendidx;
|
use super::User;
use crate::utils;
use actix_web::{error, web, HttpResponse, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Info {
pub term: String,
}
pub fn search(info: web::Query<Info>) -> Result<HttpResponse, actix_web::Error> {
let term = &info.term;
dbg!(&term);
let mut user_query_conn = utils::get_user_query_db_connection().unwrap();
let user_rows = user_query_conn
.query(
r#"SELECT
entity_id,
name,
start_date,
address,
phone_number,
username,
email,
photo,
updated_at
FROM "user"
WHERE name LIKE $1
OR address LIKE $1
OR phone_number LIKE $1
OR username LIKE $1
OFFSET 0 FETCH FIRST 5 ROWS ONLY"#,
&[&(term.to_owned() + &"%".to_owned())],
)
.map_err(|e| error::ErrorInternalServerError(e))?;
let mut users: Vec<User> = vec![];
for stored_user in user_rows {
let user = User {
id: stored_user.get(0),
name: stored_user.get(1),
start_date: stored_user.get(2),
address: stored_user.get(3),
phone_number: stored_user.get(4),
username: stored_user.get(5),
email: stored_user.get(6),
photo: stored_user.get(7),
};
users.push(user);
}
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&users).unwrap()))
}
|
use std::fs::File;
use std::io::Read;
fn main() {
let mut reader: Box<dyn Read> = Box::new(File::open("Cargo.toml").unwrap());
process_file(&mut reader);
}
fn process_file(reader: &mut Box<dyn Read>) {
let mut buf = String::new();
reader.read_to_string(&mut buf).unwrap();
println!("{}", buf);
}
|
#![no_std]
#![no_main]
//#![feature(min_const_fn)]
//#![feature(const_let)]
// pick a panicking behavior
//extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics
// extern crate panic_abort; // requires nightly
// extern crate panic_itm; // logs messages over ITM; requires ITM support
extern crate panic_semihosting; // logs messages to the host stderr; requires a debugger
extern crate embedded_hal;
extern crate stm32f0;
extern crate stm32f0xx_hal as hal;
use core::mem::size_of;
use stm32f0::stm32f0x2;
use hal::delay::Delay;
use hal::gpio::*;
use hal::i2c::*;
use hal::prelude::*;
use cortex_m::interrupt::Mutex;
use cortex_m::peripheral::Peripherals as c_m_Peripherals;
use cortex_m_semihosting::{debug, hprintln};
//use cortex_m_rt::{entry, interrupt};
use cortex_m_rt::entry;
//use embedded_hal::blocking::i2c::Write;
use core::fmt::Write;
pub use hal::stm32;
pub use hal::stm32::{interrupt, Interrupt, Peripherals, EXTI, I2C1, USB};
//pub use hal::stm32::*;
use embedded_graphics::fonts::Font6x8;
use embedded_graphics::prelude::*;
use ssd1306::prelude::*;
use ssd1306::Builder;
use core::cell::RefCell;
use core::ops::DerefMut;
mod usb;
use crate::usb::descriptors::*;
// Make our LED globally available
static LED: Mutex<RefCell<Option<gpioa::PA5<Output<PushPull>>>>> = Mutex::new(RefCell::new(None));
// Make our delay provider globally available
static DELAY: Mutex<RefCell<Option<Delay>>> = Mutex::new(RefCell::new(None));
// Make external interrupt registers globally available
static INT: Mutex<RefCell<Option<EXTI>>> = Mutex::new(RefCell::new(None));
// Make USB Driver globally available
static USBDEV: Mutex<
RefCell<Option<usb::Usb<USB, (gpioa::PA11<Alternate<AF0>>, gpioa::PA12<Alternate<AF0>>)>>>,
> = Mutex::new(RefCell::new(None));
const DEV_DESC: Device = Device::new()
.iManufacturer(1)
.iProduct(2)
.iSerialNumber(3)
.bNumConfigurations(1);
const DEV_QUAL: DeviceQualifier = DeviceQualifier::new().bcdUSB(0x0200);
const INTERFACE_DESC: Interface = Interface::new().bNumEndpoints(1).iInterface(5);
const EP01_DESC: Endpoint = Endpoint::new()
.bEndpointAddress(0x01)
.wMaxPacketSize(64)
.bInterval(1);
const CONF_DESC: Configuration = Configuration::new()
.wTotalLength(
size_of::<Configuration>() as u16
+ size_of::<Interface>() as u16
+ size_of::<Endpoint>() as u16 * 1,
) // add all descs up.
.bNumInterfaces(1)
.bConfigurationValue(1)
.iConfiguration(4)
.bmAttributes(0b1_1_0_00000) // Self powered no remote wakeup.
.bMaxPower(0xFA); // 500mA.
const ints: [Interface; 1] = [INTERFACE_DESC];
const eps: [Endpoint; 1] = [EP01_DESC];
const DESCS: usb::Descriptors = usb::Descriptors {
Device: DEV_DESC,
Configuration: CONF_DESC,
Interfaces: &ints,
Endpoints: &eps,
};
#[entry]
fn main() -> ! {
hprintln!("main()").unwrap();
if let (Some(p), Some(cp)) = (Peripherals::take(), c_m_Peripherals::take()) {
let gpioa = p.GPIOA.split();
let gpiob = p.GPIOB.split();
let gpioc = p.GPIOC.split();
let syscfg = p.SYSCFG_COMP;
let exti = p.EXTI;
let rcc = p.RCC;
// Enable clock for SYSCFG
rcc.apb2enr.modify(|_, w| w.syscfgen().set_bit());
// Configure PC13 as input (button)
let _ = gpioc.pc13.into_pull_down_input();
// Configure PA5 as output (LED)
let mut led = gpioa.pa5.into_push_pull_output();
// Turn off LED
led.set_low();
// Configure clock to 48 MHz and freeze it
let clocks = rcc
.constrain()
.cfgr
.enable_hsi48(true)
.sysclk(48.mhz())
.hclk(48.mhz())
.pclk(48.mhz())
.freeze();
hprintln!("sysclk: {}", clocks.sysclk().0).unwrap();
hprintln!("hclk: {}", clocks.hclk().0).unwrap();
hprintln!("pclk: {}", clocks.pclk().0).unwrap();
// Initialise delay provider
let mut delay = Delay::new(cp.SYST, clocks);
// Enable external interrupt for PC13
syscfg
.syscfg_exticr4
.modify(|_, w| unsafe { w.exti13().bits(0b_010) });
// Set interrupt request mask for line 13
exti.imr.modify(|_, w| w.mr13().set_bit());
// Set interrupt falling trigger for line 13
exti.ftsr.modify(|_, w| w.tr13().set_bit());
let dm = gpioa.pa11.into_alternate_af0();
let dp = gpioa.pa12.into_alternate_af0();
let usb = usb::Usb::usb(p.USB, (dm, dp), DESCS);
// Configure I2C
let scl = gpiob
.pb8
.into_alternate_af1()
.internal_pull_up(true)
.set_open_drain();
let sda = gpiob
.pb9
.into_alternate_af1()
.internal_pull_up(true)
.set_open_drain();
let i2c = I2c::i2c1(p.I2C1, (scl, sda), 400.khz());
// Configure display
let mut disp: GraphicsMode<_> = Builder::new()
.with_size(DisplaySize::Display128x32)
.connect_i2c(i2c)
.into();
disp.init().unwrap();
disp.flush().unwrap();
// Move control over LED and DELAY and EXTI into global mutexes
cortex_m::interrupt::free(move |cs| {
*LED.borrow(cs).borrow_mut() = Some(led);
*DELAY.borrow(cs).borrow_mut() = Some(delay);
*INT.borrow(cs).borrow_mut() = Some(exti);
*USBDEV.borrow(cs).borrow_mut() = Some(usb);
});
// Enable EXTI IRQ, set prio 1 and clear any pending IRQs
let mut nvic = cp.NVIC;
nvic.enable(Interrupt::EXTI4_15);
nvic.enable(Interrupt::USB);
unsafe { nvic.set_priority(Interrupt::EXTI4_15, 0) };
cortex_m::peripheral::NVIC::unpend(Interrupt::EXTI4_15);
hprintln!("init complete.").unwrap();
disp.draw(
Font6x8::render_str("this is a test")
.with_stroke(Some(1u8.into()))
.into_iter(),
);
disp.flush().unwrap();
}
loop {
// your code goes here
}
}
#[interrupt]
fn USB() {
//hprintln!("USB_ISR:").unwrap();
cortex_m::interrupt::free(|cs| {
if let &mut Some(ref mut usb) = USBDEV.borrow(cs).borrow_mut().deref_mut() {
usb.interrupt();
}
});
}
#[interrupt]
fn EXTI4_15() {
// Enter critical section
hprintln!("BUTTON_PRESS").unwrap();
cortex_m::interrupt::free(|cs| {
// Obtain all Mutex protected resources
if let (&mut Some(ref mut led), &mut Some(ref mut delay), &mut Some(ref mut exti)) = (
LED.borrow(cs).borrow_mut().deref_mut(),
DELAY.borrow(cs).borrow_mut().deref_mut(),
INT.borrow(cs).borrow_mut().deref_mut(),
) {
//hprintln!("Borrow OK!").unwrap();
// Turn on LED
led.set_high();
//hprintln!("Led ON OK!").unwrap();
// Wait a second
delay.delay_ms(100_u16);
//hprintln!("Delay OK!").unwrap();
// Turn off LED
led.set_low();
//hprintln!("Led OFF OK!").unwrap();
// Clear interrupt
exti.pr.modify(|_, w| w.pif13().set_bit());
}
});
}
|
use crate::client::Client;
use crate::style::{reset_style, set_style};
use crate::window::Window;
use serde_json::Value;
use std::collections::HashMap;
use std::io::Write;
//use termion;
use termion::clear::CurrentLine;
use termion::color;
use termion::cursor::Goto;
use termion::event::{Event, Key, MouseButton, MouseEvent};
use termion::style::{Bold, Reset};
use xrl::{ClientResult, Line, LineCache, ModifySelection, Style, Update};
#[derive(Debug, Default, Clone)]
pub struct Cursor {
pub line: u64,
pub column: u64,
}
pub struct View {
cache: LineCache,
cursor: Cursor,
window: Window,
file: Option<String>,
client: Client,
gutter_size: u16,
tab_width: u16,
}
impl View {
pub fn new(client: Client, file: Option<String>) -> View {
View {
client,
cache: LineCache::default(),
cursor: Default::default(),
window: Window::new(),
file,
gutter_size: 0,
tab_width: 4,
}
}
pub fn update_cache(&mut self, update: Update) {
debug!("updating cache");
self.cache.update(update)
}
pub fn set_cursor(&mut self, line: u64, column: u64) {
self.cursor = Cursor { line, column };
self.window.set_cursor(&self.cursor);
}
pub fn render<W: Write>(&mut self, w: &mut W, styles: &HashMap<u64, Style>, state: &str) {
self.update_window();
self.render_lines(w, styles);
self.render_status(w, state);
self.render_cursor(w);
}
pub fn resize(&mut self, height: u16) {
self.window.resize(height);
self.update_window();
self.client.scroll(
self.cache.before() + self.window.start(),
self.cache.after() + self.window.end(),
);
}
pub fn collapse_selections(&mut self) {
self.client.collapse_selections();
}
pub fn select_line(&mut self) {
self.client.select_line();
}
pub fn select_line_end(&mut self) {
self.client.select_line_end();
}
pub fn delete_line(&mut self) {
self.client.delete_line();
}
pub fn goto_line(&mut self, line: u64) {
self.client.goto_line(line)
}
pub fn copy(&mut self) -> ClientResult<Value> {
self.client.copy()
}
pub fn paste(&mut self, buffer: &str) {
self.client.paste(buffer);
}
pub fn cut(&mut self) -> ClientResult<Value> {
self.client.cut()
}
pub fn undo(&mut self) {
self.client.undo();
}
pub fn redo(&mut self) {
self.client.redo();
}
pub fn find(
&mut self,
search_term: &str,
case_sensitive: bool,
regex: bool,
whole_words: bool,
) {
self.client
.find(search_term, case_sensitive, regex, whole_words);
}
pub fn find_next(
&mut self,
wrap_around: bool,
allow_same: bool,
modify_selection: ModifySelection,
) {
self.client
.find_next(wrap_around, allow_same, modify_selection);
}
pub fn find_prev(
&mut self,
wrap_around: bool,
allow_same: bool,
modify_selection: ModifySelection,
) {
self.client
.find_prev(wrap_around, allow_same, modify_selection);
}
pub fn find_all(&mut self) {
self.client.find_all();
}
pub fn highlight_find(&mut self, visible: bool) {
self.client.highlight_find(visible);
}
pub fn save(&mut self) -> ClientResult<()> {
self.client.save(self.file.as_ref().unwrap())
}
fn update_window(&mut self) {
if self.cursor.line < self.cache.before() {
error!(
"cursor is on line {} but there are {} invalid lines in cache.",
self.cursor.line,
self.cache.before()
);
return;
}
let cursor_line = self.cursor.line - self.cache.before();
let nb_lines = self.cache.lines().len() as u64;
self.gutter_size = 1
+ (self.cache.before() + nb_lines + self.cache.after())
.to_string()
.len() as u16;
self.window.update(cursor_line, nb_lines);
}
fn get_click_location(&self, x: u64, y: u64) -> (u64, u64) {
let lineno = x + self.cache.before() + self.window.start();
if let Some(line) = self.cache.lines().get(x as usize) {
if y == 0 {
return (lineno, 0);
}
let mut text_len: u16 = 0;
for (idx, c) in line.text.chars().enumerate() {
text_len = self.translate_char_width(text_len, c);
if u64::from(text_len) >= y {
return (lineno as u64, idx as u64 + 1);
}
}
return (lineno, line.text.len() as u64 + 1);
} else {
warn!("no line at index {} found in cache", x);
return (x, y);
}
}
fn click(&mut self, x: u64, y: u64) {
let (line, column) = self.get_click_location(x, y);
self.client.click(line, column);
}
fn drag(&mut self, x: u64, y: u64) {
let (line, column) = self.get_click_location(x, y);
self.client.drag(line, column);
}
pub fn handle_input(&mut self, event: Event) {
match event {
Event::Key(key) => match key {
Key::Char(c) => self.client.insert(c),
// FIXME: avoid complexity
// Key::Ctrl(c) => match c {
// 'w' => self.client.save(self.file.as_ref().unwrap()),
// 'h' => self.client.backspace(),
// _ => error!("Unhandled input ctrl+{}", c),
// },
Key::Backspace => self.client.backspace(),
Key::Delete => self.client.delete(),
Key::Left => self.client.left(),
Key::Right => self.client.right(),
Key::Up => self.client.up(),
Key::Down => self.client.down(),
Key::Home => self.client.home(),
Key::End => self.client.end(),
Key::PageUp => self.client.page_up(),
Key::PageDown => self.client.page_down(),
k => error!("unhandled key {:?}", k),
},
Event::Mouse(mouse_event) => match mouse_event {
MouseEvent::Press(press_event, y, x) => match press_event {
MouseButton::Left => self.click(u64::from(x) - 1, u64::from(y) - 1),
MouseButton::WheelUp => self.client.up(),
MouseButton::WheelDown => self.client.down(),
button => error!("unhandled button {:?}", button),
},
MouseEvent::Release(..) => {}
MouseEvent::Hold(y, x) => self.drag(u64::from(x) - 1, u64::from(y) - 1),
},
ev => error!("unhandled event {:?}", ev),
}
}
pub fn render_error<W: Write>(&mut self, w: &mut W, msg: &str) {
let win_size = self.window.size() + 1;
write!(
w,
"{}{}{}error{}{} : {}",
Goto(1, win_size),
CurrentLine,
Bold,
color::Fg(color::Red),
Reset,
msg
)
.unwrap();
}
fn render_lines<W: Write>(&self, w: &mut W, styles: &HashMap<u64, Style>) {
debug!("rendering lines");
trace!("current cache\n{:?}", self.cache);
let lines = self
.cache
.lines()
.iter()
.skip(self.window.start() as usize)
.take(self.window.size() as usize);
let mut line_strings = String::new();
let mut line_no = self.cache.before() + self.window.start();
for (line_index, line) in lines.enumerate() {
line_strings.push_str(&self.render_line_str(line, Some(line_no), line_index, styles));
line_no += 1;
}
let line_count = self.cache.lines().len() as u16;
let win_size = self.window.size();
if win_size > line_count {
for num in line_count..win_size {
line_strings.push_str(&self.render_line_str(
&Line::default(),
None,
num as usize,
styles,
));
}
}
w.write_all(line_strings.as_bytes()).unwrap();
}
fn render_status<W: Write>(&mut self, w: &mut W, state: &str) {
let win_size = self.window.size() + 1;
let file = match self.file.as_ref().map(|s| s) {
None => "<nofile>".to_owned(),
Some(file) => file.to_owned(),
};
let cur = self.window.get_cursor();
write!(
w,
"{}{}{}{}{}{} : '{}' {} / {}",
Goto(1, win_size),
CurrentLine,
Bold,
color::Fg(color::Green),
state,
Reset,
file,
cur.line + 1,
cur.column + 1
)
.unwrap();
}
fn render_line_str(
&self,
line: &Line,
lineno: Option<u64>,
line_index: usize,
styles: &HashMap<u64, Style>,
) -> String {
let text = self.escape_control_and_add_styles(styles, line);
if let Some(line_no) = lineno {
format!(
"{}{}{}{}{}",
Goto(1, line_index as u16 + 1),
CurrentLine,
(line_no + 1).to_string(),
Goto(self.gutter_size + 1, line_index as u16 + 1),
&text
)
} else {
format!(
"{}{}~{}",
Goto(self.gutter_size + 1, line_index as u16 + 1),
CurrentLine,
&text
)
}
}
fn escape_control_and_add_styles(&self, styles: &HashMap<u64, Style>, line: &Line) -> String {
let mut position: u16 = 0;
let mut text = String::with_capacity(line.text.capacity());
for c in line.text.chars() {
match c {
'\x00'...'\x08' | '\x0a'...'\x1f' | '\x7f' => {
// Render in caret notation, i.e. '\x02' is rendered as '^B'
text.push('^');
text.push((c as u8 ^ 0x40u8) as char);
position += 2;
}
'\t' => {
let tab_width = self.tab_width_at_position(position);
text.push_str(&" ".repeat(tab_width as usize));
position += tab_width;
}
_ => {
text.push(c);
position += 1;
}
}
}
if line.styles.is_empty() {
return text;
}
let mut style_sequences = self.get_style_sequences(styles, line);
for style in style_sequences.drain(..) {
trace!("inserting style: {:?}", style);
if style.0 >= text.len() {
text.push_str(&style.1);
} else {
text.insert_str(style.0, &style.1);
}
}
trace!("styled line: {:?}", text);
text
}
fn tab_width_at_position(&self, position: u16) -> u16 {
self.tab_width - (position % self.tab_width)
}
fn get_style_sequences(
&self,
styles: &HashMap<u64, Style>,
line: &Line,
) -> Vec<(usize, String)> {
let mut style_sequences: Vec<(usize, String)> = Vec::new();
let mut prev_style_end: usize = 0;
for style_def in &line.styles {
let start_idx = if style_def.offset >= 0 {
(prev_style_end + style_def.offset as usize)
} else {
(prev_style_end - ((-style_def.offset) as usize))
};
let end_idx = start_idx + style_def.length as usize;
prev_style_end = end_idx;
if let Some(style) = styles.get(&style_def.style_id) {
let start_sequence = match set_style(style) {
Ok(s) => s,
Err(e) => {
error!("could not get CSI sequence to set style {:?}: {}", style, e);
continue;
}
};
let end_sequence = match reset_style(style) {
Ok(s) => s,
Err(e) => {
error!(
"could not get CSI sequence to reset style {:?}: {}",
style, e
);
continue;
}
};
style_sequences.push((start_idx, start_sequence));
style_sequences.push((end_idx, end_sequence));
} else {
error!(
"no style ID {} found not applying style.",
style_def.style_id
);
};
}
style_sequences.sort_by(|a, b| a.0.cmp(&b.0));
style_sequences.reverse();
trace!("{:?}", style_sequences);
style_sequences
}
fn render_cursor<W: Write>(&self, w: &mut W) {
debug!("rendering cursor");
if self.cache.is_empty() {
debug!("cache is empty, rendering cursor at the top left corner");
if let Err(e) = write!(w, "{}", Goto(1, 1)) {
error!("failed to render cursor: {}", e);
}
return;
}
if self.cursor.line < self.cache.before() {
error!(
"The cursor is on line {} which is marked invalid in the cache",
self.cursor.line
);
return;
}
let line_idx = self.cursor.line - self.cache.before();
let line = match self.cache.lines().get(line_idx as usize) {
Some(line) => line,
None => {
error!("no valid line at cursor index {}", self.cursor.line);
return;
}
};
if line_idx < self.window.start() {
error!(
"the line that has the cursor (nb={}, cache_idx={}) not within the displayed window ({:?})",
self.cursor.line,
line_idx,
self.window
);
return;
}
let line_pos = line_idx - self.window.start();
let column = line
.text
.chars()
.take(self.cursor.column as usize)
.fold(0, |acc, c| acc + self.translate_char_width(acc, c));
let cursor_pos = Goto(self.gutter_size + column as u16 + 1, line_pos as u16 + 1);
if let Err(e) = write!(w, "{}", cursor_pos) {
error!("failed to render cursor: {}", e);
}
debug!("cursor rendered at ({}, {})", line_pos, column);
}
fn translate_char_width(&self, position: u16, c: char) -> u16 {
match c {
'\x00'...'\x08' | '\x0a'...'\x1f' | '\x7f' => 2,
'\t' => self.tab_width_at_position(position),
_ => 1,
}
}
}
|
use crate::ast::{Expression, Statement, Value, Visitor};
use crate::callable::{LoxFunction, NativeFunction};
use crate::class::Class;
use crate::environment::{Environment, EnvironmentError};
use crate::instance::Instance;
use crate::token::{Token, TokenType};
use std::collections::BTreeMap;
use std::fmt;
use std::io;
use std::io::Read;
use std::time::{SystemTime, UNIX_EPOCH};
pub struct Interpreter<'a> {
globals: Environment<'a>,
environment: Environment<'a>,
out: &'a mut dyn io::Write,
}
#[derive(Debug)]
pub struct RuntimeError<'a> {
message: String,
token: Option<&'a Token<'a>>,
}
impl<'a> fmt::Display for RuntimeError<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.token {
None => write!(f, "{}", self.message),
Some(token) => write!(f, "{}\n[line {}]", self.message, token.line),
}
}
}
impl<'a> RuntimeError<'a> {
pub fn new(msg: &str, token: Option<&'a Token<'a>>) -> ErrorType<'a> {
ErrorType::RuntimeError(RuntimeError {
message: msg.to_string(),
token,
})
}
}
#[derive(Debug)]
pub struct Return<'a>(pub Value<'a>);
impl<'a> fmt::Display for Return<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "return {}", self.0)
}
}
#[derive(Debug)]
pub enum ErrorType<'a> {
Return(Return<'a>),
EnvironmentError(EnvironmentError<'a>),
RuntimeError(RuntimeError<'a>),
}
impl<'a> fmt::Display for ErrorType<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ErrorType::Return(x) => x.fmt(f),
ErrorType::EnvironmentError(x) => x.fmt(f),
ErrorType::RuntimeError(x) => x.fmt(f),
}
}
}
impl<'a> Visitor<Expression<'a>, Result<Value<'a>, ErrorType<'a>>> for Interpreter<'a> {
fn visit(&mut self, expr: &Expression<'a>) -> Result<Value<'a>, ErrorType<'a>> {
match expr {
Expression::Literal(x) => Ok(match &x.tokentype {
TokenType::String => Value::String(x.lexeme[1..x.lexeme.len() - 1].to_string()),
TokenType::Number => Value::Number(x.lexeme.parse().unwrap()),
TokenType::False => Value::Boolean(false),
TokenType::True => Value::Boolean(true),
_ => Value::Nil,
}),
Expression::Grouping(x) => self.evaluate(x),
Expression::Unary { operator, right } => {
let rv = self.evaluate(right)?;
match operator.tokentype {
TokenType::Minus => match rv {
Value::Number(r) => Ok(Value::Number(-r)),
_ => Err(RuntimeError::new(
"Operand must be a number.",
Some(operator),
)),
},
TokenType::Bang => Ok(Value::Boolean(!is_truthy(&rv))),
_ => Err(RuntimeError::new("Invalid unary operand", Some(operator))),
}
}
Expression::Binary {
left,
operator,
right,
} => {
let lv = self.evaluate(left)?;
let rv = self.evaluate(right)?;
match operator.tokentype {
TokenType::EqualEqual => Ok(Value::Boolean(is_equal(&lv, &rv))),
TokenType::BangEqual => Ok(Value::Boolean(!is_equal(&lv, &rv))),
TokenType::Plus => match &lv {
Value::Number(l) => match &rv {
Value::Number(r) => Ok(Value::Number(l + r)),
_ => Err(RuntimeError::new(
"Operands must be two numbers or two strings.",
Some(operator),
)),
},
Value::String(l) => match &rv {
Value::String(r) => {
let mut joined = l.clone();
joined.push_str(r.as_str());
Ok(Value::String(joined))
}
_ => Err(RuntimeError::new(
"Operands must be two numbers or two strings.",
Some(operator),
)),
},
_ => Err(RuntimeError::new(
"Operands must be two numbers or two strings.",
Some(operator),
)),
},
_ => match &lv {
Value::Number(l) => match &rv {
Value::Number(r) => match operator.tokentype {
TokenType::Minus => Ok(Value::Number(l - r)),
TokenType::Slash => Ok(Value::Number(l / r)),
TokenType::Star => Ok(Value::Number(l * r)),
TokenType::Plus => Ok(Value::Number(l + r)),
TokenType::Greater => Ok(Value::Boolean(l > r)),
TokenType::GreaterEqual => Ok(Value::Boolean(l >= r)),
TokenType::Less => Ok(Value::Boolean(l < r)),
TokenType::LessEqual => Ok(Value::Boolean(l <= r)),
_ => Err(RuntimeError::new(
"Invalid numerical operand",
Some(operator),
)),
},
_ => Err(RuntimeError::new(
"Operands must be numbers.",
Some(operator),
)),
},
_ => Err(RuntimeError::new(
"Operands must be numbers.",
Some(operator),
)),
},
}
}
Expression::Variable { name, scope } => match scope {
None => self.globals.get_direct(name),
Some(distance) => self.environment.get_at(name, *distance),
},
Expression::Assign { name, value, scope } => {
let value = self.evaluate(value)?;
match scope {
None => self.globals.assign_direct(name, value.clone())?,
Some(distance) => self.environment.assign_at(name, value.clone(), *distance)?,
}
Ok(value)
}
Expression::Logical {
left,
operator,
right,
} => {
let left = self.evaluate(left)?;
match operator.tokentype {
TokenType::Or => {
if is_truthy(&left) {
Ok(left)
} else {
self.evaluate(right)
}
}
TokenType::And => {
if !is_truthy(&left) {
Ok(left)
} else {
self.evaluate(right)
}
}
_ => Err(RuntimeError::new("Invalid logical operand", Some(operator))),
}
}
Expression::Call {
callee,
paren,
arguments,
} => {
let evaluated_callee = self.evaluate(callee)?;
let mut evaluated_arguments: Vec<Value> = Vec::new();
for argument in arguments {
evaluated_arguments.push(self.evaluate(argument)?);
}
match evaluated_callee {
Value::Function(function, closure, is_init) => {
if function.arity() != evaluated_arguments.len() {
Err(RuntimeError::new(
format!(
"Expected {} arguments but got {}.",
function.arity(),
evaluated_arguments.len()
)
.as_str(),
Some(paren),
))
} else {
function.call(self, &evaluated_arguments, closure, is_init)
}
}
Value::NativeFunction(function) => {
if function.arity != evaluated_arguments.len() {
Err(RuntimeError::new(
format!(
"Expected {} arguments but got {}.",
function.arity,
evaluated_arguments.len()
)
.as_str(),
Some(paren),
))
} else {
Ok((function.call)(&evaluated_arguments))
}
}
Value::Class(class) => {
let arity = class.find_method("init").map_or(0, |(f, _)| f.arity());
if evaluated_arguments.len() != arity {
Err(RuntimeError::new(
format!(
"Expected {} arguments but got {}.",
arity,
evaluated_arguments.len()
)
.as_str(),
Some(paren),
))
} else {
let instance = Instance::new(class.clone());
class.find_method("init").map(|(f, e)| {
let mut env = e.new_child();
env.define("this".to_string(), Value::Instance(instance.clone()))
.unwrap();
f.call(self, &evaluated_arguments, env, true).unwrap();
});
Ok(Value::Instance(instance))
}
}
_ => Err(RuntimeError::new(
"Can only call functions and classes.",
Some(paren),
)),
}
}
Expression::Get { object, name } => {
let object = self.evaluate(object)?;
match object {
Value::Instance(instance) => instance.get(name),
_ => Err(RuntimeError::new(
"Only instances have properties.",
Some(name),
)),
}
}
Expression::Set {
object,
name,
value,
} => {
let mut obj = self.evaluate(object)?;
if let Value::Instance(x) = &mut obj {
let value = self.evaluate(value)?;
x.set(name, value.clone());
Ok(value)
} else {
Err(RuntimeError::new("Only instances have fields.", Some(name)))
}
}
Expression::This { token, scope } => self.environment.get_at(token, scope.unwrap()),
Expression::Super {
keyword,
method,
scope,
} => {
let superclass = self.environment.get_at(keyword, scope.unwrap())?;
let object = self.environment.get_this_at(scope.unwrap() - 1)?;
if let Value::Class(sc) = superclass {
sc.find_method(method.lexeme).map_or(
Err(RuntimeError::new(
format!("Undefined property '{}'.", method.lexeme).as_str(),
Some(keyword),
)),
|(f, e)| {
let mut env = e.new_child();
env.define("this".to_string(), object).unwrap();
Ok(Value::Function(f.clone(), env, method.lexeme == "init"))
},
)
} else {
Err(RuntimeError::new(
"Wrong type for superclass value",
Some(keyword),
))
}
}
}
}
}
impl<'a> Visitor<Statement<'a>, Result<Value<'a>, ErrorType<'a>>> for Interpreter<'a> {
fn visit(&mut self, stmt: &Statement<'a>) -> Result<Value<'a>, ErrorType<'a>> {
match stmt {
Statement::Print(e) => {
let val = self.evaluate(e)?;
writeln!(self.out, "{}", val).unwrap();
}
Statement::Expression(e) => {
self.evaluate(e)?;
}
Statement::Var { name, initializer } => {
let val = match initializer {
None => Value::Nil,
Some(x) => self.evaluate(x)?,
};
self.environment
.define(name.lexeme.to_string(), val.clone())?;
}
Statement::Block(stmts) => {
self.execute_block(stmts, self.environment.new_child())?;
}
Statement::If {
condition,
then_branch,
else_branch,
} => {
if is_truthy(&self.evaluate(condition)?) {
self.execute(then_branch)?;
} else if let Some(else_branch) = else_branch {
self.execute(else_branch)?;
}
}
Statement::While { condition, body } => loop {
if let Some(x) = condition {
if !is_truthy(&self.evaluate(x)?) {
break;
}
}
self.execute(body)?;
},
Statement::Function(function) => {
self.environment.define(
function.name().lexeme.to_string(),
Value::Function(function.clone(), self.environment.clone(), false),
)?;
}
Statement::Return { keyword: _, value } => {
let val = match value {
None => Value::Nil,
Some(x) => self.evaluate(x)?,
};
return Err(ErrorType::Return(Return(val.clone())));
}
Statement::Class {
name,
superclass,
methods: method_statements,
} => {
let mut superclass_class: Option<Class> = None;
if let Some(superclass) = superclass {
if let Expression::Variable {
name: superclass_name,
scope: _,
} = superclass
{
if let Value::Class(sc) = self.evaluate(superclass)? {
superclass_class = Some(sc);
} else {
return Err(RuntimeError::new(
"Superclass must be a class.",
Some(superclass_name),
));
}
} else {
return Err(RuntimeError::new(
"Wrong type for superclass expression.",
None,
));
}
}
self.environment
.define(name.lexeme.to_string(), Value::Nil)?;
let mut environment = self.environment.clone();
if let Some(superclass) = &superclass_class {
environment = environment.new_child();
environment.define("super".to_string(), Value::Class(superclass.clone()))?;
}
let mut methods: BTreeMap<String, LoxFunction> = BTreeMap::new();
for method in method_statements {
if let Statement::Function(x) = method {
methods.insert(x.name().lexeme.to_string(), x.clone());
}
}
let class = Value::Class(Class::new(
name,
superclass_class,
methods,
environment.clone(),
));
self.environment.assign_direct(name, class)?;
}
}
Ok(Value::Nil)
}
}
impl<'a> Interpreter<'a> {
pub fn new(out: &'a mut dyn io::Write) -> Interpreter<'a> {
let mut env = Environment::new();
env.define(
"clock".to_string(),
Value::NativeFunction(NativeFunction {
call: |_: &Vec<Value>| -> Value {
Value::Number(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as f64,
)
},
arity: 0,
}),
)
.expect("Failed to define native function 'clock'");
env.define(
"getc".to_string(),
Value::NativeFunction(NativeFunction {
call: |_: &Vec<Value>| -> Value {
let mut buffer = [0; 1];
Value::Number(match io::stdin().read(&mut buffer) {
Ok(1) => buffer[0] as f64,
_ => -1.0,
})
},
arity: 0,
}),
)
.expect("Failed to define native function 'getc'");
env.define(
"chr".to_string(),
Value::NativeFunction(NativeFunction {
call: |args: &Vec<Value>| -> Value {
if let Value::Number(x) = args[0] {
if let Some(x) = std::char::from_u32(x as u32) {
let mut y = String::from("");
y.push(x);
return Value::String(y);
}
}
Value::Nil
},
arity: 1,
}),
)
.expect("Failed to define native function 'chr'");
env.define(
"exit".to_string(),
Value::NativeFunction(NativeFunction {
call: |args: &Vec<Value>| -> Value {
std::process::exit(match args[0] {
Value::Number(x) => x as i32,
_ => 0,
});
},
arity: 1,
}),
)
.expect("Failed to define native function 'exit'");
env.define(
"print_error".to_string(),
Value::NativeFunction(NativeFunction {
call: |args: &Vec<Value>| -> Value {
if let Value::String(x) = &args[0] {
eprintln!("{}", x);
}
Value::Nil
},
arity: 1,
}),
)
.expect("Failed to define native function 'print_error'");
Interpreter {
globals: env.clone(),
environment: env,
out: out,
}
}
fn evaluate(&mut self, expr: &Expression<'a>) -> Result<Value<'a>, ErrorType<'a>> {
expr.accept(self)
}
fn execute(&mut self, stmt: &Statement<'a>) -> Result<Value<'a>, ErrorType<'a>> {
stmt.accept(self)
}
pub fn interpret(
&mut self,
statements: &Vec<Statement<'a>>,
) -> Result<Value<'a>, ErrorType<'a>> {
let mut val = Value::Nil;
for stmt in statements {
val = self.execute(stmt)?;
}
Ok(val)
}
pub fn execute_block(
&mut self,
stmts: &Vec<Statement<'a>>,
env: Environment<'a>,
) -> Result<Value<'a>, ErrorType<'a>> {
let mut result = Ok(Value::Nil);
let parent = self.environment.clone();
self.environment = env;
for stmt in stmts {
result = self.execute(stmt);
if let Err(_) = &result {
break;
}
}
self.environment = parent;
result
}
}
fn is_truthy(x: &Value) -> bool {
match x {
Value::Nil => false,
Value::Boolean(x) => *x,
_ => true,
}
}
fn is_equal<'a>(lv: &Value<'a>, rv: &Value<'a>) -> bool {
match lv {
Value::Nil => match rv {
Value::Nil => true,
_ => false,
},
Value::Boolean(l) => match rv {
Value::Boolean(r) => l == r,
_ => false,
},
Value::Number(l) => match rv {
Value::Number(r) => l == r,
_ => false,
},
Value::String(l) => match rv {
Value::String(r) => l == r,
_ => false,
},
Value::Class(l) => match rv {
Value::Class(r) => l.equals(r),
_ => false,
},
Value::Instance(l) => match rv {
Value::Instance(r) => l.equals(r),
_ => false,
},
Value::Function(l, le, _) => match rv {
Value::Function(r, re, _) => l.equals(r) && le.equals(re),
_ => false,
},
_ => false,
}
}
#[cfg(test)]
mod interpreter_tests {
use crate::interpreter;
use crate::parser;
use crate::resolver;
use crate::scanner;
fn expect_output(source: &str, expected_output: &str) {
let (tokens, success) = scanner::scan_tokens(source);
assert!(success);
let (mut statements, last_error) = parser::parse(&tokens);
assert!(last_error.is_none());
let mut resolver = resolver::Resolver::new();
let result = resolver.resolve(&mut statements);
assert!(result.is_ok(), "{}", result.err().unwrap());
let mut out = Vec::new();
{
let mut interpreter = interpreter::Interpreter::new(&mut out);
let val = interpreter.interpret(&mut statements);
assert!(val.is_ok(), "{}", val.err().unwrap());
}
assert_eq!(
out.as_slice(),
expected_output.as_bytes(),
"{} != {}",
String::from_utf8(out.clone()).unwrap(),
expected_output
)
}
#[test]
fn addition_statement() {
expect_output("print 1+2;", "3\n");
}
#[test]
fn variable_declaration() {
expect_output("var x = 3; print x;", "3\n");
expect_output("var x = 3; print x + 1;", "4\n");
}
#[test]
fn variable_scope() {
expect_output("var x = 1; { var x = 2; } print x;", "1\n");
expect_output("var x = 1; { var x = 2; print x; }", "2\n");
}
#[test]
fn while_loop() {
expect_output(
"var a = 0; var b = 1; while (a < 10000) { var temp = a; a = b; b = temp + b; } print a;",
"10946\n",
);
}
#[test]
fn for_loop() {
expect_output(
r#"
var a = 1;
for(
var b = 1;
b <= 6;
b = b + 1
) {
a = a * b;
}
print a;"#,
"720\n",
)
}
#[test]
fn function_return() {
expect_output("fun square(x) { return x * x; } print square(2);", "4\n");
expect_output(
"fun sign(x) { if (x==0) { return 0; } if (x<0) { return -1; } return 1; } print sign(-2);",
"-1\n",
);
}
#[test]
fn recursion() {
expect_output(
r#"fun factorial(x) { if(x<=1) { return 1; } return x * factorial(x-1); } print factorial(5);"#,
"120\n",
);
}
#[test]
fn scope() {
expect_output(
"var a = 1; { fun get_a() { return a; } var a = 2; print get_a(); }",
"1\n",
)
}
}
|
// 3rd party imports {{{
use alpm::Alpm;
use alpm::SigLevel;
// }}}
// Own imports {{{
use crate::config::Config;
use crate::error::Error;
// }}}
/// The default path to package database.
const DB_PATH: &str = "/var/lib/pacman";
/// The default installation root.
const ROOT: &str = "/";
/// A handle for interacting with alpm.
pub struct Handle {
client: Alpm,
}
impl Handle {
/// Create a new handle from the the given `Config`.
pub fn from(config: &Config) -> Result<Self, Error> {
let mut alpm = Alpm::new(ROOT, DB_PATH)?;
for repo in &config.repos {
let db = alpm.register_syncdb_mut(repo.name.clone(), SigLevel::NONE)?;
db.set_servers(repo.servers.iter())?;
}
Ok(Self { client: alpm })
}
/// Getter for this handle's alpm client.
pub fn client(&self) -> &Alpm {
&self.client
}
/// Check whether a package comes from an official repository.
pub fn is_official_package(&self, package: &alpm::Package) -> bool {
let dbs = self.client().syncdbs();
for db in dbs {
if db.pkg(package.name()).is_ok() {
return true
}
}
false
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.