lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/error.rs
crumblingstatue/amf
4b728dc8b2ea7b8389616c8de45d7c402cf387e7
use std::error; use std::fmt; use std::io; use std::string; #[derive(Debug)] pub enum DecodeError { Io(io::Error), String(string::FromUtf8Error), Unknown { marker: u8, }, Unsupported { marker: u8, }, UnexpectedObjectEnd, CircularReference { index: usize, }, OutOfRangeReference { index: usize, }, NonZeroTimeZone { offset: i16, }, InvalidDate { millis: f64, }, ExternalizableType { name: String, }, } impl error::Error for DecodeError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { use self::DecodeError::*; match *self { Io(ref x) => x.source(), String(ref x) => x.source(), _ => None, } } } impl fmt::Display for DecodeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::DecodeError::*; match *self { Io(ref x) => write!(f, "I/O Error: {}", x), String(ref x) => write!(f, "Invalid String: {}", x), Unknown { marker } => write!(f, "Unknown marker: {}", marker), Unsupported { marker } => write!(f, "Unsupported type: maker={}", marker), UnexpectedObjectEnd => write!(f, "Unexpected occurrence of object-end-marker"), CircularReference { index } => { write!(f, "Circular references are unsupported: index={}", index) } OutOfRangeReference { index } => write!(f, "Reference index {} is out-of-range", index), NonZeroTimeZone { offset } => { write!(f, "Non zero time zone offset {} is unsupported", offset) } InvalidDate { millis } => write!(f, "Invalid date value {}", millis), ExternalizableType { ref name } => { write!(f, "Externalizable type {:?} is unsupported", name) } } } } impl PartialEq for DecodeError { fn eq(&self, other: &Self) -> bool { use self::DecodeError::*; match (self, other) { (&Unknown { marker: x }, &Unknown { marker: y }) => x == y, (&Unsupported { marker: x }, &Unsupported { marker: y }) => x == y, (&UnexpectedObjectEnd, &UnexpectedObjectEnd) => true, (&CircularReference { index: x }, &CircularReference { index: y }) => x == y, (&OutOfRangeReference { index: x }, &OutOfRangeReference { index: y }) => x == y, (&NonZeroTimeZone { offset: x }, &NonZeroTimeZone { offset: y }) => x == y, (&InvalidDate { millis: x }, &InvalidDate { millis: y }) => x == y, (&ExternalizableType { name: ref x }, &ExternalizableType { name: ref y }) => x == y, _ => false, } } } impl From<io::Error> for DecodeError { fn from(f: io::Error) -> Self { DecodeError::Io(f) } } impl From<string::FromUtf8Error> for DecodeError { fn from(f: string::FromUtf8Error) -> Self { DecodeError::String(f) } }
use std::error; use std::fmt; use std::io; use std::string; #[derive(Debug)] pub enum DecodeError { Io(io::Error), String(string::FromUtf8Error), Unknown { marker: u8, }, Unsupported { marker: u8, }, UnexpectedObjectEnd, CircularReference { index: usize,
rReference { index: x }, &CircularReference { index: y }) => x == y, (&OutOfRangeReference { index: x }, &OutOfRangeReference { index: y }) => x == y, (&NonZeroTimeZone { offset: x }, &NonZeroTimeZone { offset: y }) => x == y, (&InvalidDate { millis: x }, &InvalidDate { millis: y }) => x == y, (&ExternalizableType { name: ref x }, &ExternalizableType { name: ref y }) => x == y, _ => false, } } } impl From<io::Error> for DecodeError { fn from(f: io::Error) -> Self { DecodeError::Io(f) } } impl From<string::FromUtf8Error> for DecodeError { fn from(f: string::FromUtf8Error) -> Self { DecodeError::String(f) } }
}, OutOfRangeReference { index: usize, }, NonZeroTimeZone { offset: i16, }, InvalidDate { millis: f64, }, ExternalizableType { name: String, }, } impl error::Error for DecodeError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { use self::DecodeError::*; match *self { Io(ref x) => x.source(), String(ref x) => x.source(), _ => None, } } } impl fmt::Display for DecodeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::DecodeError::*; match *self { Io(ref x) => write!(f, "I/O Error: {}", x), String(ref x) => write!(f, "Invalid String: {}", x), Unknown { marker } => write!(f, "Unknown marker: {}", marker), Unsupported { marker } => write!(f, "Unsupported type: maker={}", marker), UnexpectedObjectEnd => write!(f, "Unexpected occurrence of object-end-marker"), CircularReference { index } => { write!(f, "Circular references are unsupported: index={}", index) } OutOfRangeReference { index } => write!(f, "Reference index {} is out-of-range", index), NonZeroTimeZone { offset } => { write!(f, "Non zero time zone offset {} is unsupported", offset) } InvalidDate { millis } => write!(f, "Invalid date value {}", millis), ExternalizableType { ref name } => { write!(f, "Externalizable type {:?} is unsupported", name) } } } } impl PartialEq for DecodeError { fn eq(&self, other: &Self) -> bool { use self::DecodeError::*; match (self, other) { (&Unknown { marker: x }, &Unknown { marker: y }) => x == y, (&Unsupported { marker: x }, &Unsupported { marker: y }) => x == y, (&UnexpectedObjectEnd, &UnexpectedObjectEnd) => true, (&Circula
random
[ { "content": "#[derive(Debug)]\n\nenum SizeOrIndex {\n\n Size(usize),\n\n Index(usize),\n\n}\n\n\n\n/// AMF3 decoder.\n\n#[derive(Debug)]\n\npub struct Decoder<R> {\n\n inner: R,\n\n traits: Vec<Trait>,\n\n strings: Vec<String>,\n\n complexes: Vec<Value>,\n\n}\n\nimpl<R> Decoder<R> {\n\n //...
Rust
src/atsame70q21b/twihs0/twihs_sr.rs
tstellanova/atsame7x-pac
f7e24c71181651c141d0727379147c388661ce0e
#[doc = "Reader of register TWIHS_SR"] pub type R = crate::R<u32, super::TWIHS_SR>; #[doc = "Reader of field `TXCOMP`"] pub type TXCOMP_R = crate::R<bool, bool>; #[doc = "Reader of field `RXRDY`"] pub type RXRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `TXRDY`"] pub type TXRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `SVREAD`"] pub type SVREAD_R = crate::R<bool, bool>; #[doc = "Reader of field `SVACC`"] pub type SVACC_R = crate::R<bool, bool>; #[doc = "Reader of field `GACC`"] pub type GACC_R = crate::R<bool, bool>; #[doc = "Reader of field `OVRE`"] pub type OVRE_R = crate::R<bool, bool>; #[doc = "Reader of field `UNRE`"] pub type UNRE_R = crate::R<bool, bool>; #[doc = "Reader of field `NACK`"] pub type NACK_R = crate::R<bool, bool>; #[doc = "Reader of field `ARBLST`"] pub type ARBLST_R = crate::R<bool, bool>; #[doc = "Reader of field `SCLWS`"] pub type SCLWS_R = crate::R<bool, bool>; #[doc = "Reader of field `EOSACC`"] pub type EOSACC_R = crate::R<bool, bool>; #[doc = "Reader of field `MCACK`"] pub type MCACK_R = crate::R<bool, bool>; #[doc = "Reader of field `TOUT`"] pub type TOUT_R = crate::R<bool, bool>; #[doc = "Reader of field `PECERR`"] pub type PECERR_R = crate::R<bool, bool>; #[doc = "Reader of field `SMBDAM`"] pub type SMBDAM_R = crate::R<bool, bool>; #[doc = "Reader of field `SMBHHM`"] pub type SMBHHM_R = crate::R<bool, bool>; #[doc = "Reader of field `SCL`"] pub type SCL_R = crate::R<bool, bool>; #[doc = "Reader of field `SDA`"] pub type SDA_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Transmission Completed (cleared by writing TWIHS_THR)"] #[inline(always)] pub fn txcomp(&self) -> TXCOMP_R { TXCOMP_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Receive Holding Register Ready (cleared by reading TWIHS_RHR)"] #[inline(always)] pub fn rxrdy(&self) -> RXRDY_R { RXRDY_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Transmit Holding Register Ready (cleared by writing TWIHS_THR)"] #[inline(always)] pub fn txrdy(&self) -> TXRDY_R { TXRDY_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Slave Read"] #[inline(always)] pub fn svread(&self) -> SVREAD_R { SVREAD_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Slave Access"] #[inline(always)] pub fn svacc(&self) -> SVACC_R { SVACC_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - General Call Access (cleared on read)"] #[inline(always)] pub fn gacc(&self) -> GACC_R { GACC_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Overrun Error (cleared on read)"] #[inline(always)] pub fn ovre(&self) -> OVRE_R { OVRE_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Underrun Error (cleared on read)"] #[inline(always)] pub fn unre(&self) -> UNRE_R { UNRE_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - Not Acknowledged (cleared on read)"] #[inline(always)] pub fn nack(&self) -> NACK_R { NACK_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - Arbitration Lost (cleared on read)"] #[inline(always)] pub fn arblst(&self) -> ARBLST_R { ARBLST_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Clock Wait State"] #[inline(always)] pub fn sclws(&self) -> SCLWS_R { SCLWS_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - End Of Slave Access (cleared on read)"] #[inline(always)] pub fn eosacc(&self) -> EOSACC_R { EOSACC_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 16 - Master Code Acknowledge (cleared on read)"] #[inline(always)] pub fn mcack(&self) -> MCACK_R { MCACK_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 18 - Timeout Error (cleared on read)"] #[inline(always)] pub fn tout(&self) -> TOUT_R { TOUT_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - PEC Error (cleared on read)"] #[inline(always)] pub fn pecerr(&self) -> PECERR_R { PECERR_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - SMBus Default Address Match (cleared on read)"] #[inline(always)] pub fn smbdam(&self) -> SMBDAM_R { SMBDAM_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - SMBus Host Header Address Match (cleared on read)"] #[inline(always)] pub fn smbhhm(&self) -> SMBHHM_R { SMBHHM_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 24 - SCL Line Value"] #[inline(always)] pub fn scl(&self) -> SCL_R { SCL_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - SDA Line Value"] #[inline(always)] pub fn sda(&self) -> SDA_R { SDA_R::new(((self.bits >> 25) & 0x01) != 0) } }
#[doc = "Reader of register TWIHS_SR"] pub type R = crate::R<u32, super::TWIHS_SR>; #[doc = "Reader of field `TXCOMP`"] pub type TXCOMP_R = crate::R<bool, bool>; #[doc = "Reader of field `RXRDY`"] pub type RXRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `TXRDY`"] pub type TXRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `SVREAD`"] pub type SVREAD_R = crate::R<bool, bool>; #[doc = "Reader of field `SVACC`"] pub type SVACC_R = crate::R<bool, bool>; #[doc = "Reader of field `GACC`"] pub type GACC_R = crate::R<bool, bool>; #[doc = "Reader of field `OVRE`"] pub type OVRE_R = crate::R<bool, bool>; #[doc = "Reader of field `UNRE`"] pub type UNRE_R = crate::R<bool, bool>; #[doc = "Reader of field `NACK`"] pub type NACK_R = crate::R<bool, bool>; #[doc = "Reader of field `ARBLST`"] pub type ARBLST_R = crate::R<bool, bool>; #[doc = "Reader of field `SCLWS`"] pub type SCLWS_R = crate::R<bool, bool>; #[doc = "Reader of field `EOSACC`"] pub type EOSACC_R = crate::R<bool, bool>; #[doc = "Reader of field `MCACK`"] pub type MCACK_R = crate::R<bool, bool>; #[doc = "Reader of field `TOUT`"] pub type TOUT_R = crate::R<bool, bool>; #[doc = "Reader of field `PECERR`"] pub type PECERR_R = crate::R<bool, bool>; #[doc = "Reader of field `SMBDAM`"] pub type SMBDAM_R = crate::R<bool, bool>; #[doc = "Reader of field `SMBHHM`"] pub type SMBHHM_R = crate::R<bool, bool>; #[doc = "Reader of field `SCL`"] pub type SCL_R = crate::R<bool, bool>; #[doc = "Reader of field `SDA`"] pub type SDA_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Transmission Completed (cleared by writing TWIHS_THR)"] #[inline(always)] pub fn txcomp(&self) -> TXCOMP_R { TXCOMP_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Receive Holding Register Ready (cleared by reading TWIHS_RHR)"] #[inline(always)] pub fn rxrdy(&self) -> RXRDY_R { RXRDY_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Transmit Holding Register Ready (cleared by writing TWIHS_THR)"] #[inline(always)] pub fn txrdy(&self) -> TXRDY_R { TXRDY_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Slave Read"] #[inline(always)] pub fn svread(&self) -> SVREAD_R { SVREAD_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Slave Access"] #[inline(always)] pub fn svacc(&self) -> SVACC_R { SVACC_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - General Call Access (cleared on read)"] #[inline(always)] pub fn gacc(&self) -> GACC_R { GACC_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Overrun Error (cleared on read)"] #[inline(always)] pub fn ovre(&self) -> OVRE_R { OVRE_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Underrun Error (cleared on read)"] #[inline(always)] pub fn unre(&self) -> UNRE_R { UNRE_R::new(((self.bits >>
#[doc = "Bit 9 - Arbitration Lost (cleared on read)"] #[inline(always)] pub fn arblst(&self) -> ARBLST_R { ARBLST_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Clock Wait State"] #[inline(always)] pub fn sclws(&self) -> SCLWS_R { SCLWS_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - End Of Slave Access (cleared on read)"] #[inline(always)] pub fn eosacc(&self) -> EOSACC_R { EOSACC_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 16 - Master Code Acknowledge (cleared on read)"] #[inline(always)] pub fn mcack(&self) -> MCACK_R { MCACK_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 18 - Timeout Error (cleared on read)"] #[inline(always)] pub fn tout(&self) -> TOUT_R { TOUT_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - PEC Error (cleared on read)"] #[inline(always)] pub fn pecerr(&self) -> PECERR_R { PECERR_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - SMBus Default Address Match (cleared on read)"] #[inline(always)] pub fn smbdam(&self) -> SMBDAM_R { SMBDAM_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - SMBus Host Header Address Match (cleared on read)"] #[inline(always)] pub fn smbhhm(&self) -> SMBHHM_R { SMBHHM_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 24 - SCL Line Value"] #[inline(always)] pub fn scl(&self) -> SCL_R { SCL_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - SDA Line Value"] #[inline(always)] pub fn sda(&self) -> SDA_R { SDA_R::new(((self.bits >> 25) & 0x01) != 0) } }
7) & 0x01) != 0) } #[doc = "Bit 8 - Not Acknowledged (cleared on read)"] #[inline(always)] pub fn nack(&self) -> NACK_R { NACK_R::new(((self.bits >> 8) & 0x01) != 0) }
random
[ { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "src/generic.rs", "rank": 0, "score": 58126.51002228791 },...
Rust
src/combinators/sequential.rs
codgician/parsic
1b2a32ab568ebf93ceb90db8b21ee931851cfd96
use crate::combinators::FunctorExt; use crate::core::{return_none, Parsable, Parser}; pub fn and<'f, A: 'f, B: 'f, S: Clone>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, (A, B), S> { Parser::new(move |stream: &mut S, logger| { let st = stream.clone(); p1.parse(stream, logger) .and_then(|x| p2.parse(stream, logger).map(|y| (x, y))) .or_else(|| return_none(stream, &st)) }) } pub fn left<'f, A: 'f, B: 'f, S: Clone + 'f>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, A, S> { p1.and(p2).map(|(l, _)| l) } pub fn right<'f, A: 'f, B: 'f, S: Clone + 'f>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, B, S> { p1.and(p2).map(|(_, r)| r) } pub fn mid<'f, A: 'f, B: 'f, C: 'f, S: Clone + 'f>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, p3: impl Parsable<Stream = S, Result = C> + 'f, ) -> Parser<'f, B, S> { p1.and(p2).and(p3).map(|((_, m), _)| m) } pub trait SequentialExt<'f, A: 'f, S>: Parsable<Stream = S, Result = A> { fn and<B: 'f>(self, p: impl Parsable<Stream = S, Result = B> + 'f) -> Parser<'f, (A, B), S> where S: Clone, Self: Sized + 'f, { and(self, p) } fn left<B: 'f>(self, p: impl Parsable<Stream = S, Result = B> + 'f) -> Parser<'f, A, S> where S: Clone + 'f, Self: Sized + 'f, { left(self, p) } fn right<B: 'f>(self, p: impl Parsable<Stream = S, Result = B> + 'f) -> Parser<'f, B, S> where S: Clone + 'f, Self: Sized + 'f, { right(self, p) } fn mid<B: 'f, C: 'f>( self, p1: impl Parsable<Stream = S, Result = B> + 'f, p2: impl Parsable<Stream = S, Result = C> + 'f, ) -> Parser<'f, B, S> where S: Clone + 'f, Self: Sized + 'f, { mid(self, p1, p2) } } impl<'f, A: 'f, S, P: Parsable<Stream = S, Result = A>> SequentialExt<'f, A, S> for P {} #[cfg(test)] mod test_sequential { use crate::combinators::*; use crate::core::Parsable; use crate::primitives::{char, satisfy, CharStream}; #[test] fn different_type_ok() { let parser = satisfy(|&ch| ch.is_digit(10)) .map_option(|ch| ch.to_digit(10)) .and(char('A')); let mut st = CharStream::new("1A+"); let (res, logs) = parser.exec(&mut st); assert_eq!(Some((1, 'A')), res); assert_eq!("+", st.as_str()); assert_eq!(0, logs.len()); } #[test] fn left_fail() { let parser = char('A').and(char('B')); let mut st = CharStream::new("BBC"); let (res, logs) = parser.exec(&mut st); assert_eq!(None, res); assert_eq!("BBC", st.as_str()); assert_eq!(1, logs.len()); } #[test] fn right_fail() { let parser = char('A').and(char('B')); let mut st = CharStream::new("ACC"); let (res, logs) = parser.exec(&mut st); assert_eq!(None, res); assert_eq!("ACC", st.as_str()); assert_eq!(1, logs.len()); } #[test] fn both_fail() { let parser = char('A').and(char('B')); let mut st = CharStream::new("CCC"); let (res, logs) = parser.exec(&mut st); assert_eq!(None, res); assert_eq!("CCC", st.as_str()); assert_eq!(1, logs.len()); } }
use crate::combinators::FunctorExt; use crate::core::{return_none, Parsable, Parser};
pub fn left<'f, A: 'f, B: 'f, S: Clone + 'f>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, A, S> { p1.and(p2).map(|(l, _)| l) } pub fn right<'f, A: 'f, B: 'f, S: Clone + 'f>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, B, S> { p1.and(p2).map(|(_, r)| r) } pub fn mid<'f, A: 'f, B: 'f, C: 'f, S: Clone + 'f>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, p3: impl Parsable<Stream = S, Result = C> + 'f, ) -> Parser<'f, B, S> { p1.and(p2).and(p3).map(|((_, m), _)| m) } pub trait SequentialExt<'f, A: 'f, S>: Parsable<Stream = S, Result = A> { fn and<B: 'f>(self, p: impl Parsable<Stream = S, Result = B> + 'f) -> Parser<'f, (A, B), S> where S: Clone, Self: Sized + 'f, { and(self, p) } fn left<B: 'f>(self, p: impl Parsable<Stream = S, Result = B> + 'f) -> Parser<'f, A, S> where S: Clone + 'f, Self: Sized + 'f, { left(self, p) } fn right<B: 'f>(self, p: impl Parsable<Stream = S, Result = B> + 'f) -> Parser<'f, B, S> where S: Clone + 'f, Self: Sized + 'f, { right(self, p) } fn mid<B: 'f, C: 'f>( self, p1: impl Parsable<Stream = S, Result = B> + 'f, p2: impl Parsable<Stream = S, Result = C> + 'f, ) -> Parser<'f, B, S> where S: Clone + 'f, Self: Sized + 'f, { mid(self, p1, p2) } } impl<'f, A: 'f, S, P: Parsable<Stream = S, Result = A>> SequentialExt<'f, A, S> for P {} #[cfg(test)] mod test_sequential { use crate::combinators::*; use crate::core::Parsable; use crate::primitives::{char, satisfy, CharStream}; #[test] fn different_type_ok() { let parser = satisfy(|&ch| ch.is_digit(10)) .map_option(|ch| ch.to_digit(10)) .and(char('A')); let mut st = CharStream::new("1A+"); let (res, logs) = parser.exec(&mut st); assert_eq!(Some((1, 'A')), res); assert_eq!("+", st.as_str()); assert_eq!(0, logs.len()); } #[test] fn left_fail() { let parser = char('A').and(char('B')); let mut st = CharStream::new("BBC"); let (res, logs) = parser.exec(&mut st); assert_eq!(None, res); assert_eq!("BBC", st.as_str()); assert_eq!(1, logs.len()); } #[test] fn right_fail() { let parser = char('A').and(char('B')); let mut st = CharStream::new("ACC"); let (res, logs) = parser.exec(&mut st); assert_eq!(None, res); assert_eq!("ACC", st.as_str()); assert_eq!(1, logs.len()); } #[test] fn both_fail() { let parser = char('A').and(char('B')); let mut st = CharStream::new("CCC"); let (res, logs) = parser.exec(&mut st); assert_eq!(None, res); assert_eq!("CCC", st.as_str()); assert_eq!(1, logs.len()); } }
pub fn and<'f, A: 'f, B: 'f, S: Clone>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, (A, B), S> { Parser::new(move |stream: &mut S, logger| { let st = stream.clone(); p1.parse(stream, logger) .and_then(|x| p2.parse(stream, logger).map(|y| (x, y))) .or_else(|| return_none(stream, &st)) }) }
function_block-full_function
[ { "content": "/// # `Parsable` trait\n\n/// Anything that is parsable should implement `Parsable` trait,\n\n/// The return types of all the combinators and combinators in this library\n\n/// Implement `Parsable` trait, meaning you can treat them as parsers\n\n/// and call `parse()` or `exec()` from them to pars...
Rust
src/core/context/default_context.rs
another-s347/rusty-p4
b2c395e1b14e105762d7eb0879315ed8a7dca7d2
use crate::app::P4app; use crate::entity::UpdateType; use crate::error::{ContextError, ContextErrorKind}; use crate::event::{CommonEvents, CoreEvent, CoreRequest, Event, PacketReceived}; use crate::p4rt::bmv2::Bmv2SwitchConnection; use crate::p4rt::pipeconf::{Pipeconf, PipeconfID}; use crate::p4rt::pure::{ new_packet_out_request, new_set_entity_request, new_write_table_entry, table_entry_to_entity, }; use crate::proto::p4runtime::{ stream_message_response, Entity, Index, MeterEntry, PacketIn, StreamMessageRequest, StreamMessageResponse, Uint128, Update, WriteRequest, WriteResponse, }; use rusty_p4_proto::proto::v1::MasterArbitrationUpdate; use crate::representation::{ConnectPoint, Device, DeviceID, DeviceType}; use crate::util::flow::Flow; use byteorder::BigEndian; use byteorder::ByteOrder; use bytes::Bytes; use failure::ResultExt; use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, Sender}; use futures::future::FutureExt; use futures::sink::SinkExt; use futures::stream::StreamExt; use log::{debug, error, info, trace, warn}; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::path::Path; use std::sync::{Arc, Mutex, RwLock}; use crate::core::connection::bmv2::Bmv2Connection; use crate::core::connection::ConnectionBox; use async_trait::async_trait; use nom::lib::std::collections::hash_map::RandomState; use crate::core::context::Context; #[derive(Clone)] pub struct DefaultContext<E> { pub core_request_sender: futures::channel::mpsc::Sender<CoreRequest>, pub event_sender: futures::channel::mpsc::Sender<CoreEvent<E>>, pub connections: HashMap<DeviceID, ConnectionBox>, pub pipeconf: Arc<HashMap<PipeconfID, Pipeconf>>, } impl<E> DefaultContext<E> where E: Debug + Event, { pub fn new( core_request_sender: futures::channel::mpsc::Sender<CoreRequest>, event_sender: futures::channel::mpsc::Sender<CoreEvent<E>>, connections: HashMap<DeviceID, ConnectionBox>, pipeconf: Arc<HashMap<PipeconfID, Pipeconf>>, ) -> DefaultContext<E> { DefaultContext { core_request_sender, event_sender, connections, pipeconf, } } pub fn update_pipeconf(&mut self, device: DeviceID, pipeconf: PipeconfID) { self.core_request_sender.try_send(CoreRequest::UpdatePipeconf { device, pipeconf, }).unwrap(); } pub async fn set_flow( &mut self, mut flow: Flow, device: DeviceID, update: UpdateType, ) -> Result<Flow, ContextError> { let hash = crate::util::hash(&flow); let connection = self.connections.get_mut(&device).ok_or(ContextError::from( ContextErrorKind::DeviceNotConnected { device }, ))?; let table_entry = flow.to_table_entry(&connection.pipeconf, hash); let request = new_set_entity_request(1, table_entry_to_entity(table_entry), update.into()); match connection.p4runtime_client.write(tonic::Request::new(request)).await { Ok(response) => { debug!(target: "core", "set entity response: {:?}", response); } Err(e) => { error!(target: "core", "grpc send error: {:?}", e); } } flow.metadata = hash; Ok(flow) } pub fn send_event(&mut self, event: E) { self.event_sender .try_send(CoreEvent::Event(event)) .unwrap(); } pub fn send_request(&mut self, request: CoreRequest) { self.core_request_sender.try_send(request).unwrap(); } pub async fn set_entity<T: crate::entity::ToEntity>( &mut self, device: DeviceID, update_type: UpdateType, entity: &T, ) -> Result<(), ContextError> { let connection = self.connections.get_mut(&device).ok_or(ContextError::from( ContextErrorKind::DeviceNotConnected { device }, ))?; if let Some(entity) = entity.to_proto_entity(&connection.pipeconf) { let request = new_set_entity_request(1, entity, update_type.into()); match connection.p4runtime_client.write(tonic::Request::new(request)).await { Ok(response) => { debug!(target: "core", "set entity response: {:?}", response); } Err(e) => { error!(target: "core", "grpc send error: {:?}", e); } } Ok(()) } else { Err(ContextError::from(ContextErrorKind::EntityIsNone)) } } pub fn remove_device(&mut self, device: DeviceID) { self.core_request_sender .try_send(CoreRequest::RemoveDevice { device }) .unwrap(); } } #[async_trait] impl<E> Context<E> for DefaultContext<E> where E: Event { type ContextState = (); fn new( core_request_sender: Sender<CoreRequest>, event_sender: Sender<CoreEvent<E>>, connections: HashMap<DeviceID, ConnectionBox, RandomState>, pipeconf: Arc<HashMap<PipeconfID, Pipeconf, RandomState>>, state: () ) -> Self { DefaultContext { core_request_sender, event_sender, connections, pipeconf, } } fn send_event(&mut self, event: E) { self.event_sender .try_send(CoreEvent::Event(event)) .unwrap(); } fn get_conn(&self) -> &HashMap<DeviceID, ConnectionBox, RandomState> { &self.connections } fn get_mut_conn(&mut self) -> &mut HashMap<DeviceID, ConnectionBox, RandomState> { &mut self.connections } fn get_connectpoint(&self, packet: &PacketReceived) -> Option<ConnectPoint> { self.connections.get(&packet.from) .map(|conn| &conn.pipeconf) .and_then(|pipeconf| { packet.metadata.iter() .find(|x| x.metadata_id == pipeconf.packetin_ingress_id) .map(|x| BigEndian::read_u16(x.value.as_ref())) }) .map(|port| ConnectPoint { device: packet.from, port: port as u32, }) } async fn insert_flow(&mut self, mut flow: Flow, device: DeviceID) -> Result<Flow, ContextError> { self.set_flow(flow, device, UpdateType::Insert).await } async fn send_packet(&mut self, to: ConnectPoint, packet: Bytes) { if let Some(c) = self.connections.get_mut(&to.device) { let request = new_packet_out_request(&c.pipeconf, to.port, packet); if let Err(err) = c.send_stream_request(request).await { error!(target: "core", "packet out err {:?}", err); } } else { error!(target: "core", "PacketOut error: connection not found for device {:?}.", to.device); } } fn add_device(&mut self, device: Device) -> bool { if self.connections.contains_key(&device.id) { return false; } self.core_request_sender .try_send(CoreRequest::AddDevice { device, }) .unwrap(); return true; } }
use crate::app::P4app; use crate::entity::UpdateType; use crate::error::{ContextError, ContextErrorKind}; use crate::event::{CommonEvents, CoreEvent, CoreRequest, Event, PacketReceived}; use crate::p4rt::bmv2::Bmv2SwitchConnection; use crate::p4rt::pipeconf::{Pipeconf, PipeconfID}; use crate::p4rt::pure::{ new_packet_out_request, new_set_entity_request, new_write_table_entry, table_entry_to_entity, }; use crate::proto::p4runtime::{ stream_message_response, Entity, Index, MeterEntry, PacketIn, StreamMessageRequest, StreamMessageResponse, Uint128, Update, WriteRequest, WriteResponse, }; use rusty_p4_proto::proto::v1::MasterArbitrationUpdate; use crate::representation::{ConnectPoint, Device, DeviceID, DeviceType}; use crate::util::flow::Flow; use byteorder::BigEndian; use byteorder::ByteOrder; use bytes::Bytes; use failure::ResultExt; use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, Sender}; use futures::future::FutureExt; use futures::sink::SinkExt; use futures::stream::StreamExt; use log::{debug, error, info, trace, warn}; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::path::Path; use std::sync::{Arc, Mutex, RwLock}; use crate::core::connection::bmv2::Bmv2Connection; use crate::core::connection::ConnectionBox; use async_trait::async_trait; use nom::lib::std::collections::hash_map::RandomState; use crate::core::context::Context; #[derive(Clone)] pub struct DefaultContext<E> { pub core_request_sender: futures::channel::mpsc::Sender<CoreRequest>, pub event_sender: futures::channel::mpsc::Sender<CoreEvent<E>>, pub connections: HashMap<DeviceID, ConnectionBox>, pub pipeconf: Arc<HashMap<PipeconfID, Pipeconf>>, } impl<E> DefaultContext<E> where E: Debug + Event, { pub fn new( core_request_sender: futures::channel::mpsc::Sender<CoreRequest>, event_sender: futures::channel::mpsc::Sender<CoreEvent<E>>, connections: HashMap<DeviceID, ConnectionBox>, pipeconf: Arc<HashMap<PipeconfID, Pipeconf>>, ) -> DefaultContext<E> { DefaultContext { core_request_sender, event_sender, connections, pipeconf, } } pub fn update_pipeconf(&mut self, device: DeviceID, pipeconf: PipeconfID) { self.core_request_sender.try_send(CoreRequest::UpdatePipeconf { device, pipeconf, }).unwrap(); } pub async fn set_flow( &mut self, mut flow: Flow, device: DeviceID, update: UpdateType, ) -> Result<Flow, ContextError> { let hash = crate::util::hash(&flow); let connection = self.connections.get_mut(&device).ok_or(ContextError::from( ContextErrorKind::DeviceNotConnected { device }, ))?; let table_entry = flow.to_table_entry(&connection.pipeconf, hash); let request = new_set_entity_request(1, table_entry_to_entity(table_entry), update.into()); match connection.p4runtime_client.write(tonic::Request::new(request)).await { Ok(response) => { debug!(target: "core", "set entity response: {:?}", response); } Err(e) => { error!(target: "core", "grpc send error: {:?}", e); } } flow.metadata = hash; Ok(flow) } pub fn send_event(&mut self, event: E) { self.event_sender .try_send(CoreEvent::Event(event)) .unwrap(); } pub fn send_request(&mut self, request: CoreRequest) { self.core_request_sender.try_send(request).unwrap(); } pub async fn set_entity<T: crate::entity::ToEntity>( &mut self, device: DeviceID, update_type: UpdateType, entity: &T, ) -> Result<(), ContextError> { let connection = self.connections.get_mut(&device).ok_or(ContextError::from( ContextErrorKind::DeviceNotConnected { device }, ))?; if let Some(entity) = entity.to_proto_entity(&connection.pipeconf) { let request = new_set_entity_request(1, entity, update_type.into()); match connection.p4runtime_client.write(tonic::Request::new(request)).await { Ok(response) => { debug!(target: "core", "set entity response: {:?}", response); } Err(e) => { error!(target: "core", "grpc send error: {:?}", e); } } Ok(()) } else { Err(ContextError::from(ContextErrorKind::EntityIsNone)) } } pub fn remove_device(&mut self, device: DeviceID) { self.core_request_sender .try_send(CoreRequest::RemoveDevice { device }) .unwrap(); } } #[async_trait] impl<E> Context<E> for DefaultContext<E> where E: Event { type ContextState = (); fn new( core_request_sender: Sender<CoreRequest>, event_sender: Sender<CoreEvent<E>>, connections: HashMap<DeviceID, ConnectionBox, RandomState>, pipeconf: Arc<HashMap<PipeconfID, Pipeconf, RandomState>>, state: () ) -> Self { DefaultContext { core_request_sender, event_sender, connections, pipeconf, } } fn send_event(&mut self, event: E) { self.event_sender .try_send(CoreEvent::Event(event)) .unwrap(); } fn get_conn(&self) -> &HashMap<DeviceID, ConnectionBox, RandomState> { &self.connections } fn get_mut_conn(&mut self) -> &mut HashMap<DeviceID, ConnectionBox, RandomState> { &mut self.connections } fn get_connectpoint(&self, packet: &PacketReceived) -> Option<ConnectPoint> { self.connections.get(&packet.from) .map(|conn| &conn.pipeconf) .and_then(|pipeconf| { packet.metadata.iter() .find(|x| x.metadata_id == pipeconf.packetin_ingress_id) .map(|x| BigEndian::read_u16(x.value.as_ref())) }) .map(|port| ConnectPoint { device: packet.from, port: port as u32, }) } async fn insert_flow(&mut self, mut flow: Flow, device: DeviceID) -> Result<Flow, ContextError> { self.set_flow(flow, device, UpdateType::Insert).await } async fn send_packet(&mut self, to: ConnectPoint, packet: Bytes) {
} fn add_device(&mut self, device: Device) -> bool { if self.connections.contains_key(&device.id) { return false; } self.core_request_sender .try_send(CoreRequest::AddDevice { device, }) .unwrap(); return true; } }
if let Some(c) = self.connections.get_mut(&to.device) { let request = new_packet_out_request(&c.pipeconf, to.port, packet); if let Err(err) = c.send_stream_request(request).await { error!(target: "core", "packet out err {:?}", err); } } else { error!(target: "core", "PacketOut error: connection not found for device {:?}.", to.device); }
if_condition
[ { "content": "pub fn new_set_entity_request(\n\n device_id: u64,\n\n entity: Entity,\n\n update_type: crate::proto::p4runtime::update::Type,\n\n) -> WriteRequest {\n\n WriteRequest {\n\n device_id,\n\n role_id: 0,\n\n election_id: Some(Uint128 { high: 0, low: 1 }),\n\n up...
Rust
src/lib.rs
matclab/automattermostatus
169b72638dbda91528e30e54a7a614e2e6a20471
#![warn(missing_docs)] use anyhow::{bail, Context, Result}; use std::fs; use std::path::PathBuf; use std::thread::sleep; use std::{collections::HashMap, time}; use tracing::{debug, error, info, warn}; use tracing_subscriber::prelude::*; use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter}; pub mod config; pub mod mattermost; pub mod offtime; pub mod state; pub mod utils; pub mod wifiscan; pub use config::{Args, SecretType, WifiStatusConfig}; pub use mattermost::{BaseSession, MMStatus, Session}; use offtime::Off; pub use state::{Cache, Location, State}; pub use wifiscan::{WiFi, WifiInterface}; pub fn setup_tracing(args: &Args) -> Result<()> { let fmt_layer = fmt::layer().with_target(false); let filter_layer = EnvFilter::try_new(args.verbose.get_level_filter().to_string()).unwrap(); tracing_subscriber::registry() .with(filter_layer) .with(fmt_layer) .init(); Ok(()) } pub fn get_cache(dir: Option<PathBuf>) -> Result<Cache> { let mut state_file_name: PathBuf; if let Some(ref state_dir) = dir { state_file_name = PathBuf::from(state_dir); fs::create_dir_all(&state_dir) .with_context(|| format!("Creating cache dir {:?}", &state_dir))?; } else { bail!("Internal Error, no `state_dir` configured"); } state_file_name.push("automattermostatus.state"); Ok(Cache::new(state_file_name)) } pub fn prepare_status(args: &Args) -> Result<HashMap<Location, MMStatus>> { let mut res = HashMap::new(); for s in &args.status { let sc: WifiStatusConfig = s.parse().with_context(|| format!("Parsing {}", s))?; debug!("Adding : {:?}", sc); res.insert( Location::Known(sc.wifi_string), MMStatus::new(sc.text, sc.emoji), ); } Ok(res) } pub fn create_session(args: &Args) -> Result<Box<dyn BaseSession>> { args.mm_url.as_ref().expect("Mattermost URL is not defined"); args.secret_type .as_ref() .expect("Internal Error: secret_type is not defined"); args.mm_secret.as_ref().expect("Secret is not defined"); let mut session = Session::new(args.mm_url.as_ref().unwrap()); let mut session: Box<dyn BaseSession> = match args.secret_type.as_ref().unwrap() { SecretType::Password => Box::new(session.with_credentials( args.mm_user.as_ref().unwrap(), args.mm_secret.as_ref().unwrap(), )), SecretType::Token => Box::new(session.with_token(args.mm_secret.as_ref().unwrap())), }; session.login()?; Ok(session) } pub fn get_wifi_and_update_status_loop( args: Args, mut status_dict: HashMap<Location, MMStatus>, ) -> Result<()> { let cache = get_cache(args.state_dir.to_owned()).context("Reading cached state")?; let mut state = State::new(&cache).context("Creating cache")?; let delay_duration = time::Duration::new( args.delay .expect("Internal error: args.delay shouldn't be None") .into(), 0, ); let wifi = WiFi::new( &args .interface_name .clone() .expect("Internal error: args.interface_name shouldn't be None"), ); if !wifi .is_wifi_enabled() .context("Checking if wifi is enabled")? { error!("wifi is disabled"); } else { info!("Wifi is enabled"); } let mut session = create_session(&args)?; loop { if !&args.is_off_time() { let ssids = wifi.visible_ssid().context("Getting visible SSIDs")?; debug!("Visible SSIDs {:#?}", ssids); let mut found_ssid = false; for (l, mmstatus) in status_dict.iter_mut() { if let Location::Known(wifi_substring) = l { if ssids.iter().any(|x| x.contains(wifi_substring)) { if wifi_substring.is_empty() { debug!("We do not match against empty SSID reserved for off time"); continue; } debug!("known wifi '{}' detected", wifi_substring); found_ssid = true; mmstatus.expires_at(&args.expires_at); if let Err(e) = state.update_status( l.clone(), Some(mmstatus), &mut session, &cache, delay_duration.as_secs(), ) { error!("Fail to update status : {}", e) } break; } } } if !found_ssid { debug!("Unknown wifi"); if let Err(e) = state.update_status( Location::Unknown, None, &mut session, &cache, delay_duration.as_secs(), ) { error!("Fail to update status : {}", e) } } } else { let off_location = Location::Known("".to_string()); if let Some(offstatus) = status_dict.get_mut(&off_location) { debug!("Setting state for Offtime"); if let Err(e) = state.update_status( off_location, Some(offstatus), &mut session, &cache, delay_duration.as_secs(), ) { error!("Fail to update status : {}", e) } } } if let Some(0) = args.delay { break; } else { sleep(delay_duration); } } Ok(()) } #[cfg(test)] mod get_cache_should { use super::*; use anyhow::anyhow; use test_log::test; #[test] fn panic_when_called_with_none() -> Result<()> { match get_cache(None) { Ok(_) => Err(anyhow!("Expected an error")), Err(e) => { assert_eq!(e.to_string(), "Internal Error, no `state_dir` configured"); Ok(()) } } } } #[cfg(test)] mod prepare_status_should { use super::*; use test_log::test; #[test] fn prepare_expected_status() -> Result<()> { let args = Args { status: vec!["a::b::c", "d::e::f", "::off::off text"] .iter() .map(|s| s.to_string()) .collect(), mm_secret: Some("AAA".to_string()), ..Default::default() }; let res = prepare_status(&args)?; let mut expected: HashMap<state::Location, mattermost::MMStatus> = HashMap::new(); expected.insert( Location::Known("".to_string()), MMStatus::new("off text".to_string(), "off".to_string()), ); expected.insert( Location::Known("a".to_string()), MMStatus::new("c".to_string(), "b".to_string()), ); expected.insert( Location::Known("d".to_string()), MMStatus::new("f".to_string(), "e".to_string()), ); assert_eq!(res, expected); Ok(()) } } #[cfg(test)] mod create_session_should { use super::*; #[test] #[should_panic(expected = "Mattermost URL is not defined")] fn panic_when_mm_url_is_none() { let args = Args { status: vec!["a::b::c".to_string()], mm_secret: Some("AAA".to_string()), mm_url: None, ..Default::default() }; let _res = create_session(&args); } } #[cfg(test)] mod main_loop_should { use super::*; #[test] #[should_panic(expected = "Internal error: args.delay shouldn't be None")] fn panic_when_args_delay_is_none() { let args = Args { status: vec!["a::b::c".to_string()], delay: None, ..Default::default() }; let _res = get_wifi_and_update_status_loop(args, HashMap::new()); } }
#![warn(missing_docs)] use anyhow::{bail, Context, Result}; use std::fs; use std::path::PathBuf; use std::thread::sleep; use std::{collections::HashMap, time}; use tracing::{debug, error, info, warn}; use tracing_subscriber::prelude::*; use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter}; pub mod config; pub mod mattermost; pub mod offtime; pub mod state; pub mod utils; pub mod wifiscan; pub use config::{Args, SecretType, WifiStatusConfig}; pub use mattermost::{BaseSession, MMStatus, Session}; use offtime::Off; pub use state::{Cache, Location, State}; pub use wifiscan::{WiFi, WifiInterface};
pub fn get_cache(dir: Option<PathBuf>) -> Result<Cache> { let mut state_file_name: PathBuf; if let Some(ref state_dir) = dir { state_file_name = PathBuf::from(state_dir); fs::create_dir_all(&state_dir) .with_context(|| format!("Creating cache dir {:?}", &state_dir))?; } else { bail!("Internal Error, no `state_dir` configured"); } state_file_name.push("automattermostatus.state"); Ok(Cache::new(state_file_name)) } pub fn prepare_status(args: &Args) -> Result<HashMap<Location, MMStatus>> { let mut res = HashMap::new(); for s in &args.status { let sc: WifiStatusConfig = s.parse().with_context(|| format!("Parsing {}", s))?; debug!("Adding : {:?}", sc); res.insert( Location::Known(sc.wifi_string), MMStatus::new(sc.text, sc.emoji), ); } Ok(res) } pub fn create_session(args: &Args) -> Result<Box<dyn BaseSession>> { args.mm_url.as_ref().expect("Mattermost URL is not defined"); args.secret_type .as_ref() .expect("Internal Error: secret_type is not defined"); args.mm_secret.as_ref().expect("Secret is not defined"); let mut session = Session::new(args.mm_url.as_ref().unwrap()); let mut session: Box<dyn BaseSession> = match args.secret_type.as_ref().unwrap() { SecretType::Password => Box::new(session.with_credentials( args.mm_user.as_ref().unwrap(), args.mm_secret.as_ref().unwrap(), )), SecretType::Token => Box::new(session.with_token(args.mm_secret.as_ref().unwrap())), }; session.login()?; Ok(session) } pub fn get_wifi_and_update_status_loop( args: Args, mut status_dict: HashMap<Location, MMStatus>, ) -> Result<()> { let cache = get_cache(args.state_dir.to_owned()).context("Reading cached state")?; let mut state = State::new(&cache).context("Creating cache")?; let delay_duration = time::Duration::new( args.delay .expect("Internal error: args.delay shouldn't be None") .into(), 0, ); let wifi = WiFi::new( &args .interface_name .clone() .expect("Internal error: args.interface_name shouldn't be None"), ); if !wifi .is_wifi_enabled() .context("Checking if wifi is enabled")? { error!("wifi is disabled"); } else { info!("Wifi is enabled"); } let mut session = create_session(&args)?; loop { if !&args.is_off_time() { let ssids = wifi.visible_ssid().context("Getting visible SSIDs")?; debug!("Visible SSIDs {:#?}", ssids); let mut found_ssid = false; for (l, mmstatus) in status_dict.iter_mut() { if let Location::Known(wifi_substring) = l { if ssids.iter().any(|x| x.contains(wifi_substring)) { if wifi_substring.is_empty() { debug!("We do not match against empty SSID reserved for off time"); continue; } debug!("known wifi '{}' detected", wifi_substring); found_ssid = true; mmstatus.expires_at(&args.expires_at); if let Err(e) = state.update_status( l.clone(), Some(mmstatus), &mut session, &cache, delay_duration.as_secs(), ) { error!("Fail to update status : {}", e) } break; } } } if !found_ssid { debug!("Unknown wifi"); if let Err(e) = state.update_status( Location::Unknown, None, &mut session, &cache, delay_duration.as_secs(), ) { error!("Fail to update status : {}", e) } } } else { let off_location = Location::Known("".to_string()); if let Some(offstatus) = status_dict.get_mut(&off_location) { debug!("Setting state for Offtime"); if let Err(e) = state.update_status( off_location, Some(offstatus), &mut session, &cache, delay_duration.as_secs(), ) { error!("Fail to update status : {}", e) } } } if let Some(0) = args.delay { break; } else { sleep(delay_duration); } } Ok(()) } #[cfg(test)] mod get_cache_should { use super::*; use anyhow::anyhow; use test_log::test; #[test] fn panic_when_called_with_none() -> Result<()> { match get_cache(None) { Ok(_) => Err(anyhow!("Expected an error")), Err(e) => { assert_eq!(e.to_string(), "Internal Error, no `state_dir` configured"); Ok(()) } } } } #[cfg(test)] mod prepare_status_should { use super::*; use test_log::test; #[test] fn prepare_expected_status() -> Result<()> { let args = Args { status: vec!["a::b::c", "d::e::f", "::off::off text"] .iter() .map(|s| s.to_string()) .collect(), mm_secret: Some("AAA".to_string()), ..Default::default() }; let res = prepare_status(&args)?; let mut expected: HashMap<state::Location, mattermost::MMStatus> = HashMap::new(); expected.insert( Location::Known("".to_string()), MMStatus::new("off text".to_string(), "off".to_string()), ); expected.insert( Location::Known("a".to_string()), MMStatus::new("c".to_string(), "b".to_string()), ); expected.insert( Location::Known("d".to_string()), MMStatus::new("f".to_string(), "e".to_string()), ); assert_eq!(res, expected); Ok(()) } } #[cfg(test)] mod create_session_should { use super::*; #[test] #[should_panic(expected = "Mattermost URL is not defined")] fn panic_when_mm_url_is_none() { let args = Args { status: vec!["a::b::c".to_string()], mm_secret: Some("AAA".to_string()), mm_url: None, ..Default::default() }; let _res = create_session(&args); } } #[cfg(test)] mod main_loop_should { use super::*; #[test] #[should_panic(expected = "Internal error: args.delay shouldn't be None")] fn panic_when_args_delay_is_none() { let args = Args { status: vec!["a::b::c".to_string()], delay: None, ..Default::default() }; let _res = get_wifi_and_update_status_loop(args, HashMap::new()); } }
pub fn setup_tracing(args: &Args) -> Result<()> { let fmt_layer = fmt::layer().with_target(false); let filter_layer = EnvFilter::try_new(args.verbose.get_level_filter().to_string()).unwrap(); tracing_subscriber::registry() .with(filter_layer) .with(fmt_layer) .init(); Ok(()) }
function_block-full_function
[ { "content": "/// Trait implementing function necessary to establish a session (getting a authenticating token).\n\npub trait BaseSession {\n\n /// Get session token\n\n fn token(&self) -> Result<&str>;\n\n\n\n /// Get session `base_uri`\n\n fn base_uri(&self) -> &str;\n\n\n\n /// Login to matter...
Rust
imtui-sys/src/bindings.rs
richinseattle/imtui-rs
09ecddbd9a0e535068406d580c9aaf21d096d7af
/* automatically generated by rust-bindgen */ extern crate imgui_sys; #[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] pub mod root { #[allow(unused_imports)] use self::super::root; use imgui_sys::ImDrawData; pub mod ImTui { #[allow(unused_imports)] use self::super::super::root; pub type TCell = u32; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct TScreen { pub nx: ::std::os::raw::c_int, pub ny: ::std::os::raw::c_int, pub nmax: ::std::os::raw::c_int, pub data: *mut root::ImTui::TCell, } #[test] fn bindgen_test_layout_TScreen() { assert_eq!( ::std::mem::size_of::<TScreen>(), 24usize, concat!("Size of: ", stringify!(TScreen)) ); assert_eq!( ::std::mem::align_of::<TScreen>(), 8usize, concat!("Alignment of ", stringify!(TScreen)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TScreen>())).nx as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(TScreen), "::", stringify!(nx) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TScreen>())).ny as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(TScreen), "::", stringify!(ny) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TScreen>())).nmax as *const _ as usize }, 8usize, concat!( "Offset of field: ", stringify!(TScreen), "::", stringify!(nmax) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TScreen>())).data as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(TScreen), "::", stringify!(data) ) ); } extern "C" { #[link_name = "\u{1}__ZNK5ImTui7TScreen4sizeEv"] pub fn TScreen_size(this: *const root::ImTui::TScreen) -> ::std::os::raw::c_int; } extern "C" { #[link_name = "\u{1}__ZN5ImTui7TScreen5clearEv"] pub fn TScreen_clear(this: *mut root::ImTui::TScreen); } extern "C" { #[link_name = "\u{1}__ZN5ImTui7TScreen6resizeEii"] pub fn TScreen_resize( this: *mut root::ImTui::TScreen, pnx: ::std::os::raw::c_int, pny: ::std::os::raw::c_int, ); } impl TScreen { #[inline] pub unsafe fn size(&self) -> ::std::os::raw::c_int { TScreen_size(self) } #[inline] pub unsafe fn clear(&mut self) { TScreen_clear(self) } #[inline] pub unsafe fn resize( &mut self, pnx: ::std::os::raw::c_int, pny: ::std::os::raw::c_int, ) { TScreen_resize(self, pnx, pny) } } } extern "C" { #[link_name = "\u{1}__Z19ImTui_ImplText_Initv"] pub fn ImTui_ImplText_Init() -> bool; } extern "C" { #[link_name = "\u{1}__Z23ImTui_ImplText_Shutdownv"] pub fn ImTui_ImplText_Shutdown(); } extern "C" { #[link_name = "\u{1}__Z23ImTui_ImplText_NewFramev"] pub fn ImTui_ImplText_NewFrame(); } extern "C" { #[link_name = "\u{1}__Z29ImTui_ImplText_RenderDrawDataP10ImDrawDataPN5ImTui7TScreenE"] pub fn ImTui_ImplText_RenderDrawData( drawData: *mut root::ImDrawData, screen: *mut root::ImTui::TScreen, ); } pub mod std { #[allow(unused_imports)] use self::super::super::root; } extern "C" { #[link_name = "\u{1}__Z22ImTui_ImplNcurses_Initbff"] pub fn ImTui_ImplNcurses_Init( mouseSupport: bool, fps_active: f32, fps_idle: f32, ) -> *mut root::ImTui::TScreen; } extern "C" { #[link_name = "\u{1}__Z26ImTui_ImplNcurses_Shutdownv"] pub fn ImTui_ImplNcurses_Shutdown(); } extern "C" { #[link_name = "\u{1}__Z26ImTui_ImplNcurses_NewFramev"] pub fn ImTui_ImplNcurses_NewFrame() -> bool; } extern "C" { #[link_name = "\u{1}__Z28ImTui_ImplNcurses_DrawScreenb"] pub fn ImTui_ImplNcurses_DrawScreen(active: bool); } extern "C" { #[link_name = "\u{1}__Z30ImTui_ImplNcurses_ProcessEventv"] pub fn ImTui_ImplNcurses_ProcessEvent() -> bool; } }
/* automatically generated by rust-bindgen */ extern crate imgui_sys; #[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] pub mod root { #[allow(unused_imports)] use self::super::root; use imgui_sys::ImDrawData; pub mod ImTui { #[allow(unused_imports)] use self::super::super::root; pub type TCell = u32; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct TScreen { pub nx: ::std::os::raw::c_int, pub ny: ::std::os::raw::c_int, pub nmax: ::std::os::raw::c_int, pub data: *mut root::ImTui::TCell, } #[test] fn bindgen_test_layout_TScreen() { assert_eq!( ::std::mem::size_of::<TScreen>(), 24usize, concat!("Size of: ", stringify!(TScreen)) ); assert_eq!( ::std::mem::align_of::<TScreen>(), 8usize, concat!("Alignment of ", stringify!(TScreen)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TScreen>())).nx as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(TScreen), "::", stringify!(nx) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TScreen>())).ny as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(TScreen), "::", stringify!(ny) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TScreen>())).nmax as *const _ as usize }, 8usize, concat!( "Offset of field: ", stringify!(TScreen), "::", stringify!(nmax) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TScreen>())).data as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(TScreen), "::", stringify!(data) ) ); } extern "C" { #[link_name = "\u{1}__ZNK5ImTui7TScreen4sizeEv"] pub fn TScreen_size(this: *const root::ImTui::TScreen) -> ::std::os::raw::c_int; } extern "C" { #[link_name = "\u{1}__ZN5ImTui7TScreen5clearEv"] pub fn TScreen_clear(this: *mut root::ImTui::TScreen); } extern "C" { #[link_name = "\u{1}__ZN5ImTui7TScreen6resizeEii"] pub fn TScreen_resize( this: *mut root::ImTui::TScreen, pnx: ::std::os::raw::c_int, pny: ::std::os::raw::c_int, ); } impl TScreen { #[inline] pub unsafe fn size(&self) -> ::std::os::raw::c_int { TScreen_size(self) } #[inline] pub unsafe fn clear(&mut self) { TScreen_clear(self) } #[inline] pub unsafe fn resize( &mut self,
} } extern "C" { #[link_name = "\u{1}__Z19ImTui_ImplText_Initv"] pub fn ImTui_ImplText_Init() -> bool; } extern "C" { #[link_name = "\u{1}__Z23ImTui_ImplText_Shutdownv"] pub fn ImTui_ImplText_Shutdown(); } extern "C" { #[link_name = "\u{1}__Z23ImTui_ImplText_NewFramev"] pub fn ImTui_ImplText_NewFrame(); } extern "C" { #[link_name = "\u{1}__Z29ImTui_ImplText_RenderDrawDataP10ImDrawDataPN5ImTui7TScreenE"] pub fn ImTui_ImplText_RenderDrawData( drawData: *mut root::ImDrawData, screen: *mut root::ImTui::TScreen, ); } pub mod std { #[allow(unused_imports)] use self::super::super::root; } extern "C" { #[link_name = "\u{1}__Z22ImTui_ImplNcurses_Initbff"] pub fn ImTui_ImplNcurses_Init( mouseSupport: bool, fps_active: f32, fps_idle: f32, ) -> *mut root::ImTui::TScreen; } extern "C" { #[link_name = "\u{1}__Z26ImTui_ImplNcurses_Shutdownv"] pub fn ImTui_ImplNcurses_Shutdown(); } extern "C" { #[link_name = "\u{1}__Z26ImTui_ImplNcurses_NewFramev"] pub fn ImTui_ImplNcurses_NewFrame() -> bool; } extern "C" { #[link_name = "\u{1}__Z28ImTui_ImplNcurses_DrawScreenb"] pub fn ImTui_ImplNcurses_DrawScreen(active: bool); } extern "C" { #[link_name = "\u{1}__Z30ImTui_ImplNcurses_ProcessEventv"] pub fn ImTui_ImplNcurses_ProcessEvent() -> bool; } }
pnx: ::std::os::raw::c_int, pny: ::std::os::raw::c_int, ) { TScreen_resize(self, pnx, pny) }
function_block-function_prefix_line
[ { "content": "type HnItemId = u32;\n\n\n", "file_path": "examples/hnterm/main.rs", "rank": 0, "score": 67556.55634805921 }, { "content": "pub fn generate_bindings(imtui_path: &Path, imgui_include_path: &Path) -> Result<Bindings, Error> {\n\n let imtui_include_path = imtui_path.join(\"incl...
Rust
procgen/src/connections.rs
gridbugs/rip
4bb5388df5d8fd694399773bf2faeba51f2cf2e5
use crate::hull::HullCell; use direction::{CardinalDirection, Direction}; use grid_2d::{ coord_2d::{static_axis, Axis, StaticAxis}, Coord, Grid, }; use rand::{seq::SliceRandom, Rng}; use std::collections::{HashMap, HashSet, VecDeque}; type RoomId = usize; type DoorCandidateId = usize; pub enum ConnectedCell { Floor, Wall, Space, Door, Window, } #[derive(Clone, Copy)] enum ClassifiedCell { Space, Wall, Room(RoomId), } fn classify_cells(grid: &Grid<HullCell>) -> Grid<ClassifiedCell> { let mut intermediate: Grid<Option<ClassifiedCell>> = Grid::new_fn(grid.size(), |_| None); let mut room_count = 0; let mut flood_fill_buffer = VecDeque::new(); for coord in grid.coord_iter() { if intermediate.get_checked(coord).is_some() { continue; } let classified_cell = match grid.get_checked(coord) { HullCell::Wall => ClassifiedCell::Wall, HullCell::Space => ClassifiedCell::Space, HullCell::Floor => { let classified_cell = ClassifiedCell::Room(room_count); flood_fill_buffer.push_back(coord); while let Some(coord) = flood_fill_buffer.pop_front() { for direction in Direction::all() { let neighbour_coord = coord + direction.coord(); if let Some(HullCell::Floor) = grid.get(neighbour_coord) { let cell = intermediate.get_checked_mut(neighbour_coord); if cell.is_none() { *cell = Some(classified_cell); flood_fill_buffer.push_back(neighbour_coord); } } } } room_count += 1; classified_cell } }; *intermediate.get_checked_mut(coord) = Some(classified_cell); } Grid::new_grid_map(intermediate, |maybe_cell| maybe_cell.unwrap()) } #[derive(Debug)] struct WindowCandidate { top_left: Coord, length: u32, axis: Axis, room: RoomId, } impl WindowCandidate { fn choose<'a, R: Rng>(&'a self, rng: &mut R) -> impl 'a + Iterator<Item = Coord> { let min_length = 1 + self.length / 8; let max_length = 1 + self.length / 3; let length = rng.gen_range(min_length, max_length + 1); let remaining_candidate_length = self.length - length; let min_offset = remaining_candidate_length / 4; let max_offset = remaining_candidate_length - min_offset; let offset = rng.gen_range(min_offset, max_offset + 1); (0..(length as i32)).map(move |i| self.top_left + Coord::new_axis(i + offset as i32, 0, self.axis.other())) } } #[derive(Debug, Clone)] struct DoorCandidate { top_left: Coord, length: u32, axis: Axis, left_room: RoomId, right_room: RoomId, } impl DoorCandidate { fn choose<R: Rng>(&self, rng: &mut R) -> Coord { let offset = rng.gen_range(0, self.length as i32); self.top_left + Coord::new_axis(offset, 0, self.axis.other()) } fn all<'a>(&'a self) -> impl 'a + Iterator<Item = Coord> { (0..(self.length as i32)).map(move |i| self.top_left + Coord::new_axis(i, 0, self.axis.other())) } } #[derive(Debug)] enum Candidate { Window(WindowCandidate), Door(DoorCandidate), } impl Candidate { fn length_mut(&mut self) -> &mut u32 { match self { Self::Door(DoorCandidate { ref mut length, .. }) => length, Self::Window(WindowCandidate { ref mut length, .. }) => length, } } } #[derive(Clone, Copy, PartialEq, Eq)] enum AbstractCandidate { Window { room: RoomId }, Door { left_room: RoomId, right_room: RoomId }, } fn classify_connection_candidates_in_axis<A: StaticAxis>(grid: &Grid<ClassifiedCell>, candidates: &mut Vec<Candidate>) { for i in 1..(grid.size().get_static::<A>().saturating_sub(1)) { let mut current_abstract_candidate = None; for j in 0..grid.size().get_static::<A::Other>() { let mid_coord = Coord::new_static_axis::<A>(i as i32, j as i32); if let ClassifiedCell::Wall = grid.get_checked(mid_coord) { let left_coord = mid_coord - Coord::new_static_axis::<A>(1, 0); let right_coord = mid_coord + Coord::new_static_axis::<A>(1, 0); let left = grid.get_checked(left_coord); let right = grid.get_checked(right_coord); if let Some(abstract_candidate) = match (*left, *right) { (ClassifiedCell::Space, ClassifiedCell::Room(room)) | (ClassifiedCell::Room(room), ClassifiedCell::Space) => Some(AbstractCandidate::Window { room }), (ClassifiedCell::Room(left_room), ClassifiedCell::Room(right_room)) => { Some(AbstractCandidate::Door { left_room, right_room }) } _ => None, } { if current_abstract_candidate != Some(abstract_candidate) { let new_candidate = match abstract_candidate { AbstractCandidate::Window { room } => Candidate::Window(WindowCandidate { top_left: mid_coord, length: 0, axis: A::axis(), room, }), AbstractCandidate::Door { left_room, right_room } => Candidate::Door(DoorCandidate { top_left: mid_coord, length: 0, axis: A::axis(), left_room, right_room, }), }; candidates.push(new_candidate); } current_abstract_candidate = Some(abstract_candidate); *candidates.last_mut().unwrap().length_mut() += 1; continue; } } current_abstract_candidate = None; } } } #[derive(Default)] struct Candidates { door: Vec<DoorCandidate>, window: Vec<WindowCandidate>, } fn classify_connection_candidates(grid: &Grid<ClassifiedCell>) -> Candidates { let mut all_candidatces = Vec::new(); classify_connection_candidates_in_axis::<static_axis::X>(grid, &mut all_candidatces); classify_connection_candidates_in_axis::<static_axis::Y>(grid, &mut all_candidatces); let mut candidates = Candidates::default(); for candidate in all_candidatces { match candidate { Candidate::Door(door) => candidates.door.push(door), Candidate::Window(window) => candidates.window.push(window), } } candidates } #[derive(Debug)] struct RoomEdge { to_room: RoomId, via: DoorCandidateId, } #[derive(Default, Debug)] struct RoomNode { edges: Vec<RoomEdge>, } type DoorCandidateGraph = HashMap<RoomId, RoomNode>; fn make_door_candidate_graph(door_candidates: &[DoorCandidate]) -> DoorCandidateGraph { let mut graph: DoorCandidateGraph = HashMap::new(); for (door_candidate_id, door_candidate) in door_candidates.into_iter().enumerate() { graph.entry(door_candidate.left_room).or_default().edges.push(RoomEdge { to_room: door_candidate.right_room, via: door_candidate_id, }); graph .entry(door_candidate.right_room) .or_default() .edges .push(RoomEdge { to_room: door_candidate.left_room, via: door_candidate_id, }); } graph } fn make_random_door_candidate_graph_minimum_spanning_tree<R: Rng>( door_candidate_graph: &DoorCandidateGraph, door_candidates: &[DoorCandidate], rng: &mut R, ) -> HashSet<DoorCandidateId> { let mut mst = HashSet::new(); let mut visited_room_ids = HashSet::new(); let mut to_visit = vec![rng.gen_range(0, door_candidates.len())]; while !to_visit.is_empty() { let door_candidate_id = to_visit.swap_remove(rng.gen_range(0, to_visit.len())); let door_candidate = &door_candidates[door_candidate_id]; let new_left = visited_room_ids.insert(door_candidate.left_room); let new_right = visited_room_ids.insert(door_candidate.right_room); if !(new_left || new_right) { continue; } mst.insert(door_candidate_id); for edge in door_candidate_graph[&door_candidate.left_room] .edges .iter() .chain(door_candidate_graph[&door_candidate.right_room].edges.iter()) { if !visited_room_ids.contains(&edge.to_room) { to_visit.push(edge.via); } } } mst } fn choose_door_candidates<R: Rng>( door_candidate_graph: &DoorCandidateGraph, door_candidates: &[DoorCandidate], rng: &mut R, ) -> Vec<DoorCandidateId> { let mut chosen_door_candidates = make_random_door_candidate_graph_minimum_spanning_tree(&door_candidate_graph, door_candidates, rng); let mut extrta_door_candidates = (0..door_candidates.len()) .filter(|id| !chosen_door_candidates.contains(id)) .collect::<Vec<_>>(); extrta_door_candidates.shuffle(rng); let num_extra_door_candidates_to_choose = extrta_door_candidates.len() / 2; chosen_door_candidates.extend(extrta_door_candidates.iter().take(num_extra_door_candidates_to_choose)); let mut chosen_door_candidates = chosen_door_candidates.into_iter().collect::<Vec<_>>(); chosen_door_candidates.sort(); chosen_door_candidates.shuffle(rng); chosen_door_candidates } fn trim_non_dividing_walls(grid: &Grid<HullCell>) -> Grid<HullCell> { let mut grid = grid.clone(); loop { let mut to_clear = Vec::new(); for (coord, cell) in grid.enumerate() { if let HullCell::Wall = cell { let mut wall_neighbour_count = 0; for direction in CardinalDirection::all() { let neighbour_coord = coord + direction.coord(); if let Some(HullCell::Wall) = grid.get(neighbour_coord) { wall_neighbour_count += 1; } } if wall_neighbour_count <= 1 { to_clear.push(coord); } } } if to_clear.is_empty() { break; } for coord in to_clear { *grid.get_checked_mut(coord) = HullCell::Floor; } } grid } fn place_door<R: Rng>(candidate: &DoorCandidate, grid: &mut Grid<ConnectedCell>, rng: &mut R) { let coord = candidate.choose(rng); *grid.get_checked_mut(coord) = ConnectedCell::Door; } fn place_window<R: Rng>(candidate: &WindowCandidate, grid: &mut Grid<ConnectedCell>, rng: &mut R) { if rng.gen_range(0, 3) > 0 { for coord in candidate.choose(rng) { *grid.get_checked_mut(coord) = ConnectedCell::Window; } } } pub fn add_connections<R: Rng>(grid: &Grid<HullCell>, rng: &mut R) -> Grid<ConnectedCell> { let classified = classify_cells(grid); let candidates = classify_connection_candidates(&classified); let door_candidate_graph = make_door_candidate_graph(&candidates.door); let chosen_door_candidates = choose_door_candidates(&door_candidate_graph, &candidates.door, rng); let mut grid = grid.clone(); for &door_candidate_id in chosen_door_candidates.iter() { if rng.gen_range(0, 10) == 0 { let candidate = &candidates.door[door_candidate_id]; for coord in candidate.all() { *grid.get_checked_mut(coord) = HullCell::Floor; } } } let grid = trim_non_dividing_walls(&grid); let classified = classify_cells(&grid); let candidates = classify_connection_candidates(&classified); let door_candidate_graph = make_door_candidate_graph(&candidates.door); let chosen_door_candidates = choose_door_candidates(&door_candidate_graph, &candidates.door, rng); let mut grid = Grid::new_grid_map_ref(&grid, |cell| match cell { HullCell::Floor => ConnectedCell::Floor, HullCell::Wall => ConnectedCell::Wall, HullCell::Space => ConnectedCell::Space, }); for &door_candidate_id in chosen_door_candidates.iter() { place_door(&candidates.door[door_candidate_id], &mut grid, rng); } for window_candidate in candidates.window.iter() { place_window(window_candidate, &mut grid, rng); } grid }
use crate::hull::HullCell; use direction::{CardinalDirection, Direction}; use grid_2d::{ coord_2d::{static_axis, Axis, StaticAxis}, Coord, Grid, }; use rand::{seq::SliceRandom, Rng}; use std::collections::{HashMap, HashSet, VecDeque}; type RoomId = usize; type DoorCandidateId = usize; pub enum ConnectedCell { Floor, Wall, Space, Door, Window, } #[derive(Clone, Copy)] enum ClassifiedCell { Space, Wall, Room(RoomId), } fn classify_cells(grid: &Grid<HullCell>) -> Grid<ClassifiedCell> { let mut intermediate: Grid<Option<ClassifiedCell>> = Grid::new_fn(grid.size(), |_| None); let mut room_count = 0; let mut flood_fill_buffer = VecDeque::new(); for coord in grid.coord_iter() { if intermediate.get_checked(coord).is_some() { continue; } let classified_cell = match grid.get_checked(coord) { HullCell::Wall => ClassifiedCell::Wall, HullCell::Space => ClassifiedCell::Space, HullCell::Floor => { let classified_cell = ClassifiedCell::Room(room_count); flood_fill_buffer.push_back(coord); while let Some(coord) = flood_fill_buffer.pop_front() { for direction in Direction::all() { let neighbour_coord = coord + direction.coord(); if let Some(HullCell::Floor) = grid.get(neighbour_coord) { let cell = intermediate.get_checked_mut(neighbour_coord); if cell.is_none() { *cell = Some(classified_cell); flood_fill_buffer.push_back(neighbour_coord); } } } } room_count += 1; classified_cell } }; *intermediate.get_checked_mut(coord) = Some(classified_cell); } Grid::new_grid_map(intermediate, |maybe_cell| maybe_cell.unwrap()) } #[derive(Debug)] struct WindowCandidate { top_left: Coord, length: u32, axis: Axis, room: RoomId, } impl WindowCandidate { fn choose<'a, R: Rng>(&'a self, rng: &mut R) -> impl 'a + Iterator<Item = Coord> { let min_length = 1 + self.length / 8; let max_length = 1 + self.length / 3; let length = rng.gen_range(min_length, max_length + 1); let remaining_candidate_length = self.length - length; let min_offset = remaining_candidate_length / 4; let max_offset = remaining_candidate_length - min_offset; let offset = rng.gen_range(min_offset, max_offset + 1); (0..(length as i32)).map(move |i| self.top_left + Coord::new_axis(i + offset as i32, 0, self.axis.other())) } } #[derive(Debug, Clone)] struct DoorCandidate { top_left: Coord, length: u32, axis: Axis, left_room: RoomId, right_room: RoomId, } impl DoorCandidate { fn choose<R: Rng>(&self, rng: &mut R) -> Coord { let offset = rng.gen_range(0, self.length as i32); self.top_left + Coord::new_axis(offset, 0, self.axis.other()) } fn all<'a>(&'a self) -> impl 'a + Iterator<Item = Coord> { (0..(self.length as i32)).map(move |i| self.top_left + Coord::new_axis(i, 0, self.axis.other())) } } #[derive(Debug)] enum Candidate { Window(WindowCandidate), Door(DoorCandidate), } impl Candidate { fn length_mut(&mut self) -> &mut u32 { match self { Self::Door(DoorCandidate { ref mut length, .. }) => length, Self::Window(WindowCandidate { ref mut length, .. }) => length, } } } #[derive(Clone, Copy, PartialEq, Eq)] enum AbstractCandidate { Window { room: RoomId }, Door { left_room: RoomId, right_room: RoomId }, } fn classify_connection_candidates_in_axis<A: StaticAxis>(grid: &Grid<ClassifiedCell>, candidates: &mut Vec<Candidate>) { for i in 1..(grid.size().get_static::<A>().saturating_sub(1)) { let mut current_abstract_candidate = None; for j in 0..grid.size().get_static::<A::Other>() { let mid_coord = Coord::new_static_axis::<A>(i as i32, j as i32); if let ClassifiedCell::Wall = grid.get_checked(mid_coord) { let left_coord = mid_coord - Coord::new_static_axis::<A>(1, 0); let right_coord = mid_coord + Coord::new_static_axis::<A>(1, 0); let left = grid.get_checked(left_coord); let right = grid.get_checked(right_coord); if let Some(abstract_candidate) = match (*left, *right) { (ClassifiedCell::Space, ClassifiedCell::Room(room)) | (ClassifiedCell::Room(room), ClassifiedCell::Space) => Some(AbstractCandidate::Window { room }), (ClassifiedCell::Room(left_room), ClassifiedCell::Room(right_room)) => { Some(AbstractCandidate::Door { left_room, right_room }) } _ => None, } { if current_abstract_candidate != Some(abstract_candidate) { let new_candidate = match abstract_candidate { AbstractCandidate::Window { room } => Candidate::Window(WindowCandidate { top_left: mid_coord, length: 0, axis: A::axis(), room, }), AbstractCandidate::Door { left_room, right_room } => Candidate::Door(DoorCandidate { top_left: mid_coord, length: 0, axis: A::axis(), left_room, right_room, }), }; candidates.push(new_candidate); } current_abstract_candidate = Some(abstract_candidate); *candidates.last_mut().unwrap().length_mut() += 1; continue; } } current_abstract_candidate = None; } } } #[derive(Default)] struct Candidates { door: Vec<DoorCandidate>, window: Vec<WindowCandidate>, } fn classify_connection_candidates(grid: &Grid<ClassifiedCell>) -> Candidates { let mut all_candidatces = Vec::new(); classify_connection_candidates_in_axis::<static_axis::X>(grid, &mut all_candidatces); classify_connection_candidates_in_axis::<static_axis::Y>(grid, &mut all_candidatces); let mut candidates = Candidates::default(); for candidate in all_candidatces { match candidate { Candidate::Door(door) => candidates.door.push(door), Candidate::Window(window) => candidates.window.push(window), } } candidates } #[derive(Debug)] struct RoomEdge { to_room: RoomId, via: DoorCandidateId, } #[derive(Default, Debug)] struct RoomNode { edges: Vec<RoomEdge>, } type DoorCandidateGraph = HashMap<RoomId, RoomNode>; fn make_door_candidate_graph(door_candidates: &[DoorCandidate]) -> DoorCandidateGraph { let mut graph: DoorCandidateGraph = HashMap::new(); for (door_candidate_id, door_candidate) in door_candidates.into_iter().enumerate() { graph.entry(door_candidate.left_room).or_default().edges.push(RoomEdge { to_room: door_candidate.right_room, via: door_candidate_id, }); graph .entry(door_candidate.right_room) .or_default() .edges .push(RoomEdge { to_room: door_candidate.left_room, via: door_candidate_id, }); } graph }
fn choose_door_candidates<R: Rng>( door_candidate_graph: &DoorCandidateGraph, door_candidates: &[DoorCandidate], rng: &mut R, ) -> Vec<DoorCandidateId> { let mut chosen_door_candidates = make_random_door_candidate_graph_minimum_spanning_tree(&door_candidate_graph, door_candidates, rng); let mut extrta_door_candidates = (0..door_candidates.len()) .filter(|id| !chosen_door_candidates.contains(id)) .collect::<Vec<_>>(); extrta_door_candidates.shuffle(rng); let num_extra_door_candidates_to_choose = extrta_door_candidates.len() / 2; chosen_door_candidates.extend(extrta_door_candidates.iter().take(num_extra_door_candidates_to_choose)); let mut chosen_door_candidates = chosen_door_candidates.into_iter().collect::<Vec<_>>(); chosen_door_candidates.sort(); chosen_door_candidates.shuffle(rng); chosen_door_candidates } fn trim_non_dividing_walls(grid: &Grid<HullCell>) -> Grid<HullCell> { let mut grid = grid.clone(); loop { let mut to_clear = Vec::new(); for (coord, cell) in grid.enumerate() { if let HullCell::Wall = cell { let mut wall_neighbour_count = 0; for direction in CardinalDirection::all() { let neighbour_coord = coord + direction.coord(); if let Some(HullCell::Wall) = grid.get(neighbour_coord) { wall_neighbour_count += 1; } } if wall_neighbour_count <= 1 { to_clear.push(coord); } } } if to_clear.is_empty() { break; } for coord in to_clear { *grid.get_checked_mut(coord) = HullCell::Floor; } } grid } fn place_door<R: Rng>(candidate: &DoorCandidate, grid: &mut Grid<ConnectedCell>, rng: &mut R) { let coord = candidate.choose(rng); *grid.get_checked_mut(coord) = ConnectedCell::Door; } fn place_window<R: Rng>(candidate: &WindowCandidate, grid: &mut Grid<ConnectedCell>, rng: &mut R) { if rng.gen_range(0, 3) > 0 { for coord in candidate.choose(rng) { *grid.get_checked_mut(coord) = ConnectedCell::Window; } } } pub fn add_connections<R: Rng>(grid: &Grid<HullCell>, rng: &mut R) -> Grid<ConnectedCell> { let classified = classify_cells(grid); let candidates = classify_connection_candidates(&classified); let door_candidate_graph = make_door_candidate_graph(&candidates.door); let chosen_door_candidates = choose_door_candidates(&door_candidate_graph, &candidates.door, rng); let mut grid = grid.clone(); for &door_candidate_id in chosen_door_candidates.iter() { if rng.gen_range(0, 10) == 0 { let candidate = &candidates.door[door_candidate_id]; for coord in candidate.all() { *grid.get_checked_mut(coord) = HullCell::Floor; } } } let grid = trim_non_dividing_walls(&grid); let classified = classify_cells(&grid); let candidates = classify_connection_candidates(&classified); let door_candidate_graph = make_door_candidate_graph(&candidates.door); let chosen_door_candidates = choose_door_candidates(&door_candidate_graph, &candidates.door, rng); let mut grid = Grid::new_grid_map_ref(&grid, |cell| match cell { HullCell::Floor => ConnectedCell::Floor, HullCell::Wall => ConnectedCell::Wall, HullCell::Space => ConnectedCell::Space, }); for &door_candidate_id in chosen_door_candidates.iter() { place_door(&candidates.door[door_candidate_id], &mut grid, rng); } for window_candidate in candidates.window.iter() { place_window(window_candidate, &mut grid, rng); } grid }
fn make_random_door_candidate_graph_minimum_spanning_tree<R: Rng>( door_candidate_graph: &DoorCandidateGraph, door_candidates: &[DoorCandidate], rng: &mut R, ) -> HashSet<DoorCandidateId> { let mut mst = HashSet::new(); let mut visited_room_ids = HashSet::new(); let mut to_visit = vec![rng.gen_range(0, door_candidates.len())]; while !to_visit.is_empty() { let door_candidate_id = to_visit.swap_remove(rng.gen_range(0, to_visit.len())); let door_candidate = &door_candidates[door_candidate_id]; let new_left = visited_room_ids.insert(door_candidate.left_room); let new_right = visited_room_ids.insert(door_candidate.right_room); if !(new_left || new_right) { continue; } mst.insert(door_candidate_id); for edge in door_candidate_graph[&door_candidate.left_room] .edges .iter() .chain(door_candidate_graph[&door_candidate.right_room].edges.iter()) { if !visited_room_ids.contains(&edge.to_room) { to_visit.push(edge.via); } } } mst }
function_block-full_function
[ { "content": "pub fn add_internal_walls<R: Rng>(grid: &Grid<HullCell>, rng: &mut R) -> Grid<HullCell> {\n\n let external_walls = ExternalWalls::classify(grid);\n\n let mut internal_walls = Vec::new();\n\n add_internal_walls_rec(\n\n &external_walls,\n\n Rect {\n\n coord: Coord:...
Rust
alacritty/src/renderer/graphics/draw.rs
SonaliBendre/alacritty-sixel
4b143ad2c623f54610a71dba1687d63a2b0f751a
use std::collections::BTreeMap; use std::mem::{self, MaybeUninit}; use crate::display::content::RenderableCell; use crate::gl::{self, types::*}; use crate::renderer::graphics::{shader, GraphicsRenderer}; use alacritty_terminal::graphics::GraphicId; use alacritty_terminal::index::{Column, Line}; use alacritty_terminal::term::SizeInfo; use log::trace; struct RenderPosition { column: Column, line: Line, offset_x: u16, offset_y: u16, padding_y: u16, } #[derive(Default)] pub struct RenderList { items: BTreeMap<GraphicId, RenderPosition>, } impl RenderList { #[inline] pub fn update(&mut self, cell: &RenderableCell, size_info: &SizeInfo) { if let Some(graphic) = &cell.graphic { let graphic_id = graphic.graphic_id(); if self.items.contains_key(&graphic_id) { return; } let render_item = RenderPosition { column: cell.point.column, line: Line(cell.point.line as i32), offset_x: graphic.offset_x, offset_y: graphic.offset_y, padding_y: size_info.padding_y() as u16, }; self.items.insert(graphic_id, render_item); } } #[inline] pub fn is_empty(&self) -> bool { self.items.is_empty() } pub fn build_vertices(self, renderer: &GraphicsRenderer) -> Vec<shader::Vertex> { use shader::VertexSide::{BottomLeft, BottomRight, TopLeft, TopRight}; let mut vertices = Vec::new(); for (graphics_id, render_item) in self.items { let graphic_texture = match renderer.graphic_textures.get(&graphics_id) { Some(tex) => tex, None => continue, }; vertices.reserve(6); let vertex = shader::Vertex { texture_id: graphic_texture.texture.0, sides: TopLeft, column: render_item.column.0 as GLuint, line: render_item.line.0 as GLuint, height: graphic_texture.height, width: graphic_texture.width, offset_x: render_item.offset_x, offset_y: render_item.offset_y, base_cell_height: graphic_texture.cell_height, padding_y: render_item.padding_y, }; vertices.push(vertex); for &sides in &[TopRight, BottomLeft, TopRight, BottomRight, BottomLeft] { vertices.push(shader::Vertex { sides, ..vertex }); } } vertices } pub fn draw(self, renderer: &GraphicsRenderer, size_info: &SizeInfo) { let vertices = self.build_vertices(renderer); unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, renderer.program.vbo); gl::BindVertexArray(renderer.program.vao); gl::UseProgram(renderer.program.id()); gl::Uniform2f( renderer.program.u_cell_dimensions, size_info.cell_width(), size_info.cell_height(), ); gl::Uniform2f( renderer.program.u_view_dimensions, size_info.width(), size_info.height(), ); gl::BlendFuncSeparate(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA, gl::SRC_ALPHA, gl::ONE); } let mut batch = [MaybeUninit::uninit(); shader::TEXTURES_ARRAY_SIZE * 6]; let mut batch_size = 0; macro_rules! send_batch { () => { #[allow(unused_assignments)] if batch_size > 0 { trace!("Call glDrawArrays with {} items", batch_size); unsafe { gl::BufferData( gl::ARRAY_BUFFER, (batch_size * mem::size_of::<shader::Vertex>()) as isize, batch.as_ptr().cast(), gl::STREAM_DRAW, ); gl::DrawArrays(gl::TRIANGLES, 0, batch_size as GLint); } batch_size = 0; } }; } let tex_slots_generator = (gl::TEXTURE0..=gl::TEXTURE31) .zip(renderer.program.u_textures.iter()) .zip(0_u32..) .map(|((tex_enum, &u_texture), index)| (tex_enum, u_texture, index)); let mut tex_slots = tex_slots_generator.clone(); let mut last_tex_slot = (0, 0); for mut vertex in vertices { if last_tex_slot.0 != vertex.texture_id { last_tex_slot = loop { match tex_slots.next() { None => { send_batch!(); tex_slots = tex_slots_generator.clone(); }, Some((tex_enum, u_texture, index)) => { unsafe { gl::ActiveTexture(tex_enum); gl::BindTexture(gl::TEXTURE_2D, vertex.texture_id); gl::Uniform1i(u_texture, index as GLint); } break (vertex.texture_id, index); }, } }; } vertex.texture_id = last_tex_slot.1; batch[batch_size] = MaybeUninit::new(vertex); batch_size += 1; if batch_size == batch.len() { send_batch!(); } } send_batch!(); unsafe { gl::BlendFunc(gl::SRC1_COLOR, gl::ONE_MINUS_SRC1_COLOR); gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, 0); gl::UseProgram(0); gl::BindVertexArray(0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } } }
use std::collections::BTreeMap; use std::mem::{self, MaybeUninit}; use crate::display::content::RenderableCell; use crate::gl::{self, types::*}; use crate::renderer::graphics::{shader, GraphicsRenderer}; use alacritty_terminal::graphics::GraphicId; use alacritty_terminal::index::{Column, Line}; use alacritty_terminal::term::SizeInfo; use log::trace; struct RenderPosition { column: Column, line: Line, offset_x: u16, offset_y: u16, padding_y: u16, } #[derive(Default)] pub struct RenderList { items: BTreeMap<GraphicId, RenderPosition>, } impl RenderList { #[inline] pub fn update(&mut self, cell: &RenderableCell, size_info: &SizeInfo) { if let Some(graphic) = &cell.graphic { let graphic_id = graphic.graphic_id(); if self.items.contains_key(&graphic_id) { return; } let render_item = RenderPosition { column: cell.point.column, line: Line(cell.point.line as i32), offset_x: graphic.offset_x, offset_y: graphic.offset_
#[inline] pub fn is_empty(&self) -> bool { self.items.is_empty() } pub fn build_vertices(self, renderer: &GraphicsRenderer) -> Vec<shader::Vertex> { use shader::VertexSide::{BottomLeft, BottomRight, TopLeft, TopRight}; let mut vertices = Vec::new(); for (graphics_id, render_item) in self.items { let graphic_texture = match renderer.graphic_textures.get(&graphics_id) { Some(tex) => tex, None => continue, }; vertices.reserve(6); let vertex = shader::Vertex { texture_id: graphic_texture.texture.0, sides: TopLeft, column: render_item.column.0 as GLuint, line: render_item.line.0 as GLuint, height: graphic_texture.height, width: graphic_texture.width, offset_x: render_item.offset_x, offset_y: render_item.offset_y, base_cell_height: graphic_texture.cell_height, padding_y: render_item.padding_y, }; vertices.push(vertex); for &sides in &[TopRight, BottomLeft, TopRight, BottomRight, BottomLeft] { vertices.push(shader::Vertex { sides, ..vertex }); } } vertices } pub fn draw(self, renderer: &GraphicsRenderer, size_info: &SizeInfo) { let vertices = self.build_vertices(renderer); unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, renderer.program.vbo); gl::BindVertexArray(renderer.program.vao); gl::UseProgram(renderer.program.id()); gl::Uniform2f( renderer.program.u_cell_dimensions, size_info.cell_width(), size_info.cell_height(), ); gl::Uniform2f( renderer.program.u_view_dimensions, size_info.width(), size_info.height(), ); gl::BlendFuncSeparate(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA, gl::SRC_ALPHA, gl::ONE); } let mut batch = [MaybeUninit::uninit(); shader::TEXTURES_ARRAY_SIZE * 6]; let mut batch_size = 0; macro_rules! send_batch { () => { #[allow(unused_assignments)] if batch_size > 0 { trace!("Call glDrawArrays with {} items", batch_size); unsafe { gl::BufferData( gl::ARRAY_BUFFER, (batch_size * mem::size_of::<shader::Vertex>()) as isize, batch.as_ptr().cast(), gl::STREAM_DRAW, ); gl::DrawArrays(gl::TRIANGLES, 0, batch_size as GLint); } batch_size = 0; } }; } let tex_slots_generator = (gl::TEXTURE0..=gl::TEXTURE31) .zip(renderer.program.u_textures.iter()) .zip(0_u32..) .map(|((tex_enum, &u_texture), index)| (tex_enum, u_texture, index)); let mut tex_slots = tex_slots_generator.clone(); let mut last_tex_slot = (0, 0); for mut vertex in vertices { if last_tex_slot.0 != vertex.texture_id { last_tex_slot = loop { match tex_slots.next() { None => { send_batch!(); tex_slots = tex_slots_generator.clone(); }, Some((tex_enum, u_texture, index)) => { unsafe { gl::ActiveTexture(tex_enum); gl::BindTexture(gl::TEXTURE_2D, vertex.texture_id); gl::Uniform1i(u_texture, index as GLint); } break (vertex.texture_id, index); }, } }; } vertex.texture_id = last_tex_slot.1; batch[batch_size] = MaybeUninit::new(vertex); batch_size += 1; if batch_size == batch.len() { send_batch!(); } } send_batch!(); unsafe { gl::BlendFunc(gl::SRC1_COLOR, gl::ONE_MINUS_SRC1_COLOR); gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, 0); gl::UseProgram(0); gl::BindVertexArray(0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } } }
y, padding_y: size_info.padding_y() as u16, }; self.items.insert(graphic_id, render_item); } }
function_block-function_prefixed
[ { "content": "pub fn derive_deserialize<T>(\n\n ident: Ident,\n\n generics: Generics,\n\n fields: Punctuated<Field, T>,\n\n) -> TokenStream {\n\n // Create all necessary tokens for the implementation.\n\n let GenericsStreams { unconstrained, constrained, phantoms } =\n\n generics_streams(g...
Rust
xhcid/src/usb/setup.rs
redox-os/drivers
36b3af426260cb1bd740426f5fb8a07a5f37e4c5
use super::DescriptorKind; use crate::driver_interface::*; #[repr(packed)] #[derive(Clone, Copy, Debug, Default)] pub struct Setup { pub kind: u8, pub request: u8, pub value: u16, pub index: u16, pub length: u16, } #[repr(u8)] pub enum ReqDirection { HostToDevice = 0, DeviceToHost = 1, } impl From<PortReqDirection> for ReqDirection { fn from(d: PortReqDirection) -> Self { match d { PortReqDirection::DeviceToHost => Self::DeviceToHost, PortReqDirection::HostToDevice => Self::HostToDevice, } } } #[repr(u8)] pub enum ReqType { Standard = 0, Class = 1, Vendor = 2, Reserved = 3, } impl From<PortReqTy> for ReqType { fn from(d: PortReqTy) -> Self { match d { PortReqTy::Standard => Self::Standard, PortReqTy::Class => Self::Class, PortReqTy::Vendor => Self::Vendor, } } } #[repr(u8)] pub enum ReqRecipient { Device = 0, Interface = 1, Endpoint = 2, Other = 3, VendorSpecific = 31, } impl From<PortReqRecipient> for ReqRecipient { fn from(d: PortReqRecipient) -> Self { match d { PortReqRecipient::Device => Self::Device, PortReqRecipient::Interface => Self::Interface, PortReqRecipient::Endpoint => Self::Endpoint, PortReqRecipient::Other => Self::Other, PortReqRecipient::VendorSpecific => Self::VendorSpecific, } } } pub const USB_SETUP_DIR_BIT: u8 = 1 << 7; pub const USB_SETUP_DIR_SHIFT: u8 = 7; pub const USB_SETUP_REQ_TY_MASK: u8 = 0x60; pub const USB_SETUP_REQ_TY_SHIFT: u8 = 5; pub const USB_SETUP_RECIPIENT_MASK: u8 = 0x1F; pub const USB_SETUP_RECIPIENT_SHIFT: u8 = 0; impl Setup { pub fn direction(&self) -> ReqDirection { if self.kind & USB_SETUP_DIR_BIT == 0 { ReqDirection::HostToDevice } else { ReqDirection::DeviceToHost } } pub const fn req_ty(&self) -> u8 { (self.kind & USB_SETUP_REQ_TY_MASK) >> USB_SETUP_REQ_TY_SHIFT } pub const fn req_recipient(&self) -> u8 { (self.kind & USB_SETUP_RECIPIENT_MASK) >> USB_SETUP_RECIPIENT_SHIFT } pub fn is_allowed_from_api(&self) -> bool { self.req_ty() == ReqType::Class as u8 || self.req_ty() == ReqType::Vendor as u8 } pub const fn get_status() -> Self { Self { kind: 0b1000_0000, request: 0x00, value: 0, index: 0, length: 2, } } pub const fn clear_feature(feature: u16) -> Self { Self { kind: 0b0000_0000, request: 0x01, value: feature, index: 0, length: 0, } } pub const fn set_feature(feature: u16) -> Self { Self { kind: 0b0000_0000, request: 0x03, value: feature, index: 0, length: 0, } } pub const fn set_address(address: u16) -> Self { Self { kind: 0b0000_0000, request: 0x05, value: address, index: 0, length: 0, } } pub const fn get_descriptor( kind: DescriptorKind, index: u8, language: u16, length: u16, ) -> Self { Self { kind: 0b1000_0000, request: 0x06, value: ((kind as u16) << 8) | (index as u16), index: language, length: length, } } pub const fn set_descriptor(kind: u8, index: u8, language: u16, length: u16) -> Self { Self { kind: 0b0000_0000, request: 0x07, value: ((kind as u16) << 8) | (index as u16), index: language, length: length, } } pub const fn get_configuration() -> Self { Self { kind: 0b1000_0000, request: 0x08, value: 0, index: 0, length: 1, } } pub const fn set_configuration(value: u8) -> Self { Self { kind: 0b0000_0000, request: 0x09, value: value as u16, index: 0, length: 0, } } pub const fn set_interface(interface: u8, alternate_setting: u8) -> Self { Self { kind: 0b0000_0001, request: 0x09, value: alternate_setting as u16, index: interface as u16, length: 0, } } }
use super::DescriptorKind; use crate::driver_interface::*; #[repr(packed)] #[derive(Clone, Copy, Debug, Default)] pub struct Setup { pub kind: u8, pub request: u8, pub value: u16, pub index: u16, pub length: u16, } #[repr(u8)] pub enum ReqDirection { HostToDevice = 0, DeviceToHost = 1, } impl From<PortReqDirection> for ReqDirection { fn from(d: PortReqDirection) -> Self { match d { PortReqDirection::DeviceToHost => Self::DeviceToHost, PortReqDirection::HostToDevice => Self::HostToDevice, } } } #[repr(u8)] pub enum ReqType { Standard = 0, Class = 1, Vendor = 2, Reserved = 3, } impl From<PortReqTy> for ReqType { fn from(d: PortReqTy) -> Self { match d { PortReqTy::Standard => Self::Standard, PortReqTy::Class => Self::Class, PortReqTy::Vendor => Self::Vendor, } } } #[repr(u8)] pub enum ReqRecipient { Device = 0, Interface = 1, Endpoint = 2, Other = 3, VendorSpecific = 31, } impl From<PortReqRecipient> for ReqRecipient { fn from(d: PortReqRecipient) -> Self { match d { PortReqRecipient::Device => Self::Device, PortReqRecipient::Interface => Self::Interface, PortReqRecipient::Endpoint => Self::Endpoint, PortReqRecipient::Other => Self::Other, PortReqRecipient::VendorSpecific => Self::VendorSpecific, } } } pub const USB_SETUP_DIR_BIT: u8 = 1 << 7; pub const USB_SETUP_DIR_SHIFT: u8 = 7; pub const USB_SETUP_REQ_TY_MASK: u8 = 0x60; pub const USB_SETUP_REQ_TY_SHIFT: u8 = 5; pub const USB_SETUP_RECIPIENT_MASK: u8 = 0x1F; pub const USB_SETUP_RECIPIENT_SHIFT: u8 = 0; impl Setup { pub fn direction(&self) -> ReqDirection { if self.kind & USB_SETUP_DIR_BIT == 0 { ReqDirection::HostToDevice } else { ReqDirection::DeviceToHost } } pub const fn req_ty(&self) -> u8 { (self.kind & USB_SETUP_REQ_TY_MASK) >> USB_SETUP_REQ_TY_SHIFT } pub const fn req_recipient(&self) -> u8 { (self.kind & USB_SETUP_RECIPIENT_MASK) >> USB_SETUP_RECIPIENT_SHIFT } pub fn is_allowed_from_api(&self) -> bool { self.req_ty() == ReqType::Class as u8 || self.req_ty() == ReqType::Vendor as u8 } pub const fn get_status() -> Self { Self { kind: 0b1000_0000, request: 0x00, value: 0, index: 0, length: 2, } } pub const fn clear_feature(feature: u16) -> Self { Self { kind: 0b0000_0000, request: 0x01, value: feature, index: 0, length: 0, } } pub const fn set_feature(feature: u16) -> Self { Self { kind: 0b0000_0000, request: 0x03, value: feature, index: 0, length: 0, } } pub const fn set_address(address: u16) -> Self { Self { kind: 0b0000_0000, request: 0x05, value: address, index: 0, length: 0, } } pub const fn get_descriptor( kind: DescriptorKind, index: u8, language: u16, length: u16, ) -> Self { Self { kind: 0b1000_0000, request: 0x06, value: ((kind as u16) << 8) | (index as u16), index: language, length: length, } } pub const fn set_descriptor(kind: u8, index: u8, language: u16, length: u16) -> Self { Self { kind: 0b0000_0000, request: 0x07, value: ((kind as u16) << 8) | (index as u16), index: language, length: length, } } pub const fn get_configuration() -> Self { Self { kind: 0b1000_0000, request: 0x08, value: 0, index: 0, length: 1, } } pub const fn set_configuration(value: u8) -> Self { Self { kind: 0b0000_0000, request: 0x09, value: value as u16, index: 0, length: 0, } } pub const fn set_interfa
}
ce(interface: u8, alternate_setting: u8) -> Self { Self { kind: 0b0000_0001, request: 0x09, value: alternate_setting as u16, index: interface as u16, length: 0, } }
function_block-function_prefixed
[ { "content": "pub fn mode_page_iter(buffer: &[u8]) -> impl Iterator<Item = AnyModePage> {\n\n ModePageIter {\n\n raw: ModePageIterRaw { buffer },\n\n }\n\n}\n", "file_path": "usbscsid/src/scsi/cmds.rs", "rank": 0, "score": 236183.29528297443 }, { "content": "pub fn enable(relati...
Rust
src/app_service.rs
Zignar-Technologies/did-api
18efc8fab44c055d2eddfd4567cf830d011e94d6
use std::str::FromStr; use actix_web::{post, web, HttpResponse}; use identity::{ core::{FromJson, ToJson}, credential::{Credential, Presentation}, iota::{ClientMap, IotaDID}, prelude::IotaDocument, }; use serde_json::{json, Value}; use crate::utils_did::validator::CredentialValidation; use crate::utils_did::validator::PresentationValidation; use crate::{ jsons_did::{ create_did_vm::CreateDidVm, create_vc::CreateVc, create_vp::CreateVp, holder_credential::HolderCredential, holder_presentation::HolderPresentation, remove_vm::RemoveVm, }, utils_did::{common, user::User}, }; #[post("/create_did")] async fn createDidApi(data_json: web::Json<CreateDidVm>) -> HttpResponse { let data = data_json.into_inner(); let account = User::new(data.nick_name.to_string(), data.password.to_string()) .expect("Error Account"); let identity = account.create_identity().unwrap(); let iota_did: &IotaDID = identity.try_did().unwrap(); let explorer = iota_did .network() .unwrap() .explorer_url() .unwrap() .to_string(); println!( "[Example] Explore the DID Document = {}/{}", iota_did .network() .unwrap() .explorer_url() .unwrap() .to_string(), iota_did.to_string() ); let explorer = format!("{}/{}", explorer, iota_did.to_string()); HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": false, "Status": "Did Created", "did": iota_did, "Explorer": explorer, })) } #[post("/add_verif_method")] async fn addVerifMethodApi(data_json: web::Json<CreateDidVm>) -> HttpResponse { let data = data_json.into_inner(); let iota_did = IotaDID::from_str(&data.did.unwrap()).unwrap(); let mut account = User::new( data.nick_name.to_string(), data.password.to_string(), ) .expect("Error Account"); let vm_randon = account.create_method(&iota_did).unwrap(); let explorer = iota_did .network() .unwrap() .explorer_url() .unwrap() .to_string(); println!( "[Example] Explore the DID Document = {}/{}", iota_did .network() .unwrap() .explorer_url() .unwrap() .to_string(), iota_did.to_string() ); let explorer = format!("{}/{}", explorer, iota_did.to_string()); HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": false, "Status": "Method Created", "Explorer": explorer, "vm_name": vm_randon })) } #[post("/create_vc")] async fn createVcApi(data_json: web::Json<CreateVc>) -> HttpResponse { let data = data_json.into_inner(); let data_issuer = data.issuer; let iota_did = IotaDID::from_str(&data_issuer.did.unwrap()).unwrap(); let account = User::new( data_issuer.nick_name.to_string(), data_issuer.password.to_string() ) .expect("Error Account"); let data_holder = data.holder; let mut credential: Credential = common::issue_degree(&iota_did, &data_holder).unwrap(); account.sign_c(&iota_did, &data_issuer.vm_name.unwrap(), &mut credential); let resolved: IotaDocument = account.resolve_identity(&iota_did).unwrap(); let verified: bool = resolved.verify_data(&credential).is_ok(); if verified == false { return HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": true, "Verified": verified, })); } let credential_str = credential.clone().to_json().unwrap(); let credential_json: Value = serde_json::from_str(&credential_str).unwrap(); HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": false, "Status": "Credential Created", "Verified": verified, "Credential": credential_json })) } #[post("/verify_validity_credential")] pub async fn verifyValidityApiCred(data_json: web::Json<HolderCredential>) -> HttpResponse { let client: ClientMap = ClientMap::new(); let validation: CredentialValidation = common::check_credential(&client, data_json).unwrap(); if validation.verified == false { return HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": true, "validation": validation.verified, })); } HttpResponse::Ok() .content_type("application/json") .json(json!({ "error": false, "validation": validation.verified, })) } #[post("/create_vp")] pub async fn createVpApi(data_json: web::Json<CreateVp>) -> HttpResponse { let data = data_json.into_inner(); let data_holder = data.holder; let iota_did = IotaDID::from_str(&data_holder.did.unwrap()).unwrap(); let account = User::new( data_holder.nick_name.to_string(), data_holder.password.to_string(), ) .expect("Error Account"); let data_holder_c = serde_json::to_string(&data.holder_credential).unwrap(); let credential: Credential = Credential::from_json(&data_holder_c).unwrap(); let mut presentation: Presentation = common::holder_presentation(&iota_did, credential).unwrap(); account.sign_p(&iota_did, &data_holder.vm_name.unwrap(), &mut presentation); let resolved: IotaDocument = account.resolve_identity(&iota_did).unwrap(); let verified: bool = resolved.verify_data(&presentation).is_ok(); if verified == false { return HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": true, "Verified": verified, })); } let presentation_str = presentation.clone().to_json().unwrap(); let presentation_json: Value = serde_json::from_str(&presentation_str).unwrap(); HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": false, "Status": "Presentation Created", "verified": verified, "Presentation": presentation_json })) } #[post("/verify_validity_presentation")] pub async fn verifyValidityApiPres(data_json: web::Json<HolderPresentation>) -> HttpResponse { let client: ClientMap = ClientMap::new(); let validation: PresentationValidation = common::check_presentation(&client, data_json).unwrap(); if validation.verified == false { return HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": true, "validation": validation.verified, })); } HttpResponse::Ok() .content_type("application/json") .json(json!({ "error": false, "validation": validation.verified, })) } #[post("/remove_vm")] async fn removeVmApi(data_json: web::Json<RemoveVm>) -> HttpResponse { let data = data_json.into_inner(); let data_issuer = data.issuer; let iota_did = IotaDID::from_str(&data_issuer.did.unwrap()).unwrap(); let mut account = User::new( data_issuer.nick_name.to_string(), data_issuer.password.to_string(), ) .expect("Error Account"); account.delete_method(&iota_did, data_issuer.vm_name.unwrap()); HttpResponse::Ok() .content_type("application/json") .json(json!({ "error": false, "Status": "Removed VM" })) }
use std::str::FromStr; use actix_web::{post, web, HttpResponse}; use identity::{ core::{FromJson, ToJson}, credential::{Credential, Presentation}, iota::{ClientMap, IotaDID}, prelude::IotaDocument, }; use serde_json::{json, Value}; use crate::utils_did::validator::CredentialValidation; use crate::utils_did::validator::PresentationValidation; use crate::{ jsons_did::{ create_did_vm::CreateDidVm, create_vc::CreateVc, create_vp::CreateVp, holder_credential::HolderCredential, holder_presentation::HolderPresentation, remove_vm::RemoveVm, }, utils_did::{common, user::User}, }; #[post("/create_did")] async fn createDidApi(data_json: web::Json<CreateDidVm>) -> HttpResponse { let data = data_json.into_inner(); let account = User::new(data.nick_name.to_string(), data.password.to_string()) .expect("Error Account"); let identity = account.create_identity().unwrap(); let iota_did: &IotaDID = identity.try_did().unwrap(); let explorer = iota_did .network() .unwrap() .explorer_url() .unwrap() .to_string(); println!( "[Example] Explore the DID Document = {}/{}", iota_did .network() .unwrap() .explorer_url() .unwrap() .to_string(), iota_did.to_string() ); let explorer = format!("{}/{}", explorer, iota_did.to_string()); HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": false, "Status": "Did Created", "did": iota_did, "Explorer": explorer, })) } #[post("/add_verif_method")] async fn addVerifMethodApi(data_json: web::Json<CreateDidVm>) -> HttpResponse { let data = data_json.into_inner(); let iota_did = IotaDID::from_str(&data.did.unwrap()).unwrap(); let mut account = User::new( data.nick_name.to_string(), data.password.to_string(), ) .expect("Error Account"); let vm_randon = account.create_method(&iota_did).unwrap(); let explorer = iota_did .network() .unwrap() .explorer_url() .unwrap() .to_string(); println!( "[Example] Explore the DID Document = {}/{}", iota_did .network() .unwrap() .explorer_url() .unwrap() .to_string(), iota_did.to_string() ); let explorer = format!("{}/{}", explorer, iota_did.to_string()); HttpResponse::Ok() .content_type("application/json") .json(json!({ "Err
#[post("/create_vc")] async fn createVcApi(data_json: web::Json<CreateVc>) -> HttpResponse { let data = data_json.into_inner(); let data_issuer = data.issuer; let iota_did = IotaDID::from_str(&data_issuer.did.unwrap()).unwrap(); let account = User::new( data_issuer.nick_name.to_string(), data_issuer.password.to_string() ) .expect("Error Account"); let data_holder = data.holder; let mut credential: Credential = common::issue_degree(&iota_did, &data_holder).unwrap(); account.sign_c(&iota_did, &data_issuer.vm_name.unwrap(), &mut credential); let resolved: IotaDocument = account.resolve_identity(&iota_did).unwrap(); let verified: bool = resolved.verify_data(&credential).is_ok(); if verified == false { return HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": true, "Verified": verified, })); } let credential_str = credential.clone().to_json().unwrap(); let credential_json: Value = serde_json::from_str(&credential_str).unwrap(); HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": false, "Status": "Credential Created", "Verified": verified, "Credential": credential_json })) } #[post("/verify_validity_credential")] pub async fn verifyValidityApiCred(data_json: web::Json<HolderCredential>) -> HttpResponse { let client: ClientMap = ClientMap::new(); let validation: CredentialValidation = common::check_credential(&client, data_json).unwrap(); if validation.verified == false { return HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": true, "validation": validation.verified, })); } HttpResponse::Ok() .content_type("application/json") .json(json!({ "error": false, "validation": validation.verified, })) } #[post("/create_vp")] pub async fn createVpApi(data_json: web::Json<CreateVp>) -> HttpResponse { let data = data_json.into_inner(); let data_holder = data.holder; let iota_did = IotaDID::from_str(&data_holder.did.unwrap()).unwrap(); let account = User::new( data_holder.nick_name.to_string(), data_holder.password.to_string(), ) .expect("Error Account"); let data_holder_c = serde_json::to_string(&data.holder_credential).unwrap(); let credential: Credential = Credential::from_json(&data_holder_c).unwrap(); let mut presentation: Presentation = common::holder_presentation(&iota_did, credential).unwrap(); account.sign_p(&iota_did, &data_holder.vm_name.unwrap(), &mut presentation); let resolved: IotaDocument = account.resolve_identity(&iota_did).unwrap(); let verified: bool = resolved.verify_data(&presentation).is_ok(); if verified == false { return HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": true, "Verified": verified, })); } let presentation_str = presentation.clone().to_json().unwrap(); let presentation_json: Value = serde_json::from_str(&presentation_str).unwrap(); HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": false, "Status": "Presentation Created", "verified": verified, "Presentation": presentation_json })) } #[post("/verify_validity_presentation")] pub async fn verifyValidityApiPres(data_json: web::Json<HolderPresentation>) -> HttpResponse { let client: ClientMap = ClientMap::new(); let validation: PresentationValidation = common::check_presentation(&client, data_json).unwrap(); if validation.verified == false { return HttpResponse::Ok() .content_type("application/json") .json(json!({ "Error": true, "validation": validation.verified, })); } HttpResponse::Ok() .content_type("application/json") .json(json!({ "error": false, "validation": validation.verified, })) } #[post("/remove_vm")] async fn removeVmApi(data_json: web::Json<RemoveVm>) -> HttpResponse { let data = data_json.into_inner(); let data_issuer = data.issuer; let iota_did = IotaDID::from_str(&data_issuer.did.unwrap()).unwrap(); let mut account = User::new( data_issuer.nick_name.to_string(), data_issuer.password.to_string(), ) .expect("Error Account"); account.delete_method(&iota_did, data_issuer.vm_name.unwrap()); HttpResponse::Ok() .content_type("application/json") .json(json!({ "error": false, "Status": "Removed VM" })) }
or": false, "Status": "Method Created", "Explorer": explorer, "vm_name": vm_randon })) }
function_block-function_prefixed
[ { "content": "pub fn holder_presentation(holder: &IotaDID, credential: Credential) -> Result<Presentation> {\n\n // Create VC \"subject\" field containing subject ID and claims about it.\n\n\n\n // Create an unsigned Presentation from the previously issued Verifiable Credential.\n\n let presentation: P...
Rust
src/lib.rs
Noskcaj19/macos-notifications
04c02ef0bf1c63bd9244eef0c3e09e8116cee8fc
extern crate cocoa; #[macro_use] extern crate objc; use objc::declare::ClassDecl; use objc::runtime::{self, Class, Method, Object, Sel}; use cocoa::base::nil; use cocoa::foundation::NSString; pub fn init() -> bool { let superclass = Class::get("NSObject").unwrap(); let mut decl = ClassDecl::new("NSBundleOverride", superclass).unwrap(); extern "C" fn bundle_identifier_override(_: &Object, _cmd: Sel) -> *mut Object { unsafe { NSString::alloc(nil).init_str("com.apple.Terminal") } } unsafe { decl.add_method( sel!(__bundleIdentifier), bundle_identifier_override as extern "C" fn(&Object, Sel) -> *mut Object, ); } decl.register(); let cls = Class::get("NSBundle").unwrap(); unsafe { let bi_original = runtime::class_getInstanceMethod(cls, Sel::register("bundleIdentifier")) as *mut Method; let custom_cls = Class::get("NSBundleOverride").unwrap(); let bi_override = runtime::class_getInstanceMethod(custom_cls, Sel::register("__bundleIdentifier")) as *mut Method; runtime::method_exchangeImplementations(bi_original, bi_override); } unsafe { let main_bundle: *mut Object = msg_send![cls, mainBundle]; let id: *mut Object = msg_send![main_bundle, bundleIdentifier]; return id.isEqualToString("com.apple.Terminal"); } } pub enum NotificationImage<'a> { Url(&'a str), File(&'a str), } pub struct Notification<'a> { title: Option<&'a str>, subtitle: Option<&'a str>, body: Option<&'a str>, content_image: Option<NotificationImage<'a>>, app_image: Option<NotificationImage<'a>>, } impl<'a> Notification<'a> { pub fn new() -> Notification<'a> { Notification { title: None, subtitle: None, body: None, content_image: None, app_image: None, } } pub fn title(&mut self, title: &'a str) -> &mut Notification<'a> { self.title = Some(title); self } pub fn subtitle(&mut self, subtitle: &'a str) -> &mut Notification<'a> { self.subtitle = Some(subtitle); self } pub fn body(&mut self, body: &'a str) -> &mut Notification<'a> { self.body = Some(body); self } pub fn content_image(&mut self, image: NotificationImage<'a>) -> &mut Notification<'a> { self.content_image = Some(image); self } pub fn app_image(&mut self, image: NotificationImage<'a>) -> &mut Notification<'a> { self.app_image = Some(image); self } pub fn deliver(&self) { let notification_cls = Class::get("NSUserNotification").unwrap(); let center = Class::get("NSUserNotificationCenter").unwrap(); unsafe { let notification: *mut Object = msg_send![notification_cls, alloc]; let notification: *mut Object = msg_send![notification, init]; if let Some(title) = self.title { msg_send![notification, setTitle:NSString::alloc(nil).init_str(title)]; } if let Some(subtitle) = self.subtitle { msg_send![notification, setSubtitle:NSString::alloc(nil).init_str(subtitle)]; } if let Some(body) = self.body { msg_send![notification, setInformativeText:NSString::alloc(nil).init_str(body)]; } if let Some(ref image_data) = self.content_image { let img_cls = Class::get("NSImage").unwrap(); let image: *mut Object = msg_send![img_cls, alloc]; let image: *mut Object = match image_data { &NotificationImage::File(file) => msg_send![ image, initWithContentsOfFile: NSString::alloc(nil).init_str(file) ], &NotificationImage::Url(url) => { let url_cls = Class::get("NSURL").unwrap(); let nsurl: *mut Object = msg_send![ url_cls, URLWithString:NSString::alloc(nil).init_str(url) ]; msg_send![image, initWithContentsOfURL: nsurl] } }; msg_send![notification, setContentImage: image]; } if let Some(ref image_data) = self.app_image { let img_cls = Class::get("NSImage").unwrap(); let image: *mut Object = msg_send![img_cls, alloc]; let image: *mut Object = match image_data { &NotificationImage::File(file) => msg_send![ image, initWithContentsOfFile: NSString::alloc(nil).init_str(file) ], &NotificationImage::Url(url) => { let url_cls = Class::get("NSURL").unwrap(); let nsurl: *mut Object = msg_send![url_cls, URLWithString:NSString::alloc(nil).init_str(url)]; msg_send![image, initWithContentsOfURL: nsurl] } }; msg_send![notification, setValue: image forKey:NSString::alloc(nil).init_str("_identityImage")]; } let default_center: *mut Object = msg_send![center, defaultUserNotificationCenter]; msg_send![default_center, deliverNotification: notification]; msg_send![notification, release]; self.runloop(); } } fn runloop(&self) { let runloop_cls = Class::get("NSRunLoop").unwrap(); let date_cls = Class::get("NSDate").unwrap(); unsafe { let current_run_loop: *mut Object = msg_send![runloop_cls, currentRunLoop]; let till_date: *mut Object = msg_send![date_cls, dateWithTimeIntervalSinceNow:0.2]; msg_send![current_run_loop, runUntilDate: till_date]; } } } #[cfg(test)] mod tests { use super::{Notification, NotificationImage}; #[test] fn init() { super::init(); } #[test] fn title() { let mut note = Notification::new(); note.title("A title"); note.deliver(); } #[test] fn subtitle() { let mut note = Notification::new(); note.title("A title"); note.subtitle("Subtitle content"); note.deliver(); } #[test] fn body() { let mut note = Notification::new(); note.title("A title"); note.subtitle("Subtitle content"); note.body("Body content"); note.deliver(); } #[test] fn content_img_path() { let mut note = Notification::new(); note.content_image(NotificationImage::File("/")); note.deliver(); } #[test] fn content_image_url() { let mut note = Notification::new(); note.content_image(NotificationImage::Url("https://google.com")); note.deliver(); } #[test] fn app_img_path() { let mut note = Notification::new(); note.app_image(NotificationImage::File("/")); note.deliver(); } #[test] fn app_img_url() { let mut note = Notification::new(); note.app_image(NotificationImage::Url("https://google.com")); note.deliver(); } }
extern crate cocoa; #[macro_use] extern crate objc; use objc::declare::ClassDecl; use objc::runtime::{self, Class, Method, Object, Sel}; use cocoa::base::nil; use cocoa::foundation::NSString; pub fn init() -> bool { let superclass = Class::get("NSObject").unwrap(); let mut decl = ClassDecl::new("NSBundleOverride", superclass).unwrap(); extern "C" fn bundle_identifier_override(_: &Object, _cmd: Sel) -> *mut Object { unsafe { NSString::alloc(nil).init_str("com.apple.Terminal") } } unsafe { decl.add_method( sel!(__bundleIdentifier), bundle_identifier_override as extern "C" fn(&Object, Sel) -> *mut Object, ); } decl.register(); let cls = Class::get("NSBundle").unwrap(); unsafe { let bi_original = runtime::class_getInstanceMethod(cls, Sel::register("bundleIdentifier")) as *mut Method; let custom_cls = Class::get("NSBundleOverride").unwrap(); let bi_override = runtime::class_getInstanceMethod(custom_cls, Sel::register("__bundleIdentifier")) as *mut Method; runtime::method_exchangeImplementations(bi_original, bi_override); } unsafe { let main_bundle: *mut Object = msg_send![cls, mainBundle]; let id: *mut Object = msg_send![main_bundle, bundleIdentifier]; return id.isEqualToString("com.apple.Terminal"); } } pub enum NotificationImage<'a> { Url(&'a str), File(&'a str), } pub struct Notification<'a> { title: Option<&'a str>, subtitle: Option<&'a str>, body: Option<&'a str>, content_image: Option<NotificationImage<'a>>, app_image: Option<NotificationImage<'a>>, } impl<'a> Notification<'a> { pub fn new() -> Notification<'a> { Notification { title: None, subtitle: None, body: None, content_image: None, app_image: None, } } pub fn title(&mut self, title: &'a str) -> &mut Notification<'a> { self.title = Some(title); self } pub fn subtitle(&mut self, subtitle: &'a str) -> &mut Notification<'a> { self.subtitle = Some(subtitle); self } pub fn body(&mut self, body: &'a str) -> &mut Notification<'a> { self.body = Some(body); self } pub fn content_image(&mut self, image: NotificationImage<'a>) -> &mut Notification<'a> { self.content_image = Some(image); self } pub fn app_image(&mut self, image: NotificationImage<'a>) -> &mut Notification<'a> { self.app_image = Some(image); self } pub fn deliver(&self) { let notification_cls = Class::get("NSUserNotification").unwrap(); let center = Class::get("NSUserNotificationCenter").unwrap(); unsafe { let notification: *mut Object = msg_send![notification_cls, alloc]; let notification: *mut Object = msg_send![notification, init]; if let Some(title) = self.title { msg_send![notification, setTitle:NSString::alloc(nil).init_str(title)]; } if let Some(subtitle) = self.subtitle { msg_send![notification, setSubtitle:NSString::alloc(nil).init_str(subtitle)]; } if let Some(body) = self.body { msg_send![notification, setInformativeText:NSString::alloc(nil).init_str(body)]; }
if let Some(ref image_data) = self.app_image { let img_cls = Class::get("NSImage").unwrap(); let image: *mut Object = msg_send![img_cls, alloc]; let image: *mut Object = match image_data { &NotificationImage::File(file) => msg_send![ image, initWithContentsOfFile: NSString::alloc(nil).init_str(file) ], &NotificationImage::Url(url) => { let url_cls = Class::get("NSURL").unwrap(); let nsurl: *mut Object = msg_send![url_cls, URLWithString:NSString::alloc(nil).init_str(url)]; msg_send![image, initWithContentsOfURL: nsurl] } }; msg_send![notification, setValue: image forKey:NSString::alloc(nil).init_str("_identityImage")]; } let default_center: *mut Object = msg_send![center, defaultUserNotificationCenter]; msg_send![default_center, deliverNotification: notification]; msg_send![notification, release]; self.runloop(); } } fn runloop(&self) { let runloop_cls = Class::get("NSRunLoop").unwrap(); let date_cls = Class::get("NSDate").unwrap(); unsafe { let current_run_loop: *mut Object = msg_send![runloop_cls, currentRunLoop]; let till_date: *mut Object = msg_send![date_cls, dateWithTimeIntervalSinceNow:0.2]; msg_send![current_run_loop, runUntilDate: till_date]; } } } #[cfg(test)] mod tests { use super::{Notification, NotificationImage}; #[test] fn init() { super::init(); } #[test] fn title() { let mut note = Notification::new(); note.title("A title"); note.deliver(); } #[test] fn subtitle() { let mut note = Notification::new(); note.title("A title"); note.subtitle("Subtitle content"); note.deliver(); } #[test] fn body() { let mut note = Notification::new(); note.title("A title"); note.subtitle("Subtitle content"); note.body("Body content"); note.deliver(); } #[test] fn content_img_path() { let mut note = Notification::new(); note.content_image(NotificationImage::File("/")); note.deliver(); } #[test] fn content_image_url() { let mut note = Notification::new(); note.content_image(NotificationImage::Url("https://google.com")); note.deliver(); } #[test] fn app_img_path() { let mut note = Notification::new(); note.app_image(NotificationImage::File("/")); note.deliver(); } #[test] fn app_img_url() { let mut note = Notification::new(); note.app_image(NotificationImage::Url("https://google.com")); note.deliver(); } }
if let Some(ref image_data) = self.content_image { let img_cls = Class::get("NSImage").unwrap(); let image: *mut Object = msg_send![img_cls, alloc]; let image: *mut Object = match image_data { &NotificationImage::File(file) => msg_send![ image, initWithContentsOfFile: NSString::alloc(nil).init_str(file) ], &NotificationImage::Url(url) => { let url_cls = Class::get("NSURL").unwrap(); let nsurl: *mut Object = msg_send![ url_cls, URLWithString:NSString::alloc(nil).init_str(url) ]; msg_send![image, initWithContentsOfURL: nsurl] } }; msg_send![notification, setContentImage: image]; }
if_condition
[ { "content": "fn main() {\n\n let dir = get_dir();\n\n let image1 = dir.join(\"rust.png\");\n\n let image2 = dir.join(\"ferris.png\");\n\n\n\n // Call init so we get notifcations\n\n macos_notifications::init();\n\n\n\n // Construct and send a new notification\n\n Notification::new()\n\n ...
Rust
research/gaia-x/pegasus/pegasus/src/operator/iteration/switch.rs
bmmcq/GraphScope
a480d941f3a3f1270ddc0570e72059e6a34dab24
use std::rc::Rc; use crate::api::{IterCondition, Notification}; use crate::communication::input::{new_input_session, InputProxy}; use crate::communication::output::{new_output, OutputProxy}; use crate::communication::Output; use crate::config::LOOP_OPT; use crate::data::{MarkedData, MicroBatch}; use crate::errors::JobExecError; use crate::graph::Port; use crate::operator::{Notifiable, OperatorCore}; use crate::progress::EndSignal; use crate::tag::tools::map::TidyTagMap; use crate::{Data, Tag}; pub(crate) struct SwitchOperator<D> { scope_level: u32, cond: IterCondition<D>, iter_scope: TidyTagMap<Vec<EndGuard>>, } impl<D> SwitchOperator<D> { pub fn new(scope_level: u32, cond: IterCondition<D>) -> Self { assert!(scope_level > 0); SwitchOperator { scope_level, cond, iter_scope: TidyTagMap::new(scope_level - 1) } } } impl<D: Data> OperatorCore for SwitchOperator<D> { fn on_receive( &mut self, inputs: &[Box<dyn InputProxy>], outputs: &[Box<dyn OutputProxy>], ) -> Result<(), JobExecError> { assert_eq!(inputs.len(), 2); let mut main = new_input_session::<D>(&inputs[0]); let leave = new_output::<D>(&outputs[0]); let enter = new_output::<D>(&outputs[1]); main.for_each_batch(|dataset| { if dataset.is_last() { let tag = dataset.tag.to_parent_uncheck(); trace_worker!("{:?} into iteration at scope level {}", tag, self.scope_level); self.iter_scope.insert(tag, vec![]); } switch(dataset, &self.cond, leave, enter) })?; let mut feedback = new_input_session::<D>(&inputs[1]); feedback.for_each_batch(|dataset| { if !dataset.is_empty() && log_enabled!(log::Level::Trace) { trace_worker!("receive feedback data of scope {:?}", dataset.tag); } if dataset.tag.current_uncheck() >= self.cond.max_iters { if !dataset.is_empty() { let mut leave_session = leave.new_session(&dataset.tag)?; for d in dataset.drain() { leave_session.give(d)?; } } if let Some(end) = dataset.take_end() { let p = end.tag.to_parent_uncheck(); let mut ends = self .iter_scope .remove(&p) .expect("unknown iteration scope;"); leave.notify_end(end)?; for e in ends.drain(..) { if let Some(end) = e.try_unwrap() { if end.tag.is_root() { assert!(self.iter_scope.is_empty()); debug_worker!( "all scopes out of iteration at scope level {};", self.scope_level ); enter.notify_end(end.clone())?; } trace_worker!("{:?} out of iteration", end.tag); leave.notify_end(end)?; } else { } } } } else { if !dataset.is_empty() { switch(dataset, &self.cond, leave, enter)?; } else { if let Some(end) = dataset.take_end() { let p = end.tag.to_parent_uncheck(); if self.iter_scope.contains_key(&p) { enter.notify_end(end)?; } else { error_worker!( "weird scope[{:?}] end in iteration {};", end.tag, self.scope_level ); unreachable!( "weird scope[{:?}] end in iteration {};", end.tag, self.scope_level ); } } else { error_worker!("both data and signal empty of {:?}", dataset.tag); unreachable!("both data and signal empty of {:?}", dataset.tag); } } } Ok(()) }) } } fn switch<D: Data>( dataset: &mut MicroBatch<D>, cond: &IterCondition<D>, leave: &Output<D>, enter: &Output<D>, ) -> Result<(), JobExecError> { if !dataset.is_last() { let mut leave_session = leave.new_session(&dataset.tag)?; let mut enter_session = enter.new_session(&dataset.tag)?; for d in dataset.drain() { if cond.is_converge(&d)? { leave_session.give(d)?; } else { enter_session.give(d)?; } } } else { debug_worker!("stop to send data of the {:?};", &dataset.tag); if !dataset.is_empty() { let tag = dataset.tag(); let mut leave_session = leave.new_session(&tag)?; let mut enter_session = enter.new_session(&tag)?; for item in dataset.drain_to_end() { match item { MarkedData::Data(d) => { if cond.is_converge(&d)? { leave_session.give(d)?; } else { enter_session.give(d)?; } } MarkedData::Marked(d, e) => { if let Some(d) = d { if cond.is_converge(&d)? { enter_session.notify_end(e)?; leave_session.give(d)?; } else { enter_session.give_last(d, e)?; } } else { enter_session.notify_end(e)?; } } } } } else if let Some(end) = dataset.take_end() { enter.notify_end(end)?; } else { unreachable!("both data and signal empty of {:?}", dataset.tag); } } Ok(()) } impl<D: Data> Notifiable for SwitchOperator<D> { fn on_notify(&mut self, n: Notification, outputs: &[Box<dyn OutputProxy>]) -> Result<(), JobExecError> { debug_worker!("on notify of {:?} on in port {}", n.tag(), n.port); let n_len = n.tag().len(); assert!(n_len < self.scope_level as usize); if n.port == 0 { if self.iter_scope.is_empty() { let end = n.take_end(); if end.tag.is_root() { debug_worker!("all scopes out of iteration at scope level {};", self.scope_level); outputs[0].notify_end(end.clone())?; outputs[1].notify_end(end)?; } } else { let end = EndGuard::new(n.take_end()); for (t, v) in self.iter_scope.iter_mut() { if &end.end.tag == &*t || end.end.tag.is_parent_of(&t) { v.push(end.clone()); } } } } Ok(()) } fn on_cancel( &mut self, port: Port, tag: Tag, inputs: &[Box<dyn InputProxy>], outputs: &[Box<dyn OutputProxy>], ) -> Result<bool, JobExecError> { if port.port == 0 { assert!(tag.len() < self.scope_level as usize); for input in inputs.iter() { input.cancel_scope(&tag); input.propagate_cancel(&tag)?; } for output in outputs.iter() { output.skip(&tag)?; } } else { assert_eq!(port.port, 1); if tag.len() == self.scope_level as usize { if let Some(nth) = tag.current() { if nth != 0 { inputs[1].cancel_scope(&tag); inputs[1].propagate_cancel(&tag)?; outputs[1].skip(&tag)?; } else { inputs[0].cancel_scope(&tag); if *LOOP_OPT { inputs[0].propagate_cancel_uncheck(&tag)?; } outputs[1].skip(&tag)?; } } else { unreachable!() } } } Ok(true) } } #[derive(Clone)] struct EndGuard { end: Rc<EndSignal>, } impl EndGuard { fn new(end: EndSignal) -> Self { EndGuard { end: Rc::new(end) } } fn try_unwrap(self) -> Option<EndSignal> { Rc::try_unwrap(self.end).ok() } } unsafe impl Send for EndGuard {}
use std::rc::Rc; use crate::api::{IterCondition, Notification}; use crate::communication::input::{new_input_session, InputProxy}; use crate::communication::output::{new_output, OutputProxy}; use crate::communication::Output; use crate::config::LOOP_OPT; use crate::data::{MarkedData, MicroBatch}; use crate::errors::JobExecError; use crate::graph::Port; use crate::operator::{Notifiable, OperatorCore}; use crate::progress::EndSignal; use crate::tag::tools::map::TidyTagMap; use crate::{Data, Tag}; pub(crate) struct SwitchOperator<D> { scope_level: u32, cond: IterCondition<D>, iter_scope: TidyTagMap<Vec<EndGuard>>, } impl<D> SwitchOperator<D> { pub fn new(scope_level: u32, cond: IterCondition<D>) -> Self { assert!(scope_level > 0); SwitchOperator { scope_level, cond, iter_scope: TidyTagMap::new(scope_level - 1) } } } impl<D: Data> OperatorCore for SwitchOperator<D> { fn on_receive( &mut self, inputs: &[Box<dyn InputProxy>], outputs: &[Box<dyn OutputProxy>], ) -> Result<(), JobExecError> { assert_eq!(inputs.len(), 2); let mut main = new_input_session::<D>(&inputs[0]); let leave = new_output::<D>(&outputs[0]); let enter = new_output::<D>(&outputs[1]); main.for_each_batch(|dataset| { if dataset.is_last() { let tag = dataset.tag.to_parent_uncheck(); trace_worker!("{:?} into iteration at scope level {}", tag, self.scope_level); self.iter_scope.insert(tag, vec![]); } switch(dataset, &self.cond, leave, enter) })?; let mut feedback = new_input_session::<D>(&inputs[1]); feedback.for_each_batch(|dataset| { if !dataset.is_empty() && log_enabled!(log::Level::Trace) { trace_worker!("receive feedback data of scope {:?}", dataset.tag); } if dataset.tag.current_uncheck() >= self.cond.max_iters { if !dataset.is_empty() { let mut leave_session = leave.new_session(&dataset.tag)?; for d in dataset.drain() { leave_session.give(d)?; }
error_worker!("both data and signal empty of {:?}", dataset.tag); unreachable!("both data and signal empty of {:?}", dataset.tag); } } } Ok(()) }) } } fn switch<D: Data>( dataset: &mut MicroBatch<D>, cond: &IterCondition<D>, leave: &Output<D>, enter: &Output<D>, ) -> Result<(), JobExecError> { if !dataset.is_last() { let mut leave_session = leave.new_session(&dataset.tag)?; let mut enter_session = enter.new_session(&dataset.tag)?; for d in dataset.drain() { if cond.is_converge(&d)? { leave_session.give(d)?; } else { enter_session.give(d)?; } } } else { debug_worker!("stop to send data of the {:?};", &dataset.tag); if !dataset.is_empty() { let tag = dataset.tag(); let mut leave_session = leave.new_session(&tag)?; let mut enter_session = enter.new_session(&tag)?; for item in dataset.drain_to_end() { match item { MarkedData::Data(d) => { if cond.is_converge(&d)? { leave_session.give(d)?; } else { enter_session.give(d)?; } } MarkedData::Marked(d, e) => { if let Some(d) = d { if cond.is_converge(&d)? { enter_session.notify_end(e)?; leave_session.give(d)?; } else { enter_session.give_last(d, e)?; } } else { enter_session.notify_end(e)?; } } } } } else if let Some(end) = dataset.take_end() { enter.notify_end(end)?; } else { unreachable!("both data and signal empty of {:?}", dataset.tag); } } Ok(()) } impl<D: Data> Notifiable for SwitchOperator<D> { fn on_notify(&mut self, n: Notification, outputs: &[Box<dyn OutputProxy>]) -> Result<(), JobExecError> { debug_worker!("on notify of {:?} on in port {}", n.tag(), n.port); let n_len = n.tag().len(); assert!(n_len < self.scope_level as usize); if n.port == 0 { if self.iter_scope.is_empty() { let end = n.take_end(); if end.tag.is_root() { debug_worker!("all scopes out of iteration at scope level {};", self.scope_level); outputs[0].notify_end(end.clone())?; outputs[1].notify_end(end)?; } } else { let end = EndGuard::new(n.take_end()); for (t, v) in self.iter_scope.iter_mut() { if &end.end.tag == &*t || end.end.tag.is_parent_of(&t) { v.push(end.clone()); } } } } Ok(()) } fn on_cancel( &mut self, port: Port, tag: Tag, inputs: &[Box<dyn InputProxy>], outputs: &[Box<dyn OutputProxy>], ) -> Result<bool, JobExecError> { if port.port == 0 { assert!(tag.len() < self.scope_level as usize); for input in inputs.iter() { input.cancel_scope(&tag); input.propagate_cancel(&tag)?; } for output in outputs.iter() { output.skip(&tag)?; } } else { assert_eq!(port.port, 1); if tag.len() == self.scope_level as usize { if let Some(nth) = tag.current() { if nth != 0 { inputs[1].cancel_scope(&tag); inputs[1].propagate_cancel(&tag)?; outputs[1].skip(&tag)?; } else { inputs[0].cancel_scope(&tag); if *LOOP_OPT { inputs[0].propagate_cancel_uncheck(&tag)?; } outputs[1].skip(&tag)?; } } else { unreachable!() } } } Ok(true) } } #[derive(Clone)] struct EndGuard { end: Rc<EndSignal>, } impl EndGuard { fn new(end: EndSignal) -> Self { EndGuard { end: Rc::new(end) } } fn try_unwrap(self) -> Option<EndSignal> { Rc::try_unwrap(self.end).ok() } } unsafe impl Send for EndGuard {}
} if let Some(end) = dataset.take_end() { let p = end.tag.to_parent_uncheck(); let mut ends = self .iter_scope .remove(&p) .expect("unknown iteration scope;"); leave.notify_end(end)?; for e in ends.drain(..) { if let Some(end) = e.try_unwrap() { if end.tag.is_root() { assert!(self.iter_scope.is_empty()); debug_worker!( "all scopes out of iteration at scope level {};", self.scope_level ); enter.notify_end(end.clone())?; } trace_worker!("{:?} out of iteration", end.tag); leave.notify_end(end)?; } else { } } } } else { if !dataset.is_empty() { switch(dataset, &self.cond, leave, enter)?; } else { if let Some(end) = dataset.take_end() { let p = end.tag.to_parent_uncheck(); if self.iter_scope.contains_key(&p) { enter.notify_end(end)?; } else { error_worker!( "weird scope[{:?}] end in iteration {};", end.tag, self.scope_level ); unreachable!( "weird scope[{:?}] end in iteration {};", end.tag, self.scope_level ); } } else {
random
[ { "content": "pub fn u32_to_vec(x: u32) -> Vec<u8> {\n\n int_to_vec!(x, u32)\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/groot/src/db/common/bytes/transform.rs", "rank": 0, "score": 354433.37192331563 }, { "content": "/// Parses an escape sequence within a string literal....
Rust
2016/day14/src/main.rs
RussellChamp/AdventOfCode
492784bd690d7323990dcddd64b20459bf3263ae
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; #[derive(Debug)] struct Key { idx: u64, letters: Vec<char>, is_valid: bool, hash: String, } fn repeat_letters(line: &String, size: u64, only_first: bool) -> Vec<char> { let mut result: Vec<char> = vec![]; let mut count = 1; let bytes = line.as_bytes(); 'outer: for idx in 0..line.len() - 2 { if bytes[idx] == bytes[idx + 1] { count = count + 1; if count == size && result.iter().position(|&c| c == (bytes[idx] as char)) == None { result.push(bytes[idx] as char); if only_first { break 'outer; } } } else { count = 1; } } result } fn purge_keys(keys: Vec<Key>, idx: u64, threshold: u64) -> Vec<Key> { let old_len = keys.len(); let new_keys: Vec<Key> = keys.into_iter() .filter(|key| key.is_valid || key.idx + threshold > idx) .collect::<Vec<_>>(); if old_len > new_keys.len() { } new_keys } fn validate_keys(keys: &mut Vec<Key>, key_char: char, idx: u64, threshold: u64) { let mut count = 0; keys.into_iter() .map(|key| { if !key.is_valid && key.idx + threshold > idx && key.letters.iter().position(|&c| c == key_char) != None { key.is_valid = true; count = count + 1; } key }) .collect::<Vec<_>>(); if count > 0 { } } fn we_are_done(keys: &Vec<Key>, pad_size: usize) -> bool { keys.iter().take_while(|key| key.is_valid ).collect::<Vec<_>>().len() >= pad_size } const PAD_SIZE: usize = 64; const THRESHOLD: u64 = 1000; fn main() { println!("I did something wrong on this one and am not getting the correct answer. :("); let mut keys: Vec<Key> = vec![]; let mut hasher = Md5::new(); let salt = "ahsbgdzn"; for idx in 0..std::u64::MAX { hasher.input(format!("{}{}", salt, idx).as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let output_str: String = output.iter().map(|&c| format!("{:x}", c)).collect(); for r in repeat_letters(&output_str, 5, false) { keys = purge_keys(keys, idx, THRESHOLD); validate_keys(&mut keys, r, idx, THRESHOLD); } let threepeats = repeat_letters(&output_str, 3, true); if threepeats.len() > 0 { let new_key = Key { idx: idx, letters: threepeats, is_valid: false, hash: String::from(output_str) }; keys.push(new_key); } if we_are_done(&keys, PAD_SIZE) { if keys.len() >= PAD_SIZE { println!("We're done! Finished on idx {}", idx); println!("The {}th key is {:?}", PAD_SIZE, keys.iter().nth(PAD_SIZE).unwrap()); } else { println!("Uh oh! We didn't find enough keys. :("); } break; } hasher.reset(); } }
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; #[derive(Debug)] struct Key { idx: u64, letters: Vec<char>, is_valid: bool, hash: String, } fn repeat_letters(line: &String, size: u64, only_first: bool) -> Vec<char> { let mut result: Vec<char> = vec![]; let mut count = 1; let bytes = line.as_bytes(); 'outer: for idx in 0..line.len() - 2 { if bytes[idx] == bytes[idx + 1] { count = count + 1; if count == size && result.iter().position(|&c| c == (bytes[idx] as char)) == None { result.push(bytes[idx] as char); if only_first { break 'outer; } } } else { count = 1; } } result } fn purge_keys(keys: Vec<Key>, idx: u64, threshold: u64) -> Vec<Key> { let old_len = keys.len(); let new_keys: Vec<Key> = keys.into_iter() .filter(|key| key.is_valid || key.idx + threshold > idx) .collect::<Vec<_>>(); if old_len > new_keys.len() { } new_keys } fn validate_keys(keys: &mut Vec<Key>, key_char: char, idx: u64, threshold: u64) { let mut count = 0; keys.into_iter() .map(|key| { if !key.is_valid && key.idx + threshold > idx && key.letters.iter().position(|&c| c == key_char) != None { key.is_valid = true; count = count + 1; } key }) .collect::<Vec<_>>(); if count > 0 { } } fn we_are_done(keys: &Vec<Key>, pad_size: usize) -> bool { keys.iter().take_while(|key| key.is_valid ).collect::<Vec<_>>().len() >= pad_size } const PAD_SIZE: usize = 64; const THRESHOLD: u64 = 1000; fn main() { println!("I did something wrong on this one and am not getting the correct answer. :("); let mut keys: Vec<Key> = vec![]; let mut hasher = Md5::new(); let salt = "ahsbgdzn"; for idx in 0..std::u64::MAX { hasher.input(format!("{}{}", salt, idx).as_bytes()); let mut output = [0; 16]; hasher.result(&mut output); let output_str: String = output.iter().map(|&c| format!("{:x}", c)).collect(); for r in repeat_letters(&output_str, 5, false) { keys = purge_keys(keys, idx, THRESHOLD); validate_keys(&mut keys, r, idx, THRESHOLD); } let threepeats = repeat_letters(&output_str, 3, true); if threepeats.len() > 0 { let new_key = Key { idx: idx, letters: threepeats, is_valid: false, hash: String::from(output_str) }; keys.push(new_key); } if we_are_done(&keys, PAD_SIZ
E) { if keys.len() >= PAD_SIZE { println!("We're done! Finished on idx {}", idx); println!("The {}th key is {:?}", PAD_SIZE, keys.iter().nth(PAD_SIZE).unwrap()); } else { println!("Uh oh! We didn't find enough keys. :("); } break; } hasher.reset(); } }
function_block-function_prefixed
[ { "content": "fn build_maze(maze: &mut Vec<Vec<(bool, u32)>>, key: u32) {\n\n for row in 0..MAZE_HEIGHT {\n\n for col in 0..MAZE_WIDTH {\n\n match get_space(col as u32, row as u32, key) {\n\n Space::Open => maze[row][col] = (true, u32::max_value()),\n\n Space::...
Rust
bee-snapshot/src/lib.rs
neumoxx/bee-p
2a68c3c6c17bd2c8dd36d8274ef0db3a04d50b16
pub(crate) mod constants; pub(crate) mod pruning; pub(crate) mod worker; pub mod config; pub mod event; pub mod global; pub mod local; pub mod metadata; use bee_common::shutdown_stream::ShutdownStream; use bee_common_ext::{bee_node::BeeNode, event::Bus, shutdown_tokio::Shutdown, worker::Worker}; use bee_crypto::ternary::Hash; use bee_ledger::state::LedgerState; use bee_protocol::{event::LatestSolidMilestoneChanged, tangle::tangle, MilestoneIndex}; use chrono::{offset::TimeZone, Utc}; use futures::channel::{mpsc, oneshot}; use log::{info, warn}; use tokio::spawn; use std::{path::Path, sync::Arc}; #[derive(Debug)] pub enum Error { Global(global::FileError), Local(local::FileError), Download(local::DownloadError), } pub async fn init( config: &config::SnapshotConfig, bee_node: Arc<BeeNode>, bus: Arc<Bus<'static>>, shutdown: &mut Shutdown, ) -> Result<(LedgerState, MilestoneIndex, u64), Error> { let (state, index, timestamp) = match config.load_type() { config::LoadType::Global => { info!("Loading global snapshot file {}...", config.global().path()); let snapshot = global::GlobalSnapshot::from_file(config.global().path(), MilestoneIndex(*config.global().index())) .map_err(Error::Global)?; tangle().clear_solid_entry_points(); tangle().add_solid_entry_point(Hash::zeros(), MilestoneIndex(*config.global().index())); info!( "Loaded global snapshot file from with index {} and {} balances.", *config.global().index(), snapshot.state().len() ); (snapshot.into_state(), *config.global().index(), 0) } config::LoadType::Local => { if !Path::new(config.local().path()).exists() { local::download_local_snapshot(config.local()) .await .map_err(Error::Download)?; } info!("Loading local snapshot file {}...", config.local().path()); let snapshot = local::LocalSnapshot::from_file(config.local().path()).map_err(Error::Local)?; info!( "Loaded local snapshot file from {} with index {}, {} solid entry points, {} seen milestones and \ {} balances.", Utc.timestamp(snapshot.metadata().timestamp() as i64, 0).to_rfc2822(), snapshot.metadata().index(), snapshot.metadata().solid_entry_points().len(), snapshot.metadata().seen_milestones().len(), snapshot.state.len() ); tangle().update_latest_solid_milestone_index(snapshot.metadata().index().into()); tangle().update_latest_milestone_index(snapshot.metadata().index().into()); tangle().update_snapshot_index(snapshot.metadata().index().into()); tangle().update_pruning_index(snapshot.metadata().index().into()); tangle().add_solid_entry_point(Hash::zeros(), MilestoneIndex(0)); for (hash, index) in snapshot.metadata().solid_entry_points() { tangle().add_solid_entry_point(*hash, MilestoneIndex(*index)); } for _seen_milestone in snapshot.metadata().seen_milestones() { } let index = snapshot.metadata().index(); let timestamp = snapshot.metadata().timestamp(); (snapshot.into_state(), index, timestamp) } }; let (snapshot_worker_tx, snapshot_worker_rx) = mpsc::unbounded(); let (snapshot_worker_shutdown_tx, snapshot_worker_shutdown_rx) = oneshot::channel(); shutdown.add_worker_shutdown( snapshot_worker_shutdown_tx, spawn(worker::SnapshotWorker::new(config.clone()).start( ShutdownStream::new(snapshot_worker_shutdown_rx, snapshot_worker_rx), bee_node, (), )), ); bus.add_listener(move |latest_solid_milestone: &LatestSolidMilestoneChanged| { if let Err(e) = snapshot_worker_tx.unbounded_send(worker::SnapshotWorkerEvent(latest_solid_milestone.0.clone())) { warn!( "Failed to send milestone {} to snapshot worker: {:?}.", *latest_solid_milestone.0.index(), e ) } }); Ok((state, MilestoneIndex(index), timestamp)) }
pub(crate) mod constants; pub(crate) mod pruning; pub(crate) mod worker; pub mod config; pub mod event; pub mod global; pub mod local; pub mod metadata; use bee_common::shutdown_stream::ShutdownStream; use bee_common_ext::{bee_node::BeeNode, event::Bus, shutdown_tokio::Shutdown, worker::Worker}; use bee_crypto::ternary::Hash; use bee_ledger::state::LedgerState; use bee_protocol::{event::LatestSolidMilestoneChanged, tangle::tangle, MilestoneIndex}; use chrono::{offset::TimeZone, Utc}; use futures::channel::{mpsc, oneshot}; use log::{info, warn}; use tokio::spawn; use std::{path::Path, sync::Arc}; #[derive(Debug)] pub enum Error { Global(global::FileError), Local(local::FileError), Download(local::DownloadError), } pub async fn init( config: &config::SnapshotConfig, bee_node: Arc<BeeNode>, bus: Arc<Bus<'static>>, shutdown: &mut Shutdown, ) -> Result<(LedgerState, MilestoneIndex, u64), Error> { let (state, index, timestamp) = match config.load_type() { config::LoadType::Global => { info!("Loading global snapshot file {}...", config.global().path()); let snapshot = global::GlobalSnapshot::from_file(config.global().path(), MilestoneIndex(*config.global().index())) .map_err(Error::Global)?; tangle().clear_solid_entry_points(); tangle().add_solid_entry_point(Hash::zeros(), MilestoneIndex(*config.global().index())); info!( "Loaded global snapshot file from with index {} and {} balances.", *config.global().index(), snapshot.state().len() ); (snapshot.into_state(), *config.global().index(), 0) } config::LoadType::Local => { if !Path::new(config.local().path()).exists() { local::download_local_snapshot(config.local()) .await .map_err(Error::Download)?; } info!("Loading local snapshot file {}...", config.local().path()); let snapshot = local::LocalSnapshot::from_file(config.local().path()).map_err(Error::Local)?; info!( "Loaded local snapshot file from {} with index {}, {} solid entry points, {} seen milestones and \ {} balances.", Utc.timestamp(snapshot.metadata().timestamp() as i64, 0).to_rfc2822(), snapshot.metadata().index(), snapshot.metadata().solid_entry_points().len(), snapshot.metadata().seen_milestones().len(), snapshot.state.len() ); tangle().update_latest_solid_milestone_index(snapshot.metadata().index().into()); tangle().update_latest_milestone_index(snapshot.metadata().index().into()); tangle().update_snapshot_index(snapshot.metadata().index().into()); tangle().update_pruning_index(snapshot.metadata().index().into()); tangle().add_solid_entry_point(Hash::zeros(), MilestoneIndex(0)); for (hash, index) in snapshot.metadata().solid_entry_points() { tangle().add_solid_entry_point(*hash, MilestoneIndex(*index)); } for _seen_milestone in snapshot.metadata().seen_milestones() { } let index = snapshot.metadata().index(); let timestamp = snapshot.metadata().timestamp(); (snapshot.into_state(), index, timestamp) } }; let (snapshot_worker_tx, snapshot_worker_rx) = mpsc::unbounded(); let (snapshot_worker_shutdown_tx, snapshot_worker_shutdown_rx) = oneshot::channel(); shutdown.add_worker_shutdow
n( snapshot_worker_shutdown_tx, spawn(worker::SnapshotWorker::new(config.clone()).start( ShutdownStream::new(snapshot_worker_shutdown_rx, snapshot_worker_rx), bee_node, (), )), ); bus.add_listener(move |latest_solid_milestone: &LatestSolidMilestoneChanged| { if let Err(e) = snapshot_worker_tx.unbounded_send(worker::SnapshotWorkerEvent(latest_solid_milestone.0.clone())) { warn!( "Failed to send milestone {} to snapshot worker: {:?}.", *latest_solid_milestone.0.index(), e ) } }); Ok((state, MilestoneIndex(index), timestamp)) }
function_block-function_prefixed
[ { "content": "// TODO testing\n\npub fn get_new_solid_entry_points(target_index: MilestoneIndex) -> Result<DashMap<Hash, MilestoneIndex>, Error> {\n\n let solid_entry_points = DashMap::<Hash, MilestoneIndex>::new();\n\n for index in *target_index - SOLID_ENTRY_POINT_CHECK_THRESHOLD_PAST..*target_index {\n...
Rust
xtask/src/main.rs
dureuill/yew-sse-example
c1bbc94bbcbd91cb7a4b7ab3a3361514983ff1bf
use std::ops::Index; use cargo_metadata::camino::Utf8PathBuf; use cargo_metadata::Metadata; use clap::crate_version; use clap::Clap; use color_eyre::eyre::Context; use color_eyre::eyre::ContextCompat; use color_eyre::eyre::Result; use color_eyre::owo_colors::colors::xterm::UserGreen; use color_eyre::owo_colors::colors::xterm::UserYellow; use color_eyre::owo_colors::OwoColorize; use color_eyre::Help; #[derive(Clap)] #[clap(version=crate_version!())] struct Opts { #[clap(subcommand)] cmd: SubCommand, } #[derive(Clap)] enum SubCommand { Dist(Dist), Run(Run), Install(Install), } #[derive(Clap)] struct Dist { #[clap(long)] release: bool, } #[derive(Clap)] struct Run { #[clap(long)] release: bool, } impl Run { fn to_dist(&self) -> Dist { Dist { release: self.release, } } } #[derive(Clap)] struct Install { #[clap(short, long)] output: Option<Utf8PathBuf>, } impl Install { fn to_dist(&self) -> Dist { Dist { release: true, } } } fn main() -> Result<()> { color_eyre::install()?; let opts: Opts = Opts::parse(); match opts.cmd { SubCommand::Dist(config) => dist(config)?, SubCommand::Run(config) => run(config)?, SubCommand::Install(config) => install(config)?, } Ok(()) } fn dist_path(metadata: &Metadata, is_release: bool) -> Utf8PathBuf { metadata .target_directory .join("static/dist") .join(if is_release { "release" } else { "debug" }) } fn backend_path(metadata: &Metadata, is_release: bool) -> Utf8PathBuf { metadata .target_directory .join(if is_release { "release" } else { "debug" }) .join("backend") } fn output_default_path(metadata: &Metadata) -> Utf8PathBuf { metadata.workspace_root.join("output") } fn dist(config: Dist) -> Result<()> { let cmd = cargo_metadata::MetadataCommand::new(); let metadata = cmd.exec()?; let frontend = metadata .workspace_members .iter() .find(|pkg| metadata[pkg].name == "frontend") .wrap_err("Could not find package 'frontend'")?; let html_path = metadata .index(frontend) .manifest_path .with_file_name("index.html"); let dist_path = dist_path(&metadata, config.release); println!( "- Distributing frontend in {}", dist_path.bold().fg::<UserGreen>() ); std::fs::create_dir_all(&dist_path).wrap_err("Could not write to the target directory")?; let trunk_version = duct::cmd!("trunk", "--version") .read() .wrap_err("Could not find `trunk`") .note("`trunk` is required for the build") .suggestion("Install `trunk` with `cargo install trunk`")?; println!("- Using {}", trunk_version.bold().fg::<UserGreen>()); let release = if config.release { Some("--release") } else { None }; let args = IntoIterator::into_iter(["build", "--dist", dist_path.as_str(), html_path.as_str()]) .chain(release); duct::cmd("trunk", args).run()?; Ok(()) } fn run(config: Run) -> Result<()> { dist(config.to_dist())?; let cmd = cargo_metadata::MetadataCommand::new(); let metadata = cmd.exec()?; let dist_path = dist_path(&metadata, config.release); let release = if config.release { Some("--release") } else { None }; let args = IntoIterator::into_iter(["run", "-p", "backend"]).chain(release); duct::cmd("cargo", args) .env("ROCKET_DIST", dist_path) .run() .wrap_err("Could not run server")?; Ok(()) } fn install(config: Install) -> Result<()> { dist(config.to_dist())?; let cmd = cargo_metadata::MetadataCommand::new(); let metadata = cmd.exec()?; let dist_path = dist_path(&metadata, true); let backend_path = backend_path(&metadata, true); let output_dir = config.output.unwrap_or_else(|| output_default_path(&metadata)); println!( "- Building backend in {}", backend_path.bold().fg::<UserGreen>() ); let args = IntoIterator::into_iter(["build", "--release", "-p", "backend"]); duct::cmd("cargo", args) .run() .wrap_err("Could not build backend")?; println!( "- Copying frontend to {}", output_dir.join("static/dist").bold().fg::<UserGreen>() ); std::fs::create_dir_all(&output_dir).wrap_err("Cannot create output dir")?; std::fs::remove_dir_all(&output_dir).wrap_err("Error while cleaning output directory")?; std::fs::create_dir_all(&output_dir.join("static")).wrap_err("Cannot create output dir")?; let errors = copy_dir::copy_dir(&dist_path, &output_dir.join("static/dist")) .wrap_err("Could not copy dist dir to output dir")?; if !errors.is_empty() { eprintln!( "{} Copy succeeded, but the following errors occurred during the copy:", "WARNING:".bold().fg::<UserYellow>() ); for error in errors { eprintln!("\t{}", error.fg::<UserYellow>()) } } println!( "- Copying backend to {}", output_dir.join("backend").bold().fg::<UserGreen>() ); std::fs::copy(backend_path, output_dir.join("backend")) .wrap_err("Copying the backend failed")?; Ok(()) }
use std::ops::Index; use cargo_metadata::camino::Utf8PathBuf; use cargo_metadata::Metadata; use clap::crate_version; use clap::Clap; use color_eyre::eyre::Context; use color_eyre::eyre::ContextCompat; use color_eyre::eyre::Result; use color_eyre::owo_colors::colors::xterm::UserGreen; use color_eyre::owo_colors::colors::xterm::UserYellow; use color_eyre::owo_colors::OwoColorize; use color_eyre::Help; #[derive(Clap)] #[clap(version=crate_version!())] struct Opts { #[clap(subcommand)] cmd: SubCommand, } #[derive(Clap)] enum SubCommand { Dist(Dist), Run(Run), Install(Install), } #[derive(Clap)] struct Dist { #[clap(long)] release: bool, } #[derive(Clap)] struct Run { #[clap(long)] release: bool, } impl Run { fn to_dist(&self) -> Dist { Dist { release: self.release, } } } #[derive(Clap)] struct Install { #[clap(short, long)] output: Option<Utf8PathBuf>, } impl Install { fn to_dist(&self) -> Dist { Dist { release: true, } } } fn main() -> Result<()> { color_eyre::install()?; let opts: Opts = Opts::parse(); match opts.cmd { SubCommand::Dist(config) => dist(config)?, SubCommand::Run(config) => run(config)?, SubCommand::Install(config) => install(config)?, } Ok(()) } fn dist_path(metadata: &Metadata, is_release: bool) -> Utf8PathBuf { metadata .target_directory .join("static/dist") .join(if is_release { "release" } else { "debug" }) } fn backend_path(metadata: &Metadata, is_release: bool) -> Utf8PathBuf { metadata .target_directory .join(if is_release { "release" } else { "debug" }) .join("backend") } fn output_default_path(metadata: &Metadata) -> Utf8PathBuf { metadata.workspace_root.join("output") } fn dist(config: Dist) -> Result<()> { let cmd = cargo_metadata::MetadataCommand::new(); let metadata = cmd.exec()?; let frontend = metadata .workspace_members .iter() .find(|pkg| metadata[pkg].name == "frontend") .wrap_err("Could not find package 'frontend'")?; let html_path = metadata .index(frontend) .manifest_path .with_file_name("index.html"); let dist_path = dist_path(&metadata, config.release); println!( "- Distributing frontend in {}", dist_path.bold().fg::<UserGreen>() ); std::fs::create_dir_all(&dist_path).wrap_err("Could not write to the target directory")?; let trunk_version = duct::cmd!("trunk", "--version") .read() .wrap_err("Could not find `trunk`") .note("`trunk` is required for the build") .suggestion("Install `trunk` with `cargo install trunk`")?; println!("- Using {}", trunk_version.bold().fg::<UserGreen>()); let release = if config.release { Some("--release") } else { None }; let args = IntoIterator::into_iter(["build", "--dist", dist_path.as_str(), html_path.as_str()]) .chain(release); duct::cmd("trunk", args).run()?; Ok(()) } fn run(config: Run) -> Result<()> { dist(config.to_dist())?; let cmd = cargo_metadata::MetadataCommand::new(); let metadata = cmd.exec()?; let dist_path = dist_path(&metadata, config.release); let release = if config.release { Some("--release") } else { None }; let args = IntoIterator::into_iter(["run", "-p", "backend"]).chain(release); duct::cmd("cargo", args) .env("ROCKET_DIST", dist_path) .run() .wrap_err("Could not run server")?; Ok(()) } fn install(config: Install) -> Result<()> { dist(config.to_dist())?; let cmd = cargo_metadata::MetadataCommand::new(); let metadata = cmd.exec()?; let dist_path = dist_path(&metadata, true); let backend_path = backend_path(&metadata, true); let output_dir = config.output.unwrap_or_else(|| output_default_path(&metadata)); println!( "- Building backend in {}", backend_path.bold().fg::<UserGreen>() ); let args = IntoIterator::into_iter(["build", "--release", "-p", "backend"]); duct::cmd("cargo", args) .run() .wrap_err("Could not build backend")?; println!( "- Copying frontend to {}", output_dir.join("static/dist").bold().fg::<UserGreen>() ); std::fs::create_dir_all(&output_dir).wrap_err("Cannot create output dir")?; std::fs::remove_dir_all(&output_dir).wrap_err("Error while cleaning output directory")?; std::fs::create_dir_all(&output_dir.join("static")).wrap_err("Cannot create output dir")?; let errors = copy_dir::copy_dir(&dist_path, &output_dir.join("static/dist")) .wrap_err("Could not copy dist dir to output dir")?;
println!( "- Copying backend to {}", output_dir.join("backend").bold().fg::<UserGreen>() ); std::fs::copy(backend_path, output_dir.join("backend")) .wrap_err("Copying the backend failed")?; Ok(()) }
if !errors.is_empty() { eprintln!( "{} Copy succeeded, but the following errors occurred during the copy:", "WARNING:".bold().fg::<UserYellow>() ); for error in errors { eprintln!("\t{}", error.fg::<UserYellow>()) } }
if_condition
[ { "content": "fn main() {\n\n yew::start_app::<Model>();\n\n}", "file_path": "frontend/src/main.rs", "rank": 9, "score": 69425.33094278068 }, { "content": "#[derive(Debug, Clone)]\n\nenum Message {\n\n Message(String),\n\n}\n\n\n", "file_path": "backend/src/main.rs", "rank": 10...
Rust
ndless-async/src/keypad.rs
jkcoxson/ndless-rs
6242bd3e08c8d6aeac419e19431acc91ba9c0ff1
use alloc::rc::{Rc, Weak}; use core::cell::{Ref, RefCell}; use core::future::Future; use core::mem; use core::pin::Pin; use core::task::{Context, Poll}; use core::time::Duration; use crossbeam_queue::ArrayQueue; use futures_util::{stream::Stream, task::AtomicWaker, StreamExt}; use ignore_result::Ignore; use ndless::alloc::vec::Vec; use ndless::input::{iter_keys, Key}; use ndless::prelude::*; use ndless::timer::{get_ticks, Ticks, TICKS_PER_SECOND}; use crate::timer::TimerListener; #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)] pub enum KeyState { Pressed, Released, } #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)] pub struct KeyEvent { pub key: Key, pub state: KeyState, pub tick_at: u32, } struct SharedKeyQueue { queue: ArrayQueue<KeyEvent>, waker: AtomicWaker, } #[derive(Default)] struct KeypadListenerInner { queues: RefCell<Vec<Rc<SharedKeyQueue>>>, keys: RefCell<Vec<Key>>, } impl KeypadListenerInner { fn poll(&self) { let mut queues = self.queues.borrow_mut(); queues.retain(|queue| Rc::strong_count(queue) > 1); if queues.is_empty() { return; } let mut keys = self.keys.borrow_mut(); let mut retain_i = 0; let mut change = false; iter_keys().for_each(|key| { if let Some((i, _)) = keys.iter().enumerate().find(|(_, other)| key == **other) { if i > retain_i { let (beginning, end) = keys.split_at_mut(i); mem::swap(&mut beginning[retain_i], &mut end[0]); } retain_i += 1; } else { change = true; keys.push(key); let tick_at = get_ticks(); queues.iter_mut().for_each(|queue| { queue .queue .push(KeyEvent { key, state: KeyState::Pressed, tick_at, }) .ignore() }); if keys.len() > retain_i + 1 { let (last, beginning) = keys.split_last_mut().unwrap(); mem::swap(&mut beginning[retain_i], last); } retain_i += 1; } }); let tick_at = get_ticks(); for _ in retain_i..keys.len() { change = true; let key = keys.pop().unwrap(); queues.iter_mut().for_each(|queue| { queue .queue .push(KeyEvent { key, state: KeyState::Released, tick_at, }) .ignore() }); } if change { queues.iter_mut().for_each(|queue| queue.waker.wake()); } } } pub struct KeypadListener<'a> { timer_listener: Option<&'a TimerListener>, rate: u32, interval: RefCell<Weak<RefCell<dyn Future<Output = ()> + Unpin>>>, inner: Rc<KeypadListenerInner>, } impl<'a> KeypadListener<'a> { pub fn new(timer_listener: &'a TimerListener) -> Self { Self::new_with_hz(timer_listener, 30) } pub fn new_with_hz(timer_listener: &'a TimerListener, hz: u32) -> Self { Self::new_with_ticks(timer_listener, TICKS_PER_SECOND / hz) } pub fn new_with_ms(timer_listener: &'a TimerListener, dur: u32) -> Self { Self::new_with_rate(timer_listener, Duration::from_millis(dur as u64)) } pub fn new_with_rate(timer_listener: &'a TimerListener, dur: Duration) -> Self { Self::new_with_ticks(timer_listener, dur.as_ticks()) } pub fn new_with_ticks(timer_listener: &'a TimerListener, ticks: u32) -> Self { Self { timer_listener: Some(timer_listener), rate: ticks, interval: RefCell::new(Weak::<RefCell<futures_util::future::Ready<()>>>::new()), inner: Default::default(), } } pub fn new_manually_polled() -> Self { Self { timer_listener: None, rate: 0, interval: RefCell::new(Weak::<RefCell<futures_util::future::Ready<()>>>::new()), inner: Default::default(), } } fn interval(&self) -> Rc<RefCell<dyn Future<Output = ()> + Unpin>> { if let Some(interval) = self.interval.borrow().upgrade() { return interval; } let listener = self.inner.clone(); let interval: Rc<RefCell<dyn Future<Output = ()> + Unpin>> = if let Some(timer_listener) = self.timer_listener { Rc::new(RefCell::new( timer_listener.every_ticks(self.rate).for_each(move |_| { listener.poll(); futures_util::future::ready(()) }), )) } else { Rc::new(RefCell::new(futures_util::future::pending())) }; self.interval.replace(Rc::downgrade(&interval)); interval } pub fn poll(&self) { self.inner.poll(); } pub fn stream(&self) -> KeyStream { let mut queues = self.inner.queues.borrow_mut(); let queue = Rc::new(SharedKeyQueue { queue: ArrayQueue::new(100), waker: AtomicWaker::new(), }); queues.push(queue.clone()); KeyStream { queue, interval: self.interval(), } } pub fn stream_with_buffer(&self, size: usize) -> KeyStream { let mut queues = self.inner.queues.borrow_mut(); let queue = Rc::new(SharedKeyQueue { queue: ArrayQueue::new(size), waker: AtomicWaker::new(), }); queues.push(queue.clone()); KeyStream { queue, interval: self.interval(), } } pub fn list_keys(&self) -> Ref<Vec<Key>> { self.inner.keys.borrow() } } pub struct KeyStream { queue: Rc<SharedKeyQueue>, interval: Rc<RefCell<dyn Future<Output = ()> + Unpin>>, } impl Stream for KeyStream { type Item = KeyEvent; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let mut interval = self.interval.borrow_mut(); let _ = Pin::new(&mut *interval).poll(cx); self.queue.waker.register(cx.waker()); if let Ok(key) = self.queue.queue.pop() { Poll::Ready(Some(key)) } else { Poll::Pending } } }
use alloc::rc::{Rc, Weak}; use core::cell::{Ref, RefCell}; use core::future::Future; use core::mem; use core::pin::Pin; use core::task::{Context, Poll}; use core::time::Duration; use crossbeam_queue::ArrayQueue; use futures_util::{stream::Stream, task::AtomicWaker, StreamExt}; use ignore_result::Ignore; use ndless::alloc::vec::Vec; use ndless::input::{iter_keys, Key}; use ndless::prelude::*; use ndless::timer::{get_ticks, Ticks, TICKS_PER_SECOND}; use crate::timer::TimerListener; #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)] pub enum KeyState { Pressed, Released, } #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)] pub struct KeyEvent { pub key: Key, pub state: KeyState, pub tick_at: u32, } struct SharedKeyQueue { queue: ArrayQueue<KeyEvent>, waker: AtomicWaker, } #[derive(Default)] struct KeypadListenerInner { queues: RefCell<Vec<Rc<SharedKeyQueue>>>, keys: RefCell<Vec<Key>>, } impl KeypadListenerInner { fn poll(&self) { let mut queues = self.queues.borrow_mut(); queues.retain(|queue| Rc::strong_count(queue) > 1); if queues.is_empty() { return; } let mut keys = self.keys.borrow_mut(); let mut retain_i = 0; let mut change = false; iter_keys().for_each(|key| { if let Some((i, _)) = keys.iter().enumerate().find(|(_, other)| key == **other) { if i > retain_i { let (beginning, end) = keys.split_at_mut(i); mem::swap(&mut beginning[retain_i], &mut end[0]); } retain_i += 1; } else { change = true; keys.push(key); let tick_at = get_ticks(); queues.iter_mut().for_each(|queue| { queue .queue .push(KeyEvent { key, state: KeyState::Pressed, tick_at, }) .ignore() }); if keys.len() > retain_i + 1 { let (last, beginning) = keys.split_last_mut().unwrap(); mem::swap(&mut beginning[retain_i], last); } retain_i += 1; } }); let tick_at = get_ticks(); for _ in retain_i..keys.len() { change = true; let key = keys.pop().unwrap(); queues.iter_mut().for_each(|queue| { queue .queue .push(KeyEvent { key, state: KeyState::Released, tick_at, }) .ignore() }); } if change { queues.iter_mut().for_each(|queue| queue.waker.wake()); } } } pub struct KeypadListener<'a> { timer_listener: Option<&'a TimerListener>, rate: u32, interval: RefCell<Weak<RefCell<dyn Future<Output = ()> + Unpin>>>, inner: Rc<KeypadListenerInner>, } impl<'a> KeypadListener<'a> { pub fn new(timer_listener: &'a TimerListener) -> Self { Self::new_with_hz(timer_listener, 30) } pub fn new_with_hz(timer_listener: &'a TimerListener, hz: u32) -> Self { Self::new_with_ticks(timer_listener, TICKS_PER_SECOND / hz) } pub fn new_with_ms(timer_listener: &'a TimerListener, dur: u32) -> Self { Self::new_with_rate(timer_listener, Duration::from_millis(dur as u64)) } pub fn new_with_rate(timer_listener: &'a TimerListener, dur: Duration) -> Self { Self::new_with_ticks(timer_listener, dur.as_ticks()) } pub fn new_with_ticks(timer_listener: &'a TimerListener, ticks: u32) -> Self { Self { timer_listener: Some(timer_listener), rate: ticks, interval: RefCell::new(Weak::<RefCell<futures_util::future::Ready<()>>>::new()), inner: Default::default(), } } pub fn new_manually_polled() -> Self { Self { timer_listener: None, rate: 0, interval: RefCell::new(Weak::<RefCell<futures_util::future::Ready<()>>>::new()), inner: Default::default(), } } fn interval(&self) -> Rc<RefCell<dyn Future<Output = ()> + Unpin>> { if let Some(interval) = self.interval.borrow().upgrade() { return interval; } let listener = self.inner.clone(); let interval: Rc<RefCell<dyn Future<Output = ()> + Unpin>> = if let Some(timer_listener) = self.timer_listener { Rc::new(RefCell::new( timer_listener.every_ticks(self.rate).for_each(move |_| { listener.poll(); futures_util::future::ready(()) }), )) } else { Rc::new(RefCell::new(futures_util::future::pending())) }; self.interval.replace(Rc::downgrade(&interval)); interval } pub fn poll(&self) { self.inner.poll(); }
pub fn stream_with_buffer(&self, size: usize) -> KeyStream { let mut queues = self.inner.queues.borrow_mut(); let queue = Rc::new(SharedKeyQueue { queue: ArrayQueue::new(size), waker: AtomicWaker::new(), }); queues.push(queue.clone()); KeyStream { queue, interval: self.interval(), } } pub fn list_keys(&self) -> Ref<Vec<Key>> { self.inner.keys.borrow() } } pub struct KeyStream { queue: Rc<SharedKeyQueue>, interval: Rc<RefCell<dyn Future<Output = ()> + Unpin>>, } impl Stream for KeyStream { type Item = KeyEvent; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let mut interval = self.interval.borrow_mut(); let _ = Pin::new(&mut *interval).poll(cx); self.queue.waker.register(cx.waker()); if let Ok(key) = self.queue.queue.pop() { Poll::Ready(Some(key)) } else { Poll::Pending } } }
pub fn stream(&self) -> KeyStream { let mut queues = self.inner.queues.borrow_mut(); let queue = Rc::new(SharedKeyQueue { queue: ArrayQueue::new(100), waker: AtomicWaker::new(), }); queues.push(queue.clone()); KeyStream { queue, interval: self.interval(), } }
function_block-full_function
[ { "content": "/// Returns true if the specific key is pressed.\n\n/// Note that you may pass either an owned [`Key`] or a borrowed [`&Key`][Key].\n\npub fn is_key_pressed(key: impl Borrow<Key>) -> bool {\n\n\tKEY_MAPPING\n\n\t\t.iter()\n\n\t\t.find(|(_, other)| other == key.borrow())\n\n\t\t.map_or(\n\n\t\t\tfa...
Rust
reql/src/cmd/do_.rs
kid/rethinkdb-rs
945e161aec8288fa4f915bc59bc0575438a1d4ae
use super::args::Args; use crate::{cmd, Command, Func}; use ql2::term::TermType; use serde::Serialize; pub trait Arg { fn arg(self, parent: Option<Command>) -> cmd::Arg<()>; } impl Arg for Command { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let cmd = Command::new(TermType::Funcall).with_arg(self); match parent { Some(parent) => cmd.with_arg(parent).into_arg(), None => cmd.into_arg(), } } } impl<T> Arg for T where T: Serialize, { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { Command::from_json(self).arg(parent) } } impl Arg for Args<(Command, Command)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((arg, expr)) = self; expr.arg(parent).with_arg(arg) } } #[allow(array_into_iter)] #[allow(clippy::into_iter_on_ref)] impl<const N: usize> Arg for Args<([Command; N], Command)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((args, expr)) = self; let mut cmd = expr.arg(parent); for arg in args.into_iter().cloned() { cmd = cmd.with_arg(arg); } cmd } } #[allow(array_into_iter)] #[allow(clippy::into_iter_on_ref)] impl<T, const N: usize> Arg for Args<([T; N], Command)> where T: Serialize + Clone, { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((args, expr)) = self; let mut cmd = expr.arg(parent); for arg in args.into_iter().cloned() { let arg = Command::from_json(arg); cmd = cmd.with_arg(arg); } cmd } } impl Arg for Args<(Command, Func)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((arg, Func(func))) = self; func.arg(parent).with_arg(arg) } } #[allow(array_into_iter)] #[allow(clippy::into_iter_on_ref)] impl<const N: usize> Arg for Args<([Command; N], Func)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((args, Func(func))) = self; let mut cmd = func.arg(parent); for arg in args.into_iter().cloned() { cmd = cmd.with_arg(arg); } cmd } } #[allow(array_into_iter)] #[allow(clippy::into_iter_on_ref)] impl<T, const N: usize> Arg for Args<([T; N], Func)> where T: Serialize + Clone, { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((args, Func(func))) = self; let mut cmd = func.arg(parent); for arg in args.into_iter().cloned() { let arg = Command::from_json(arg); cmd = cmd.with_arg(arg); } cmd } } impl Arg for Func { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Func(func) = self; func.arg(parent) } } #[cfg(test)] mod tests { use crate::{self as reql, cmd, func, r}; #[test] fn r_do() { let counter = crate::current_counter(); let query = r.do_(r.args(([10, 20], func!(|x, y| x + y)))); let serialised = cmd::serialise(&query); let expected = format!( r#"[64,[[69,[[2,[2,3]],[24,[[10,[{}]],[10,[{}]]]]]],10,20]]"#, counter, counter + 1 ); assert_eq!(serialised, expected); } #[test] fn r_db_table_get_do() { let counter = crate::current_counter(); let query = r .db("mydb") .table("table1") .get("johndoe@example.com") .do_(func!(|doc| r .db("mydb") .table("table2") .get(doc.get_field("id")))); let serialised = cmd::serialise(&query); let expected = format!( r#"[64,[[69,[[2,[1]],[16,[[15,[[14,["mydb"]],"table2"]],[31,[[10,[{}]],"id"]]]]]],[16,[[15,[[14,["mydb"]],"table1"]],"johndoe@example.com"]]]]"#, counter ); assert_eq!(serialised, expected); } }
use super::args::Args; use crate::{cmd, Command, Func}; use ql2::term::TermType; use serde::Serialize; pub trait Arg { fn arg(self, parent: Option<Command>) -> cmd::Arg<()>; } impl Arg for Command { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let cmd = Command::new(TermType::Funcall).with_arg(self);
} } impl<T> Arg for T where T: Serialize, { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { Command::from_json(self).arg(parent) } } impl Arg for Args<(Command, Command)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((arg, expr)) = self; expr.arg(parent).with_arg(arg) } } #[allow(array_into_iter)] #[allow(clippy::into_iter_on_ref)] impl<const N: usize> Arg for Args<([Command; N], Command)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((args, expr)) = self; let mut cmd = expr.arg(parent); for arg in args.into_iter().cloned() { cmd = cmd.with_arg(arg); } cmd } } #[allow(array_into_iter)] #[allow(clippy::into_iter_on_ref)] impl<T, const N: usize> Arg for Args<([T; N], Command)> where T: Serialize + Clone, { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((args, expr)) = self; let mut cmd = expr.arg(parent); for arg in args.into_iter().cloned() { let arg = Command::from_json(arg); cmd = cmd.with_arg(arg); } cmd } } impl Arg for Args<(Command, Func)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((arg, Func(func))) = self; func.arg(parent).with_arg(arg) } } #[allow(array_into_iter)] #[allow(clippy::into_iter_on_ref)] impl<const N: usize> Arg for Args<([Command; N], Func)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((args, Func(func))) = self; let mut cmd = func.arg(parent); for arg in args.into_iter().cloned() { cmd = cmd.with_arg(arg); } cmd } } #[allow(array_into_iter)] #[allow(clippy::into_iter_on_ref)] impl<T, const N: usize> Arg for Args<([T; N], Func)> where T: Serialize + Clone, { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((args, Func(func))) = self; let mut cmd = func.arg(parent); for arg in args.into_iter().cloned() { let arg = Command::from_json(arg); cmd = cmd.with_arg(arg); } cmd } } impl Arg for Func { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Func(func) = self; func.arg(parent) } } #[cfg(test)] mod tests { use crate::{self as reql, cmd, func, r}; #[test] fn r_do() { let counter = crate::current_counter(); let query = r.do_(r.args(([10, 20], func!(|x, y| x + y)))); let serialised = cmd::serialise(&query); let expected = format!( r#"[64,[[69,[[2,[2,3]],[24,[[10,[{}]],[10,[{}]]]]]],10,20]]"#, counter, counter + 1 ); assert_eq!(serialised, expected); } #[test] fn r_db_table_get_do() { let counter = crate::current_counter(); let query = r .db("mydb") .table("table1") .get("johndoe@example.com") .do_(func!(|doc| r .db("mydb") .table("table2") .get(doc.get_field("id")))); let serialised = cmd::serialise(&query); let expected = format!( r#"[64,[[69,[[2,[1]],[16,[[15,[[14,["mydb"]],"table2"]],[31,[[10,[{}]],"id"]]]]]],[16,[[15,[[14,["mydb"]],"table1"]],"johndoe@example.com"]]]]"#, counter ); assert_eq!(serialised, expected); } }
match parent { Some(parent) => cmd.with_arg(parent).into_arg(), None => cmd.into_arg(), }
if_condition
[ { "content": "pub trait Arg {\n\n fn arg(self) -> cmd::Arg<()>;\n\n}\n\n\n\nimpl Arg for Command {\n\n fn arg(self) -> cmd::Arg<()> {\n\n Self::new(TermType::Or).with_arg(self).into_arg()\n\n }\n\n}\n", "file_path": "reql/src/cmd/or.rs", "rank": 0, "score": 216228.98313413086 }, ...
Rust
cranelift/codegen/src/isa/x64/abi.rs
jgouly/wasmtime-old
715ca4112a1bd187a32e8238e3bce2b5a2c9d635
#![allow(dead_code)] #![allow(non_snake_case)] use crate::ir; use crate::ir::types; use crate::ir::types::*; use crate::ir::StackSlot; use crate::ir::Type; use crate::isa; use crate::isa::x64::inst::*; use crate::isa::x64::*; use crate::machinst::*; use alloc::vec::Vec; use regalloc::{RealReg, Reg, RegClass, Set, SpillSlot, Writable}; #[derive(Clone, Debug)] enum ABIArg { Reg(RealReg), Stack, } #[derive(Clone, Debug)] enum ABIRet { Reg(RealReg), Mem, } pub struct X64ABIBody { args: Vec<ABIArg>, rets: Vec<ABIRet>, stackslots: Vec<usize>, stackslots_size: usize, clobbered: Set<Writable<RealReg>>, spillslots: Option<usize>, spill_area_sizeB: Option<usize>, call_conv: isa::CallConv, } fn in_int_reg(ty: types::Type) -> bool { match ty { types::I8 | types::I16 | types::I32 | types::I64 => true, types::B1 | types::B8 | types::B16 | types::B32 | types::B64 => true, _ => false, } } fn get_intreg_for_arg_ELF(idx: usize) -> Option<Reg> { match idx { 0 => Some(reg_RDI()), 1 => Some(reg_RSI()), 2 => Some(reg_RDX()), 3 => Some(reg_RCX()), 4 => Some(reg_R8()), 5 => Some(reg_R9()), _ => None, } } fn get_intreg_for_retval_ELF(idx: usize) -> Option<Reg> { match idx { 0 => Some(reg_RAX()), 1 => Some(reg_RDX()), _ => None, } } fn is_callee_save_ELF(r: RealReg) -> bool { match r.get_class() { RegClass::I64 => match r.get_hw_encoding() as u8 { ENC_RBX | ENC_RBP | ENC_R12 | ENC_R13 | ENC_R14 | ENC_R15 => true, _ => false, }, _ => unimplemented!(), } } fn get_callee_saves(regs: Vec<Writable<RealReg>>) -> Vec<Writable<RealReg>> { regs.into_iter() .filter(|r| is_callee_save_ELF(r.to_reg())) .collect() } impl X64ABIBody { pub fn new(f: &ir::Function) -> Self { println!("X64 ABI: func signature {:?}", f.signature); let mut args = vec![]; let mut next_int_arg = 0; for param in &f.signature.params { match param.purpose { ir::ArgumentPurpose::Normal => { if in_int_reg(param.value_type) { if let Some(reg) = get_intreg_for_arg_ELF(next_int_arg) { args.push(ABIArg::Reg(reg.to_real_reg())); } else { unimplemented!("passing arg on the stack"); } next_int_arg += 1; } else { unimplemented!("non int normal register") } } ir::ArgumentPurpose::VMContext => { debug_assert!(f.signature.call_conv.extends_baldrdash()); args.push(ABIArg::Reg(reg_R14().to_real_reg())); } _ => unimplemented!("other parameter purposes"), } } let mut rets = vec![]; let mut next_int_retval = 0; for ret in &f.signature.returns { match ret.purpose { ir::ArgumentPurpose::Normal => { if in_int_reg(ret.value_type) { if let Some(reg) = get_intreg_for_retval_ELF(next_int_retval) { rets.push(ABIRet::Reg(reg.to_real_reg())); } else { unimplemented!("passing return on the stack"); } next_int_retval += 1; } else { unimplemented!("returning non integer normal value"); } } _ => { unimplemented!("non normal argument purpose"); } } } let mut stack_offset: usize = 0; let mut stackslots = vec![]; for (stackslot, data) in f.stack_slots.iter() { let off = stack_offset; stack_offset += data.size as usize; stack_offset = (stack_offset + 7) & !7usize; assert_eq!(stackslot.as_u32() as usize, stackslots.len()); stackslots.push(off); } Self { args, rets, stackslots, stackslots_size: stack_offset, clobbered: Set::empty(), spillslots: None, spill_area_sizeB: None, call_conv: f.signature.call_conv.clone(), } } } impl ABIBody<Inst> for X64ABIBody { fn num_args(&self) -> usize { unimplemented!() } fn num_retvals(&self) -> usize { unimplemented!() } fn num_stackslots(&self) -> usize { unimplemented!() } fn liveins(&self) -> Set<RealReg> { let mut set: Set<RealReg> = Set::empty(); for arg in &self.args { if let &ABIArg::Reg(r) = arg { set.insert(r); } } println!("X64 ABI: liveins {:?}", set); set } fn liveouts(&self) -> Set<RealReg> { let mut set: Set<RealReg> = Set::empty(); for ret in &self.rets { if let &ABIRet::Reg(r) = ret { set.insert(r); } } println!("X64 ABI: liveouts {:?}", set); set } fn gen_copy_arg_to_reg(&self, idx: usize, to_reg: Writable<Reg>) -> Inst { match &self.args[idx] { ABIArg::Reg(from_reg) => { if from_reg.get_class() == RegClass::I32 || from_reg.get_class() == RegClass::I64 { return i_Mov_R_R(/*is64=*/ true, from_reg.to_reg(), to_reg); } unimplemented!("moving from non-int arg to vreg"); } ABIArg::Stack => unimplemented!("moving from stack arg to vreg"), } } fn gen_copy_reg_to_retval(&self, idx: usize, from_reg: Reg) -> Inst { match &self.rets[idx] { ABIRet::Reg(to_reg) => { if to_reg.get_class() == RegClass::I32 || to_reg.get_class() == RegClass::I64 { return i_Mov_R_R( /*is64=*/ true, from_reg, Writable::<Reg>::from_reg(to_reg.to_reg()), ); } unimplemented!("moving from vreg to non-int return value"); } ABIRet::Mem => { panic!("moving from vreg to memory return value"); } } } fn gen_ret(&self) -> Inst { i_Ret() } fn gen_epilogue_placeholder(&self) -> Inst { i_epilogue_placeholder() } fn set_num_spillslots(&mut self, slots: usize) { self.spillslots = Some(slots); } fn set_clobbered(&mut self, clobbered: Set<Writable<RealReg>>) { self.clobbered = clobbered; } fn load_stackslot( &self, _slot: StackSlot, _offset: usize, _ty: Type, _into_reg: Writable<Reg>, ) -> Inst { unimplemented!() } fn store_stackslot(&self, _slot: StackSlot, _offset: usize, _ty: Type, _from_reg: Reg) -> Inst { unimplemented!() } fn load_spillslot(&self, _slot: SpillSlot, _ty: Type, _into_reg: Writable<Reg>) -> Inst { unimplemented!() } fn store_spillslot(&self, _slot: SpillSlot, _ty: Type, _from_reg: Reg) -> Inst { unimplemented!() } fn gen_prologue(&mut self) -> Vec<Inst> { let total_stacksize = self.stackslots_size + 8 * self.spillslots.unwrap(); let total_stacksize = (total_stacksize + 15) & !15; let r_rbp = reg_RBP(); let r_rsp = reg_RSP(); let w_rbp = Writable::<Reg>::from_reg(r_rbp); let w_rsp = Writable::<Reg>::from_reg(r_rsp); let mut insts = vec![]; if !self.call_conv.extends_baldrdash() { insts.push(i_Push64(ip_RMI_R(r_rbp))); insts.push(i_Mov_R_R(true, r_rsp, w_rbp)); } let mut callee_saved_used = 0; let clobbered = get_callee_saves(self.clobbered.to_vec()); for reg in clobbered { let r_reg = reg.to_reg(); match r_reg.get_class() { RegClass::I64 => { insts.push(i_Push64(ip_RMI_R(r_reg.to_reg()))); callee_saved_used += 8; } _ => unimplemented!(), } } let mut spill_area_sizeB = total_stacksize; match callee_saved_used % 16 { 0 => spill_area_sizeB += 0, 8 => spill_area_sizeB += 8, _ => panic!("gen_prologue(x86): total_stacksize is not 8-aligned"), } if spill_area_sizeB > 0x7FFF_FFFF { panic!("gen_prologue(x86): total_stacksize >= 2G"); } if spill_area_sizeB > 0 { insts.push(i_Alu_RMI_R( true, RMI_R_Op::Sub, ip_RMI_I(spill_area_sizeB as u32), w_rsp, )); } debug_assert!(self.spill_area_sizeB.is_none()); self.spill_area_sizeB = Some(spill_area_sizeB); insts } fn gen_epilogue(&self) -> Vec<Inst> { let r_rbp = reg_RBP(); let r_rsp = reg_RSP(); let w_rbp = Writable::<Reg>::from_reg(r_rbp); let w_rsp = Writable::<Reg>::from_reg(r_rsp); let mut insts = vec![]; let spill_area_sizeB = self.spill_area_sizeB.unwrap(); if spill_area_sizeB > 0 { insts.push(i_Alu_RMI_R( true, RMI_R_Op::Add, ip_RMI_I(spill_area_sizeB as u32), w_rsp, )); } let mut tmp_insts = vec![]; let clobbered = get_callee_saves(self.clobbered.to_vec()); for w_real_reg in clobbered { match w_real_reg.to_reg().get_class() { RegClass::I64 => { tmp_insts.push(i_Pop64(Writable::<Reg>::from_reg( w_real_reg.to_reg().to_reg(), ))) } _ => unimplemented!(), } } tmp_insts.reverse(); for i in tmp_insts { insts.push(i); } if !self.call_conv.extends_baldrdash() { insts.push(i_Pop64(w_rbp)); insts.push(i_Ret()); } insts } fn frame_size(&self) -> u32 { self.spill_area_sizeB .expect("frame size not computed before prologue generation") as u32 } fn get_spillslot_size(&self, rc: RegClass, ty: Type) -> u32 { match (rc, ty) { (RegClass::I64, _) => 1, (RegClass::V128, F32) | (RegClass::V128, F64) => 1, (RegClass::V128, _) => 2, _ => panic!("Unexpected register class!"), } } fn gen_spill(&self, _to_slot: SpillSlot, _from_reg: RealReg, _ty: Type) -> Inst { unimplemented!() } fn gen_reload(&self, _to_reg: Writable<RealReg>, _from_slot: SpillSlot, _ty: Type) -> Inst { unimplemented!() } }
#![allow(dead_code)] #![allow(non_snake_case)] use crate::ir; use crate::ir::types; use crate::ir::types::*; use crate::ir::StackSlot; use crate::ir::Type; use crate::isa; use crate::isa::x64::inst::*; use crate::isa::x64::*; use crate::machinst::*; use alloc::vec::Vec; use regalloc::{RealReg, Reg, RegClass, Set, SpillSlot, Writable}; #[derive(Clone, Debug)] enum ABIArg { Reg(RealReg), Stack, } #[derive(Clone, Debug)] enum ABIRet { Reg(RealReg), Mem, } pub struct X64ABIBody { args: Vec<ABIArg>, rets: Vec<ABIRet>, stackslots: Vec<usize>, stackslots_size: usize, clobbered: Set<Writable<RealReg>>, spillslots: Option<usize>, spill_area_sizeB: Option<usize>, call_conv: isa::CallConv, }
fn get_intreg_for_arg_ELF(idx: usize) -> Option<Reg> { match idx { 0 => Some(reg_RDI()), 1 => Some(reg_RSI()), 2 => Some(reg_RDX()), 3 => Some(reg_RCX()), 4 => Some(reg_R8()), 5 => Some(reg_R9()), _ => None, } } fn get_intreg_for_retval_ELF(idx: usize) -> Option<Reg> { match idx { 0 => Some(reg_RAX()), 1 => Some(reg_RDX()), _ => None, } } fn is_callee_save_ELF(r: RealReg) -> bool { match r.get_class() { RegClass::I64 => match r.get_hw_encoding() as u8 { ENC_RBX | ENC_RBP | ENC_R12 | ENC_R13 | ENC_R14 | ENC_R15 => true, _ => false, }, _ => unimplemented!(), } } fn get_callee_saves(regs: Vec<Writable<RealReg>>) -> Vec<Writable<RealReg>> { regs.into_iter() .filter(|r| is_callee_save_ELF(r.to_reg())) .collect() } impl X64ABIBody { pub fn new(f: &ir::Function) -> Self { println!("X64 ABI: func signature {:?}", f.signature); let mut args = vec![]; let mut next_int_arg = 0; for param in &f.signature.params { match param.purpose { ir::ArgumentPurpose::Normal => { if in_int_reg(param.value_type) { if let Some(reg) = get_intreg_for_arg_ELF(next_int_arg) { args.push(ABIArg::Reg(reg.to_real_reg())); } else { unimplemented!("passing arg on the stack"); } next_int_arg += 1; } else { unimplemented!("non int normal register") } } ir::ArgumentPurpose::VMContext => { debug_assert!(f.signature.call_conv.extends_baldrdash()); args.push(ABIArg::Reg(reg_R14().to_real_reg())); } _ => unimplemented!("other parameter purposes"), } } let mut rets = vec![]; let mut next_int_retval = 0; for ret in &f.signature.returns { match ret.purpose { ir::ArgumentPurpose::Normal => { if in_int_reg(ret.value_type) { if let Some(reg) = get_intreg_for_retval_ELF(next_int_retval) { rets.push(ABIRet::Reg(reg.to_real_reg())); } else { unimplemented!("passing return on the stack"); } next_int_retval += 1; } else { unimplemented!("returning non integer normal value"); } } _ => { unimplemented!("non normal argument purpose"); } } } let mut stack_offset: usize = 0; let mut stackslots = vec![]; for (stackslot, data) in f.stack_slots.iter() { let off = stack_offset; stack_offset += data.size as usize; stack_offset = (stack_offset + 7) & !7usize; assert_eq!(stackslot.as_u32() as usize, stackslots.len()); stackslots.push(off); } Self { args, rets, stackslots, stackslots_size: stack_offset, clobbered: Set::empty(), spillslots: None, spill_area_sizeB: None, call_conv: f.signature.call_conv.clone(), } } } impl ABIBody<Inst> for X64ABIBody { fn num_args(&self) -> usize { unimplemented!() } fn num_retvals(&self) -> usize { unimplemented!() } fn num_stackslots(&self) -> usize { unimplemented!() } fn liveins(&self) -> Set<RealReg> { let mut set: Set<RealReg> = Set::empty(); for arg in &self.args { if let &ABIArg::Reg(r) = arg { set.insert(r); } } println!("X64 ABI: liveins {:?}", set); set } fn liveouts(&self) -> Set<RealReg> { let mut set: Set<RealReg> = Set::empty(); for ret in &self.rets { if let &ABIRet::Reg(r) = ret { set.insert(r); } } println!("X64 ABI: liveouts {:?}", set); set } fn gen_copy_arg_to_reg(&self, idx: usize, to_reg: Writable<Reg>) -> Inst { match &self.args[idx] { ABIArg::Reg(from_reg) => { if from_reg.get_class() == RegClass::I32 || from_reg.get_class() == RegClass::I64 { return i_Mov_R_R(/*is64=*/ true, from_reg.to_reg(), to_reg); } unimplemented!("moving from non-int arg to vreg"); } ABIArg::Stack => unimplemented!("moving from stack arg to vreg"), } } fn gen_copy_reg_to_retval(&self, idx: usize, from_reg: Reg) -> Inst { match &self.rets[idx] { ABIRet::Reg(to_reg) => { if to_reg.get_class() == RegClass::I32 || to_reg.get_class() == RegClass::I64 { return i_Mov_R_R( /*is64=*/ true, from_reg, Writable::<Reg>::from_reg(to_reg.to_reg()), ); } unimplemented!("moving from vreg to non-int return value"); } ABIRet::Mem => { panic!("moving from vreg to memory return value"); } } } fn gen_ret(&self) -> Inst { i_Ret() } fn gen_epilogue_placeholder(&self) -> Inst { i_epilogue_placeholder() } fn set_num_spillslots(&mut self, slots: usize) { self.spillslots = Some(slots); } fn set_clobbered(&mut self, clobbered: Set<Writable<RealReg>>) { self.clobbered = clobbered; } fn load_stackslot( &self, _slot: StackSlot, _offset: usize, _ty: Type, _into_reg: Writable<Reg>, ) -> Inst { unimplemented!() } fn store_stackslot(&self, _slot: StackSlot, _offset: usize, _ty: Type, _from_reg: Reg) -> Inst { unimplemented!() } fn load_spillslot(&self, _slot: SpillSlot, _ty: Type, _into_reg: Writable<Reg>) -> Inst { unimplemented!() } fn store_spillslot(&self, _slot: SpillSlot, _ty: Type, _from_reg: Reg) -> Inst { unimplemented!() } fn gen_prologue(&mut self) -> Vec<Inst> { let total_stacksize = self.stackslots_size + 8 * self.spillslots.unwrap(); let total_stacksize = (total_stacksize + 15) & !15; let r_rbp = reg_RBP(); let r_rsp = reg_RSP(); let w_rbp = Writable::<Reg>::from_reg(r_rbp); let w_rsp = Writable::<Reg>::from_reg(r_rsp); let mut insts = vec![]; if !self.call_conv.extends_baldrdash() { insts.push(i_Push64(ip_RMI_R(r_rbp))); insts.push(i_Mov_R_R(true, r_rsp, w_rbp)); } let mut callee_saved_used = 0; let clobbered = get_callee_saves(self.clobbered.to_vec()); for reg in clobbered { let r_reg = reg.to_reg(); match r_reg.get_class() { RegClass::I64 => { insts.push(i_Push64(ip_RMI_R(r_reg.to_reg()))); callee_saved_used += 8; } _ => unimplemented!(), } } let mut spill_area_sizeB = total_stacksize; match callee_saved_used % 16 { 0 => spill_area_sizeB += 0, 8 => spill_area_sizeB += 8, _ => panic!("gen_prologue(x86): total_stacksize is not 8-aligned"), } if spill_area_sizeB > 0x7FFF_FFFF { panic!("gen_prologue(x86): total_stacksize >= 2G"); } if spill_area_sizeB > 0 { insts.push(i_Alu_RMI_R( true, RMI_R_Op::Sub, ip_RMI_I(spill_area_sizeB as u32), w_rsp, )); } debug_assert!(self.spill_area_sizeB.is_none()); self.spill_area_sizeB = Some(spill_area_sizeB); insts } fn gen_epilogue(&self) -> Vec<Inst> { let r_rbp = reg_RBP(); let r_rsp = reg_RSP(); let w_rbp = Writable::<Reg>::from_reg(r_rbp); let w_rsp = Writable::<Reg>::from_reg(r_rsp); let mut insts = vec![]; let spill_area_sizeB = self.spill_area_sizeB.unwrap(); if spill_area_sizeB > 0 { insts.push(i_Alu_RMI_R( true, RMI_R_Op::Add, ip_RMI_I(spill_area_sizeB as u32), w_rsp, )); } let mut tmp_insts = vec![]; let clobbered = get_callee_saves(self.clobbered.to_vec()); for w_real_reg in clobbered { match w_real_reg.to_reg().get_class() { RegClass::I64 => { tmp_insts.push(i_Pop64(Writable::<Reg>::from_reg( w_real_reg.to_reg().to_reg(), ))) } _ => unimplemented!(), } } tmp_insts.reverse(); for i in tmp_insts { insts.push(i); } if !self.call_conv.extends_baldrdash() { insts.push(i_Pop64(w_rbp)); insts.push(i_Ret()); } insts } fn frame_size(&self) -> u32 { self.spill_area_sizeB .expect("frame size not computed before prologue generation") as u32 } fn get_spillslot_size(&self, rc: RegClass, ty: Type) -> u32 { match (rc, ty) { (RegClass::I64, _) => 1, (RegClass::V128, F32) | (RegClass::V128, F64) => 1, (RegClass::V128, _) => 2, _ => panic!("Unexpected register class!"), } } fn gen_spill(&self, _to_slot: SpillSlot, _from_reg: RealReg, _ty: Type) -> Inst { unimplemented!() } fn gen_reload(&self, _to_reg: Writable<RealReg>, _from_slot: SpillSlot, _ty: Type) -> Inst { unimplemented!() } }
fn in_int_reg(ty: types::Type) -> bool { match ty { types::I8 | types::I16 | types::I32 | types::I64 => true, types::B1 | types::B8 | types::B16 | types::B32 | types::B64 => true, _ => false, } }
function_block-full_function
[ { "content": "fn memarg_regs(memarg: &MemArg, used: &mut Set<Reg>, modified: &mut Set<Writable<Reg>>) {\n\n match memarg {\n\n &MemArg::Unscaled(reg, ..) | &MemArg::UnsignedOffset(reg, ..) => {\n\n used.insert(reg);\n\n }\n\n &MemArg::RegScaled(r1, r2, ..) => {\n\n ...
Rust
src/test/instruction_tests/instr_vfmsub213ss.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vfmsub213ss_1() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 121, 171, 195], OperandSize::Dword, ) } #[test] fn vfmsub213ss_2() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM3)), operand3: Some(Indirect(EBX, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 97, 171, 59], OperandSize::Dword, ) } #[test] fn vfmsub213ss_3() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM1)), operand3: Some(Direct(XMM6)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 113, 171, 254], OperandSize::Qword, ) } #[test] fn vfmsub213ss_4() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectScaledIndexedDisplaced( RSI, RDI, Eight, 912513807, Some(OperandSize::Dword), None, )), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 97, 171, 172, 254, 15, 219, 99, 54], OperandSize::Qword, ) } #[test] fn vfmsub213ss_5() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM4)), operand3: Some(Direct(XMM4)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Down), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 242, 93, 189, 171, 204], OperandSize::Dword, ) } #[test] fn vfmsub213ss_6() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM5)), operand3: Some(IndirectDisplaced( EBX, 1132410721, Some(OperandSize::Dword), None, )), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 242, 85, 143, 171, 187, 97, 55, 127, 67], OperandSize::Dword, ) } #[test] fn vfmsub213ss_7() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM23)), operand3: Some(Direct(XMM3)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 242, 69, 150, 171, 227], OperandSize::Qword, ) } #[test] fn vfmsub213ss_8() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM31)), operand2: Some(Direct(XMM21)), operand3: Some(IndirectDisplaced( RCX, 851224790, Some(OperandSize::Dword), None, )), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 98, 85, 130, 171, 185, 214, 168, 188, 50], OperandSize::Qword, ) }
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vfmsub213ss_1() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 121, 171, 195], OperandSize::Dword, ) } #[test] fn vfmsub213ss_2() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM3)), operand3: Some(Indirect(EBX, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 97, 171, 59], OperandSize::Dword, ) } #[test] fn vfmsub213ss_3() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM1)), operand3: Some(Direct(XMM6)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 113, 171, 254], OperandSize::Qword, ) } #[test] fn vfmsub213ss_4() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectScaledIndexedDisplaced( RSI, RDI, Eight, 912513807, Some(OperandSize::Dword), None, )), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 97, 171, 172, 254, 15, 219, 99, 54], OperandSize::Qword, ) } #[test] fn vfmsub213ss_5()
EBX, 1132410721, Some(OperandSize::Dword), None, )), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 242, 85, 143, 171, 187, 97, 55, 127, 67], OperandSize::Dword, ) } #[test] fn vfmsub213ss_7() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM23)), operand3: Some(Direct(XMM3)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 242, 69, 150, 171, 227], OperandSize::Qword, ) } #[test] fn vfmsub213ss_8() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM31)), operand2: Some(Direct(XMM21)), operand3: Some(IndirectDisplaced( RCX, 851224790, Some(OperandSize::Dword), None, )), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 98, 85, 130, 171, 185, 214, 168, 188, 50], OperandSize::Qword, ) }
{ run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM4)), operand3: Some(Direct(XMM4)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Down), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 242, 93, 189, 171, 204], OperandSize::Dword, ) } #[test] fn vfmsub213ss_6() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM5)), operand3: Some(IndirectDisplaced(
random
[ { "content": "fn encode32_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
src/assets/texture.rs
jkugelman/roomdust
3b23685ab36b24dd76ba72f7ac099943e7bd4b5a
use std::collections::BTreeMap; use std::convert::TryInto; use std::ops::{Deref, Index}; use bytes::Buf; use crate::wad::{self, Lump, Wad}; #[derive(Clone, Debug)] pub struct TextureBank(BTreeMap<String, Texture>); impl TextureBank { pub fn load(wad: &Wad) -> wad::Result<Self> { let mut textures = BTreeMap::new(); for lump in Self::texture_lumps(wad)? { Self::load_from(&lump, &mut textures)?; } Ok(Self(textures)) } fn texture_lumps(wad: &Wad) -> wad::Result<Vec<Lump>> { let iter = Some(wad.lump("TEXTURE1")?).into_iter(); let iter = iter.chain(wad.try_lump("TEXTURE2")?); Ok(iter.collect()) } fn load_from(lump: &Lump, textures: &mut BTreeMap<String, Texture>) -> wad::Result<()> { let mut cursor = lump.cursor(); cursor.need(4)?; let count = cursor.get_u32_le(); let mut offsets = Vec::with_capacity(count.clamp(0, 1024) as usize); let need: usize = count .checked_mul(4) .ok_or_else(|| lump.error(format!("bad count {}", count)))? .try_into() .unwrap(); cursor.need(need)?; for _ in 0..count { offsets.push(cursor.get_u32_le()); } cursor.clear(); cursor.done()?; for offset in offsets { let texture = Texture::load(lump, offset.try_into().unwrap())?; textures.insert(texture.name.clone(), texture); } Ok(()) } pub fn get(&self, name: &str) -> Option<&Texture> { self.0.get(&name.to_ascii_uppercase()) } } impl Index<&str> for TextureBank { type Output = Texture; fn index(&self, name: &str) -> &Self::Output { self.get(name).expect("texture not found") } } impl Deref for TextureBank { type Target = BTreeMap<String, Texture>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug)] pub struct Texture { pub name: String, pub width: u16, pub height: u16, patches: Vec<PatchPlacement>, } impl Texture { fn load(lump: &Lump, offset: usize) -> wad::Result<Self> { let mut cursor = lump.cursor(); cursor.skip(offset)?; cursor.need(22)?; let name = cursor.get_name(); let _flags = cursor.get_u16_le(); let _unused = cursor.get_u16_le(); let width = cursor.get_u16_le(); let height = cursor.get_u16_le(); let _unused = cursor.get_u32_le(); let patch_count: usize = cursor.get_u16_le().into(); let mut patches = Vec::with_capacity(patch_count.clamp(0, 64)); cursor.need(patch_count * 10)?; for _ in 0..patch_count { let x = cursor.get_u16_le(); let y = cursor.get_u16_le(); let patch = cursor.get_u16_le(); let _unused = cursor.get_u16_le(); let _unused = cursor.get_u16_le(); patches.push(PatchPlacement { x, y, patch }); } cursor.clear(); cursor.done()?; Ok(Self { name, width, height, patches, }) } } #[derive(Clone, Debug)] struct PatchPlacement { pub x: u16, pub y: u16, pub patch: u16, } #[cfg(test)] mod tests { use super::*; use crate::assets::PatchBank; use crate::wad::test::*; #[test] fn load() { let patches = PatchBank::load(&BIOTECH_WAD).unwrap(); let textures = TextureBank::load(&BIOTECH_WAD).unwrap(); let exit_door = textures.get("EXITDOOR").unwrap(); assert_eq!(exit_door.name, "EXITDOOR"); assert_eq!(exit_door.width, 128); assert_eq!(exit_door.height, 72); assert_eq!(exit_door.patches.len(), 4); assert_eq!(exit_door.patches[0].x, 0); assert_eq!(exit_door.patches[0].y, 0); assert_eq!( patches.get(exit_door.patches[0].patch).unwrap().name, "DOOR3_6" ); assert_eq!(exit_door.patches[1].x, 64); assert_eq!(exit_door.patches[1].y, 0); assert_eq!( patches.get(exit_door.patches[1].patch).unwrap().name, "DOOR3_4" ); assert_eq!(exit_door.patches[2].x, 88); assert_eq!(exit_door.patches[2].y, 0); assert_eq!( patches.get(exit_door.patches[2].patch).unwrap().name, "DOOR3_5" ); assert_eq!(exit_door.patches[3].x, 112); assert_eq!(exit_door.patches[3].y, 0); assert_eq!( patches.get(exit_door.patches[3].patch).unwrap().name, "T14_5" ); } }
use std::collections::BTreeMap; use std::convert::TryInto; use std::ops::{Deref, Index}; use bytes::Buf; use crate::wad::{self, Lump, Wad}; #[derive(Clone, Debug)] pub struct TextureBank(BTreeMap<String, Texture>); impl TextureBank { pub fn load(wad: &Wad) -> wad::Result<Self> { let mut textures = BTreeMap::new(); for lump in Self::texture_lumps(wad)? { Self::load_from(&lump, &mut textures)?; } Ok(Self(textures)) } fn texture_lumps(wad: &Wad) -> wad::Result<Vec<Lump>> { let iter = Some(wad.lump("TEXTURE1")?).into_iter(); let iter = iter.chain(wad.try_lump("TEXTURE2")?); Ok(iter.collect()) } fn load_from(lump: &Lump, textures: &mut BTreeMap<String, Texture>) -> wad::Result<()> { let mut cursor = lump.cursor(); cursor.need(4)?; let count = cursor.get_u32_le(); let mut offsets = Vec::with_capacity(count.clamp(0, 1024) as usize); let need: usize = count .checked_mul(4) .ok_or_else(|| lump.error(format!("bad count {}", count)))? .try_into() .unwrap(); cursor.need(need)?; for _ in 0..count { offsets.push(cursor.get_u32_le()); } cursor.clear(); cursor.done()?; for offset in offsets { let texture = Texture::load(lum
pub fn get(&self, name: &str) -> Option<&Texture> { self.0.get(&name.to_ascii_uppercase()) } } impl Index<&str> for TextureBank { type Output = Texture; fn index(&self, name: &str) -> &Self::Output { self.get(name).expect("texture not found") } } impl Deref for TextureBank { type Target = BTreeMap<String, Texture>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug)] pub struct Texture { pub name: String, pub width: u16, pub height: u16, patches: Vec<PatchPlacement>, } impl Texture { fn load(lump: &Lump, offset: usize) -> wad::Result<Self> { let mut cursor = lump.cursor(); cursor.skip(offset)?; cursor.need(22)?; let name = cursor.get_name(); let _flags = cursor.get_u16_le(); let _unused = cursor.get_u16_le(); let width = cursor.get_u16_le(); let height = cursor.get_u16_le(); let _unused = cursor.get_u32_le(); let patch_count: usize = cursor.get_u16_le().into(); let mut patches = Vec::with_capacity(patch_count.clamp(0, 64)); cursor.need(patch_count * 10)?; for _ in 0..patch_count { let x = cursor.get_u16_le(); let y = cursor.get_u16_le(); let patch = cursor.get_u16_le(); let _unused = cursor.get_u16_le(); let _unused = cursor.get_u16_le(); patches.push(PatchPlacement { x, y, patch }); } cursor.clear(); cursor.done()?; Ok(Self { name, width, height, patches, }) } } #[derive(Clone, Debug)] struct PatchPlacement { pub x: u16, pub y: u16, pub patch: u16, } #[cfg(test)] mod tests { use super::*; use crate::assets::PatchBank; use crate::wad::test::*; #[test] fn load() { let patches = PatchBank::load(&BIOTECH_WAD).unwrap(); let textures = TextureBank::load(&BIOTECH_WAD).unwrap(); let exit_door = textures.get("EXITDOOR").unwrap(); assert_eq!(exit_door.name, "EXITDOOR"); assert_eq!(exit_door.width, 128); assert_eq!(exit_door.height, 72); assert_eq!(exit_door.patches.len(), 4); assert_eq!(exit_door.patches[0].x, 0); assert_eq!(exit_door.patches[0].y, 0); assert_eq!( patches.get(exit_door.patches[0].patch).unwrap().name, "DOOR3_6" ); assert_eq!(exit_door.patches[1].x, 64); assert_eq!(exit_door.patches[1].y, 0); assert_eq!( patches.get(exit_door.patches[1].patch).unwrap().name, "DOOR3_4" ); assert_eq!(exit_door.patches[2].x, 88); assert_eq!(exit_door.patches[2].y, 0); assert_eq!( patches.get(exit_door.patches[2].patch).unwrap().name, "DOOR3_5" ); assert_eq!(exit_door.patches[3].x, 112); assert_eq!(exit_door.patches[3].y, 0); assert_eq!( patches.get(exit_door.patches[3].patch).unwrap().name, "T14_5" ); } }
p, offset.try_into().unwrap())?; textures.insert(texture.name.clone(), texture); } Ok(()) }
function_block-function_prefixed
[ { "content": "#[derive(Debug)]\n\nstruct LumpLocation {\n\n pub offset: usize,\n\n pub size: usize,\n\n pub name: String,\n\n}\n\n\n\nimpl WadFile {\n\n /// Loads a WAD file from disk.\n\n pub fn load(path: impl AsRef<Path>) -> wad::Result<Arc<Self>> {\n\n let path = path.as_ref();\n\n ...
Rust
src/dataflow-types/src/client/controller/storage.rs
pjmore/materialize
5a46f9b30910679d504c94438b1d1c5ace4e80c7
use std::collections::BTreeMap; use differential_dataflow::lattice::Lattice; use timely::progress::{Antichain, Timestamp}; use tracing::error; use super::SinceUpperMap; use crate::client::SourceConnector; use crate::client::{Client, Command, StorageCommand}; use crate::Update; use mz_expr::GlobalId; use mz_expr::PartitionId; pub struct StorageControllerState<T> { source_descriptions: BTreeMap<GlobalId, Option<(crate::sources::SourceDesc, Antichain<T>)>>, pub(super) since_uppers: SinceUpperMap<T>, } pub struct StorageController<'a, C, T> { pub(super) storage: &'a mut StorageControllerState<T>, pub(super) client: &'a mut C, } #[derive(Debug)] pub enum StorageError { SourceIdReused(GlobalId), } impl<T> StorageControllerState<T> { pub(super) fn new() -> Self { Self { source_descriptions: BTreeMap::default(), since_uppers: SinceUpperMap::default(), } } } impl<'a, C: Client<T>, T: Timestamp + Lattice> StorageController<'a, C, T> { pub async fn create_sources( &mut self, mut bindings: Vec<(GlobalId, (crate::sources::SourceDesc, Antichain<T>))>, ) -> Result<(), StorageError> { bindings.sort_by_key(|b| b.0); bindings.dedup(); for pos in 1..bindings.len() { if bindings[pos - 1].0 == bindings[pos].0 { Err(StorageError::SourceIdReused(bindings[pos].0))?; } } for (id, description_since) in bindings.iter() { match self.storage.source_descriptions.get(&id) { Some(None) => Err(StorageError::SourceIdReused(*id))?, Some(Some(prior_description)) => { if prior_description != description_since { Err(StorageError::SourceIdReused(*id))? } } None => { } } } for (id, (description, since)) in bindings.iter() { self.storage .source_descriptions .insert(*id, Some((description.clone(), since.clone()))); self.storage.since_uppers.insert( *id, (since.clone(), Antichain::from_elem(Timestamp::minimum())), ); } self.client .send(Command::Storage(StorageCommand::CreateSources(bindings))) .await; Ok(()) } pub async fn drop_sources(&mut self, identifiers: Vec<GlobalId>) { for id in identifiers.iter() { if !self.storage.source_descriptions.contains_key(id) { error!("Source id {} dropped without first being created", id); } else { self.storage.source_descriptions.insert(*id, None); } } self.client .send(Command::Storage(StorageCommand::DropSources(identifiers))) .await } pub async fn table_insert(&mut self, id: GlobalId, updates: Vec<Update<T>>) { self.client .send(Command::Storage(StorageCommand::Insert { id, updates })) .await } pub async fn update_durability_frontiers(&mut self, updates: Vec<(GlobalId, Antichain<T>)>) { self.client .send(Command::Storage(StorageCommand::DurabilityFrontierUpdates( updates, ))) .await } pub async fn add_source_timestamping( &mut self, id: GlobalId, connector: SourceConnector, bindings: Vec<(PartitionId, T, crate::sources::MzOffset)>, ) { self.client .send(Command::Storage(StorageCommand::AddSourceTimestamping { id, connector, bindings, })) .await } pub async fn allow_source_compaction(&mut self, frontiers: Vec<(GlobalId, Antichain<T>)>) { for (id, frontier) in frontiers.iter() { self.storage.since_uppers.advance_since_for(*id, frontier); } self.client .send(Command::Storage(StorageCommand::AllowSourceCompaction( frontiers, ))) .await } pub async fn drop_source_timestamping(&mut self, id: GlobalId) { self.client .send(Command::Storage(StorageCommand::DropSourceTimestamping { id, })) .await } pub async fn advance_all_table_timestamps(&mut self, advance_to: T) { self.client .send(Command::Storage(StorageCommand::AdvanceAllLocalInputs { advance_to, })) .await } }
use std::collections::BTreeMap; use differential_dataflow::lattice::Lattice; use timely::progress::{Antichain, Timestamp}; use tracing::error; use super::SinceUpperMap; use crate::client::SourceConnector; use crate::client::{Client, Command, StorageCommand}; use crate::Update; use mz_expr::GlobalId; use mz_expr::PartitionId; pub struct StorageControllerState<T> { source_descriptions: BTreeMap<GlobalId, Option<(crate::sources::SourceDesc, Antichain<T>)>>, pub(super) since_uppers: SinceUpperMap<T>, } pub struct StorageController<'a, C, T> { pub(super) storage: &'a mut StorageControllerState<T>, pub(super) client: &'a mut C, } #[derive(Debug)] pub enum StorageError { SourceIdReused(GlobalId), } impl<T> StorageControllerState<T> { pub(super) fn new() -> Self { Self { source_descriptions: BTreeMap::default(), since_uppers: SinceUpperMap::default(), } } } impl<'a, C: Client<T>, T: Timestamp + Lattice> StorageController<'a, C, T> { pub async fn create_sources( &mut self, mut bindings: Vec<(GlobalId, (crate::sources::SourceDesc, Antichain<T>))>, ) -> Result<(), StorageError> { bindings.sort_by_key(|b| b.0); bindings.dedup(); for pos in 1..bindings.len() { if bindings[pos - 1].0 == bindings[pos].0 { Err(StorageError::SourceIdReused(bindings[pos].0))?; } } for (id, description_since) in bindings.iter() { match self.storage.source_descriptions.get(&id) { Some(None) => Err(StorageError::SourceIdReused(*id))?, Some(Some(prior_description)) => {
} None => { } } } for (id, (description, since)) in bindings.iter() { self.storage .source_descriptions .insert(*id, Some((description.clone(), since.clone()))); self.storage.since_uppers.insert( *id, (since.clone(), Antichain::from_elem(Timestamp::minimum())), ); } self.client .send(Command::Storage(StorageCommand::CreateSources(bindings))) .await; Ok(()) } pub async fn drop_sources(&mut self, identifiers: Vec<GlobalId>) { for id in identifiers.iter() { if !self.storage.source_descriptions.contains_key(id) { error!("Source id {} dropped without first being created", id); } else { self.storage.source_descriptions.insert(*id, None); } } self.client .send(Command::Storage(StorageCommand::DropSources(identifiers))) .await } pub async fn table_insert(&mut self, id: GlobalId, updates: Vec<Update<T>>) { self.client .send(Command::Storage(StorageCommand::Insert { id, updates })) .await } pub async fn update_durability_frontiers(&mut self, updates: Vec<(GlobalId, Antichain<T>)>) { self.client .send(Command::Storage(StorageCommand::DurabilityFrontierUpdates( updates, ))) .await } pub async fn add_source_timestamping( &mut self, id: GlobalId, connector: SourceConnector, bindings: Vec<(PartitionId, T, crate::sources::MzOffset)>, ) { self.client .send(Command::Storage(StorageCommand::AddSourceTimestamping { id, connector, bindings, })) .await } pub async fn allow_source_compaction(&mut self, frontiers: Vec<(GlobalId, Antichain<T>)>) { for (id, frontier) in frontiers.iter() { self.storage.since_uppers.advance_since_for(*id, frontier); } self.client .send(Command::Storage(StorageCommand::AllowSourceCompaction( frontiers, ))) .await } pub async fn drop_source_timestamping(&mut self, id: GlobalId) { self.client .send(Command::Storage(StorageCommand::DropSourceTimestamping { id, })) .await } pub async fn advance_all_table_timestamps(&mut self, advance_to: T) { self.client .send(Command::Storage(StorageCommand::AdvanceAllLocalInputs { advance_to, })) .await } }
if prior_description != description_since { Err(StorageError::SourceIdReused(*id))? }
if_condition
[ { "content": "pub fn build_compression(cmd: &mut BuiltinCommand) -> Result<Compression, anyhow::Error> {\n\n match cmd.args.opt_string(\"compression\") {\n\n Some(s) => s.parse(),\n\n None => Ok(Compression::None),\n\n }\n\n}\n\n\n", "file_path": "src/testdrive/src/action/file.rs", "...
Rust
src/driver/text.rs
jutuon/vga
678dc64cf3cb3fd17fb5bd3ce6cdb92f10fab64c
use volatile::Volatile; use crate::io::{ VIDEO_RAM_START_ADDRESS, MemoryMappedIo, PortIo, }; use crate::raw::{ VgaRegisters, }; pub use vga_framebuffer::Colour; use vga_framebuffer::Char; pub const TEXT_BUFFER_FIST_BYTE_ADDRESS: usize = 0xB8000; pub const VIDEO_RAM_BYTES_BEFORE_TEXT: usize = TEXT_BUFFER_FIST_BYTE_ADDRESS - VIDEO_RAM_START_ADDRESS; pub const VGA_TEXT_WIDTH: usize = 80; pub const VGA_TEXT_HEIGHT: usize = 25; pub const VGA_TEXT_CHAR_COUNT: usize = VGA_TEXT_WIDTH * VGA_TEXT_HEIGHT; pub const TEXT_BUFFER_BYTE_COUNT: usize = 80 * 25 * 2; pub struct TextMode<T: PortIo, U: MemoryMappedIo> { registers: VgaRegisters<T>, ram: U, } impl <T: PortIo, U: MemoryMappedIo> TextMode<T, U> { pub fn new(io: T, ram: U) -> Self { Self { registers: VgaRegisters::new(io), ram, } } pub fn vga_text_ram(&self) -> &[Volatile<u8>] { let (_, text_buffer_and_other_ram) = self.ram.video_ram().split_at(VIDEO_RAM_BYTES_BEFORE_TEXT); let (text_buffer, _) = text_buffer_and_other_ram.split_at(TEXT_BUFFER_BYTE_COUNT); text_buffer } pub fn vga_text_ram_mut(&mut self) -> &mut [Volatile<u8>] { let (_, text_buffer_and_other_ram) = self.ram.video_ram_mut().split_at_mut(VIDEO_RAM_BYTES_BEFORE_TEXT); let (text_buffer, _) = text_buffer_and_other_ram.split_at_mut(TEXT_BUFFER_BYTE_COUNT); text_buffer } pub fn vga_chars(&self) -> impl Iterator<Item=VgaCharRef<'_>> { VgaCharRef::raw_slice_to_ref_slice(self.vga_text_ram()) } pub fn vga_chars_mut(&mut self) -> impl Iterator<Item=VgaCharRefMut<'_>> { VgaCharRefMut::raw_slice_to_ref_mut_slice(self.vga_text_ram_mut()) } pub fn attribute_bit_7(&mut self, setting: AttributeBit7) { let value = setting == AttributeBit7::Blink; self.registers.attribute_controller().ar10().modify(|_, w| w.enable_blinking_slash_select_background_intensity().bit(value)); } pub fn read_char(&self, character_i: usize) -> VgaChar { self.vga_chars().nth(character_i).unwrap().read() } pub fn write_char(&mut self, character_i: usize, vga_char: VgaChar) { self.vga_chars_mut().nth(character_i).unwrap().write(vga_char) } pub fn clear_screen(&mut self, value: VgaChar) { for mut vga_char in self.vga_chars_mut() { vga_char.write(value) } } pub fn lines(&self) -> impl Iterator<Item=VgaCharLine<'_>> { self.vga_text_ram().chunks_exact(VGA_TEXT_WIDTH * 2).map(|raw_line| { VgaCharLine { raw_line } }) } pub fn lines_mut(&mut self) -> impl Iterator<Item=VgaCharLineMut<'_>> { self.vga_text_ram_mut().chunks_exact_mut(VGA_TEXT_WIDTH * 2).map(|raw_line| { VgaCharLineMut { raw_line } }) } pub fn copy_line_to(&mut self, src_i: usize, target_i: usize) { if src_i == target_i { return; } let src_and_target = self.lines_mut().enumerate().fold((None, None), |(src, target), (i, line)| { if i == src_i { return (Some(line), target) } if i == target_i { return (src, Some(line)) } (src, target) }); match src_and_target { (None, _) => panic!("source index '{}' is out of bounds", src_i), (_, None) => panic!("target index '{}' is out of bounds", target_i), (Some(src), Some(mut target)) => { target.write_line(&src) } } } pub fn scroll(&mut self) { self.scroll_range(..); } fn scroll_inclusive_range(&mut self, range: core::ops::RangeInclusive<usize>) { let (start_i, mut end_i) = range.into_inner(); if end_i < start_i { return; } if start_i >= VGA_TEXT_HEIGHT { return; } if end_i >= VGA_TEXT_HEIGHT { end_i = VGA_TEXT_HEIGHT - 1; } let (mut iter, copy_count) = if start_i == 0 { (self.lines_mut().skip(0), end_i) } else { (self.lines_mut().skip(start_i - 1), end_i - start_i + 1) }; let mut target = iter.next().unwrap(); let iter = iter.take(copy_count); for src in iter { target.write_line(&src); target = src; } } pub fn scroll_range<R: core::ops::RangeBounds<usize>>(&mut self, range: R) { use core::ops::Bound; let start_i = match range.start_bound() { Bound::Included(&i) => i, Bound::Excluded(&i) if i == usize::max_value() => return, Bound::Excluded(&i) => i + 1, Bound::Unbounded => 0, }; let end_i = match range.end_bound() { Bound::Included(&i) => i, Bound::Excluded(&i) if i == 0 => return, Bound::Excluded(&i) => i - 1, Bound::Unbounded => VGA_TEXT_HEIGHT - 1, }; self.scroll_inclusive_range(start_i..=end_i); } pub fn cursor_visibility(&mut self) -> bool { !self.registers.crt_controller().cr0a().read().text_cursor_off().bit() } pub fn set_cursor_visibility(&mut self, visible: bool) { self.registers.crt_controller().cr0a().modify(|_, w| w.text_cursor_off().bit(!visible)); } pub fn cursor_height(&mut self) -> (u8, u8) { let start = self.registers.crt_controller().cr0a().read().text_cursor_start().bits(); let end = self.registers.crt_controller().cr0b().read().text_cursor_end().bits(); (start, end) } pub fn set_cursor_height(&mut self, start: u8, end: u8) { assert!(start <= end, "error: start > end, start = {}, end = {}", start, end); self.registers.crt_controller().cr0a().modify(|_, w| w.text_cursor_start().bits(start)); self.registers.crt_controller().cr0b().modify(|_, w| w.text_cursor_end().bits(end)); } pub fn cursor_character_index(&mut self) -> Result<usize, IndexOutOfBounds> { let low_byte = self.registers.crt_controller().cr0f().read().text_cursor_location_low_byte().bits(); let high_byte = self.registers.crt_controller().cr0e().read().text_cursor_location_high_byte().bits(); let location = ((high_byte as u16) << 8) | low_byte as u16; if (location as usize) < VGA_TEXT_CHAR_COUNT { Ok(location as usize) } else { Err(IndexOutOfBounds(location)) } } pub fn set_cursor_character_index(&mut self, character_i: usize) { if character_i >= VGA_TEXT_CHAR_COUNT { panic!("Max value for character_i is '{}'", VGA_TEXT_CHAR_COUNT); } let low_byte = character_i as u8; let high_byte = (character_i >> 8) as u8; self.registers.crt_controller().cr0f().modify(|_, w| w.text_cursor_location_low_byte().bits(low_byte)); self.registers.crt_controller().cr0e().modify(|_, w| w.text_cursor_location_high_byte().bits(high_byte)); } } #[derive(Debug)] pub struct IndexOutOfBounds(pub u16); #[derive(Debug, Clone, Copy, PartialEq)] pub enum AttributeBit7 { Blink, Intensity, } pub struct VgaCharLine<'a> { raw_line: &'a [Volatile<u8>], } impl VgaCharLine<'_> { pub fn iter(&self) -> impl Iterator<Item=VgaCharRef<'_>> { VgaCharRef::raw_slice_to_ref_slice(self.raw_line) } } pub struct VgaCharLineMut<'a> { raw_line: &'a mut [Volatile<u8>], } impl VgaCharLineMut<'_> { pub fn iter_mut(&mut self) -> impl Iterator<Item=VgaCharRefMut<'_>> { VgaCharRefMut::raw_slice_to_ref_mut_slice(self.raw_line) } pub fn iter(&self) -> impl Iterator<Item=VgaCharRef<'_>> { VgaCharRef::raw_slice_to_ref_slice(self.raw_line) } pub fn write_line<'a, T: Into<VgaCharLine<'a>>>(&mut self, src: T) { for (src, mut target) in src.into().iter().zip(self.iter_mut()) { target.write(src.read()) } } pub fn clear_with(&mut self, value: VgaChar) { for mut target in self.iter_mut() { target.write(value) } } } impl <'a, 'b> From<&'b VgaCharLineMut<'a>> for VgaCharLine<'b> { fn from(value: &'b VgaCharLineMut<'a>) -> Self { Self { raw_line: value.raw_line } } } impl <'a> From<VgaCharLineMut<'a>> for VgaCharLine<'a> { fn from(value: VgaCharLineMut<'a>) -> Self { Self { raw_line: value.raw_line } } } pub struct VgaCharRef<'a> { character: &'a Volatile<u8>, attributes: &'a Volatile<u8>, } impl VgaCharRef<'_> { fn raw_slice_to_ref_slice(raw: &[Volatile<u8>]) -> impl Iterator<Item=VgaCharRef<'_>> { raw.chunks_exact(2).map(|data| { VgaCharRef { character: &data[0], attributes: &data[1], } }) } pub fn read(&self) -> VgaChar { VgaChar { character: self.character.read(), attributes: self.attributes.read(), } } } pub struct VgaCharRefMut<'a> { character: &'a mut Volatile<u8>, attributes: &'a mut Volatile<u8>, } impl VgaCharRefMut<'_> { fn raw_slice_to_ref_mut_slice(raw: &mut [Volatile<u8>]) -> impl Iterator<Item=VgaCharRefMut<'_>> { raw.chunks_exact_mut(2).map(|data| { let (character, attributes) = data.split_first_mut().unwrap(); VgaCharRefMut { character: character, attributes: &mut attributes[0], } }) } fn as_ref(&self) -> VgaCharRef<'_> { VgaCharRef { character: self.character, attributes: self.attributes, } } pub fn write(&mut self, value: VgaChar) { self.character.write(value.character); self.attributes.write(value.attributes); } pub fn read(&self) -> VgaChar { self.as_ref().read() } } #[derive(Debug, Clone, Copy, PartialEq)] pub struct VgaChar { pub character: u8, pub attributes: u8, } impl VgaChar { const FOREGROUND_COLOR_MASK: u8 = 0b0000_0111; const FOREGROUND_INTENSITY_MASK: u8 = 0b0000_1000; const BACKGROUND_COLOR_MASK: u8 = 0b0111_0000; const BACKGROUND_INTENSITY_OR_BLINK_MASK: u8 = 0b1000_0000; pub fn empty() -> Self { Self { character: 0, attributes: 0, } } pub fn new(c: char) -> Self { Self::empty().character(c) } pub fn character(mut self, c: char) -> Self { self.character = Char::map_char(c).to_byte(); self } pub fn foreground_color(mut self, color: Colour) -> Self { self.attributes &= !Self::FOREGROUND_COLOR_MASK; self.attributes |= color as u8; self } pub fn foreground_intensity(mut self, value: bool) -> Self { if value { self.attributes |= Self::FOREGROUND_INTENSITY_MASK; } else { self.attributes &= !Self::FOREGROUND_INTENSITY_MASK; } self } pub fn background_color(mut self, color: Colour) -> Self { self.attributes &= !Self::BACKGROUND_COLOR_MASK; let value = (color as u8) << 4; self.attributes |= value; self } fn bit_7(mut self, value: bool) -> Self { if value { self.attributes |= Self::BACKGROUND_INTENSITY_OR_BLINK_MASK; } else { self.attributes &= !Self::BACKGROUND_INTENSITY_OR_BLINK_MASK; } self } pub fn blink(self, value: bool) -> Self { self.bit_7(value) } pub fn background_intensity(self, value: bool) -> Self { self.bit_7(value) } }
use volatile::Volatile; use crate::io::{ VIDEO_RAM_START_ADDRESS, MemoryMappedIo, PortIo, }; use crate::raw::{ VgaRegisters, }; pub use vga_framebuffer::Colour; use vga_framebuffer::Char; pub const TEXT_BUFFER_FIST_BYTE_ADDRESS: usize = 0xB8000; pub const VIDEO_RAM_BYTES_BEFORE_TEXT: usize = TEXT_BUFFER_FIST_BYTE_ADDRESS - VIDEO_RAM_START_ADDRESS; pub const VGA_TEXT_WIDTH: usize = 80; pub const VGA_TEXT_HEIGHT: usize = 25; pub const VGA_TEXT_CHAR_COUNT: usize = VGA_TEXT_WIDTH * VGA_TEXT_HEIGHT; pub const TEXT_BUFFER_BYTE_COUNT: usize = 80 * 25 * 2; pub struct TextMode<T: PortIo, U: MemoryMappedIo> { registers: VgaRegisters<T>, ram: U, } impl <T: PortIo, U: MemoryMappedIo> TextMode<T, U> { pub fn new(io: T, ram: U) -> Self { Self { registers: VgaRegisters::new(io), ram, } } pub fn vga_text_ram(&self) -> &[Volatile<u8>] { let (_, text_buffer_and_other_ram) = self.ram.video_ram().split_at(VIDEO_RAM_BYTES_BEFORE_TEXT); let (text_buffer, _) = text_buffer_and_other_ram.split_at(TEXT_BUFFER_BYTE_COUNT); text_buffer } pub fn vga_text_ram_mut(&mut self) -> &mut [Volatile<u8>] { let (_, text_buffer_and_other_ram) = self.ram.video_ram_mut().split_at_mut(VIDEO_RAM_BYTES_BEFORE_TEXT); let (text_buffer, _) = text_buffer_and_other_ram.split_at_mut(TEXT_BUFFER_BYTE_COUNT); text_buffer } pub fn vga_chars(&self) -> impl Iterator<Item=VgaCharRef<'_>> { VgaCharRef::raw_slice_to_ref_slice(self.vga_text_ram()) } pub fn vga_chars_mut(&mut self) -> impl Iterator<Item=VgaCharRefMut<'_>> { VgaCharRefMut::raw_slice_to_ref_mut_slice(self.vga_text_ram_mut()) } pub fn attribute_bit_7(&mut self, setting: AttributeBit7) { let value = setting == AttributeBit7::Blink; self.registers.attribute_controller().ar10().modify(|_, w| w.enable_blinking_slash_select_background_intensity().bit(value)); } pub fn read_char(&self, character_i: usize)
rator<Item=VgaCharRefMut<'_>> { VgaCharRefMut::raw_slice_to_ref_mut_slice(self.raw_line) } pub fn iter(&self) -> impl Iterator<Item=VgaCharRef<'_>> { VgaCharRef::raw_slice_to_ref_slice(self.raw_line) } pub fn write_line<'a, T: Into<VgaCharLine<'a>>>(&mut self, src: T) { for (src, mut target) in src.into().iter().zip(self.iter_mut()) { target.write(src.read()) } } pub fn clear_with(&mut self, value: VgaChar) { for mut target in self.iter_mut() { target.write(value) } } } impl <'a, 'b> From<&'b VgaCharLineMut<'a>> for VgaCharLine<'b> { fn from(value: &'b VgaCharLineMut<'a>) -> Self { Self { raw_line: value.raw_line } } } impl <'a> From<VgaCharLineMut<'a>> for VgaCharLine<'a> { fn from(value: VgaCharLineMut<'a>) -> Self { Self { raw_line: value.raw_line } } } pub struct VgaCharRef<'a> { character: &'a Volatile<u8>, attributes: &'a Volatile<u8>, } impl VgaCharRef<'_> { fn raw_slice_to_ref_slice(raw: &[Volatile<u8>]) -> impl Iterator<Item=VgaCharRef<'_>> { raw.chunks_exact(2).map(|data| { VgaCharRef { character: &data[0], attributes: &data[1], } }) } pub fn read(&self) -> VgaChar { VgaChar { character: self.character.read(), attributes: self.attributes.read(), } } } pub struct VgaCharRefMut<'a> { character: &'a mut Volatile<u8>, attributes: &'a mut Volatile<u8>, } impl VgaCharRefMut<'_> { fn raw_slice_to_ref_mut_slice(raw: &mut [Volatile<u8>]) -> impl Iterator<Item=VgaCharRefMut<'_>> { raw.chunks_exact_mut(2).map(|data| { let (character, attributes) = data.split_first_mut().unwrap(); VgaCharRefMut { character: character, attributes: &mut attributes[0], } }) } fn as_ref(&self) -> VgaCharRef<'_> { VgaCharRef { character: self.character, attributes: self.attributes, } } pub fn write(&mut self, value: VgaChar) { self.character.write(value.character); self.attributes.write(value.attributes); } pub fn read(&self) -> VgaChar { self.as_ref().read() } } #[derive(Debug, Clone, Copy, PartialEq)] pub struct VgaChar { pub character: u8, pub attributes: u8, } impl VgaChar { const FOREGROUND_COLOR_MASK: u8 = 0b0000_0111; const FOREGROUND_INTENSITY_MASK: u8 = 0b0000_1000; const BACKGROUND_COLOR_MASK: u8 = 0b0111_0000; const BACKGROUND_INTENSITY_OR_BLINK_MASK: u8 = 0b1000_0000; pub fn empty() -> Self { Self { character: 0, attributes: 0, } } pub fn new(c: char) -> Self { Self::empty().character(c) } pub fn character(mut self, c: char) -> Self { self.character = Char::map_char(c).to_byte(); self } pub fn foreground_color(mut self, color: Colour) -> Self { self.attributes &= !Self::FOREGROUND_COLOR_MASK; self.attributes |= color as u8; self } pub fn foreground_intensity(mut self, value: bool) -> Self { if value { self.attributes |= Self::FOREGROUND_INTENSITY_MASK; } else { self.attributes &= !Self::FOREGROUND_INTENSITY_MASK; } self } pub fn background_color(mut self, color: Colour) -> Self { self.attributes &= !Self::BACKGROUND_COLOR_MASK; let value = (color as u8) << 4; self.attributes |= value; self } fn bit_7(mut self, value: bool) -> Self { if value { self.attributes |= Self::BACKGROUND_INTENSITY_OR_BLINK_MASK; } else { self.attributes &= !Self::BACKGROUND_INTENSITY_OR_BLINK_MASK; } self } pub fn blink(self, value: bool) -> Self { self.bit_7(value) } pub fn background_intensity(self, value: bool) -> Self { self.bit_7(value) } }
-> VgaChar { self.vga_chars().nth(character_i).unwrap().read() } pub fn write_char(&mut self, character_i: usize, vga_char: VgaChar) { self.vga_chars_mut().nth(character_i).unwrap().write(vga_char) } pub fn clear_screen(&mut self, value: VgaChar) { for mut vga_char in self.vga_chars_mut() { vga_char.write(value) } } pub fn lines(&self) -> impl Iterator<Item=VgaCharLine<'_>> { self.vga_text_ram().chunks_exact(VGA_TEXT_WIDTH * 2).map(|raw_line| { VgaCharLine { raw_line } }) } pub fn lines_mut(&mut self) -> impl Iterator<Item=VgaCharLineMut<'_>> { self.vga_text_ram_mut().chunks_exact_mut(VGA_TEXT_WIDTH * 2).map(|raw_line| { VgaCharLineMut { raw_line } }) } pub fn copy_line_to(&mut self, src_i: usize, target_i: usize) { if src_i == target_i { return; } let src_and_target = self.lines_mut().enumerate().fold((None, None), |(src, target), (i, line)| { if i == src_i { return (Some(line), target) } if i == target_i { return (src, Some(line)) } (src, target) }); match src_and_target { (None, _) => panic!("source index '{}' is out of bounds", src_i), (_, None) => panic!("target index '{}' is out of bounds", target_i), (Some(src), Some(mut target)) => { target.write_line(&src) } } } pub fn scroll(&mut self) { self.scroll_range(..); } fn scroll_inclusive_range(&mut self, range: core::ops::RangeInclusive<usize>) { let (start_i, mut end_i) = range.into_inner(); if end_i < start_i { return; } if start_i >= VGA_TEXT_HEIGHT { return; } if end_i >= VGA_TEXT_HEIGHT { end_i = VGA_TEXT_HEIGHT - 1; } let (mut iter, copy_count) = if start_i == 0 { (self.lines_mut().skip(0), end_i) } else { (self.lines_mut().skip(start_i - 1), end_i - start_i + 1) }; let mut target = iter.next().unwrap(); let iter = iter.take(copy_count); for src in iter { target.write_line(&src); target = src; } } pub fn scroll_range<R: core::ops::RangeBounds<usize>>(&mut self, range: R) { use core::ops::Bound; let start_i = match range.start_bound() { Bound::Included(&i) => i, Bound::Excluded(&i) if i == usize::max_value() => return, Bound::Excluded(&i) => i + 1, Bound::Unbounded => 0, }; let end_i = match range.end_bound() { Bound::Included(&i) => i, Bound::Excluded(&i) if i == 0 => return, Bound::Excluded(&i) => i - 1, Bound::Unbounded => VGA_TEXT_HEIGHT - 1, }; self.scroll_inclusive_range(start_i..=end_i); } pub fn cursor_visibility(&mut self) -> bool { !self.registers.crt_controller().cr0a().read().text_cursor_off().bit() } pub fn set_cursor_visibility(&mut self, visible: bool) { self.registers.crt_controller().cr0a().modify(|_, w| w.text_cursor_off().bit(!visible)); } pub fn cursor_height(&mut self) -> (u8, u8) { let start = self.registers.crt_controller().cr0a().read().text_cursor_start().bits(); let end = self.registers.crt_controller().cr0b().read().text_cursor_end().bits(); (start, end) } pub fn set_cursor_height(&mut self, start: u8, end: u8) { assert!(start <= end, "error: start > end, start = {}, end = {}", start, end); self.registers.crt_controller().cr0a().modify(|_, w| w.text_cursor_start().bits(start)); self.registers.crt_controller().cr0b().modify(|_, w| w.text_cursor_end().bits(end)); } pub fn cursor_character_index(&mut self) -> Result<usize, IndexOutOfBounds> { let low_byte = self.registers.crt_controller().cr0f().read().text_cursor_location_low_byte().bits(); let high_byte = self.registers.crt_controller().cr0e().read().text_cursor_location_high_byte().bits(); let location = ((high_byte as u16) << 8) | low_byte as u16; if (location as usize) < VGA_TEXT_CHAR_COUNT { Ok(location as usize) } else { Err(IndexOutOfBounds(location)) } } pub fn set_cursor_character_index(&mut self, character_i: usize) { if character_i >= VGA_TEXT_CHAR_COUNT { panic!("Max value for character_i is '{}'", VGA_TEXT_CHAR_COUNT); } let low_byte = character_i as u8; let high_byte = (character_i >> 8) as u8; self.registers.crt_controller().cr0f().modify(|_, w| w.text_cursor_location_low_byte().bits(low_byte)); self.registers.crt_controller().cr0e().modify(|_, w| w.text_cursor_location_high_byte().bits(high_byte)); } } #[derive(Debug)] pub struct IndexOutOfBounds(pub u16); #[derive(Debug, Clone, Copy, PartialEq)] pub enum AttributeBit7 { Blink, Intensity, } pub struct VgaCharLine<'a> { raw_line: &'a [Volatile<u8>], } impl VgaCharLine<'_> { pub fn iter(&self) -> impl Iterator<Item=VgaCharRef<'_>> { VgaCharRef::raw_slice_to_ref_slice(self.raw_line) } } pub struct VgaCharLineMut<'a> { raw_line: &'a mut [Volatile<u8>], } impl VgaCharLineMut<'_> { pub fn iter_mut(&mut self) -> impl Ite
random
[ { "content": " pub trait RegisterRelIoW<T: RegisterGroup, U: Sized> {\n\n fn write(&mut self, rel_address: u16, value: U);\n\n }\n", "file_path": "src/raw/generated.rs", "rank": 0, "score": 79613.21741051001 }, { "content": " pub trait RegisterAbsIoW<T: RegisterGroup, U: Size...
Rust
src/lib/fixture_tests.rs
loalang/loalang
745edc192564b3f362ad1623fbb8853fcefa876e
use crate::optimization::Optimizable; use crate::*; use serde::Deserialize; extern crate serde_yaml; extern crate simple_logging; #[derive(Deserialize)] struct FixtureConfig { main_class: Option<String>, expected: FixtureExpectations, } #[derive(Deserialize)] struct FixtureExpectations { success: bool, stdout: Vec<String>, } #[test] fn fixtures() { simple_logging::log_to_stderr(LevelFilter::Debug); let mut failures = vec![]; for entry in glob::glob("src/__fixtures__/*").unwrap() { let entry = entry.unwrap(); let fixture_name = entry.file_name().and_then(std::ffi::OsStr::to_str).unwrap(); eprintln!("\n{} ===============================", fixture_name); if fixture_name.starts_with("_") { eprintln!("Skipping"); continue; } eprintln!("Parsing."); let mut fixture_config_path = entry.clone(); fixture_config_path.push("fixture.yml"); let fixture_config: FixtureConfig = serde_yaml::from_reader(std::fs::File::open(fixture_config_path).unwrap()).unwrap(); let mut source_files_path = entry.clone(); source_files_path.push("**"); source_files_path.push("*.loa"); let mut diagnostics = vec![]; let mut test_comments = vec![]; let mut sources = Source::files(source_files_path.to_str().unwrap()).unwrap(); sources.extend(Source::stdlib().unwrap()); if let Some(ref main_class) = fixture_config.main_class { sources.push(Source::main(main_class)); } eprintln!("Analyzing."); let mut analysis: semantics::Analysis = sources .into_iter() .map(syntax::Parser::new) .map(syntax::Parser::parse_with_test_comments) .map(|(t, d, c)| { diagnostics.extend(d); test_comments.extend(c); (t.source.uri.clone(), t) }) .into(); diagnostics.extend(analysis.check().clone()); let actual_success = !Diagnostic::failed(&diagnostics); 'expected_comment: for comment in test_comments.iter() { for diagnostic in diagnostics.iter() { if matches(comment, diagnostic) { continue 'expected_comment; } } failures.push(format!( "Expected diagnostic: {:?} @ {}", comment.lexeme(), comment.span )); } 'actual_diagnostic: for diagnostic in diagnostics { for comment in test_comments.iter() { if matches(comment, &diagnostic) { continue 'actual_diagnostic; } } failures.push(format!("Unexpected diagnostic: {:#?}", diagnostic)); } if !actual_success { continue; } if let Some(_) = fixture_config.main_class { eprintln!("Generating."); let mut generator = generation::Generator::new(&mut analysis); let mut assembly = generator.generate_all().unwrap(); eprintln!("Optimizing."); assembly.optimize(); eprintln!("Running."); eprintln!("{:?}", assembly); let mut vm = vm::VM::new(); let result = vm.eval_pop::<()>(assembly.clone().into()).unwrap(); let actual_stdout = format!("{}\n", result); let expected_stdout: String = fixture_config .expected .stdout .into_iter() .map(|s| format!("{}\n", s)) .collect(); if actual_stdout != expected_stdout { failures.push(format!( "{}:\nExpected output: {}\n Actual output: {}", fixture_name, expected_stdout, actual_stdout )); } } if fixture_config.expected.success != actual_success { failures.push(format!( "Expected {} to {}", fixture_name, if fixture_config.expected.success { "be successful" } else { "fail" } )); } } assert!(failures.is_empty(), "\n\n{}", failures.join("\n\n")); } fn matches(comment: &syntax::Token, diagnostic: &Diagnostic) -> bool { let d_span = diagnostic.span(); ( comment.span.start.line, comment.span.start.uri.clone(), &comment.lexeme()[4..], ) == ( d_span.start.line, d_span.start.uri.clone(), diagnostic.to_string().as_str(), ) }
use crate::optimization::Optimizable; use crate::*; use serde::Deserialize; extern crate serde_yaml; extern crate simple_logging; #[derive(Deserialize)] struct FixtureConfig { main_class: Option<String>, expected: FixtureExpectations, } #[derive(Deserialize)] struct FixtureExpectations { success: bool, stdout: Vec<String>, } #[test] fn fixtures() { simple_logging::log_to_stderr(LevelFilter::Debug); let mut failures = vec![]; for entry in glob::glob("src/__fixtures__/*").unwrap() { let entry = entry.unwrap(); let fixture_name = entry.file_name().and_then(std::ffi::OsStr::to_str).unwrap(); eprintln!("\n{} ===============================", fixture_name); if fixture_name.starts_with("_") { eprintln!("Skipping"); continue; } eprintln!("Parsing."); let mut fixture_config_path = entry.clone(); fixture_config_path.push("fixture.yml"); let fixture_config: FixtureConfig = serde_yaml::from_reader(std::fs::File::open(fixture_config_path).unwrap()).unwrap(); let mut source_files_path = entry.clone(); source_files_path.push("**"); source_files_path.push("*.loa"); let mut diagnostics = vec![]; let mut test_comments = vec![]; let mut sources = Source::files(source_files_path.to_str().unwrap()).unwrap(); sources.extend(Source::stdlib().unwrap()); if let Some(ref main_class) = fixture_config.main_class { sources.push(Source::main(main_class)); } eprintln!("Analyzing."); let mut analysis: semantics::Analysis = sources .into_iter() .map(syntax::Parser::new) .map(syntax::Parser::parse_with_test_comments) .map(|(t, d, c)| { diagnostics.extend(d); test_comments.extend(c); (t.source.uri.clone(), t) }) .into(); diagnostics.extend(analysis.check().clone()); let actual_success = !Diagnostic::failed(&diagnostics); 'expected_comment: for comment in test_comments.iter() { for diagnostic in diagnostics.iter() { if matches(comment, diagnostic) { continue 'expected_comment; } } failures.push(format!( "Expected diagnostic: {:?} @ {}", comment.lexeme(), comment.span )); } 'actual_diagnostic: for diagnostic in diagnostics { for comment in test_comments.iter() { if matches(comment, &diagnostic) { continue 'actual_diagnostic; } } failures.push(format!("Unexpected diagnostic: {:#?}", diagnostic)); } if !actual_success { continue; } if let Some(_) = fixture_config.main_class { eprintln!("Generating."); let mut generator = generation::Generator::new(&mut analysis); let mut assembly = generator.generate_all().unwrap(); eprintln!("Optimizing."); assembly.optimize(); eprintln!("Running."); eprintln!("{:?}", assembly); let mut vm = vm::VM::new(); let result = vm.eval_pop::<()>(assembly.clone().into()).unwrap(); let actual_stdout = format!("{}\n", result); let expected_stdout: String = fixture_config .expected .stdout .into_iter() .map(|s| format!("{}\n", s)) .collect(); if actual_stdout != expected_stdout { failures.push(format!( "{}:\nExpected output: {}\n Actual output: {}", fixture_name, expected_stdout, actual_stdout )); } } if fixture_config.expected.success != actual_success { failures.push(format!( "Expected {} to {}", fixture_name, if fixture_config.expected.success { "be successful" } else { "fail" } )); } } assert!(failures.is_empty(), "\n\n{}", failures.join("\n\n")); } fn matches(comment: &syntax::Token, diagnostic: &Diagnostic) -> bool { let d_span = diagnostic.spa
n(); ( comment.span.start.line, comment.span.start.uri.clone(), &comment.lexeme()[4..], ) == ( d_span.start.line, d_span.start.uri.clone(), diagnostic.to_string().as_str(), ) }
function_block-function_prefixed
[ { "content": "pub fn is_valid_symbol(string: &String) -> bool {\n\n let source = Source::new(SourceKind::Module, URI::Exact(\"tmp\".into()), string.clone());\n\n let tokens = tokenize(source);\n\n\n\n tokens.len() == 2 && matches!(tokens[0].kind, TokenKind::SimpleSymbol(_))\n\n}\n\n\n", "file_path"...
Rust
src/api/process/process.rs
DaanA32/lunatic
b7dc3f98e10c50337526f8a42cb39032f7b4b9be
use anyhow::Result; use async_wormhole::{ stack::{OneMbStack, Stack}, AsyncWormhole, AsyncYielder, }; use lazy_static::lazy_static; use smol::{Executor as TaskExecutor, Task}; use uptown_funk::{Executor, FromWasm, HostFunctions, ToWasm}; use crate::module::{LunaticModule, Runtime}; use crate::{ api::{channel::ChannelReceiver, heap_profiler::HeapProfilerState}, linker::*, }; use log::info; use std::future::Future; use super::api::ProcessState; lazy_static! { pub static ref EXECUTOR: TaskExecutor<'static> = TaskExecutor::new(); } pub enum FunctionLookup { TableIndex(u32), Name(&'static str), } #[derive(Clone)] pub enum MemoryChoice { Existing, New(Option<u32>), } pub struct Process { task: Task<Result<()>>, } impl Process { pub fn task(self) -> Task<Result<()>> { self.task } pub fn create_with_api<A>( module: LunaticModule, function: FunctionLookup, memory: MemoryChoice, api: A, ) -> anyhow::Result<(A::Return, impl Future<Output = Result<()>>)> where A: HostFunctions + 'static, A::Wrap: Send, { let created_at = std::time::Instant::now(); let runtime = module.runtime(); let (ret, api) = api.split(); let stack = OneMbStack::new()?; let mut process = AsyncWormhole::new(stack, move |yielder| { let yielder_ptr = &yielder as *const AsyncYielder<anyhow::Result<()>> as usize; match module.runtime() { Runtime::Wasmtime => { let mut linker = WasmtimeLunaticLinker::new(module, yielder_ptr, memory)?; linker.add_api::<A>(api); let instance = linker.instance()?; match function { FunctionLookup::Name(name) => { let func = instance.get_func(name).ok_or_else(|| { anyhow::Error::msg(format!( "No function {} in wasmtime instance", name )) })?; let performance_timer = std::time::Instant::now(); func.call(&[])?; info!(target: "performance", "Process {} finished in {:.5} ms.", name, performance_timer.elapsed().as_secs_f64() * 1000.0); } FunctionLookup::TableIndex(index) => { let func = instance.get_func("lunatic_spawn_by_index").ok_or_else(|| { anyhow::Error::msg( "No function lunatic_spawn_by_index in wasmtime instance", ) })?; func.call(&[(index as i32).into()])?; } } Ok(()) } } })?; let mut wasmtime_cts_saver = super::tls::CallThreadStateSaveWasmtime::new(); process.set_pre_post_poll(move || match runtime { Runtime::Wasmtime => wasmtime_cts_saver.swap(), }); info!(target: "performance", "Total time {:.5} ms.", created_at.elapsed().as_secs_f64() * 1000.0); Ok((ret, process)) } pub async fn create( context_receiver: Option<ChannelReceiver>, module: LunaticModule, function: FunctionLookup, memory: MemoryChoice, profiler: <HeapProfilerState as HostFunctions>::Wrap, ) -> Result<()> { let api = crate::api::default::DefaultApi::new(context_receiver, module.clone()); let ((p, _), fut) = Process::create_with_api(module, function, memory, api)?; profiler.lock().unwrap().add_process(p.clone()); fut.await?; p.lock().unwrap().free_all(); Ok(()) } pub fn spawn<Fut>(future: Fut) -> Self where Fut: Future<Output = Result<()>> + Send + 'static, { let task = EXECUTOR.spawn(future); Self { task } } } impl ToWasm<&mut ProcessState> for Process { type To = u32; fn to( state: &mut ProcessState, _: &impl Executor, process: Self, ) -> Result<u32, uptown_funk::Trap> { Ok(state.processes.add(process)) } } impl FromWasm<&mut ProcessState> for Process { type From = u32; fn from( state: &mut ProcessState, _: &impl Executor, process_id: u32, ) -> Result<Self, uptown_funk::Trap> where Self: Sized, { match state.processes.remove(process_id) { Some(process) => Ok(process), None => Err(uptown_funk::Trap::new("Process not found")), } } }
use anyhow::Result; use async_wormhole::{ stack::{OneMbStack, Stack}, AsyncWormhole, AsyncYielder, }; use lazy_static::lazy_static; use smol::{Executor as TaskExecutor, Task}; use uptown_funk::{Executor, FromWasm, HostFunctions, ToWasm}; use crate::module::{LunaticModule, Runtime}; use crate::{ api::{channel::ChannelReceiver, heap_profiler::HeapProfilerState}, linker::*, }; use log::info; use std::future::Future; use super::api::ProcessState; lazy_static! { pub static ref EXECUTOR: TaskExecutor<'static> = TaskExecutor::new(); } pub enum FunctionLookup { TableIndex(u32), Name(&'static str), } #[derive(Clone)] pub enum MemoryChoice { Existing, New(Option<u32>), } pub struct Process { task: Task<Result<()>>, } impl Process { pub fn task(self) -> Task<Result<()>> { self.task } pub fn create_with_api<A>( module: LunaticModule, function: FunctionLookup, memory: MemoryChoice, api: A, ) -> anyhow::Result<(A::Return, impl Future<Output = Result<()>>)> where A: HostFunctions + 'static, A::Wrap: Send, { let created_at = std::time::Instant::now(); let runtime = module.runtime(); let (ret, api) = api.split(); let stack = OneMbStack::new()?; let mut process = AsyncWormhole::new(stack, move |yielder| { let yielder_ptr = &yielder as *const AsyncYielder<anyhow::Result<()>> as usize; match module.runtime() { Runtime::Wasmtime => { let mut linker = WasmtimeLunaticLinker::new(module, yielder_ptr, memory)?; linker.add_api::<A>(api); let instance = linker.instance()?; match function { FunctionLookup::Name(name) => {
pub async fn create( context_receiver: Option<ChannelReceiver>, module: LunaticModule, function: FunctionLookup, memory: MemoryChoice, profiler: <HeapProfilerState as HostFunctions>::Wrap, ) -> Result<()> { let api = crate::api::default::DefaultApi::new(context_receiver, module.clone()); let ((p, _), fut) = Process::create_with_api(module, function, memory, api)?; profiler.lock().unwrap().add_process(p.clone()); fut.await?; p.lock().unwrap().free_all(); Ok(()) } pub fn spawn<Fut>(future: Fut) -> Self where Fut: Future<Output = Result<()>> + Send + 'static, { let task = EXECUTOR.spawn(future); Self { task } } } impl ToWasm<&mut ProcessState> for Process { type To = u32; fn to( state: &mut ProcessState, _: &impl Executor, process: Self, ) -> Result<u32, uptown_funk::Trap> { Ok(state.processes.add(process)) } } impl FromWasm<&mut ProcessState> for Process { type From = u32; fn from( state: &mut ProcessState, _: &impl Executor, process_id: u32, ) -> Result<Self, uptown_funk::Trap> where Self: Sized, { match state.processes.remove(process_id) { Some(process) => Ok(process), None => Err(uptown_funk::Trap::new("Process not found")), } } }
let func = instance.get_func(name).ok_or_else(|| { anyhow::Error::msg(format!( "No function {} in wasmtime instance", name )) })?; let performance_timer = std::time::Instant::now(); func.call(&[])?; info!(target: "performance", "Process {} finished in {:.5} ms.", name, performance_timer.elapsed().as_secs_f64() * 1000.0); } FunctionLookup::TableIndex(index) => { let func = instance.get_func("lunatic_spawn_by_index").ok_or_else(|| { anyhow::Error::msg( "No function lunatic_spawn_by_index in wasmtime instance", ) })?; func.call(&[(index as i32).into()])?; } } Ok(()) } } })?; let mut wasmtime_cts_saver = super::tls::CallThreadStateSaveWasmtime::new(); process.set_pre_post_poll(move || match runtime { Runtime::Wasmtime => wasmtime_cts_saver.swap(), }); info!(target: "performance", "Total time {:.5} ms.", created_at.elapsed().as_secs_f64() * 1000.0); Ok((ret, process)) }
function_block-function_prefix_line
[ { "content": "/// Adds WASM functions required by the stdlib implementation:\n\n/// * `lunatic_spawn_by_index(i32)`\n\n/// - receives the index of the function (in the table) to be called indirectly.\n\npub fn patch(module: &mut Module) -> Result<()> {\n\n if let Some(main_function_table) = module.tables.m...
Rust
connectorx/src/s3.rs
Yizhou150/connector-x
3c56c539d29bc252d205a20700edd63efec301ab
use anyhow::Error; use arrow::datatypes::{Schema, SchemaRef}; use arrow::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; use arrow::json::reader::ReaderBuilder; use arrow::record_batch::RecordBatch; use fehler::throws; use flate2::read::GzDecoder; use futures::stream::{FuturesOrdered, StreamExt}; use futures::TryFutureExt; use rusoto_core::Region; use rusoto_s3::{GetObjectOutput, GetObjectRequest, S3Client, S3}; use serde_json::{from_str, Value}; use std::collections::HashMap; use std::io::{Cursor, Read}; use std::sync::Arc; use strum::EnumString; use tokio::io::AsyncReadExt; use tokio::task::spawn_blocking; #[derive(Debug, Clone, Copy, EnumString)] pub enum JsonFormat { JsonL, Array, } #[throws(Error)] pub async fn read_s3<S>( bucket: &str, objects: &[S], schema: &str, json_format: JsonFormat, ) -> HashMap<String, Vec<(*const FFI_ArrowArray, *const FFI_ArrowSchema)>> where S: AsRef<str>, { let client = S3Client::new(Region::UsWest2); let schema = Arc::new(Schema::from(&from_str::<Value>(schema)?)?); let mut futs: FuturesOrdered<_> = objects .iter() .map(|obj| { client .get_object(GetObjectRequest { bucket: bucket.into(), key: obj.as_ref().to_string(), ..Default::default() }) .err_into() .and_then(|resp| read_as_record_batch(resp, schema.clone(), json_format)) }) .collect(); let mut table = HashMap::new(); while let Some(rb) = futs.next().await { if let Some(batches) = rb? { for batch in batches { for (i, f) in batch.schema().fields().iter().enumerate() { use arrow::datatypes::DataType::*; match f.data_type() { Null | Boolean | Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64 | Float16 | Float32 | Float64 | Utf8 | LargeUtf8 | Binary | LargeBinary => {} _ => continue, } table .entry(f.name().clone()) .or_insert_with(Vec::new) .push(batch.column(i).to_raw()?) } } } } table } #[throws(Error)] async fn read_as_record_batch( payload: GetObjectOutput, schema: SchemaRef, json_format: JsonFormat, ) -> Option<Vec<RecordBatch>> { if payload.body.as_ref().is_none() { return None; } let mut buf = vec![]; payload .body .unwrap() .into_async_read() .read_to_end(&mut buf) .await?; let batches = spawn_blocking(move || -> Result<_, Error> { let mut rawjson = vec![]; GzDecoder::new(&*buf).read_to_end(&mut rawjson)?; let mut reader = match json_format { JsonFormat::Array => { array_to_jsonl(rawjson.as_mut()); ReaderBuilder::new() .with_schema(schema) .build(Cursor::new(&rawjson[1..rawjson.len() - 1]))? } JsonFormat::JsonL => ReaderBuilder::new() .with_schema(schema) .build(Cursor::new(&rawjson[..]))?, }; let mut batches = vec![]; while let Some(rb) = reader.next()? { batches.push(rb); } Ok(batches) }) .await??; Some(batches) } fn array_to_jsonl(data: &mut [u8]) { let mut indent = 0; let n = data.len(); for i in 0..n { if data[i] == b',' && indent == 0 { data[i] = b'\n'; } else if data[i] == b'{' { indent += 1; } else if data[i] == b'}' { indent -= 1; } else if i < n - 6 && &data[i..i + 6] == b"[\"new\"" { data[i..i + 6].copy_from_slice(b"[10001"); } else if i < n - 9 && &data[i..i + 9] == b"[\"change\"" { data[i..i + 9].copy_from_slice(b"[10000002"); } else if i < n - 9 && &data[i..i + 9] == b"[\"delete\"" { data[i..i + 9].copy_from_slice(b"[10000004"); } } }
use anyhow::Error; use arrow::datatypes::{Schema, SchemaRef}; use arrow::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; use arrow::js
um::EnumString; use tokio::io::AsyncReadExt; use tokio::task::spawn_blocking; #[derive(Debug, Clone, Copy, EnumString)] pub enum JsonFormat { JsonL, Array, } #[throws(Error)] pub async fn read_s3<S>( bucket: &str, objects: &[S], schema: &str, json_format: JsonFormat, ) -> HashMap<String, Vec<(*const FFI_ArrowArray, *const FFI_ArrowSchema)>> where S: AsRef<str>, { let client = S3Client::new(Region::UsWest2); let schema = Arc::new(Schema::from(&from_str::<Value>(schema)?)?); let mut futs: FuturesOrdered<_> = objects .iter() .map(|obj| { client .get_object(GetObjectRequest { bucket: bucket.into(), key: obj.as_ref().to_string(), ..Default::default() }) .err_into() .and_then(|resp| read_as_record_batch(resp, schema.clone(), json_format)) }) .collect(); let mut table = HashMap::new(); while let Some(rb) = futs.next().await { if let Some(batches) = rb? { for batch in batches { for (i, f) in batch.schema().fields().iter().enumerate() { use arrow::datatypes::DataType::*; match f.data_type() { Null | Boolean | Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64 | Float16 | Float32 | Float64 | Utf8 | LargeUtf8 | Binary | LargeBinary => {} _ => continue, } table .entry(f.name().clone()) .or_insert_with(Vec::new) .push(batch.column(i).to_raw()?) } } } } table } #[throws(Error)] async fn read_as_record_batch( payload: GetObjectOutput, schema: SchemaRef, json_format: JsonFormat, ) -> Option<Vec<RecordBatch>> { if payload.body.as_ref().is_none() { return None; } let mut buf = vec![]; payload .body .unwrap() .into_async_read() .read_to_end(&mut buf) .await?; let batches = spawn_blocking(move || -> Result<_, Error> { let mut rawjson = vec![]; GzDecoder::new(&*buf).read_to_end(&mut rawjson)?; let mut reader = match json_format { JsonFormat::Array => { array_to_jsonl(rawjson.as_mut()); ReaderBuilder::new() .with_schema(schema) .build(Cursor::new(&rawjson[1..rawjson.len() - 1]))? } JsonFormat::JsonL => ReaderBuilder::new() .with_schema(schema) .build(Cursor::new(&rawjson[..]))?, }; let mut batches = vec![]; while let Some(rb) = reader.next()? { batches.push(rb); } Ok(batches) }) .await??; Some(batches) } fn array_to_jsonl(data: &mut [u8]) { let mut indent = 0; let n = data.len(); for i in 0..n { if data[i] == b',' && indent == 0 { data[i] = b'\n'; } else if data[i] == b'{' { indent += 1; } else if data[i] == b'}' { indent -= 1; } else if i < n - 6 && &data[i..i + 6] == b"[\"new\"" { data[i..i + 6].copy_from_slice(b"[10001"); } else if i < n - 9 && &data[i..i + 9] == b"[\"change\"" { data[i..i + 9].copy_from_slice(b"[10000002"); } else if i < n - 9 && &data[i..i + 9] == b"[\"delete\"" { data[i..i + 9].copy_from_slice(b"[10000004"); } } }
on::reader::ReaderBuilder; use arrow::record_batch::RecordBatch; use fehler::throws; use flate2::read::GzDecoder; use futures::stream::{FuturesOrdered, StreamExt}; use futures::TryFutureExt; use rusoto_core::Region; use rusoto_s3::{GetObjectOutput, GetObjectRequest, S3Client, S3}; use serde_json::{from_str, Value}; use std::collections::HashMap; use std::io::{Cursor, Read}; use std::sync::Arc; use str
random
[ { "content": "use super::{Consume, Destination, DestinationPartition};\n\nuse crate::data_order::DataOrder;\n\nuse crate::dummy_typesystem::DummyTypeSystem;\n\nuse crate::errors::{ConnectorAgentError, Result};\n\nuse crate::typesystem::{Realize, TypeAssoc, TypeSystem};\n\nuse anyhow::anyhow;\n\nuse arrow::datat...
Rust
rpc/src/streaming.rs
jjs-dev/commons
f53ebfa3bd973aa711f79f4d824fa297ac21b1ad
use futures_util::StreamExt; use std::{convert::Infallible, marker::PhantomData, pin::Pin}; use tokio::io::AsyncBufReadExt; pub struct Streaming<E, F>(Infallible, PhantomData<(E, F)>); impl<E, F> crate::Direction for Streaming<E, F> where E: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static, F: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static, { type Tx = StreamingTx<E, F>; type Rx = StreamingRx<E, F>; } #[derive(serde::Serialize, serde::Deserialize)] enum Item<E, F> { Event(E), Finish(F), } pub struct StreamingTx<E, F> { phantom: PhantomData<(E, F)>, sender: hyper::body::Sender, } impl<E, F> crate::Transmit for StreamingTx<E, F> where E: serde::Serialize + Send + Sync + 'static, F: serde::Serialize + Send + Sync + 'static, { type BatchError = SendError; type BatchData = (futures_util::stream::BoxStream<'static, E>, F); type BatchFuture = futures_util::future::BoxFuture<'static, Result<(), SendError>>; fn from_body_sender(sender: hyper::body::Sender) -> Self { Self { phantom: PhantomData, sender, } } fn send_batch(mut self, mut batch: Self::BatchData) -> Self::BatchFuture { Box::pin(async move { while let Some(event) = batch.0.next().await { self.send_event(event).await?; } self.finish(batch.1).await }) } } #[derive(Debug, thiserror::Error)] pub enum SendError { #[error("serialization failed")] Serialize(serde_json::Error), #[error("data not sent to client")] Network(hyper::Error), } impl<E: serde::Serialize, F: serde::Serialize> StreamingTx<E, F> { async fn priv_send(&mut self, item: Item<E, F>) -> Result<(), SendError> { let mut message = serde_json::to_vec(&item).map_err(SendError::Serialize)?; message.push(b'\n'); self.sender .send_data(message.into()) .await .map_err(SendError::Network) } pub async fn send_event(&mut self, event: E) -> Result<(), SendError> { self.priv_send(Item::Event(event)).await } pub async fn finish(&mut self, finish: F) -> Result<(), SendError> { self.priv_send(Item::Finish(finish)).await } } impl<E, F> StreamingTx<E, F> {} pub struct StreamingRx<E, F> { phantom: PhantomData<(E, F)>, body: tokio::io::BufReader<Pin<Box<dyn tokio::io::AsyncRead + Send + Sync + 'static>>>, finish: Option<F>, } impl<E, F> crate::Receive for StreamingRx<E, F> where E: serde::de::DeserializeOwned + Send + 'static, F: serde::de::DeserializeOwned + Send + 'static, { type BatchData = (Vec<E>, F); type BatchError = RecvError; type BatchFuture = futures_util::future::BoxFuture<'static, Result<Self::BatchData, RecvError>>; fn from_body(body: hyper::Body) -> Self { let body = body.map(|chunk| { chunk.map_err(|hyper_err| std::io::Error::new(std::io::ErrorKind::Other, hyper_err)) }); Self { phantom: PhantomData, body: tokio::io::BufReader::new(Box::pin(tokio::io::stream_reader(body))), finish: None, } } fn recv_batch(mut self) -> Self::BatchFuture { Box::pin(async move { let mut events = Vec::new(); loop { let item = self.recv_next_item().await?; match item { Item::Event(ev) => events.push(ev), Item::Finish(fin) => break Ok((events, fin)), } } }) } } #[derive(Debug, thiserror::Error)] pub enum RecvError { #[error("unable to read response")] Network(hyper::Error), #[error("io error")] Io(std::io::Error), #[error("parsing failed")] Deserialize(serde_json::Error), #[error("unexpected data")] Unexpected, } impl<E: serde::de::DeserializeOwned, F: serde::de::DeserializeOwned> StreamingRx<E, F> { async fn recv_next_item(&mut self) -> Result<Item<E, F>, RecvError> { let mut line = String::new(); self.body .read_line(&mut line) .await .map_err(RecvError::Io)?; Ok(serde_json::from_str(line.trim()).map_err(RecvError::Deserialize)?) } pub async fn next_event(&mut self) -> Result<Option<E>, RecvError> { if self.finish.is_some() { return Ok(None); } match self.recv_next_item().await? { Item::Event(ev) => Ok(Some(ev)), Item::Finish(fin) => { self.finish = Some(fin); Ok(None) } } } pub async fn finish(mut self) -> Result<F, RecvError> { if let Some(f) = self.finish { return Ok(f); } match self.recv_next_item().await? { Item::Event(_) => Err(RecvError::Unexpected), Item::Finish(fin) => Ok(fin), } } }
use futures_util::StreamExt; use std::{convert::Infallible, marker::PhantomData, pin::Pin}; use tokio::io::AsyncBufReadExt; pub struct Streaming<E, F>(Infallible, PhantomData<(E, F)>); impl<E, F> crate::Direction for Streaming<E, F> where E: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static, F: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static, { type Tx = StreamingTx<E, F>; type Rx = StreamingRx<E, F>; } #[derive(serde::Serialize, serde::Deserialize)] enum Item<E, F> { Event(E), Finish(F), } pub struct StreamingTx<E, F> { phantom: PhantomData<(E, F)>, sender: hyper::body::Sender, } impl<E, F> crate::Transmit for StreamingTx<E, F> where E: serde::Serialize + Send + Sync + 'static, F: serde::Serialize + Send + Sync + 'static, { type BatchError = SendError; type BatchData = (futures_util::stream::BoxStream<'static, E>, F); type BatchFuture = futures_util::future::BoxFuture<'static, Result<(), SendError>>; fn from_body_sender(sender: hyper::body::Sender) -> Self { Self { phantom: PhantomData, sender, } }
} #[derive(Debug, thiserror::Error)] pub enum SendError { #[error("serialization failed")] Serialize(serde_json::Error), #[error("data not sent to client")] Network(hyper::Error), } impl<E: serde::Serialize, F: serde::Serialize> StreamingTx<E, F> { async fn priv_send(&mut self, item: Item<E, F>) -> Result<(), SendError> { let mut message = serde_json::to_vec(&item).map_err(SendError::Serialize)?; message.push(b'\n'); self.sender .send_data(message.into()) .await .map_err(SendError::Network) } pub async fn send_event(&mut self, event: E) -> Result<(), SendError> { self.priv_send(Item::Event(event)).await } pub async fn finish(&mut self, finish: F) -> Result<(), SendError> { self.priv_send(Item::Finish(finish)).await } } impl<E, F> StreamingTx<E, F> {} pub struct StreamingRx<E, F> { phantom: PhantomData<(E, F)>, body: tokio::io::BufReader<Pin<Box<dyn tokio::io::AsyncRead + Send + Sync + 'static>>>, finish: Option<F>, } impl<E, F> crate::Receive for StreamingRx<E, F> where E: serde::de::DeserializeOwned + Send + 'static, F: serde::de::DeserializeOwned + Send + 'static, { type BatchData = (Vec<E>, F); type BatchError = RecvError; type BatchFuture = futures_util::future::BoxFuture<'static, Result<Self::BatchData, RecvError>>; fn from_body(body: hyper::Body) -> Self { let body = body.map(|chunk| { chunk.map_err(|hyper_err| std::io::Error::new(std::io::ErrorKind::Other, hyper_err)) }); Self { phantom: PhantomData, body: tokio::io::BufReader::new(Box::pin(tokio::io::stream_reader(body))), finish: None, } } fn recv_batch(mut self) -> Self::BatchFuture { Box::pin(async move { let mut events = Vec::new(); loop { let item = self.recv_next_item().await?; match item { Item::Event(ev) => events.push(ev), Item::Finish(fin) => break Ok((events, fin)), } } }) } } #[derive(Debug, thiserror::Error)] pub enum RecvError { #[error("unable to read response")] Network(hyper::Error), #[error("io error")] Io(std::io::Error), #[error("parsing failed")] Deserialize(serde_json::Error), #[error("unexpected data")] Unexpected, } impl<E: serde::de::DeserializeOwned, F: serde::de::DeserializeOwned> StreamingRx<E, F> { async fn recv_next_item(&mut self) -> Result<Item<E, F>, RecvError> { let mut line = String::new(); self.body .read_line(&mut line) .await .map_err(RecvError::Io)?; Ok(serde_json::from_str(line.trim()).map_err(RecvError::Deserialize)?) } pub async fn next_event(&mut self) -> Result<Option<E>, RecvError> { if self.finish.is_some() { return Ok(None); } match self.recv_next_item().await? { Item::Event(ev) => Ok(Some(ev)), Item::Finish(fin) => { self.finish = Some(fin); Ok(None) } } } pub async fn finish(mut self) -> Result<F, RecvError> { if let Some(f) = self.finish { return Ok(f); } match self.recv_next_item().await? { Item::Event(_) => Err(RecvError::Unexpected), Item::Finish(fin) => Ok(fin), } } }
fn send_batch(mut self, mut batch: Self::BatchData) -> Self::BatchFuture { Box::pin(async move { while let Some(event) = batch.0.next().await { self.send_event(event).await?; } self.finish(batch.1).await }) }
function_block-function_prefix_line
[ { "content": "/// Creates new channel, returning one sender and one receiver.\n\n/// Other can be created using `Clone::clone`\n\npub fn channel<T: Send + 'static>() -> (Sender<T>, Receiver<T>) {\n\n let inner = Inner {\n\n q: Mutex::new(Queue {\n\n values: VecDeque::new(),\n\n w...
Rust
tests/parse_test.rs
msanou/crystallake
f72eada9f9ea3dbb6846a8549095394f90959108
extern crate crystalrake; use crystalrake::json::*; #[test] fn true_value() { let t = "true".parse::<JsonValue>(); if let Ok(JsonValue::Boolean(b)) = t { assert!(b, "expect true, but {}", b); } else { panic!("unexpect value : {:?}", t); } } #[test] fn true_string() { let t = "\"true\"".parse::<JsonValue>().unwrap(); assert_eq!(t, JsonValue::String("true".to_string())); } #[test] fn false_value() { let f = "false".parse::<JsonValue>(); if let Ok(JsonValue::Boolean(b)) = f { assert!(!b, "expect false, but {}", b); } else { panic!("unexpect value : {:?}", f); } } #[test] fn false_string() { let t = "\"false\"".parse::<JsonValue>().unwrap(); assert_eq!(t, JsonValue::String("false".to_string())); } #[test] fn number_value() { let json_value = "1234567890.0987654321".parse::<JsonValue>(); if let Ok(JsonValue::Number(number)) = json_value { let integer = number as u64; assert_eq!(integer, 1234567890); assert_eq!(number.fract(),0.0987654321f64); } else { panic!("unexpect value : {:?}", json_value); } } #[test] fn number_string() { let t = "\"1234567890.0987654321\"".parse::<JsonValue>().unwrap(); assert_eq!(t, JsonValue::String("1234567890.0987654321".to_string())); } #[test] fn empty_object() { let json_value = "{}".parse::<JsonValue>().unwrap(); let expect_result = JsonValue::Objects(Vec::new()); assert_eq!(json_value, expect_result); } #[test] fn array_value() { let json_value = r#" [ 12345, true, false, null, "Hello, world", { "object" : {} } ]"#.parse::<JsonValue>().unwrap(); let object : JsonObject = JsonObject::new("object", JsonValue::Objects(Vec::new())); let values = Vec::from([ JsonValue::Number(12345f64), JsonValue::Boolean(true), JsonValue::Boolean(false), JsonValue::Null, JsonValue::String("Hello, world".to_string()), object.into()]); assert_eq!(JsonValue::Array(values), json_value); } #[test] fn one_object() { let json_value = r#"{"name" : 12345}"#.parse::<JsonValue>().unwrap(); let expect_result = JsonValue::Objects(Vec::from([JsonObject::new("name", 12345f64)])); assert_eq!(json_value, expect_result); } #[test] fn nested_empty_object() { let json_value = r#"{ "empty" : {} }"#.parse::<JsonValue>().unwrap(); let expect_result = JsonValue::Objects(Vec::from([JsonObject::new("empty", JsonValue::Objects(Vec::new()))])); assert_eq!(json_value, expect_result); } #[test] fn nested_empty_array() { let json_value = r#"[ {"empty" : []} ]"#.parse::<JsonValue>().unwrap(); let expect_result = JsonValue::Array(vec![JsonValue::Objects(vec![JsonObject::new("empty", JsonValue::Array(Vec::new()))])]); assert_eq!(json_value, expect_result); } #[test] fn null_value() { let json_value = "null".parse::<JsonValue>(); if let Ok(v) = json_value { assert!(v.is_null()); } else { panic!("unexpect value : {:?}", json_value); } } #[test] fn null_string() { let json_value = "\"null\"".parse::<JsonValue>().unwrap(); assert_eq!(json_value, JsonValue::String("null".to_string())); } #[test] fn contain_utf16() { let json_value = r#""\u3042\u3044\u3046abc""#.parse::<JsonValue>(); if let Ok(JsonValue::String(v)) = json_value { assert_eq!(v, "あいうabc".to_string()); } else { panic!("unexpect value : {:?}", json_value); } } #[test] fn contain_emoji() { let json_value = r#""\uD83D\uDE04\uD83D\uDE07\uD83D\uDC7A""#.parse::<JsonValue>(); if let Ok(JsonValue::String(v)) = json_value { assert_eq!(v, r#"😄😇👺"#.to_string()); } else { panic!("unexpect value : {:?}", json_value); } }
extern crate crystalrake; use crystalrake::json::*; #[test] fn true_value() { let t = "true".parse::<JsonValue>(); if let Ok(JsonValue::Boolean(b)) = t { assert!(b, "expect true, but {}", b); } else { panic!("unexpect value : {:?}", t); } } #[test] fn true_string() { let t = "\"true\"".parse::<JsonValue>().unwrap(); assert_eq!(t, JsonValue::String("true".to_string())); } #[test] fn false_value() { let f = "false".parse::<JsonValue>(); if let Ok(JsonValue::Boolean(b)) = f { assert!(!b, "expect false, but {}", b); } else { panic!("unexpect value : {:?}", f); } } #[test] fn false_string() { let t = "\"false\"".parse::<JsonValue>().unwrap(); assert_eq!(t, JsonValue::String("false".to_string())); } #[test] fn number_value() { let json_value = "1234567890.0987654321".parse::<JsonValue>(); if let Ok(JsonValue::Number(number)) = json_value { let integer = number as u64; assert_eq!(integer, 1234567890); assert_eq!(number.fract(),0.0987654321f64); } else { panic!("unexpect value : {:?}", json_value); } } #[test] fn number_string() { let t = "\"1234567890.0987654321\"".parse::<JsonValue>().unwrap(); assert_eq!(t, JsonValue::String("1234567890.0987654321".to_string())); } #[test] fn empty_object() { let json_value = "{}".parse::<JsonValue>().unwrap(); let expect_result = JsonValue::Objects(Vec::new()); assert_eq!(json_value, expect_result); } #[test] fn array_value() { let json_value = r#" [ 12345, true, false, null, "Hello, world", { "object" : {} } ]"#.parse::<JsonValue>().unwrap(); let object : JsonObject = JsonObject::new("object", JsonValue::Objects(Vec::new())); let values = Vec::from([ JsonValue::Number(12345f64), JsonValue::Boolean(true), JsonValue::Boolean(false), JsonValue::Null, JsonValue::String("Hello, world".to_string()), object.into()]); assert_eq!(JsonValue::Array(values), json_value); } #[test] fn one_object() { let json_value = r#"{"name" : 12345}"#.parse::<JsonValue>().unwrap(); let expect_result = JsonValue::Objects(Vec::from([JsonObject::new("name", 12345f64)])); assert_eq!(json_value, expect_result); } #[test] fn nested_empty_object() { let json_value = r#"{ "empty" : {} }"#.parse::<JsonValue>().unwrap(); let expect_result = JsonValue::Objects(Vec::from([JsonObject::new("empty", JsonValue::Objects(Vec::new()))])); assert_eq!(json_value, expect_result); } #[test] fn nested_empty_array() { let json_value = r#"[ {"empty" : []} ]"#.parse::<JsonValue>().unwrap(); let expect_result = JsonValue::Array(vec![JsonValue::Objects(vec![JsonObject::new("empty", JsonValue::Array(Vec::new()))])]); assert_eq!(json_value, expect_result); } #[test] fn null_value() { let json_value = "null".parse::<JsonValue>(); if let Ok(v) = json_value { assert!(v.is_null()); } else { panic!("unexpect value : {:?}", json_value); } } #[test] fn null_string() { let json_value = "\"null\"".parse::<JsonValue>().unwrap(); assert_eq!(json_value, JsonValue::String("null".to_string())); } #[test] fn contain_utf16() { let json_value = r#""\u3042\u3044\u3046abc""#.parse::<JsonValue>(); if let Ok(JsonValue::String(v)) = json_value { assert_eq!(v, "あいうabc".to_string()); } else { panic!("unexpect value : {:?}", json_value); } } #[test]
fn contain_emoji() { let json_value = r#""\uD83D\uDE04\uD83D\uDE07\uD83D\uDC7A""#.parse::<JsonValue>(); if let Ok(JsonValue::String(v)) = json_value { assert_eq!(v, r#"😄😇👺"#.to_string()); } else { panic!("unexpect value : {:?}", json_value); } }
function_block-function_prefix_line
[ { "content": "#[test]\n\n#[allow(overflowing_literals)]\n\nfn simple_deserialize() {\n\n let a : A = \"1000000000000000\".parse::<JsonValue>().unwrap().deserialize().unwrap();\n\n assert_eq!(a, A::new(1000000000000000));\n\n}", "file_path": "tests/deserialize_test.rs", "rank": 15, "score": 473...
Rust
src/chopper/types.rs
snaar/drat
8c9c1e2e413d8a93f3fd50df852915a27cb37e6f
use std::cmp::Ordering; use std::fmt; use ndarray::ArrayD; use crate::chopper::error::{Error, Result}; use crate::util::timestamp_util; use crate::util::tz::ChopperTz; pub type ChainId = usize; pub type NodeId = usize; pub type Nanos = u64; #[derive(Copy, Clone)] pub struct TimestampRange { pub begin: Option<Nanos>, pub end: Option<Nanos>, } pub static TIMESTAMP_RANGE_ALL: TimestampRange = TimestampRange { begin: None, end: None, }; impl TimestampRange { pub fn new( begin: Option<impl AsRef<str>>, end: Option<impl AsRef<str>>, timezone: &ChopperTz, ) -> Result<Self> { let begin = match begin { Some(t) => Some(timestamp_util::parse_datetime_range_element( t.as_ref(), timezone, )?), None => None, }; let end = match end { Some(t) => Some(timestamp_util::parse_datetime_range_element( t.as_ref(), timezone, )?), None => None, }; Ok(TimestampRange { begin, end }) } } #[derive(Clone, Debug)] pub struct Header { field_names: Vec<String>, field_types: Vec<FieldType>, } impl Header { pub fn generate_default_field_names(field_count: usize) -> Vec<String> { let mut field_names: Vec<String> = Vec::new(); for i in 0..field_count { field_names.push(format!("col_{}", i)); } field_names } } impl PartialEq for Header { fn eq(&self, other: &Header) -> bool { self.field_names().eq(other.field_names()) && self.field_types().eq(other.field_types()) } } impl Header { pub fn new(field_names: Vec<String>, field_types: Vec<FieldType>) -> Self { Header { field_names, field_types, } } pub fn field_names(&self) -> &Vec<String> { &self.field_names } pub fn update_field_names(&mut self, new_names: Vec<String>) { self.field_names = new_names; } pub fn field_types(&self) -> &Vec<FieldType> { &self.field_types } pub fn update_field_types(&mut self, new_types: Vec<FieldType>) { self.field_types = new_types; } pub fn field_names_mut(&mut self) -> &mut Vec<String> { &mut self.field_names } pub fn field_types_mut(&mut self) -> &mut Vec<FieldType> { &mut self.field_types } pub fn field_index(&self, name: &str) -> Result<usize> { match self.field_names.iter().position(|s| s == name) { None => Err(Error::ColumnMissing(name.to_string())), Some(i) => Ok(i), } } } #[derive(Clone, Debug, PartialEq)] pub enum FieldValue { Boolean(bool), Byte(u8), ByteBuf(Vec<u8>), Char(u16), Double(f64), Float(f32), Int(i32), Long(i64), Short(i16), String(String), MultiDimDoubleArray(ArrayD<f64>), None, } impl PartialOrd for FieldValue { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { match self { FieldValue::Boolean(v) => { if let FieldValue::Boolean(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Byte(v) => { if let FieldValue::Byte(o) = other { v.partial_cmp(o) } else { None } } FieldValue::ByteBuf(v) => { if let FieldValue::ByteBuf(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Char(v) => { if let FieldValue::Char(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Double(v) => { if let FieldValue::Double(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Float(v) => { if let FieldValue::Float(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Int(v) => { if let FieldValue::Int(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Long(v) => { if let FieldValue::Long(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Short(v) => { if let FieldValue::Short(o) = other { v.partial_cmp(o) } else { None } } FieldValue::String(v) => { if let FieldValue::String(o) = other { v.partial_cmp(o) } else { None } } FieldValue::MultiDimDoubleArray(_) => None, FieldValue::None => { if &FieldValue::None == other { Some(Ordering::Equal) } else { None } } } } } impl fmt::Display for FieldValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self { FieldValue::Boolean(x) => f.write_str(format!("bool[{}]", x).as_str()), FieldValue::Byte(x) => f.write_str(format!("byte[{}]", x).as_str()), FieldValue::ByteBuf(x) => f.write_str(format!("u8[len={}]", x.len()).as_str()), FieldValue::Char(x) => f.write_str(format!("char[{}]", x).as_str()), FieldValue::Double(x) => f.write_str(format!("double[{}]", x).as_str()), FieldValue::Float(x) => f.write_str(format!("float[{}]", x).as_str()), FieldValue::Int(x) => f.write_str(format!("int[{}]", x).as_str()), FieldValue::Long(x) => f.write_str(format!("long[{}]", x).as_str()), FieldValue::Short(x) => f.write_str(format!("short[{}]", x).as_str()), FieldValue::String(x) => f.write_str(format!("string[{}]", x.as_str()).as_str()), FieldValue::MultiDimDoubleArray(x) => { f.write_str("f64[shape=(")?; f.write_str( &x.shape() .iter() .map(|d| d.to_string()) .collect::<Vec<String>>() .join("x"), )?; f.write_str(")]")?; Ok(()) } FieldValue::None => f.write_str("none[]"), } } } impl FieldValue { pub fn string_field_to_float(&self) -> Result<f64> { if let FieldValue::String(string) = self { let float = string.parse::<f64>().unwrap(); Ok(float) } else { Err(Error::from("expected FieldValue::String")) } } pub fn string_field_to_string(&self) -> Result<&str> { if let FieldValue::String(string) = self { Ok(string) } else { Err(Error::from("expected FieldValue::String")) } } pub fn matches_field_type(&self, field_type: FieldType) -> bool { let self_type = match self { FieldValue::Boolean(_) => FieldType::Boolean, FieldValue::Byte(_) => FieldType::Byte, FieldValue::ByteBuf(_) => FieldType::ByteBuf, FieldValue::Char(_) => FieldType::Char, FieldValue::Double(_) => FieldType::Double, FieldValue::Float(_) => FieldType::Float, FieldValue::Int(_) => FieldType::Int, FieldValue::Long(_) => FieldType::Long, FieldValue::Short(_) => FieldType::Short, FieldValue::String(_) => FieldType::String, FieldValue::MultiDimDoubleArray(_) => FieldType::MultiDimDoubleArray, FieldValue::None => return true, }; self_type == field_type } } #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] pub enum FieldType { Boolean, Byte, ByteBuf, Char, Double, Float, Int, Long, Short, String, MultiDimDoubleArray, } #[derive(Clone, Debug, PartialEq)] pub struct Row { pub timestamp: Nanos, pub field_values: Vec<FieldValue>, } impl Row { pub fn empty() -> Row { Row { timestamp: 0, field_values: vec![], } } }
use std::cmp::Ordering; use std::fmt; use ndarray::ArrayD; use crate::chopper::error::{Error, Result}; use crate::util::timestamp_util; use crate::util::tz::ChopperTz; pub type ChainId = usize; pub type NodeId = usize; pub type Nanos = u64; #[derive(Copy, Clone)] pub struct TimestampRange { pub begin: Option<Nanos>, pub end: Option<Nanos>, } pub static TIMESTAMP_RANGE_ALL: TimestampRange = TimestampRange { begin: None, end: None, }; impl TimestampRange { pub fn new( begin: Option<impl AsRef<str>>, end: Option<impl AsRef<str>>, timezone: &ChopperTz, ) -> Result<Self> { let begin = match begin { Some(t) => Some(timestamp_util::parse_datetime_range_element( t.as_ref(), timezone, )?), None => None, }; let end = match end { Some(t) => Some(timestamp_util::parse_datetime_range_element( t.as_ref(), timezone, )?), None => None, }; Ok(TimestampRange { begin, end }) } } #[derive(Clone, Debug)] pub struct Header { field_names: Vec<String>, field_types: Vec<FieldType>, } impl Header { pub fn generate_default_field_names(field_count: usize) -> Vec<String> { let mut field_names: Vec<String> = Vec::new(); for i in 0..field_count { field_names.push(format!("col_{}", i)); } field_names } } impl PartialEq for Header { fn eq(&self, other: &Header) -> bool { self.field_names().eq(other.field_names()) && self.field_types().eq(other.field_types()) } } impl Header { pub fn new(field_names: Vec<String>, field_types: Vec<FieldType>) -> Self { Header { field_names, field_types, } } pub fn field_names(&self) -> &Vec<String> { &self.field_names } pub fn update_field_names(&mut self, new_names: Vec<String>) { self.field_names = new_names; } pub fn field_types(&self) -> &Vec<FieldType> { &self.field_types } pub fn update_field_types(&mut self, new_types: Vec<FieldType>) { self.field_types = new_types; } pub fn field_names_mut(&mut self) -> &mut Vec<String> { &mut self.field_names } pub fn field_types_mut(&mut self) -> &mut Vec<FieldType> { &mut self.field_types } pub fn field_index(&self, name: &str) -> Result<usize> { match self.field_names.iter().position(|s| s == name) { None => Err(Error::ColumnMissing(name.to_string())), Some(i) => Ok(i), } } } #[derive(Clone, Debug, PartialEq)] pub enum FieldValue { Boolean(bool), Byte(u8), ByteBuf(Vec<u8>), Char(u16), Double(f64), Float(f32), Int(i32), Long(i64), Short(i16), String(String), MultiDimDoubleArray(ArrayD<f64>), None, } impl PartialOrd for FieldValue { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { match self { FieldValue::Boolean(v) => { if let FieldValue::Boolean(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Byte(v) => { if let FieldValue::Byte(o) = other { v.partial_cmp(o) } else { None } } FieldValue::ByteBuf(v) => { if let FieldValue::ByteBuf(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Char(v) => { if let FieldValue::Char(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Double(v) => { if let FieldValue::Double(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Float(v) => { if let FieldValue::Float(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Int(v) => { if let FieldValue::Int(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Long(v) => { if let FieldValue::Long(o) = other { v.partial_cmp(o) } else { None } } FieldValue::Short(v) => { if let FieldValue::Short(o) = other { v.partial_cmp(o) } else { None } } FieldValue::String(v) => { if let FieldValue::String(o) = other { v.partial_cmp(o) } else { None } } FieldValue::MultiDimDoubleArray(_) => None, FieldValue::None => { if &FieldValue::None == other { Some(Ordering::Equal) } else { None } } } } } impl fmt::Display for FieldValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self { FieldValue::Boolean(x) => f.write_str(format!("bool[{}]", x).as_str()), FieldValue::Byte(x) => f.write_str(format!("byte[{}]", x).as_str()), FieldValue::ByteBuf(x) => f.write_str(format!("u8[len={}]", x.len()).as_str()), FieldValue::Char(x) => f.write_str(format!("char[{}]", x).as_str()), FieldValue::Double(x) => f.write_str(format!("double[{}]", x).as_str()), FieldValue::Float(x) => f.write_str(format!("float[{}]", x).as_str()), FieldValue::Int(x) => f.write_str(format!("int[{}]", x).as_str()), FieldValue::Long(x) => f.write_str(format!("long[{}]", x).as_str()), FieldValue::Short(x) => f.write_str(format!("short[{}]", x).as_str()), FieldValue::String(x) => f.write_str(format!("string[{}]", x.as_str()).as_str()), FieldValue::MultiDimDoubleArray(x) => { f.write_str("f64[shape=(")?; f.write_str( &x.shape() .iter() .map(|d| d.to_string()) .collect::<Vec<String>>() .join("x"), )?; f.write_str(")]")?; Ok(()) } FieldValue::None => f.write_str("none[]"), } } } impl FieldValue { pub fn string_field_to_float(&self) -> Result<f64> {
} pub fn string_field_to_string(&self) -> Result<&str> { if let FieldValue::String(string) = self { Ok(string) } else { Err(Error::from("expected FieldValue::String")) } } pub fn matches_field_type(&self, field_type: FieldType) -> bool { let self_type = match self { FieldValue::Boolean(_) => FieldType::Boolean, FieldValue::Byte(_) => FieldType::Byte, FieldValue::ByteBuf(_) => FieldType::ByteBuf, FieldValue::Char(_) => FieldType::Char, FieldValue::Double(_) => FieldType::Double, FieldValue::Float(_) => FieldType::Float, FieldValue::Int(_) => FieldType::Int, FieldValue::Long(_) => FieldType::Long, FieldValue::Short(_) => FieldType::Short, FieldValue::String(_) => FieldType::String, FieldValue::MultiDimDoubleArray(_) => FieldType::MultiDimDoubleArray, FieldValue::None => return true, }; self_type == field_type } } #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] pub enum FieldType { Boolean, Byte, ByteBuf, Char, Double, Float, Int, Long, Short, String, MultiDimDoubleArray, } #[derive(Clone, Debug, PartialEq)] pub struct Row { pub timestamp: Nanos, pub field_values: Vec<FieldValue>, } impl Row { pub fn empty() -> Row { Row { timestamp: 0, field_values: vec![], } } }
if let FieldValue::String(string) = self { let float = string.parse::<f64>().unwrap(); Ok(float) } else { Err(Error::from("expected FieldValue::String")) }
if_condition
[]
Rust
pallets/worker/src/prover.rs
edgeware-builders/substrate-eth-light-client
acdfa163ccbb1ccfb3b7f4681bd1ec05d706cd07
#![cfg_attr(not(feature = "std"), no_std)] use crate::*; use rlp::Rlp; pub trait Prover { fn extract_nibbles(a: Vec<u8>) -> Vec<u8>; fn concat_nibbles(a: Vec<u8>) -> Vec<u8>; fn assert_ethclient_hash( block_number: u64, expected_block_hash: H256, ) -> bool; fn verify_log_entry( log_index: u64, log_entry_data: Vec<u8>, receipt_index: u64, receipt_data: Vec<u8>, header_data: Vec<u8>, proof: Vec<Vec<u8>>, ) -> bool; fn verify_trie_proof( expected_root: H256, key: Vec<u8>, proof: Vec<Vec<u8>>, expected_value: Vec<u8>, ) -> bool; fn _verify_trie_proof( expected_root: H256, key: Vec<u8>, proof: Vec<Vec<u8>>, key_index: usize, proof_index: usize, expected_value: Vec<u8>, ) -> bool; } impl<T: Config> Prover for Module<T> { fn extract_nibbles(a: Vec<u8>) -> Vec<u8> { a.iter().flat_map(|b| vec![b >> 4, b & 0x0F]).collect() } fn concat_nibbles(a: Vec<u8>) -> Vec<u8> { a.iter() .enumerate() .filter(|(i, _)| i % 2 == 0) .zip(a.iter().enumerate().filter(|(i, _)| i % 2 == 1)) .map(|((_, x), (_, y))| (x << 4) | y) .collect() } fn assert_ethclient_hash( block_number: u64, expected_block_hash: H256, ) -> bool { match Self::block_hash_safe(block_number) { Some(hash) => hash == expected_block_hash, None => false, } } fn verify_log_entry( log_index: u64, log_entry_data: Vec<u8>, receipt_index: u64, receipt_data: Vec<u8>, header_data: Vec<u8>, proof: Vec<Vec<u8>>, ) -> bool { let log_entry: ethereum::Log = rlp::decode(log_entry_data.as_slice()).unwrap(); let receipt: ethereum::Receipt = rlp::decode(receipt_data.as_slice()).unwrap(); let header: ethereum::Header = rlp::decode(header_data.as_slice()).unwrap(); if receipt.logs[log_index as usize] == log_entry { return false; } let verification_result = Self::verify_trie_proof( header.receipts_root, rlp::encode(&receipt_index), proof, receipt_data, ); if !verification_result { return false; } Self::assert_ethclient_hash(header.number.as_u64(), header.hash()) } fn verify_trie_proof( expected_root: H256, key: Vec<u8>, proof: Vec<Vec<u8>>, expected_value: Vec<u8>, ) -> bool { let mut actual_key = vec![]; for el in key { if actual_key.len() + 1 == proof.len() { actual_key.push(el); } else { actual_key.push(el / 16); actual_key.push(el % 16); } } Self::_verify_trie_proof( expected_root, actual_key, proof, 0, 0, expected_value, ) } fn _verify_trie_proof( expected_root: H256, key: Vec<u8>, proof: Vec<Vec<u8>>, key_index: usize, proof_index: usize, expected_value: Vec<u8>, ) -> bool { let node = &proof[proof_index]; let dec = Rlp::new(&node.as_slice()); if key_index == 0 { if sp_io::hashing::keccak_256(node) != expected_root.0 { return false; } } else if node.len() < 32 { if dec.as_raw() != expected_root.0 { return false; } } else { if sp_io::hashing::keccak_256(node) != expected_root.0 { return false; } } if dec.iter().count() == 17 { if key_index == key.len() { if dec .at(dec.iter().count() - 1) .unwrap() .as_val::<Vec<u8>>() .unwrap() == expected_value { return true; } } else if key_index < key.len() { let new_expected_root = dec .at(key[key_index] as usize) .unwrap() .as_val::<Vec<u8>>() .unwrap(); let mut trunc_expected_root: [u8; 32] = [0; 32]; for i in 0..new_expected_root.len() { if i == 32 { break; } trunc_expected_root[i] = new_expected_root[i]; } if new_expected_root.len() != 0 { return Self::_verify_trie_proof( trunc_expected_root.into(), key, proof, key_index + 1, proof_index + 1, expected_value, ); } } else { panic!("This should not be reached if the proof has the correct format"); } } else if dec.iter().count() == 2 { let nibbles = Self::extract_nibbles( dec.at(0).unwrap().as_val::<Vec<u8>>().unwrap(), ); let (prefix, nibble) = (nibbles[0], nibbles[1]); if prefix == 2 { let key_end = &nibbles[2..]; if Self::concat_nibbles(key_end.to_vec()) == &key[key_index..] && expected_value == dec.at(1).unwrap().as_val::<Vec<u8>>().unwrap() { return true; } } else if prefix == 3 { let key_end = &nibbles[2..]; if nibble == key[key_index] && Self::concat_nibbles(key_end.to_vec()) == &key[key_index + 1..] && expected_value == dec.at(1).unwrap().as_val::<Vec<u8>>().unwrap() { return true; } } else if prefix == 0 { let shared_nibbles = &nibbles[2..]; let extension_length = shared_nibbles.len(); if Self::concat_nibbles(shared_nibbles.to_vec()) == &key[key_index..key_index + extension_length] { let new_expected_root = dec.at(1).unwrap().as_val::<Vec<u8>>().unwrap(); let mut trunc_expected_root: [u8; 32] = [0; 32]; for i in 0..new_expected_root.len() { if i == 32 { break; } trunc_expected_root[i] = new_expected_root[i]; } return Self::_verify_trie_proof( trunc_expected_root.into(), key, proof, key_index + extension_length, proof_index + 1, expected_value, ); } } else if prefix == 1 { let shared_nibbles = &nibbles[2..]; let extension_length = 1 + shared_nibbles.len(); if nibble == key[key_index] && Self::concat_nibbles(shared_nibbles.to_vec()) == &key[key_index + 1..key_index + extension_length] { let new_expected_root = dec.at(1).unwrap().as_val::<Vec<u8>>().unwrap(); let mut trunc_expected_root: [u8; 32] = [0; 32]; for i in 0..new_expected_root.len() { if i == 32 { break; } trunc_expected_root[i] = new_expected_root[i]; } return Self::_verify_trie_proof( trunc_expected_root.into(), key, proof, key_index + extension_length, proof_index + 1, expected_value, ); } } else { panic!("This should not be reached if the proof has the correct format"); } } else { panic!("This should not be reached if the proof has the correct format"); } expected_value.len() == 0 } }
#![cfg_attr(not(feature = "std"), no_std)] use crate::*; use rlp::Rlp; pub trait Prover { fn extract_nibbles(a: Vec<u8>) -> Vec<u8>; fn concat_nibbles(a: Vec<u8>) -> Vec<u8>; fn assert_ethclient_hash( block_number: u64, expected_block_hash: H256, ) -> bool; fn verify_log_entry( log_index: u64, log_entry_data: Vec<u8>, receipt_index: u64, receipt_data: Vec<u8>, header_data: Vec<u8>, proof: Vec<Vec<u8>>, ) -> bool; fn verify_trie_proof( expected_root: H256, key: Vec<u8>, proof: Vec<Vec<u8>>, expected_value: Vec<u8>, ) -> bool; fn _verify_trie_proof( expected_root: H256, key: Vec<u8>, proof: Vec<Vec<u8>>, key_index: usize, proof_index: usize, expected_value: Vec<u8>, ) -> bool; } impl<T: Config> Prover for Module<T> { fn extract_nibbles(a: Vec<u8>) -> Vec<u8> { a.iter().flat_map(|b| vec![b >> 4, b & 0x0F]).collect() } fn concat_nibbles(a: Vec<u8>) -> Vec<u8> { a.ite
fn assert_ethclient_hash( block_number: u64, expected_block_hash: H256, ) -> bool { match Self::block_hash_safe(block_number) { Some(hash) => hash == expected_block_hash, None => false, } } fn verify_log_entry( log_index: u64, log_entry_data: Vec<u8>, receipt_index: u64, receipt_data: Vec<u8>, header_data: Vec<u8>, proof: Vec<Vec<u8>>, ) -> bool { let log_entry: ethereum::Log = rlp::decode(log_entry_data.as_slice()).unwrap(); let receipt: ethereum::Receipt = rlp::decode(receipt_data.as_slice()).unwrap(); let header: ethereum::Header = rlp::decode(header_data.as_slice()).unwrap(); if receipt.logs[log_index as usize] == log_entry { return false; } let verification_result = Self::verify_trie_proof( header.receipts_root, rlp::encode(&receipt_index), proof, receipt_data, ); if !verification_result { return false; } Self::assert_ethclient_hash(header.number.as_u64(), header.hash()) } fn verify_trie_proof( expected_root: H256, key: Vec<u8>, proof: Vec<Vec<u8>>, expected_value: Vec<u8>, ) -> bool { let mut actual_key = vec![]; for el in key { if actual_key.len() + 1 == proof.len() { actual_key.push(el); } else { actual_key.push(el / 16); actual_key.push(el % 16); } } Self::_verify_trie_proof( expected_root, actual_key, proof, 0, 0, expected_value, ) } fn _verify_trie_proof( expected_root: H256, key: Vec<u8>, proof: Vec<Vec<u8>>, key_index: usize, proof_index: usize, expected_value: Vec<u8>, ) -> bool { let node = &proof[proof_index]; let dec = Rlp::new(&node.as_slice()); if key_index == 0 { if sp_io::hashing::keccak_256(node) != expected_root.0 { return false; } } else if node.len() < 32 { if dec.as_raw() != expected_root.0 { return false; } } else { if sp_io::hashing::keccak_256(node) != expected_root.0 { return false; } } if dec.iter().count() == 17 { if key_index == key.len() { if dec .at(dec.iter().count() - 1) .unwrap() .as_val::<Vec<u8>>() .unwrap() == expected_value { return true; } } else if key_index < key.len() { let new_expected_root = dec .at(key[key_index] as usize) .unwrap() .as_val::<Vec<u8>>() .unwrap(); let mut trunc_expected_root: [u8; 32] = [0; 32]; for i in 0..new_expected_root.len() { if i == 32 { break; } trunc_expected_root[i] = new_expected_root[i]; } if new_expected_root.len() != 0 { return Self::_verify_trie_proof( trunc_expected_root.into(), key, proof, key_index + 1, proof_index + 1, expected_value, ); } } else { panic!("This should not be reached if the proof has the correct format"); } } else if dec.iter().count() == 2 { let nibbles = Self::extract_nibbles( dec.at(0).unwrap().as_val::<Vec<u8>>().unwrap(), ); let (prefix, nibble) = (nibbles[0], nibbles[1]); if prefix == 2 { let key_end = &nibbles[2..]; if Self::concat_nibbles(key_end.to_vec()) == &key[key_index..] && expected_value == dec.at(1).unwrap().as_val::<Vec<u8>>().unwrap() { return true; } } else if prefix == 3 { let key_end = &nibbles[2..]; if nibble == key[key_index] && Self::concat_nibbles(key_end.to_vec()) == &key[key_index + 1..] && expected_value == dec.at(1).unwrap().as_val::<Vec<u8>>().unwrap() { return true; } } else if prefix == 0 { let shared_nibbles = &nibbles[2..]; let extension_length = shared_nibbles.len(); if Self::concat_nibbles(shared_nibbles.to_vec()) == &key[key_index..key_index + extension_length] { let new_expected_root = dec.at(1).unwrap().as_val::<Vec<u8>>().unwrap(); let mut trunc_expected_root: [u8; 32] = [0; 32]; for i in 0..new_expected_root.len() { if i == 32 { break; } trunc_expected_root[i] = new_expected_root[i]; } return Self::_verify_trie_proof( trunc_expected_root.into(), key, proof, key_index + extension_length, proof_index + 1, expected_value, ); } } else if prefix == 1 { let shared_nibbles = &nibbles[2..]; let extension_length = 1 + shared_nibbles.len(); if nibble == key[key_index] && Self::concat_nibbles(shared_nibbles.to_vec()) == &key[key_index + 1..key_index + extension_length] { let new_expected_root = dec.at(1).unwrap().as_val::<Vec<u8>>().unwrap(); let mut trunc_expected_root: [u8; 32] = [0; 32]; for i in 0..new_expected_root.len() { if i == 32 { break; } trunc_expected_root[i] = new_expected_root[i]; } return Self::_verify_trie_proof( trunc_expected_root.into(), key, proof, key_index + extension_length, proof_index + 1, expected_value, ); } } else { panic!("This should not be reached if the proof has the correct format"); } } else { panic!("This should not be reached if the proof has the correct format"); } expected_value.len() == 0 } }
r() .enumerate() .filter(|(i, _)| i % 2 == 0) .zip(a.iter().enumerate().filter(|(i, _)| i % 2 == 1)) .map(|((_, x), (_, y))| (x << 4) | y) .collect() }
function_block-function_prefixed
[ { "content": "/// This pallet's configuration trait\n\npub trait Config: system::Config + CreateSignedTransaction<Call<Self>> {\n\n /// The identifier type for an offchain worker.\n\n type AuthorityId: AppCrypto<Self::Public, Self::Signature>;\n\n\n\n /// The overarching event type.\n\n type Event: ...
Rust
src/year2018/day10.rs
CraZySacX/aoc
c96faf4c3fb0f39db0c2f5b573a307e5c779e421
use error::Result; use regex::Regex; use std::io::BufRead; pub fn find_solution<T: BufRead>(reader: T, _second_star: bool) -> Result<u32> { println!("{}", align(reader, false)?); Ok(0) } fn align<T: BufRead>(reader: T, test: bool) -> Result<String> { let line_re = Regex::new(r"position=<(.*), (.*)> velocity=<(.*), (.*)>")?; let mut star_map: Vec<(isize, isize, isize, isize)> = Vec::new(); for line in reader.lines().filter_map(|x| x.ok()) { for cap in line_re.captures_iter(&line) { let x = (&cap[1]).trim().parse::<isize>()?; let y = (&cap[2]).trim().parse::<isize>()?; let vx = (&cap[3]).trim().parse::<isize>()?; let vy = (&cap[4]).trim().parse::<isize>()?; star_map.push((x, y, vx, vy)); } } let max_step = if test { 3 } else { 10619 }; for _ in 0..max_step { move_stars(&mut star_map); } Ok(show_stars(&star_map)) } fn move_stars(star_map: &mut Vec<(isize, isize, isize, isize)>) { for star in star_map { star.0 += star.2; star.1 += star.3; } } fn show_stars(star_map: &[(isize, isize, isize, isize)]) -> String { let mut output = String::new(); let mut min_x = isize::max_value(); let mut min_y = isize::max_value(); let mut max_x = isize::min_value(); let mut max_y = isize::min_value(); for star in star_map { if star.0 < min_x { min_x = star.0; } if star.0 > max_x { max_x = star.0; } if star.1 < min_y { min_y = star.1; } if star.1 > max_y { max_y = star.1; } } for y in min_y..=max_y { for x in min_x..=max_x { let mut found_star = false; for star in star_map { if star.0 == x && star.1 == y { output.push('#'); found_star = true; break; } } if !found_star { output.push('.'); } } output.push('\n'); } output } #[cfg(test)] mod one_star { use super::align; use error::Result; use std::io::Cursor; const TEST_CHAIN: &str = r"position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0> position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1> position=< 2, -4> velocity=< 2, 2> position=<-6, 10> velocity=< 2, -2> position=< 1, 8> velocity=< 1, -1> position=< 1, 7> velocity=< 1, 0> position=<-3, 11> velocity=< 1, -2> position=< 7, 6> velocity=<-1, -1> position=<-2, 3> velocity=< 1, 0> position=<-4, 3> velocity=< 2, 0> position=<10, -3> velocity=<-1, 1> position=< 5, 11> velocity=< 1, -2> position=< 4, 7> velocity=< 0, -1> position=< 8, -2> velocity=< 0, 1> position=<15, 0> velocity=<-2, 0> position=< 1, 6> velocity=< 1, 0> position=< 8, 9> velocity=< 0, -1> position=< 3, 3> velocity=<-1, 1> position=< 0, 5> velocity=< 0, -1> position=<-2, 2> velocity=< 2, 0> position=< 5, -2> velocity=< 1, 2> position=< 1, 4> velocity=< 2, 1> position=<-2, 7> velocity=< 2, -2> position=< 3, 6> velocity=<-1, -1> position=< 5, 0> velocity=< 1, 0> position=<-6, 0> velocity=< 2, 0> position=< 5, 9> velocity=< 1, -2> position=<14, 7> velocity=<-2, 0> position=<-3, 6> velocity=< 2, -1>"; const EXPECTED: &str = r"#...#..### #...#...#. #...#...#. #####...#. #...#...#. #...#...#. #...#...#. #...#..### "; #[test] fn solution() -> Result<()> { assert_eq!(align(Cursor::new(TEST_CHAIN), true)?, EXPECTED); Ok(()) } } #[cfg(test)] mod two_star { #[test] fn solution() { assert!(true); } }
use error::Result; use regex::Regex; use std::io::BufRead; pub fn find_solution<T: BufRead>(reader: T, _second_star: bool) -> Result<u32> { println!("{}", align(reader, false)?); Ok(0) } fn align<T: BufRead>(reader: T, test: bool) -> Result<String> { let line_re = Regex::new(r"position=<(.*), (.*)> velocity=<(.*), (.*)>")?; let mut star_map: Vec<(isize, isize, isize, isize)> = Vec::new(); for line in reader.lines().filter_map(|x| x.ok()) { for cap in line_re.captures_iter(&line) { let x = (&cap[1]).trim().parse::<isize>()?; let y = (&cap[2]).trim().parse::<isize>()?; let vx = (&cap[3]).trim().parse::<isize>()?; let vy = (&cap[4]).trim().parse::<isize>()?; star_map.push((x, y, vx, vy)); } } let max_step = if test { 3 } else { 10619 }; for _ in 0..max_step { move_stars(&mut star_map); } Ok(show_stars(&star_map)) } fn move_stars(star_map: &mut Vec<(isize, isize, isize, isize)>) { for star in star_map { star.0 += star.2; star.1 += star.3; } } fn show_stars(star_map: &[(isize, isize, isize, isize)]) -> String { let mut output = String::new(); let mut min_x = isize::max_value(); let mut min_y = isize::max_value(); let mut max_x = isize::min_value(); let mut max_y = isize::min_value(); for star in star_map { if star.0 < min_x { min_x = star.0; }
#[cfg(test)] mod one_star { use super::align; use error::Result; use std::io::Cursor; const TEST_CHAIN: &str = r"position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0> position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1> position=< 2, -4> velocity=< 2, 2> position=<-6, 10> velocity=< 2, -2> position=< 1, 8> velocity=< 1, -1> position=< 1, 7> velocity=< 1, 0> position=<-3, 11> velocity=< 1, -2> position=< 7, 6> velocity=<-1, -1> position=<-2, 3> velocity=< 1, 0> position=<-4, 3> velocity=< 2, 0> position=<10, -3> velocity=<-1, 1> position=< 5, 11> velocity=< 1, -2> position=< 4, 7> velocity=< 0, -1> position=< 8, -2> velocity=< 0, 1> position=<15, 0> velocity=<-2, 0> position=< 1, 6> velocity=< 1, 0> position=< 8, 9> velocity=< 0, -1> position=< 3, 3> velocity=<-1, 1> position=< 0, 5> velocity=< 0, -1> position=<-2, 2> velocity=< 2, 0> position=< 5, -2> velocity=< 1, 2> position=< 1, 4> velocity=< 2, 1> position=<-2, 7> velocity=< 2, -2> position=< 3, 6> velocity=<-1, -1> position=< 5, 0> velocity=< 1, 0> position=<-6, 0> velocity=< 2, 0> position=< 5, 9> velocity=< 1, -2> position=<14, 7> velocity=<-2, 0> position=<-3, 6> velocity=< 2, -1>"; const EXPECTED: &str = r"#...#..### #...#...#. #...#...#. #####...#. #...#...#. #...#...#. #...#...#. #...#..### "; #[test] fn solution() -> Result<()> { assert_eq!(align(Cursor::new(TEST_CHAIN), true)?, EXPECTED); Ok(()) } } #[cfg(test)] mod two_star { #[test] fn solution() { assert!(true); } }
if star.0 > max_x { max_x = star.0; } if star.1 < min_y { min_y = star.1; } if star.1 > max_y { max_y = star.1; } } for y in min_y..=max_y { for x in min_x..=max_x { let mut found_star = false; for star in star_map { if star.0 == x && star.1 == y { output.push('#'); found_star = true; break; } } if !found_star { output.push('.'); } } output.push('\n'); } output }
function_block-function_prefix_line
[ { "content": "fn lca<T: BufRead>(reader: T, max_i: usize, max_j: usize, _second_star: bool, test: bool) -> Result<Array2<char>> {\n\n let mut lca = Array2::<char>::default((max_i, max_j));\n\n\n\n for (j, line) in reader.lines().filter_map(|x| x.ok()).enumerate() {\n\n for (i, ch) in line.chars().e...
Rust
src/endian/write.rs
zaksabeast/no_std_io
092305d45807619ad35a5bb89f3396f562c27f13
use crate::Error; use core::mem; pub trait EndianWrite { fn get_size(&self) -> usize; fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error>; fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error>; } impl EndianWrite for bool { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<bool>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = [*self as u8]; dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<bool>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = [*self as u8]; dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for u8 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u8>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u8>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i8 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i8>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i8>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for u16 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u16>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u16>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i16 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i16>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i16>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for u32 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u32>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u32>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i32 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i32>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i32>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for u64 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u64>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u64>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i64 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i64>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i64>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl<const SIZE: usize> EndianWrite for [u8; SIZE] { #[inline(always)] fn get_size(&self) -> usize { SIZE } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { if SIZE > dst.len() { return Err(Error::InvalidSize { wanted_size: SIZE, offset: 0, data_len: dst.len(), }); } dst[..SIZE].copy_from_slice(self); Ok(SIZE) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { if SIZE > dst.len() { return Err(Error::InvalidSize { wanted_size: SIZE, offset: 0, data_len: dst.len(), }); } dst[..SIZE].copy_from_slice(self); Ok(SIZE) } } impl EndianWrite for () { fn get_size(&self) -> usize { 0 } fn try_write_le(&self, _dst: &mut [u8]) -> Result<usize, Error> { Ok(0) } fn try_write_be(&self, _dst: &mut [u8]) -> Result<usize, Error> { Ok(0) } }
use crate::Error; use core::mem; pub trait EndianWrite { fn get_size(&self) -> usize; fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error>; fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error>; } impl EndianWrite for bool { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<bool>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = [*self as u8]; dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<bool>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = [*self as u8]; dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for u8 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u8>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u8>(); if byte_count > dst.len() { return Err(Error::InvalidSize {
); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u64>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i64 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i64>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i64>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl<const SIZE: usize> EndianWrite for [u8; SIZE] { #[inline(always)] fn get_size(&self) -> usize { SIZE } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { if SIZE > dst.len() { return Err(Error::InvalidSize { wanted_size: SIZE, offset: 0, data_len: dst.len(), }); } dst[..SIZE].copy_from_slice(self); Ok(SIZE) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { if SIZE > dst.len() { return Err(Error::InvalidSize { wanted_size: SIZE, offset: 0, data_len: dst.len(), }); } dst[..SIZE].copy_from_slice(self); Ok(SIZE) } } impl EndianWrite for () { fn get_size(&self) -> usize { 0 } fn try_write_le(&self, _dst: &mut [u8]) -> Result<usize, Error> { Ok(0) } fn try_write_be(&self, _dst: &mut [u8]) -> Result<usize, Error> { Ok(0) } }
wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i8 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i8>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i8>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for u16 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u16>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u16>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i16 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i16>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i16>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for u32 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u32>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u32>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i32 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i32>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<i32>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for u64 { #[inline(always)] fn get_size(&self) -> usize { mem::size_of::<Self>() } #[inline(always)] fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u64>(); if byte_count > dst.len() { return Err(Error::InvalidSize { wanted_size: byte_count, offset: 0, data_len: dst.len(), }
random
[ { "content": "#[test]\n\nfn should_error_if_there_are_not_enough_bytes() {\n\n let bytes = vec![0xaa, 0xbb, 0xcc, 0xdd];\n\n let result = bytes\n\n .read_le::<Test>(0)\n\n .expect_err(\"This should have failed\");\n\n assert_eq!(\n\n result,\n\n Error::InvalidSize {\n\n ...
Rust
src/flows_node.rs
maidsafe/routing_model
97f11a3dda8a6ff12a4db19b2096867ec9fa2d59
use crate::{ state::JoiningState, utilities::{ GenesisPfxInfo, LocalEvent, Name, ProofRequest, RelocatedInfo, Rpc, TryResult, WaitedEvent, }, }; use unwrap::unwrap; #[derive(Debug, PartialEq)] pub struct JoiningRelocateCandidate<'a>(pub &'a mut JoiningState); impl<'a> JoiningRelocateCandidate<'a> { pub fn start_event_loop(&mut self, relocated_info: RelocatedInfo) { self.0.join_routine.relocated_info = Some(relocated_info); self.connect_or_send_candidate_info(); self.start_refused_timeout(); } pub fn try_next(&mut self, event: WaitedEvent) -> TryResult { let result = match event { WaitedEvent::Rpc(rpc) => self.try_rpc(rpc), WaitedEvent::LocalEvent(local_event) => self.try_local_event(local_event), _ => TryResult::Unhandled, }; if result == TryResult::Unhandled { self.discard(); } TryResult::Handled } fn try_rpc(&mut self, rpc: Rpc) -> TryResult { if !rpc .destination() .map(|name| self.0.action.is_our_name(name)) .unwrap_or(false) { return TryResult::Unhandled; } match rpc { Rpc::NodeApproval(_, info) => { self.exit(info); TryResult::Handled } Rpc::ConnectionInfoResponse { source, .. } => { self.send_candidate_info(source); TryResult::Handled } Rpc::ResourceProof { proof, source, .. } => { self.start_compute_resource_proof(source, proof); TryResult::Handled } Rpc::ResourceProofReceipt { source, .. } => { self.send_next_proof_response(source); TryResult::Handled } _ => TryResult::Unhandled, } } fn try_local_event(&mut self, local_event: LocalEvent) -> TryResult { match local_event { LocalEvent::ResourceProofForElderReady(source) => { self.send_next_proof_response(source); TryResult::Handled } LocalEvent::JoiningTimeoutResendInfo => { self.connect_or_send_candidate_info(); TryResult::Handled } _ => TryResult::Unhandled, } } fn exit(&mut self, info: GenesisPfxInfo) { self.0.join_routine.routine_complete_output = Some(info); } fn discard(&mut self) {} fn send_next_proof_response(&mut self, source: Name) { if let Some(next_part) = self.0.action.get_next_resource_proof_part(source) { self.0 .action .send_resource_proof_response(source, next_part); } } fn send_candidate_info(&mut self, destination: Name) { self.0 .action .send_candidate_info(destination, unwrap!(self.0.join_routine.relocated_info)); } fn connect_or_send_candidate_info(&mut self) { let relocated_info = unwrap!(self.0.join_routine.relocated_info); let (connected, unconnected) = self.0.action.get_connected_and_unconnected(relocated_info); for name in unconnected { self.0.action.send_connection_info_request(name); } for name in connected { self.0.action.send_candidate_info(name, relocated_info); } self.0 .action .schedule_event(LocalEvent::JoiningTimeoutResendInfo); } fn start_refused_timeout(&mut self) { self.0 .action .schedule_event(LocalEvent::JoiningTimeoutProofRefused); } fn start_compute_resource_proof(&mut self, source: Name, proof: ProofRequest) { self.0.action.start_compute_resource_proof(source, proof); } }
use crate::{ state::JoiningState, utilities::{ GenesisPfxInfo, LocalEvent, Name, ProofRequest, RelocatedInfo, Rpc, TryResult, WaitedEvent, }, }; use unwrap::unwrap; #[derive(Debug, PartialEq)] pub struct JoiningRelocateCandidate<'a>(pub &'a mut JoiningState); impl<'a> JoiningRelocateCandidate<'a> { pub fn start_event_loop(&mut self, relocated_info: RelocatedInfo) { self.0.join_routine.relocated_info = Some(relocated_info); self.connect_or_send_candidate_info(); self.start_refused_timeout(); } pub fn try_next(&mut self, event: WaitedEvent) -> TryResult { let result = match event { WaitedEvent::Rpc(rpc) => self.try_rpc(rpc), WaitedEvent::LocalEvent(local_event) => self.try_local_event(local_event), _ => TryResult::Unhandled, }; if result == TryResult::Unhandled { self.discard(); } TryResult::Handled } fn try_rpc(&mut self, rpc: Rpc) -> TryResult { if !rpc .destination() .map(|name| self.0.action.is_our_name(name)) .unwrap_or(false) { return TryResult::Unhandled; } match rpc { Rpc::NodeApproval(_, info) => { self.exit(info); TryResult::Handled } Rpc::ConnectionInfoResponse { source, .. } => { self.send_candidate_info(source); TryResult::Handled } Rpc::ResourceProof { proof, source, .. } => { self.start_compute_resource_proof(source, proof); TryResult::Handled } Rpc::ResourceProofReceipt { source, .. } => { self.send_next_proof_response(source); TryResult::Handled } _ => TryResult::Unhandled, } } fn try_local_event(&mut self, local_event: LocalEvent) -> TryResult { match local_event { LocalEvent::ResourceProofForElderReady(source) => { self.send_next_proof_response(source); TryResult::H
fn exit(&mut self, info: GenesisPfxInfo) { self.0.join_routine.routine_complete_output = Some(info); } fn discard(&mut self) {} fn send_next_proof_response(&mut self, source: Name) { if let Some(next_part) = self.0.action.get_next_resource_proof_part(source) { self.0 .action .send_resource_proof_response(source, next_part); } } fn send_candidate_info(&mut self, destination: Name) { self.0 .action .send_candidate_info(destination, unwrap!(self.0.join_routine.relocated_info)); } fn connect_or_send_candidate_info(&mut self) { let relocated_info = unwrap!(self.0.join_routine.relocated_info); let (connected, unconnected) = self.0.action.get_connected_and_unconnected(relocated_info); for name in unconnected { self.0.action.send_connection_info_request(name); } for name in connected { self.0.action.send_candidate_info(name, relocated_info); } self.0 .action .schedule_event(LocalEvent::JoiningTimeoutResendInfo); } fn start_refused_timeout(&mut self) { self.0 .action .schedule_event(LocalEvent::JoiningTimeoutProofRefused); } fn start_compute_resource_proof(&mut self, source: Name, proof: ProofRequest) { self.0.action.start_compute_resource_proof(source, proof); } }
andled } LocalEvent::JoiningTimeoutResendInfo => { self.connect_or_send_candidate_info(); TryResult::Handled } _ => TryResult::Unhandled, } }
function_block-function_prefixed
[ { "content": "fn process_events(mut state: MemberState, events: &[Event]) -> MemberState {\n\n for event in events.iter().cloned() {\n\n if TryResult::Unhandled == state.try_next(event) {\n\n state.failure_event(event);\n\n }\n\n\n\n if state.failure.is_some() {\n\n ...
Rust
src/adapters/twitter.rs
w3f/polkadot-registrar-bot
3c5aa36cf5de8edae0ac434947eb585b7ca92c75
use crate::adapters::Adapter; use crate::primitives::{ExternalMessage, ExternalMessageType, MessageId, Timestamp}; use crate::Result; use hmac::{Hmac, Mac}; use rand::{thread_rng, Rng}; use reqwest::header::{self, HeaderValue}; use reqwest::{Client, Request}; use serde::de::DeserializeOwned; use serde::Serialize; use sha1::Sha1; use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use std::time::{SystemTime, UNIX_EPOCH}; use std::{cmp::Ordering, hash::Hash}; #[derive(Clone, Debug, Eq, PartialEq)] pub struct ReceivedMessageContext { sender: TwitterId, id: u64, message: String, } #[derive(Debug, Clone, Eq, Hash, PartialEq, Serialize, Deserialize)] pub struct TwitterId(u64); impl TwitterId { pub fn as_u64(&self) -> u64 { self.0 } } impl Ord for TwitterId { fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) } } impl PartialOrd for TwitterId { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl From<u64> for TwitterId { fn from(val: u64) -> Self { TwitterId(val) } } impl TryFrom<String> for TwitterId { type Error = anyhow::Error; fn try_from(val: String) -> Result<Self> { Ok(TwitterId(val.parse::<u64>()?)) } } pub struct TwitterBuilder { consumer_key: Option<String>, consumer_secret: Option<String>, token: Option<String>, token_secret: Option<String>, } impl TwitterBuilder { pub fn new() -> Self { TwitterBuilder { consumer_key: None, consumer_secret: None, token: None, token_secret: None, } } pub fn consumer_key(mut self, key: String) -> Self { self.consumer_key = Some(key); self } pub fn consumer_secret(mut self, key: String) -> Self { self.consumer_secret = Some(key); self } pub fn token(mut self, token: String) -> Self { self.token = Some(token); self } pub fn token_secret(mut self, secret: String) -> Self { self.token_secret = Some(secret); self } pub fn build(self) -> Result<TwitterClient> { Ok(TwitterClient { client: Client::new(), consumer_key: self .consumer_key .ok_or_else(|| anyhow!("consumer key name not specified"))?, consumer_secret: self .consumer_secret .ok_or_else(|| anyhow!("consumer secret name not specified"))?, token: self.token.ok_or_else(|| anyhow!("token not specified"))?, token_secret: self .token_secret .ok_or_else(|| anyhow!("token secret not specified"))?, twitter_ids: HashMap::new(), cache: HashSet::new(), }) } } fn gen_nonce() -> String { let random: [u8; 16] = thread_rng().gen(); hex::encode(random) } fn gen_timestamp() -> u64 { let start = SystemTime::now(); start .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_secs() } #[derive(Clone)] pub struct TwitterClient { client: Client, consumer_key: String, consumer_secret: String, token: String, token_secret: String, twitter_ids: HashMap<TwitterId, String>, cache: HashSet<MessageId>, } impl TwitterClient { async fn request_messages(&mut self) -> Result<Vec<ExternalMessage>> { debug!("Requesting Twitter messages"); let mut messages = self .get_request::<ApiMessageRequest>( "https://api.twitter.com/1.1/direct_messages/events/list.json", None, ) .await? .parse()?; messages.retain(|message| !self.cache.contains(&message.id.into())); if messages.is_empty() { debug!("No new Twitter messages found"); return Ok(vec![]); } else { debug!("Fetched {} message(-s)", messages.len()); } #[rustfmt::skip] let mut to_lookup: Vec<&TwitterId> = messages .iter() .filter(|message| { !self.twitter_ids.contains_key(&message.sender) }) .map(|message| &message.sender) .collect(); to_lookup.sort(); to_lookup.dedup(); debug!("Looking up Twitter Ids"); if !to_lookup.is_empty() { let lookup_results = self.lookup_twitter_id(Some(&to_lookup), None).await?; self.twitter_ids.extend(lookup_results); } let mut parsed_messages = vec![]; for message in messages { let sender = self .twitter_ids .get(&message.sender) .ok_or_else(|| anyhow!("Failed to find Twitter handle based on Id"))? .clone(); let id = message.id.into(); parsed_messages.push(ExternalMessage { origin: ExternalMessageType::Twitter(sender), id, timestamp: Timestamp::now(), values: vec![message.message.into()], }); self.cache.insert(id); } Ok(parsed_messages) } fn authenticate_request( &self, url: &str, request: &mut Request, params: Option<&[(&str, &str)]>, ) -> Result<()> { use urlencoding::encode; let nonce = gen_nonce(); let timestamp = gen_timestamp().to_string(); let mut fields = vec![ ("oauth_consumer_key", self.consumer_key.as_str()), ("oauth_nonce", nonce.as_str()), ("oauth_signature_method", "HMAC-SHA1"), ("oauth_timestamp", &timestamp), ("oauth_token", self.token.as_str()), ("oauth_version", "1.0"), ]; if let Some(params) = params { fields.append(&mut params.to_vec()); } fields.sort_by(|(a, _), (b, _)| a.cmp(b)); let mut params = String::new(); for (name, val) in &fields { params.push_str(&format!("{}={}&", encode(name), encode(val))); } params.pop(); let base = format!("GET&{}&{}", encode(url), encode(&params)); let sign_key = format!( "{}&{}", encode(&self.consumer_secret), encode(&self.token_secret) ); let mut mac: Hmac<Sha1> = Hmac::new_from_slice(sign_key.as_bytes()).unwrap(); mac.update(base.as_bytes()); let sig = base64::encode(mac.finalize().into_bytes()); fields.push(("oauth_signature", &sig)); fields.sort_by(|(a, _), (b, _)| a.cmp(b)); let mut oauth_header = String::new(); oauth_header.push_str("OAuth "); for (name, val) in &fields { oauth_header.push_str(&format!("{}={}, ", encode(name), encode(val))) } oauth_header.pop(); oauth_header.pop(); request .headers_mut() .insert(header::AUTHORIZATION, HeaderValue::from_str(&oauth_header)?); Ok(()) } async fn get_request<T: DeserializeOwned>( &self, url: &str, params: Option<&[(&str, &str)]>, ) -> Result<T> { let mut full_url = String::from(url); if let Some(params) = params { full_url.push('?'); for (key, val) in params { full_url.push_str(&format!("{}={}&", key, val)); } full_url.pop(); } let mut request = self.client.get(&full_url).build()?; self.authenticate_request(url, &mut request, params)?; let resp = self.client.execute(request).await?; let txt = resp.text().await?; debug!("Twitter response: {:?}", txt); serde_json::from_str::<T>(&txt).map_err(|err| err.into()) } async fn lookup_twitter_id( &self, twitter_ids: Option<&[&TwitterId]>, accounts: Option<&[&String]>, ) -> Result<HashMap<TwitterId, String>> { let mut params = vec![]; let mut lookup = String::new(); if let Some(twitter_ids) = twitter_ids { for twitter_id in twitter_ids { lookup.push_str(&twitter_id.as_u64().to_string()); lookup.push(','); } lookup.pop(); params.push(("user_id", lookup.as_str())) } let mut lookup = String::new(); if let Some(accounts) = accounts { for account in accounts { lookup.push_str(&account.as_str().replace('@', "")); lookup.push(','); } lookup.pop(); params.push(("screen_name", lookup.as_str())) } #[derive(Deserialize)] struct UserObject { id: TwitterId, screen_name: String, } debug!("Params: {:?}", params); let user_objects = self .get_request::<Vec<UserObject>>( "https://api.twitter.com/1.1/users/lookup.json", Some(&params), ) .await?; if user_objects.is_empty() { return Err(anyhow!("unrecognized data")); } Ok(user_objects .into_iter() .map(|obj| (obj.id, format!("@{}", obj.screen_name.to_lowercase()))) .collect()) } } #[derive(Debug, Deserialize, Serialize)] struct ApiMessageRequest { events: Vec<ApiEvent>, } #[derive(Debug, Deserialize, Serialize)] struct ApiEvent { #[serde(rename = "type")] t_type: String, id: String, created_timestamp: Option<String>, message_create: ApiMessageCreate, } #[derive(Debug, Deserialize, Serialize)] struct ApiMessageCreate { target: ApiTarget, sender_id: Option<String>, message_data: ApiMessageData, } #[derive(Debug, Deserialize, Serialize)] struct ApiTarget { recipient_id: String, } #[derive(Debug, Deserialize, Serialize)] struct ApiMessageData { text: String, } impl ApiMessageRequest { fn parse(self) -> Result<Vec<ReceivedMessageContext>> { let mut messages = vec![]; for event in self.events { let message = ReceivedMessageContext { sender: event .message_create .sender_id .ok_or_else(|| anyhow!("unrecognized data"))? .try_into()?, message: event.message_create.message_data.text, id: event.id.parse().map_err(|_| anyhow!("unrecognized data"))?, }; messages.push(message); } Ok(messages) } } #[async_trait] impl Adapter for TwitterClient { type MessageType = (); fn name(&self) -> &'static str { "Twitter" } async fn fetch_messages(&mut self) -> Result<Vec<ExternalMessage>> { self.request_messages().await } async fn send_message(&mut self, _to: &str, _content: Self::MessageType) -> Result<()> { unimplemented!() } }
use crate::adapters::Adapter; use crate::primitives::{ExternalMessage, ExternalMessageType, MessageId, Timestamp}; use crate::Result; use hmac::{Hmac, Mac}; use rand::{thread_rng, Rng}; use reqwest::header::{self, HeaderValue}; use reqwest::{Client, Request}; use serde::de::DeserializeOwned; use serde::Serialize; use sha1::Sha1; use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use std::time::{SystemTime, UNIX_EPOCH}; use std::{cmp::Ordering, hash::Hash}; #[derive(Clone, Debug, Eq, PartialEq)] pub struct ReceivedMessageContext { sender: TwitterId, id: u64, message: String, } #[derive(Debug, Clone, Eq, Hash, PartialEq, Serialize, Deserialize)] pub struct TwitterId(u64); impl TwitterId { pub fn as_u64(&self) -> u64 { self.0 } } impl Ord for TwitterId { fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) } } impl PartialOrd for TwitterId { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl From<u64> for TwitterId { fn from(val: u64) -> Self { TwitterId(val) } } impl TryFrom<String> for TwitterId { type Error = anyhow::Error; fn try_from(val: String) -> Result<Self> { Ok(TwitterId(val.parse::<u64>()?)) } } pub struct TwitterBuilder { consumer_key: Option<String>, consumer_secret: Option<String>, token: Option<String>, token_secret: Option<String>, } impl TwitterBuilder { pub fn new() -> Self { TwitterBuilder { consumer_key: None, consumer_secret: None, token: None, token_secret: None, } } pub fn consumer_key(mut self, key: String) -> Self { self.consumer_key = Some(key); self } pub fn consumer_secret(mut self, key: String) -> Self { self.consumer_secret = Some(key); self } pub fn token(mut self, token: String) -> Self { self.token = Some(token); self } pub fn token_secret(mut self, secret: String) -> Self { self.token_secret = Some(secret); self } pub fn build(self) -> Result<TwitterClient> { Ok(TwitterClient { client: Client::new(), consumer_key: self .consumer_key .ok_or_else(|| anyhow!("consumer key name not specified"))?, consumer_secret: self .consumer_secret .ok_or_else(|| anyhow!("consumer secret name not specified"))?, token: self.token.ok_or_else(|| anyhow!("token not specified"))?, token_secret: self .token_secret .ok_or_else(|| anyhow!("token secret not specified"))?, twitter_ids: HashMap::new(), cache: HashSet::new(), }) } } fn gen_nonce() -> String { let random: [u8; 16] = thread_rng().gen(); hex::encode(random) } fn gen_timestamp() -> u64 { let start = SystemTime::now(); start .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_secs() } #[derive(Clone)] pub struct TwitterClient { client: Client, consumer_key: String, consumer_secret: String, token: String, token_secret: String, twitter_ids: HashMap<TwitterId, String>, cache: HashSet<MessageId>, } impl TwitterClient { async fn request_messages(&mut self) -> Result<Vec<ExternalMessage>> { debug!("Requesting Twitter messages"); let mut messages = self .get_request::<ApiMessageRequest>( "https://api.twitter.com/1.1/direct_messages/events/list.json", None, ) .await? .parse()?; messages.retain(|message| !self.cache.contains(&message.id.into())); if messages.is_empty() { debug!("No new Twitter messages found"); return Ok(vec![]); } else { debug!("Fetched {} message(-s)", messages.len()); } #[rustfmt::skip] let mut to_lookup: Vec<&TwitterId> = messages .iter() .filter(|message| { !self.twitter_ids.contains_key(&message.sender) }) .map(|message| &message.sender) .collect(); to_lookup.sort(); to_lookup.dedup(); debug!("Looking up Twitter Ids"); if !to_lookup.is_empty() { let lookup_results = self.lookup_twitter_id(Some(&to_lookup), None).await?; self.twitter_ids.extend(lookup_results); } let mut parsed_messages = vec![]; for message in messages { let sender = self .twitter_ids .get(&message.sender) .ok_or_else(|| anyhow!("Failed to find Twitter handle based on Id"))? .clone(); let id = message.id.into(); parsed_messages.push(ExternalMessage { origin: ExternalMessageType::Twitter(sender), id, timestamp: Timestamp::now(), values: vec![message.message.into()], }); self.cache.insert(id); } Ok(parsed_messages) } fn authenticate_request( &self, url: &str, request: &mut Request, params: Option<&[(&str, &str)]>, ) -> Result<()> { use urlencoding::encode; let nonce = gen_nonce(); let timestamp = gen_timestamp().to_string(); let mut fields = vec![ ("oauth_consumer_key", self.consumer_key.as_str()), ("oauth_nonce", nonce.as_str()), ("oauth_signature_method", "HMAC-SHA1"), ("oauth_timestamp", &timestamp), ("oauth_token", self.token.as_str()), ("oauth_version", "1.0"), ]; if let Some(params) = params { fields.append(&mut params.to_vec()); } fields.sort_by(|(a, _), (b, _)| a.cmp(b)); let mut params = String::new(); for (name, val) in &fields { params.push_str(&format!("{}={}&", encode(name), encode(val))); } params.pop(); let base = format!("GET&{}&{}", encode(url), encode(&params)); let sign_key = format!( "{}&{}", encode(&self.consumer_secret), encode(&self.token_secret) ); let mut mac: Hmac<Sha1> = Hmac::new_from_slice(sign_key.as_bytes()).unwrap(); mac.update(base.as_bytes()); let sig = base64::encode(mac.finalize().into_bytes()); fields.push(("oauth_signature", &sig)); fields.sort_by(|(a, _), (b, _)| a.cmp(b)); let mut oauth_header = String::new(); oauth_header.push_str("OAuth "); for (name, val) in &fields { oauth_header.push_str(&format!("{}={}, ", encode(name), encode(val))) } oauth_header.pop(); oauth_header.pop(); request .headers_mut() .insert(header::AUTHORIZATION, HeaderValue::from_str(&oauth_header)?); Ok(()) } async fn get_request<T: DeserializeOwned>( &self, url: &str, params: Option<&[(&str, &str)]>, ) -> Result<T> { let mut full_url = String::from(url); if let Some(params) = params { full_url.push('?'); for (key, val) in params { full_url.push_str(&format!("{}={}&", key, val)); } full_url.pop(); } let mut request = self.client.get(&full_url).build()?; self.authenticate_request(url, &mut request, params)?; let resp = self.client.execute(request).await?; let txt = resp.text().await?; debug!("Twitter response: {:?}", txt); serde_json::from_str::<T>(&txt).map_err(|err| err.into()) } async fn lookup_twitter_id( &self, twitter_ids: Option<&[&TwitterId]>, accounts: Option<&[&String]>, ) -> Result<HashMap<TwitterId, String>> { let mut params = vec![]; let mut lookup = String::new(); if let Some(twitter_ids) = twitter_ids { for twitter_id in twitter_ids { lookup.push_str(&twitter_id.as_u64().to_string()); lookup.push(','); } lookup.pop(); params.push(("user_id", lookup.as_str())) } let mut lookup = String::new(); if let Some(accounts) = accounts { for account in accounts { lookup.push_str(&account.as_str().replace('@', "")); lookup.push(','); } lookup.pop(); params.push(("screen_name", lookup.as_str())) } #[derive(Deserialize)] struct UserObject { id: TwitterId, screen_name: String, } debug!("Params: {:?}", params); let user_objects = self .get_request::<Vec<UserObject>>( "https://api.twitter.com/1.1/users/lookup.json", Some(&params), ) .await?; if user_objects.is_empty() { return Err(anyhow!("unrecognized data")); } Ok(user_objects .
} #[derive(Debug, Deserialize, Serialize)] struct ApiMessageRequest { events: Vec<ApiEvent>, } #[derive(Debug, Deserialize, Serialize)] struct ApiEvent { #[serde(rename = "type")] t_type: String, id: String, created_timestamp: Option<String>, message_create: ApiMessageCreate, } #[derive(Debug, Deserialize, Serialize)] struct ApiMessageCreate { target: ApiTarget, sender_id: Option<String>, message_data: ApiMessageData, } #[derive(Debug, Deserialize, Serialize)] struct ApiTarget { recipient_id: String, } #[derive(Debug, Deserialize, Serialize)] struct ApiMessageData { text: String, } impl ApiMessageRequest { fn parse(self) -> Result<Vec<ReceivedMessageContext>> { let mut messages = vec![]; for event in self.events { let message = ReceivedMessageContext { sender: event .message_create .sender_id .ok_or_else(|| anyhow!("unrecognized data"))? .try_into()?, message: event.message_create.message_data.text, id: event.id.parse().map_err(|_| anyhow!("unrecognized data"))?, }; messages.push(message); } Ok(messages) } } #[async_trait] impl Adapter for TwitterClient { type MessageType = (); fn name(&self) -> &'static str { "Twitter" } async fn fetch_messages(&mut self) -> Result<Vec<ExternalMessage>> { self.request_messages().await } async fn send_message(&mut self, _to: &str, _content: Self::MessageType) -> Result<()> { unimplemented!() } }
into_iter() .map(|obj| (obj.id, format!("@{}", obj.screen_name.to_lowercase()))) .collect()) }
function_block-function_prefix_line
[ { "content": "fn try_decode_hex(display_name: &mut String) {\n\n if display_name.starts_with(\"0x\") {\n\n // Might be a false positive. Leave it as is if it cannot be decoded.\n\n if let Ok(name) = hex::decode(&display_name[2..]) {\n\n if let Ok(name) = String::from_utf8(name) {\n\n...
Rust
simulator/src/memory.rs
Laegluin/mikrorechner
7e5e878072c941e422889465c43dea838b83e5fd
use crate::vm; use byteorder::{ByteOrder, LittleEndian}; use rand; use std::cmp::min; use std::mem; use std::ptr; pub type Word = u32; pub const WORD_BYTES: Word = mem::size_of::<Word>() as Word; pub const WORD_BITS: Word = WORD_BYTES * 8; pub const OP_CODE_BITS: Word = 5; pub const REG_REF_BITS: Word = 6; const WRITABLE_MEM_START_ADDR: Word = 0x80000000; const PAGE_LEN: usize = 4096; const LEVEL_1_TABLE_LEN: usize = 1024; const LEVEL_2_TABLE_LEN: usize = 1024; pub struct Memory { init_value: u8, page_table: Level2Table, } pub enum Access { All, Protected, } impl Memory { pub fn new() -> Memory { Memory { init_value: rand::random(), page_table: Level2Table::empty(), } } pub fn store_word(&mut self, addr: Word, value: Word) -> Result<(), vm::ErrorKind> { let mut bytes = [0; WORD_BYTES as usize]; LittleEndian::write_u32(&mut bytes, value); self.store(addr, &bytes, Access::Protected) } pub fn store(&mut self, addr: Word, buf: &[u8], access: Access) -> Result<(), vm::ErrorKind> { if buf.len() > (Word::max_value() - addr) as usize { return Err(vm::ErrorKind::OutOfBoundsMemoryAccess(addr, buf.len())); } match access { Access::All => (), Access::Protected => { if addr < WRITABLE_MEM_START_ADDR { return Err(vm::ErrorKind::ReadOnlyMemoryWriteAccess(addr)); } } } let mut ptr = addr; let mut remaining = buf; while !remaining.is_empty() { let (memory, _) = self.mem_ref(ptr, remaining.len() as Word); let memory_len = memory.len(); memory[..].copy_from_slice(&remaining[..memory_len]); ptr += memory_len as Word; remaining = &remaining[memory_len..]; } Ok(()) } pub fn load_word(&mut self, addr: Word) -> Result<Word, vm::ErrorKind> { let mut bytes = [0; WORD_BYTES as usize]; self.load(addr, &mut bytes)?; Ok(LittleEndian::read_u32(&bytes)) } pub fn load(&mut self, addr: Word, buf: &mut [u8]) -> Result<(), vm::ErrorKind> { if buf.len() > (Word::max_value() - addr) as usize { return Err(vm::ErrorKind::OutOfBoundsMemoryAccess(addr, buf.len())); } let buf_len = buf.len() as Word; let mut ptr = addr; let mut bytes_read = 0; while bytes_read < buf_len as usize { match self.mem_ref(ptr, buf_len - bytes_read as Word) { (_, true) => return Err(vm::ErrorKind::UninitializedMemoryAccess(ptr)), (memory, _) => { let memory_len = memory.len(); buf[bytes_read..bytes_read + memory_len].copy_from_slice(&memory); ptr += memory_len as Word; bytes_read += memory_len; } } } Ok(()) } fn mem_ref(&mut self, addr: Word, len: Word) -> (&mut [u8], bool) { let lvl_2_idx = addr >> 22; let lvl_1_idx = (addr >> 12) & (Word::max_value() >> 22); let page_idx = addr & (Word::max_value() >> 20); let init_value = self.init_value; let mut is_page_fault = false; let page = self.page_table.tables[lvl_2_idx as usize] .get_or_insert_with(|| Box::new(Level1Table::empty())) .pages[lvl_1_idx as usize] .get_or_insert_with(|| { is_page_fault = true; Box::new([init_value; PAGE_LEN]) }); let start = page_idx as usize; let end = min(page.len(), (page_idx + len) as usize); (&mut page[start..end], is_page_fault) } } struct Level2Table { tables: [Option<Box<Level1Table>>; LEVEL_2_TABLE_LEN], } impl Level2Table { fn empty() -> Level2Table { unsafe { let mut tables: [Option<Box<Level1Table>>; LEVEL_2_TABLE_LEN] = mem::uninitialized(); for table in &mut tables[..] { ptr::write(table, None); } Level2Table { tables } } } } struct Level1Table { pages: [Option<Box<[u8; PAGE_LEN]>>; LEVEL_1_TABLE_LEN], } impl Level1Table { fn empty() -> Level1Table { unsafe { let mut pages: [Option<Box<[u8; PAGE_LEN]>>; LEVEL_1_TABLE_LEN] = mem::uninitialized(); for page in &mut pages[..] { ptr::write(page, None); } Level1Table { pages } } } } #[cfg(test)] mod test { use super::*; #[test] fn mem_ref() { let mut mem = Memory::new(); assert!(mem.mem_ref(0, 100).1); let mut mem = Memory::new(); mem.store(0, &[0; 10], Access::All).unwrap(); mem.store(10, &[1; 10], Access::All).unwrap(); assert_eq!(mem.mem_ref(0, 10), (&mut *vec![0; 10], false)); assert_eq!(mem.mem_ref(10, 10), (&mut *vec![1; 10], false)); assert_eq!( mem.mem_ref(0, 20), ( &mut *vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], false ) ); } #[test] #[should_panic] fn store_panic_on_overflow() { let mut mem = Memory::new(); mem.store(Word::max_value(), &[1, 2, 3, 4], Access::All) .unwrap(); } #[test] #[should_panic] fn load_panic_on_overflow() { let mut mem = Memory::new(); mem.load(Word::max_value(), &mut vec![0; 11]).unwrap(); } #[test] fn load_and_store() { let mut mem = Memory::new(); mem.load(0, &mut vec![0; 42]).unwrap_err(); let mut mem = Memory::new(); mem.store(0, &[1, 2, 3, 4], Access::All).unwrap(); let mut buf = vec![0; 4]; mem.load(0, &mut buf).unwrap(); assert_eq!(vec![1, 2, 3, 4], buf); let mut buf = vec![0; 2]; mem.load(2, &mut buf).unwrap(); assert_eq!(vec![3, 4], buf); let mut mem = Memory::new(); mem.store(PAGE_LEN as Word - 3, &[1, 2, 3, 4, 5, 6], Access::All) .unwrap(); let mut buf = vec![0; 6]; mem.load(PAGE_LEN as Word - 3, &mut buf).unwrap(); assert_eq!(vec![1, 2, 3, 4, 5, 6], buf); } #[test] fn out_of_bounds_mem_access() { let mut mem = Memory::new(); assert_eq!( mem.load_word(0xffffffff).unwrap_err(), vm::ErrorKind::OutOfBoundsMemoryAccess(0xffffffff, 4) ); assert_eq!( mem.store_word(0xffffffff, 0xdeaddead).unwrap_err(), vm::ErrorKind::OutOfBoundsMemoryAccess(0xffffffff, 4) ); } }
use crate::vm; use byteorder::{ByteOrder, LittleEndian}; use rand; use std::cmp::min; use std::mem; use std::ptr; pub type Word = u32; pub const WORD_BYTES: Word = mem::size_of::<Word>() as Word; pub const WORD_BITS: Word = WORD_BYTES * 8; pub const OP_CODE_BITS: Word = 5; pub const REG_REF_BITS: Word = 6; const WRITABLE_MEM_START_ADDR: Word = 0x80000000; const PAGE_LEN: usize = 4096; const LEVEL_1_TABLE_LEN: usize = 1024; const LEVEL_2_TABLE_LEN: usize = 1024; pub struct Memory { init_value: u8, page_table: Level2Table, } pub enum Access { All, Protected, } impl Memory {
pub fn store_word(&mut self, addr: Word, value: Word) -> Result<(), vm::ErrorKind> { let mut bytes = [0; WORD_BYTES as usize]; LittleEndian::write_u32(&mut bytes, value); self.store(addr, &bytes, Access::Protected) } pub fn store(&mut self, addr: Word, buf: &[u8], access: Access) -> Result<(), vm::ErrorKind> { if buf.len() > (Word::max_value() - addr) as usize { return Err(vm::ErrorKind::OutOfBoundsMemoryAccess(addr, buf.len())); } match access { Access::All => (), Access::Protected => { if addr < WRITABLE_MEM_START_ADDR { return Err(vm::ErrorKind::ReadOnlyMemoryWriteAccess(addr)); } } } let mut ptr = addr; let mut remaining = buf; while !remaining.is_empty() { let (memory, _) = self.mem_ref(ptr, remaining.len() as Word); let memory_len = memory.len(); memory[..].copy_from_slice(&remaining[..memory_len]); ptr += memory_len as Word; remaining = &remaining[memory_len..]; } Ok(()) } pub fn load_word(&mut self, addr: Word) -> Result<Word, vm::ErrorKind> { let mut bytes = [0; WORD_BYTES as usize]; self.load(addr, &mut bytes)?; Ok(LittleEndian::read_u32(&bytes)) } pub fn load(&mut self, addr: Word, buf: &mut [u8]) -> Result<(), vm::ErrorKind> { if buf.len() > (Word::max_value() - addr) as usize { return Err(vm::ErrorKind::OutOfBoundsMemoryAccess(addr, buf.len())); } let buf_len = buf.len() as Word; let mut ptr = addr; let mut bytes_read = 0; while bytes_read < buf_len as usize { match self.mem_ref(ptr, buf_len - bytes_read as Word) { (_, true) => return Err(vm::ErrorKind::UninitializedMemoryAccess(ptr)), (memory, _) => { let memory_len = memory.len(); buf[bytes_read..bytes_read + memory_len].copy_from_slice(&memory); ptr += memory_len as Word; bytes_read += memory_len; } } } Ok(()) } fn mem_ref(&mut self, addr: Word, len: Word) -> (&mut [u8], bool) { let lvl_2_idx = addr >> 22; let lvl_1_idx = (addr >> 12) & (Word::max_value() >> 22); let page_idx = addr & (Word::max_value() >> 20); let init_value = self.init_value; let mut is_page_fault = false; let page = self.page_table.tables[lvl_2_idx as usize] .get_or_insert_with(|| Box::new(Level1Table::empty())) .pages[lvl_1_idx as usize] .get_or_insert_with(|| { is_page_fault = true; Box::new([init_value; PAGE_LEN]) }); let start = page_idx as usize; let end = min(page.len(), (page_idx + len) as usize); (&mut page[start..end], is_page_fault) } } struct Level2Table { tables: [Option<Box<Level1Table>>; LEVEL_2_TABLE_LEN], } impl Level2Table { fn empty() -> Level2Table { unsafe { let mut tables: [Option<Box<Level1Table>>; LEVEL_2_TABLE_LEN] = mem::uninitialized(); for table in &mut tables[..] { ptr::write(table, None); } Level2Table { tables } } } } struct Level1Table { pages: [Option<Box<[u8; PAGE_LEN]>>; LEVEL_1_TABLE_LEN], } impl Level1Table { fn empty() -> Level1Table { unsafe { let mut pages: [Option<Box<[u8; PAGE_LEN]>>; LEVEL_1_TABLE_LEN] = mem::uninitialized(); for page in &mut pages[..] { ptr::write(page, None); } Level1Table { pages } } } } #[cfg(test)] mod test { use super::*; #[test] fn mem_ref() { let mut mem = Memory::new(); assert!(mem.mem_ref(0, 100).1); let mut mem = Memory::new(); mem.store(0, &[0; 10], Access::All).unwrap(); mem.store(10, &[1; 10], Access::All).unwrap(); assert_eq!(mem.mem_ref(0, 10), (&mut *vec![0; 10], false)); assert_eq!(mem.mem_ref(10, 10), (&mut *vec![1; 10], false)); assert_eq!( mem.mem_ref(0, 20), ( &mut *vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], false ) ); } #[test] #[should_panic] fn store_panic_on_overflow() { let mut mem = Memory::new(); mem.store(Word::max_value(), &[1, 2, 3, 4], Access::All) .unwrap(); } #[test] #[should_panic] fn load_panic_on_overflow() { let mut mem = Memory::new(); mem.load(Word::max_value(), &mut vec![0; 11]).unwrap(); } #[test] fn load_and_store() { let mut mem = Memory::new(); mem.load(0, &mut vec![0; 42]).unwrap_err(); let mut mem = Memory::new(); mem.store(0, &[1, 2, 3, 4], Access::All).unwrap(); let mut buf = vec![0; 4]; mem.load(0, &mut buf).unwrap(); assert_eq!(vec![1, 2, 3, 4], buf); let mut buf = vec![0; 2]; mem.load(2, &mut buf).unwrap(); assert_eq!(vec![3, 4], buf); let mut mem = Memory::new(); mem.store(PAGE_LEN as Word - 3, &[1, 2, 3, 4, 5, 6], Access::All) .unwrap(); let mut buf = vec![0; 6]; mem.load(PAGE_LEN as Word - 3, &mut buf).unwrap(); assert_eq!(vec![1, 2, 3, 4, 5, 6], buf); } #[test] fn out_of_bounds_mem_access() { let mut mem = Memory::new(); assert_eq!( mem.load_word(0xffffffff).unwrap_err(), vm::ErrorKind::OutOfBoundsMemoryAccess(0xffffffff, 4) ); assert_eq!( mem.store_word(0xffffffff, 0xdeaddead).unwrap_err(), vm::ErrorKind::OutOfBoundsMemoryAccess(0xffffffff, 4) ); } }
pub fn new() -> Memory { Memory { init_value: rand::random(), page_table: Level2Table::empty(), } }
function_block-full_function
[ { "content": "pub fn to_hex(word: Word) -> String {\n\n let width = WORD_BYTES as usize * 2 + 2;\n\n format!(\"{:#0width$x}\", word, width = width)\n\n}\n\n\n", "file_path": "simulator/src/support.rs", "rank": 0, "score": 217301.66889780847 }, { "content": "struct Instruction(u32);\n\n...
Rust
examples/minijava/src/enumabsyn.rs
chuckcscccl/rustlr
0e9794cca27589c25115325f69fb5b417a77400d
/* Abstract syntax for minijava (adopted from 2014 java program) Using internally generated RetTypeEnum */ #![allow(dead_code)] use rustlr::LBox; use crate::Expr::*; use crate::Stat::*; use crate::Declaration::*; #[derive(Debug)] pub enum Expr<'t> { Int(i32), Strlit(&'t str), Bool(bool), Var(&'t str), Thisptr, Binop(&'static str,LBox<Expr<'t>>,LBox<Expr<'t>>), Notexp(LBox<Expr<'t>>), Field(&'t str,LBox<Expr<'t>>), Newarray(LBox<Expr<'t>>), Newobj(&'t str), Callexp(LBox<Expr<'t>>,&'t str,Vec<LBox<Expr<'t>>>), Nothing, } impl<'t> Default for Expr<'t> { fn default()->Self {Nothing} } #[derive(Debug)] pub enum Stat<'t> { Whilest(LBox<Expr<'t>>,LBox<Stat<'t>>), Ifstat(LBox<Expr<'t>>,LBox<Stat<'t>>,LBox<Stat<'t>>), Vardecst(&'t str,&'t str,LBox<Expr<'t>>), Returnst(LBox<Expr<'t>>), Assignst(&'t str,LBox<Expr<'t>>), ArAssignst(LBox<Expr<'t>>,LBox<Expr<'t>>,LBox<Expr<'t>>), Callstat(LBox<Expr<'t>>,&'t str,Vec<LBox<Expr<'t>>>), Nopst, Blockst(Vec<LBox<Stat<'t>>>), } impl<'t> Default for Stat<'t> {fn default()->Self {Nopst} } #[derive(Debug)] pub struct VarDec<'t> { pub dname:&'t str, pub dtype:&'t str, pub initval:Expr<'t>, } impl<'t> Default for VarDec<'t> { fn default() -> Self { VarDec{dname:"",dtype:"",initval:Nothing} } } #[derive(Debug)] pub struct MethodDec<'t> { pub formals:Vec<LBox<VarDec<'t>>>, pub body: Vec<LBox<Stat<'t>>>, pub classname: &'t str, pub methodname: &'t str, } impl<'t> Default for MethodDec<'t> { fn default() -> Self { MethodDec{formals:Vec::new(),classname:"",methodname:"",body:Vec::new()} } } #[derive(Debug)] pub struct ClassDec<'t> { pub superclass:&'t str, pub classname:&'t str, pub vars: Vec<LBox<VarDec<'t>>>, pub methods: Vec<LBox<MethodDec<'t>>>, } impl<'t> Default for ClassDec<'t> { fn default()->Self { ClassDec{superclass:"Object",classname:"",vars:Vec::new(),methods:Vec::new()}} } #[derive(Debug)] pub enum Declaration<'t> { Mdec(MethodDec<'t>), Vdec(VarDec<'t>), Cdec(ClassDec<'t>), } #[derive(Debug)] pub struct Mainclass<'t> { pub classname:&'t str, pub argvname: &'t str, pub body : Stat<'t>, } impl<'t> Default for Mainclass<'t> { fn default()->Self { Mainclass {classname:"",argvname:"",body:Stat::default(),}} } #[derive(Debug)] pub struct Program<'t> { pub mainclass:LBox<Mainclass<'t>>, pub otherclasses: Vec<LBox<ClassDec<'t>>>, } impl<'t> Default for Program<'t> { fn default()->Self { Program {mainclass:LBox::default(), otherclasses:Vec::new()}} } pub fn separatedecs<'t>(mut ds:Vec<LBox<Declaration<'t>>>,vars:&mut Vec<LBox<VarDec<'t>>>,mths:&mut Vec<LBox<MethodDec<'t>>>) { while ds.len()>0 { let mut dec = ds.pop().unwrap(); match &mut *dec { Vdec(vd) => { let vdec = std::mem::replace(vd,VarDec::default()); vars.push(dec.transfer(vdec)); }, Mdec(md) => { let mdec = std::mem::replace(md,MethodDec::default()); mths.push(dec.transfer(mdec)); }, _ => {}, } } }
/* Abstract syntax for minijava (adopted from 2014 java program) Using internally generated RetTypeEnum */ #![allow(dead_code)] use rustlr::LBox; use crate::Expr::*; use crate::Stat::*; use crate::Declaration::*; #[derive(Debug)] pub enum Expr<'t> { Int(i32), Strlit(&'t str), Bool(bool), Var(&'t str), Thisptr, Binop(&'static str,LBox<Expr<'t>>,LBox<Expr<'t>>), Notexp(LBox<Expr<'t>>), Field(&'t str,LBox<Expr<'t>>), Newarray(LBox<Expr<'t>>), Newobj(&'t str), Callexp(LBox<Expr<'t>>,&'t str,Vec<LBox<Expr<'t>>>), Nothing, } impl<'t> Default for Expr<'t> { fn default()->Self {Nothing} } #[derive(Debug)] pub enum Stat<'t> { Whilest(LBox<Expr<'t>>,LBox<Stat<'t>>), Ifstat(LBox<Expr<'t>>,LBox<Stat<'t>>,LBox<Stat<'t>>), Vardecst(&'t str,&'t str,LBox<Expr<'t>>), Returnst(LBox<Expr<'t>>), Assignst(&'t str,LBox<Expr<'t>>), ArAssignst(LBox<Expr<'t>>,LBox<Expr<'t>>,LBox<Expr<'t>>), Callstat(LBox<Expr<'t>>,&'t str,Vec<LBox<Expr<'t>>>), Nopst, Blockst(Vec<LBox<Stat<'t>>>), } impl<'t> Default for Stat<'t> {fn default()->Self {Nopst} } #[derive(Debug)] pub struct VarDec<'t> { pub dname:&'t str, pub dtype:&'t str, pub initval:Expr<'t>, } impl<'t> Default for VarDec<'t> { fn default() -> Self { VarDec{dname:"",dtype:"",initval:Nothing} } } #[derive(Debug)] pub struct MethodDec<'t> { pub formals:Vec<LBox<VarDec<'t>>>, pub body: Vec<LBox<Stat<'t>>>, pub classname: &'t str, pub methodname: &'t str, } impl<'t> Default for MethodDec<'t> { fn default() -> Self { MethodDec{formals:Vec::new(),classname:"",methodname:"",body:Vec::new()} } } #[derive(Debug)] pub struct ClassDec<'t> { pub superclass:&'t str, pub classname:&'t str, pub vars: Vec<LBox<VarDec<'t>>>, pub methods: Vec<LBox<MethodDec<'t>>>, } impl<'t> Default for ClassDec<'t> { fn default()->Self { ClassDec{superclass:"Object",classname:"",vars:Vec::new(),methods:Vec::new()}} } #[derive(Debug)] pub enum Declaration<'t> { Mdec(MethodDec<'t>), Vdec(VarDec<'t>), Cdec(ClassDec<'t>), } #[derive(Debug)] pub struct Mainclass<'t> { pub classname:&'t str, pub argvname: &'t str, pub body : Stat<'t>, } impl<'t> Default for Mainclass<'t> { fn default()->Self { Mainclass {classname:"",argvname:"",body:Stat::default(),}} } #[derive(Debug)] pub struct Program<'t> { pub mainclass:LBox<Mainclass<'t>>, pub otherclasses: Vec<LBox<ClassDec<'t>>>, } impl<'t> Default for Program<'t> { fn default()->Self { Program {mainclass:LBox::default(), otherclasses:Vec::new()}} } pub fn separatedecs<'t>(mut ds:Vec<LBox<Declaration<'t>>>,vars:&mut Vec<LBox<VarDec<'t>>>,mths:&mut Vec<LBox<MethodDec<'t>>>) { while ds.len()>0 { let mut dec = ds.pop().unwrap(); match &mut *dec { Vdec(vd) => { let vdec = std::mem::replace(vd,VarDec::default()); va
rs.push(dec.transfer(vdec)); }, Mdec(md) => { let mdec = std::mem::replace(md,MethodDec::default()); mths.push(dec.transfer(mdec)); }, _ => {}, } } }
function_block-function_prefixed
[ { "content": "pub fn parse_train_with<'lt>(parser:&mut ZCParser<RetTypeEnum<'lt>,Program<'lt>>, lexer:&mut mjenumlexer<'lt>, parserpath:&str) -> Result<Program<'lt>,Program<'lt>>\n\n{\n\n if let RetTypeEnum::Enumvariant_0(_xres_) = parser.parse_train(lexer,parserpath) {\n\n if !parser.error_occurred() {Ok(...
Rust
src/main.rs
zxrs/pinion
95a7e624b40040e4b208731bb6c3e06b6950612f
#![windows_subsystem = "windows"] use anyhow::{ensure, Error, Result}; use image::{self, imageops, GenericImageView}; use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; use std::env; use std::mem; use std::ptr; use std::slice; use winapi::{ ctypes::c_void, shared::{ minwindef::{HIWORD, LOWORD, LPARAM, LRESULT, TRUE, UINT, WPARAM}, windef::{HFONT, HMENU, HWND, RECT}, }, um::{ commdlg::{GetOpenFileNameW, OFN_FILEMUSTEXIST, OPENFILENAMEW}, wingdi::{ BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, CreateFontW, DeleteDC, DeleteObject, SelectObject, SetDIBits, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, CLIP_DEFAULT_PRECIS, DEFAULT_CHARSET, DEFAULT_PITCH, DEFAULT_QUALITY, DIB_RGB_COLORS, FF_DONTCARE, OUT_DEFAULT_PRECIS, SRCCOPY, }, winuser::{ BeginPaint, CreateWindowExW, DefWindowProcW, DispatchMessageW, EndPaint, GetMessageW, GetSysColorBrush, InvalidateRect, LoadCursorW, LoadIconW, MessageBoxW, PostQuitMessage, RegisterClassW, SendMessageW, SetWindowTextW, ShowWindow, TranslateMessage, UpdateWindow, BN_CLICKED, BS_PUSHBUTTON, COLOR_MENUBAR, CW_USEDEFAULT, IDI_APPLICATION, MB_OK, MSG, PAINTSTRUCT, SW_SHOW, WM_COMMAND, WM_CREATE, WM_DESTROY, WM_PAINT, WM_SETFONT, WNDCLASSW, WS_CAPTION, WS_CHILD, WS_OVERLAPPED, WS_SYSMENU, WS_VISIBLE, }, }, }; static mut H_WINDOW: HWND = ptr::null_mut(); static mut H_FONT: HFONT = ptr::null_mut(); static mut BUF: Vec<u8> = Vec::new(); static mut DATA_LEN: usize = 0; static mut WIDTH: i32 = 0; static mut HEIGHT: i32 = 0; const ID_OPEN_BUTTON: i32 = 2100; fn main() -> Result<()> { unsafe { let class_name = l("pinion_window_class"); let wnd_class = WNDCLASSW { style: 0, lpfnWndProc: Some(window_proc), cbClsExtra: 0, cbWndExtra: 0, hInstance: ptr::null_mut(), hIcon: LoadIconW(ptr::null_mut(), IDI_APPLICATION), hCursor: LoadCursorW(ptr::null_mut(), IDI_APPLICATION), hbrBackground: GetSysColorBrush(COLOR_MENUBAR), lpszMenuName: ptr::null_mut(), lpszClassName: class_name.as_ptr(), }; RegisterClassW(&wnd_class); let title = format!("{} v{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); H_WINDOW = CreateWindowExW( 0, class_name.as_ptr(), l(&title).as_ptr(), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 656, 551, ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), ); ensure!(!H_WINDOW.is_null(), "CreateWindowExW failed."); BUF.reserve(640 * 480 * 3); ShowWindow(H_WINDOW, SW_SHOW); UpdateWindow(H_WINDOW); let mut msg = init::<MSG>(); loop { if GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 { break; } TranslateMessage(&msg); DispatchMessageW(&msg); } } Ok(()) } unsafe extern "system" fn window_proc( h_wnd: HWND, msg: UINT, w_param: WPARAM, l_param: LPARAM, ) -> LRESULT { match msg { WM_CREATE => create(h_wnd), WM_COMMAND => command(h_wnd, w_param), WM_PAINT => { if DATA_LEN > 0 { paint(h_wnd) } else { return DefWindowProcW(h_wnd, msg, w_param, l_param); } } WM_DESTROY => { DeleteObject(H_FONT as *mut c_void); PostQuitMessage(0); Ok(()) } _ => return DefWindowProcW(h_wnd, msg, w_param, l_param), } .map_err(msg_box) .ok(); 0 } unsafe fn create(h_wnd: HWND) -> Result<()> { create_font()?; create_button(h_wnd)?; Ok(()) } unsafe fn create_font() -> Result<()> { H_FONT = CreateFontW( 18, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, l("メイリオ").as_ptr(), ); ensure!(!H_FONT.is_null(), "CreateFontW failed."); Ok(()) } unsafe fn create_button(h_wnd: HWND) -> Result<()> { let h_button = CreateWindowExW( 0, l("BUTTON").as_ptr(), l("Open").as_ptr(), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 4, 4, 80, 24, h_wnd, ID_OPEN_BUTTON as HMENU, ptr::null_mut(), ptr::null_mut(), ); ensure!(!h_button.is_null(), "CreateWindowExW BUTTON failed.",); SendMessageW(h_button, WM_SETFONT, H_FONT as WPARAM, 0); Ok(()) } unsafe fn command(h_wnd: HWND, w_param: WPARAM) -> Result<()> { let msg = HIWORD(w_param as u32); let id = LOWORD(w_param as u32) as i32; if msg == BN_CLICKED { if id == ID_OPEN_BUTTON { let file_path = open_dialog(h_wnd)?; read_image(&file_path)?; } } Ok(()) } unsafe fn read_image(file_path: &str) -> Result<()> { let img = image::open(file_path)?; let img = if img.width() > 640 || img.height() > 480 { let new_size = if img.width() as f32 / img.height() as f32 > 1.333 { 640 } else { if img.width() > img.height() { (480.0 / img.height() as f32 * img.width() as f32) as u32 } else { 480 } }; img.resize(new_size, new_size, imageops::Lanczos3) } else { img }; WIDTH = img.width() as i32; HEIGHT = img.height() as i32; let bgr = img.into_bgr(); ensure!(bgr.len() <= 640 * 480 * 3, "Invalid data length."); let remain = (3 * WIDTH as usize) % 4; if remain > 0 { let chunk_size = 3 * WIDTH as usize; let line_bytes_len = chunk_size + 4 - remain; DATA_LEN = line_bytes_len * HEIGHT as usize; let mut p = BUF.as_mut_ptr(); bgr.chunks(chunk_size).for_each(|c| { ptr::copy_nonoverlapping(c.as_ptr(), p, chunk_size); p = p.add(line_bytes_len); }); } else { DATA_LEN = (WIDTH * HEIGHT * 3) as usize; ptr::copy_nonoverlapping(bgr.as_ptr(), BUF.as_mut_ptr(), DATA_LEN); }; let rc = RECT { top: 32, left: 0, right: 640, bottom: 512, }; InvalidateRect(H_WINDOW, &rc, TRUE); SetWindowTextW(H_WINDOW, l(file_path).as_ptr()); Ok(()) } unsafe fn open_dialog(h_wnd: HWND) -> Result<String> { const MAX_PATH: u32 = 260; let mut buf = [0u16; MAX_PATH as usize]; let filter = l("Image file\0*.jpg;*.png;*.gif;*.bmp\0"); let title = l("Choose a image file"); let mut ofn = zeroed::<OPENFILENAMEW>(); ofn.lStructSize = mem::size_of::<OPENFILENAMEW>() as u32; ofn.lpstrFilter = filter.as_ptr(); ofn.lpstrTitle = title.as_ptr(); ofn.lpstrFile = buf.as_mut_ptr(); ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_FILEMUSTEXIST; ofn.hwndOwner = h_wnd; ensure!(GetOpenFileNameW(&mut ofn) != 0, "Cannot get file path."); let slice = slice::from_raw_parts(ofn.lpstrFile, MAX_PATH as usize); Ok(decode(slice)) } unsafe fn paint(h_wnd: HWND) -> Result<()> { let mut ps = init::<PAINTSTRUCT>(); let hdc = BeginPaint(h_wnd, &mut ps); let mut bi = zeroed::<BITMAPINFO>(); bi.bmiHeader = zeroed::<BITMAPINFOHEADER>(); bi.bmiHeader.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32; bi.bmiHeader.biWidth = WIDTH; bi.bmiHeader.biHeight = -HEIGHT; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 24; bi.bmiHeader.biSizeImage = DATA_LEN as u32; bi.bmiHeader.biCompression = BI_RGB; let h_bmp = CreateCompatibleBitmap(hdc, WIDTH, HEIGHT); SetDIBits( hdc, h_bmp, 0, HEIGHT as u32, BUF.as_ptr() as *const c_void, &bi, DIB_RGB_COLORS, ); let h_mdc = CreateCompatibleDC(hdc); SelectObject(h_mdc, h_bmp as *mut c_void); let padding_left = (640 - WIDTH) / 2; let padding_top = (480 - HEIGHT) / 2; BitBlt( hdc, padding_left, padding_top + 32, WIDTH, HEIGHT, h_mdc, 0, 0, SRCCOPY, ); DeleteDC(h_mdc); DeleteObject(h_bmp as *mut c_void); EndPaint(h_wnd, &ps); Ok(()) } fn msg_box(e: Error) { unsafe { MessageBoxW( H_WINDOW, l(&e.to_string()).as_ptr(), l("Error").as_ptr(), MB_OK, ) }; } fn l(source: &str) -> Vec<u16> { source.encode_utf16().chain(Some(0)).collect() } fn decode(source: &[u16]) -> String { decode_utf16(source.iter().take_while(|&n| n != &0).cloned()) .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)) .collect() } unsafe fn init<T>() -> T { mem::MaybeUninit::<T>::uninit().assume_init() } unsafe fn zeroed<T>() -> T { mem::MaybeUninit::<T>::zeroed().assume_init() }
#![windows_subsystem = "windows"] use anyhow::{ensure, Error, Result}; use image::{self, imageops, GenericImageView}; use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; use std::env; use std::mem; use std::ptr; use std::slice; use winapi::{ ctypes::c_void, shared::{ minwindef::{HIWORD, LOWORD, LPARAM, LRESULT, TRUE, UINT, WPARAM}, windef::{HFONT, HMENU, HWND, RECT}, }, um::{ commdlg::{GetOpenFileNameW, OFN_FILEMUSTEXIST, OPENFILENAMEW}, wingdi::{ BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, CreateFontW, DeleteDC, DeleteObject, SelectObject, SetDIBits, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, CLIP_DEFAULT_PRECIS, DEFAULT_CHARSET, DEFAULT_PITCH, DEFAULT_QUALITY, DIB_RGB_COLORS, FF_DONTCARE, OUT_DEFAULT_PRECIS, SRCCOPY, }, winuser::{ BeginPaint, CreateWindowExW, DefWindowProcW, DispatchMessageW, EndPaint, GetMessageW, GetSysColorBrush, InvalidateRect, LoadCursorW, LoadIconW, MessageBoxW, PostQuitMessage, RegisterClassW, SendMessageW, SetWindowTextW, ShowWindow, TranslateMessage, UpdateWindow, BN_CLICKED, BS_PUSHBUTTON, COLOR_MENUBAR, CW_USEDEFAULT, IDI_APPLICATION, MB_OK, MSG, PAINTSTRUCT, SW_SHOW, WM_COMMAND, WM_CREATE, WM_DESTROY, WM_PAINT, WM_SETFONT, WNDCLASSW, WS_CAPTION, WS_CHILD, WS_OVERLAPPED, WS_SYSMENU, WS_VISIBLE, }, }, }; static mut H_WINDOW: HWND = ptr::null_mut(); static mut H_FONT: HFONT = ptr::null_mut(); static mut BUF: Vec<u8> = Vec::new(); static mut DATA_LEN: usize = 0; static mut WIDTH: i32 = 0; static mut HEIGHT: i32 = 0; const ID_OPEN_BUTTON: i32 = 2100; fn main() -> Result<()> { unsafe { let class_name = l("pinion_window_class"); let wnd_class = WNDCLASSW { style: 0, lpfnWndProc: Some(window_proc), cbClsExtra: 0, cbWndExtra: 0, hInstance: ptr::null_mut(), hIcon: LoadIconW(ptr::null_mut(), IDI_APPLICATION), hCursor: LoadCursorW(ptr::null_mut(), IDI_APPLICATION), hbrBackground: GetSysColorBrush(COLOR_MENUBAR), lpszMenuName: ptr::null_mut(), lpszClassName: class_name.as_ptr(), }; RegisterClassW(&wnd_class); let title = format!("{} v{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); H_WINDOW = CreateWindowExW( 0, class_name.as_ptr(), l(&title).as_ptr(), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 656, 551, ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), ); ensure!(!H_WINDOW.is_null(), "CreateWindowExW failed."); BUF.reserve(640 * 480 * 3); ShowWindow(H_WINDOW, SW_SHOW); UpdateWindow(H_WINDOW); let mut msg = init::<MSG>(); loop { if GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 { break; } TranslateMessage(&msg); DispatchMessageW(&msg); } } Ok(()) } unsafe extern "system" fn window_proc( h_wnd: HWND, msg: UINT, w_param: WPARAM, l_param: LPARAM, ) -> LRESULT { match msg { WM_CREATE => create(h_wnd), WM_COMMAND => command(h_wnd, w_param), WM_PAINT => { if DATA_LEN > 0 { paint(h_wnd) } else { return DefWindowProcW(h_wnd, msg, w_param, l_param); } } WM_DESTROY => { DeleteObject(H_FONT as *mut c_void); PostQuitMessage(0); Ok(()) } _ => return DefWindowProcW(h_wnd, msg, w_param, l_param), } .map_err(msg_box) .ok(); 0 } unsafe fn create(h_wnd: HWND) -> Result<()> { create_font()?; create_button(h_wnd)?; Ok(()) } unsafe fn create_font() -> Result<()> { H_FONT = CreateFontW( 18, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, l("メイリオ").as_ptr(), ); ensure!(!H_FONT.is_null(), "CreateFontW failed."); Ok(()) } unsafe fn create_button(h_wnd: HWND) -> Result<()> { let h_button = CreateWindowExW( 0, l("BUTTON").as_ptr(), l("Open").as_ptr(), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 4, 4, 80, 24, h_wnd, ID_OPEN_BUTTON as HMENU, ptr::null_mut(), ptr::null_mut(), ); ensure!(!h_button.is_null(), "CreateWindowExW BUTTON failed.",); SendMessageW(h_button, WM_SETFONT, H_FONT as WPARAM, 0); Ok(()) } unsafe fn command(h_wnd: HWND, w_param: WPARAM) -> Result<()> { let msg = HIWORD(w_param as u32); let id = LOWORD(w_param as u32) as i32; if msg == BN_CLICKED { if id == ID_OPEN_BUTTON { let file_path = open_dialog(h_wnd)?; read_image(&file_path)?; } } Ok(()) } unsafe fn read_image(file_path: &str) -> Result<()> { let img = image::open(file_path)?; let img = if img.width() > 640 || img.height() > 480 { let new_size = if img.width() as f32 / img.height() as f32 > 1.333 { 640 } else { if img.width() > img.height() { (480.0 / img.height() as f32 * img.width() as f32) as u32 } else { 480 } }; img.resize(new_size, new_size, imageops::Lanczos3) } else { img }; WIDTH = img.width() as i32; HEIGHT = img.height() as i32; let bgr = img.into_bgr(); ensure!(bgr.len() <= 640 * 480 * 3, "Invalid data length."); let remain = (3 * WIDTH as usize) % 4; if remain > 0 { let chunk_size = 3 * WIDTH as usize; let line_bytes_len = chunk_size + 4 - remain; DATA_LEN = line_bytes_len * HEIGHT as usize; let mut p = BUF.as_mut_ptr(); bgr.chunks(chunk_size).for_each(|c| { ptr::copy_nonoverlapping(c.as_ptr(), p, chunk_size); p = p.add(line_bytes_len); }); } else { DATA_LEN = (WIDTH * HEIGHT * 3) as usize; ptr::copy_nonoverlapping(bgr.as_ptr(), BUF.as_mut_ptr(), DATA_LEN); }; let rc = RECT { top: 32, left: 0, right: 640, bottom: 512, }; InvalidateRect(H_WINDOW, &rc, TRUE); SetWindowTextW(H_WINDOW, l(file_path).as_ptr()); Ok(()) } unsafe fn open_dialog(h_wnd: HWND) -> Result<String> { const MAX_PATH: u32 = 260; let mut buf = [0u16; MAX_PATH as usize]; let filter = l("Image file\0*.jpg;*.png;*.gif;*.bmp\0"); let title = l("Choose a image file"); let mut ofn = zeroed::<OPENFILENAMEW>(); ofn.lStructSize = mem::size_of::<OPENFILENAMEW>() as u32; ofn.lpstrFilter = filter.as_ptr(); ofn.lpstrTitle = title.as_ptr(); ofn.lpstrFile = buf.as_mut_ptr(); ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_FILEMUSTEXIST; ofn.hwndOwner = h_wnd; ensure!(GetOpenFileNameW(&mut ofn) != 0, "Cannot get file path."); let slice = slice::from_raw_parts(ofn.lpstrFile, MAX_PATH as usize); Ok(decode(slice)) } unsafe fn paint(h_wnd: HWND) -> Result<()> { let mut ps = init::<PAINTS
fn msg_box(e: Error) { unsafe { MessageBoxW( H_WINDOW, l(&e.to_string()).as_ptr(), l("Error").as_ptr(), MB_OK, ) }; } fn l(source: &str) -> Vec<u16> { source.encode_utf16().chain(Some(0)).collect() } fn decode(source: &[u16]) -> String { decode_utf16(source.iter().take_while(|&n| n != &0).cloned()) .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)) .collect() } unsafe fn init<T>() -> T { mem::MaybeUninit::<T>::uninit().assume_init() } unsafe fn zeroed<T>() -> T { mem::MaybeUninit::<T>::zeroed().assume_init() }
TRUCT>(); let hdc = BeginPaint(h_wnd, &mut ps); let mut bi = zeroed::<BITMAPINFO>(); bi.bmiHeader = zeroed::<BITMAPINFOHEADER>(); bi.bmiHeader.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32; bi.bmiHeader.biWidth = WIDTH; bi.bmiHeader.biHeight = -HEIGHT; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 24; bi.bmiHeader.biSizeImage = DATA_LEN as u32; bi.bmiHeader.biCompression = BI_RGB; let h_bmp = CreateCompatibleBitmap(hdc, WIDTH, HEIGHT); SetDIBits( hdc, h_bmp, 0, HEIGHT as u32, BUF.as_ptr() as *const c_void, &bi, DIB_RGB_COLORS, ); let h_mdc = CreateCompatibleDC(hdc); SelectObject(h_mdc, h_bmp as *mut c_void); let padding_left = (640 - WIDTH) / 2; let padding_top = (480 - HEIGHT) / 2; BitBlt( hdc, padding_left, padding_top + 32, WIDTH, HEIGHT, h_mdc, 0, 0, SRCCOPY, ); DeleteDC(h_mdc); DeleteObject(h_bmp as *mut c_void); EndPaint(h_wnd, &ps); Ok(()) }
function_block-function_prefixed
[ { "content": "# pinion\n\nAn image viewer sample application for Windows written in Rust.\n", "file_path": "README.md", "rank": 18, "score": 3.0048466812659997 } ]
Rust
changeforest-py/src/control.rs
mlondschien/changeforest
4188ba4de34e05214a8cf6a3bb88912067695c14
use biosphere::MaxFeatures; use changeforest::Control; use pyo3::exceptions; use pyo3::prelude::{pyclass, FromPyObject, PyAny, PyErr, PyResult}; use pyo3::prelude::{PyObject, Python}; pub fn control_from_pyobj(py: Python, obj: Option<PyObject>) -> PyResult<Control> { let mut control = Control::default(); if let Some(obj) = obj { if let Ok(pyvalue) = obj.getattr(py, "minimal_relative_segment_length") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_minimal_relative_segment_length(value); } }; if let Ok(pyvalue) = obj.getattr(py, "minimal_gain_to_split") { if let Ok(value) = pyvalue.extract::<Option<f64>>(py) { control = control.with_minimal_gain_to_split(value); } }; if let Ok(pyvalue) = obj.getattr(py, "model_selection_alpha") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_model_selection_alpha(value); } }; if let Ok(pyvalue) = obj.getattr(py, "model_selection_alpha") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_model_selection_alpha(value); } }; if let Ok(pyvalue) = obj.getattr(py, "model_selection_n_permutations") { if let Ok(value) = pyvalue.extract::<usize>(py) { control = control.with_model_selection_n_permutations(value); } }; if let Ok(pyvalue) = obj.getattr(py, "number_of_wild_segments") { if let Ok(value) = pyvalue.extract::<usize>(py) { control = control.with_number_of_wild_segments(value); } }; if let Ok(pyvalue) = obj.getattr(py, "seed") { if let Ok(value) = pyvalue.extract::<u64>(py) { control = control.with_seed(value); control.random_forest_parameters = control.random_forest_parameters.with_seed(value); } }; if let Ok(pyvalue) = obj.getattr(py, "seeded_segments_alpha") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_seeded_segments_alpha(value); } }; if let Ok(pyvalue) = obj.getattr(py, "random_forest_n_estimators") { if let Ok(value) = pyvalue.extract::<usize>(py) { control.random_forest_parameters = control.random_forest_parameters.with_n_estimators(value); } }; if let Ok(pyvalue) = obj.getattr(py, "random_forest_max_depth") { if let Ok(value) = pyvalue.extract::<Option<usize>>(py) { control.random_forest_parameters = control.random_forest_parameters.with_max_depth(value); } }; if let Ok(pyvalue) = obj.getattr(py, "random_forest_max_features") { if let Ok(value) = pyvalue.extract::<PyMaxFeatures>(py) { control.random_forest_parameters = control .random_forest_parameters .with_max_features(value.value); } }; if let Ok(pyvalue) = obj.getattr(py, "random_forest_n_jobs") { if let Ok(value) = pyvalue.extract::<Option<i32>>(py) { control.random_forest_parameters = control.random_forest_parameters.with_n_jobs(value); } }; } Ok(control) } #[pyclass(name = "MaxFeatures")] pub struct PyMaxFeatures { pub value: MaxFeatures, } impl PyMaxFeatures { fn new(value: MaxFeatures) -> Self { PyMaxFeatures { value } } } impl FromPyObject<'_> for PyMaxFeatures { fn extract(ob: &'_ PyAny) -> PyResult<Self> { if let Ok(value) = ob.extract::<usize>() { Ok(PyMaxFeatures::new(MaxFeatures::Value(value))) } else if let Ok(value) = ob.extract::<f64>() { if value > 1. || value <= 0. { Err(PyErr::new::<exceptions::PyTypeError, _>(format!( "Got max_features {}", value ))) } else { Ok(PyMaxFeatures::new(MaxFeatures::Fraction(value))) } } else if let Ok(value) = ob.extract::<Option<String>>() { if value.is_none() { Ok(PyMaxFeatures::new(MaxFeatures::None)) } else { if value.as_ref().unwrap() == "sqrt" { Ok(PyMaxFeatures::new(MaxFeatures::Sqrt)) } else { Err(PyErr::new::<exceptions::PyTypeError, _>(format!( "Unknown value for max_features: {}", value.unwrap() ))) } } } else { Err(PyErr::new::<exceptions::PyTypeError, _>(format!( "Unknown value for max_features: {}", ob ))) } } }
use biosphere::MaxFeatures; use changeforest::Control; use pyo3::exceptions; use pyo3::prelude::{pyclass, FromPyObject, PyAny, PyErr, PyResult}; use pyo3::prelude::{PyObject, Python}; pub fn control_from_pyobj(py: Python, obj: Option<PyObject>) -> PyResult<Control> { let mut control = Control::default(); if let Some(obj) = obj { if let Ok(pyvalue) = obj.getattr(py, "minimal_relative_segment_length") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_minimal_relative_segment_length(value); } }; if let Ok(pyvalue) = obj.getattr(py, "minimal_gain_to_split") { if let Ok(value) = pyvalue.extract::<Option<f64>>(py) { control = control.with_minimal_gain_to_split(value); } }; if let Ok(pyvalue) = obj.getattr(py, "model_selection_alpha") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_model_selection_alpha(value); } }; if let Ok(pyvalue) = obj.getattr(py, "model_selection_alpha") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_model_selection_alpha(value); } }; if let Ok(pyvalue) = obj.getattr(py, "model_selection_n_permutations") { if let Ok(value) = pyvalue.extract::<usize>(py) { control = control.with_model_selection_n_permutations(value); } }; if let Ok(pyvalue) = obj.getattr(py, "number_of_wild_segments") { if let Ok(value) = pyvalue.extract::<usize>(py) { control = control.with_number_of_wild_segments(value); } }; if let Ok(pyvalue) = obj.getattr(py, "seed") { if let Ok(value) = pyvalue.extract::<u64>(py) { control = control.with_seed(value);
control.random_forest_parameters.with_n_jobs(value); } }; } Ok(control) } #[pyclass(name = "MaxFeatures")] pub struct PyMaxFeatures { pub value: MaxFeatures, } impl PyMaxFeatures { fn new(value: MaxFeatures) -> Self { PyMaxFeatures { value } } } impl FromPyObject<'_> for PyMaxFeatures { fn extract(ob: &'_ PyAny) -> PyResult<Self> { if let Ok(value) = ob.extract::<usize>() { Ok(PyMaxFeatures::new(MaxFeatures::Value(value))) } else if let Ok(value) = ob.extract::<f64>() { if value > 1. || value <= 0. { Err(PyErr::new::<exceptions::PyTypeError, _>(format!( "Got max_features {}", value ))) } else { Ok(PyMaxFeatures::new(MaxFeatures::Fraction(value))) } } else if let Ok(value) = ob.extract::<Option<String>>() { if value.is_none() { Ok(PyMaxFeatures::new(MaxFeatures::None)) } else { if value.as_ref().unwrap() == "sqrt" { Ok(PyMaxFeatures::new(MaxFeatures::Sqrt)) } else { Err(PyErr::new::<exceptions::PyTypeError, _>(format!( "Unknown value for max_features: {}", value.unwrap() ))) } } } else { Err(PyErr::new::<exceptions::PyTypeError, _>(format!( "Unknown value for max_features: {}", ob ))) } } }
control.random_forest_parameters = control.random_forest_parameters.with_seed(value); } }; if let Ok(pyvalue) = obj.getattr(py, "seeded_segments_alpha") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_seeded_segments_alpha(value); } }; if let Ok(pyvalue) = obj.getattr(py, "random_forest_n_estimators") { if let Ok(value) = pyvalue.extract::<usize>(py) { control.random_forest_parameters = control.random_forest_parameters.with_n_estimators(value); } }; if let Ok(pyvalue) = obj.getattr(py, "random_forest_max_depth") { if let Ok(value) = pyvalue.extract::<Option<usize>>(py) { control.random_forest_parameters = control.random_forest_parameters.with_max_depth(value); } }; if let Ok(pyvalue) = obj.getattr(py, "random_forest_max_features") { if let Ok(value) = pyvalue.extract::<PyMaxFeatures>(py) { control.random_forest_parameters = control .random_forest_parameters .with_max_features(value.value); } }; if let Ok(pyvalue) = obj.getattr(py, "random_forest_n_jobs") { if let Ok(value) = pyvalue.extract::<Option<i32>>(py) { control.random_forest_parameters =
function_block-random_span
[ { "content": "pub fn changeforest(\n\n X: &ndarray::ArrayView2<'_, f64>,\n\n method: &str,\n\n segmentation_type: &str,\n\n control: &Control,\n\n) -> BinarySegmentationResult {\n\n let segmentation_type_enum: SegmentationType;\n\n let mut tree: BinarySegmentationTree;\n\n\n\n if segmentati...
Rust
src/tokenstream.rs
nikodemus/foolang
f8d824a8d7ef5ef828911a8b4d0d6419ad29bf6e
use crate::source_location::Span; use crate::unwind::Unwind; #[allow(non_camel_case_types)] #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum Token { EOF, HEX_INTEGER, BIN_INTEGER, DEC_INTEGER, SINGLE_FLOAT, DOUBLE_FLOAT, BLOCK_COMMENT, COMMENT, BLOCK_STRING, STRING, WORD, KEYWORD, SIGIL, } #[cfg(test)] impl Token { pub(crate) fn name(&self) -> String { format!("{:?}", self) } } pub struct TokenStream<'a> { source: &'a str, indices: std::cell::RefCell<std::str::CharIndices<'a>>, span: Span, current: (usize, char), offset: usize, } impl<'a> TokenStream<'a> { pub(crate) fn new(source: &'a str) -> TokenStream<'a> { let mut stream = TokenStream { source, indices: std::cell::RefCell::new(source.char_indices()), span: 0..0, current: (0, '.'), offset: 0, }; if source.len() > 0 { stream.next(); } else { } return stream; } #[cfg(test)] pub(crate) fn slice(&self) -> &str { &self.source[self.span()] } pub(crate) fn slice_at(&self, span: Span) -> &str { &self.source[span] } pub(crate) fn span(&self) -> Span { self.span.clone() } fn len(&self) -> usize { self.source.len() } fn pos(&self) -> usize { self.current.0 } fn character(&self) -> char { self.current.1 } fn result(&mut self, token: Token, span: Span) -> Result<Token, Unwind> { self.span = span; Ok(token) } pub(crate) fn scan(&mut self) -> Result<Token, Unwind> { if self.at_eof() { return self.result(Token::EOF, self.len()..self.len()); } if self.at_whitespace() { while self.at_whitespace() { self.next(); } return self.scan(); } if self.at_special() { let start = self.next(); return self.result(Token::SIGIL, start..self.pos()); } if self.at_digit(10) { return self.scan_number(); } if self.at_str("---") { let start = self.consume("---"); while !self.at_str("---") { if self.at_eof() { return self.result(Token::EOF, self.len()..self.len()); } else { self.next(); } } self.consume("---"); return self.result(Token::BLOCK_COMMENT, start..self.pos()); } if self.at_str("--") { let start = self.consume("--"); while !self.at_newline() { self.next(); } return self.result(Token::COMMENT, start..self.pos()); } if self.at_str(r#"""""#) { let start = self.consume(r#"""""#); while !self.at_str(r#"""""#) { self.next(); if self.at_str("\\") { self.next(); self.next(); } } self.consume(r#"""""#); return self.result(Token::BLOCK_STRING, start..self.pos()); } if self.at_str(r#"""#) { let start = self.consume(r#"""#); while !self.at_str(r#"""#) { if self.at_str("\\") { self.next(); self.next(); } else { self.next(); } } self.consume(r#"""#); return self.result(Token::STRING, start..self.pos()); } if self.at_word() { let start = self.next(); loop { while self.at_word() { self.next(); } if self.at_char(':') { let pos = self.next(); if self.at_char(':') { self.reset(pos); } else { return self.result(Token::KEYWORD, start..self.pos()); } } if self.at_char('.') { let pos = self.next(); if self.at_word() { continue; } else { self.reset(pos); } } return self.result(Token::WORD, start..self.pos()); } } assert!(self.at_sigil()); let start = self.next(); while self.at_sigil() { self.next(); } return self.result(Token::SIGIL, start..self.pos()); } fn scan_number(&mut self) -> Result<Token, Unwind> { let start = self.next(); if self.at_char('x') || self.at_char('X') { self.next(); while self.at_word() { self.next(); } return self.result(Token::HEX_INTEGER, start..self.pos()); } if self.at_char('b') || self.at_char('B') { self.next(); while self.at_word() { self.next(); } return self.result(Token::BIN_INTEGER, start..self.pos()); } while self.at_digit(10) || self.at_char('_') { self.next(); } let dot = self.at_char('.'); if dot { let p = self.pos(); self.next(); if self.at_whitespace() { self.reset(p); return self.result(Token::DEC_INTEGER, start..self.pos()); } while self.at_digit(10) || self.at_char('_') { self.next(); } } let single = self.at_char('f') || self.at_char('F'); let double = self.at_char('e') || self.at_char('E'); if single || double { self.next(); if self.at_char('+') || self.at_char('-') { self.next(); } while self.at_word() { self.next(); } if single { return self.result(Token::SINGLE_FLOAT, start..self.pos()); } else { return self.result(Token::DOUBLE_FLOAT, start..self.pos()); } } while self.at_word() { self.next(); } if dot { return self.result(Token::DOUBLE_FLOAT, start..self.pos()); } else { return self.result(Token::DEC_INTEGER, start..self.pos()); } } fn at_eof(&self) -> bool { self.pos() >= self.len() } fn at_whitespace(&self) -> bool { !self.at_eof() && self.character().is_whitespace() } fn at_alphanumeric(&self) -> bool { !self.at_eof() && self.character().is_alphanumeric() } fn at_digit(&self, base: u32) -> bool { !self.at_eof() && self.character().is_digit(base) } fn at_newline(&self) -> bool { self.at_char('\n') } fn at_special(&self) -> bool { if self.at_eof() { return false; } let c = self.character(); return c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == '.' || c == ';' || c == '$' || c == '!' || c == '#'; } fn at_terminating(&self) -> bool { self.at_whitespace() || self.at_special() } fn at_word(&self) -> bool { self.at_alphanumeric() || self.at_char('_') } fn at_sigil(&self) -> bool { !(self.at_eof() || self.at_word() || self.at_terminating()) } fn at_char(&self, c: char) -> bool { !self.at_eof() && c == self.character() } fn at_str(&self, target: &str) -> bool { let start = self.pos(); let end = start + target.len(); if self.len() < end { return false; } &self.source[start..end] == target } fn next(&mut self) -> usize { let p = self.pos(); self.current = match self.indices.borrow_mut().next() { Some((p, ch)) => (p + self.offset, ch), None => (self.len(), '.'), }; return p; } fn consume(&mut self, target: &str) -> usize { assert!(self.at_str(target)); let p = self.pos(); self.reset(p + target.len()); return p; } fn reset(&mut self, position: usize) { self.offset = position; self.indices = std::cell::RefCell::new(self.source[position..].char_indices()); self.next(); } }
use crate::source_location::Span; use crate::unwind::Unwind; #[allow(non_camel_case_types)] #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum Token { EOF, HEX_INTEGER, BIN_INTEGER, DEC_INTEGER, SINGLE_FLOAT, DOUBLE_FLOAT, BLOCK_COMMENT, COMMENT, BLOCK_STRING, STRING, WORD, KEYWORD, SIGIL, } #[cfg(test)] impl Token { pub(crate) fn name(&self) -> String { format!("{:?}", self) } } pub struct TokenStream<'a> { source: &'a str, indices: std::cell::RefCell<std::str::CharIndices<'a>>, span: Span, current: (usize, char), offset: usize, } impl<'a> TokenStream<'a> { pub(crate) fn new(source: &'a str) -> TokenStream<'a> { let mut stream = TokenStream { source, indices: std::cell::RefCell::new(source.char_indices()), span: 0..0, current: (0, '.'), offset: 0, }; if source.len() > 0 { stream.next(); } else { } return stream; } #[cfg(test)] pub(crate) fn slice(&self) -> &str { &self.source[self.span()] } pub(crate) fn slice_at(&self, span: Span) -> &str { &self.source[span] } pub(crate) fn span(&self) -> Span { self.span.clone() } fn len(&self) -> usize { self.source.len() } fn pos(&self) -> usize { self.current.0 } fn character(&self) -> char { self.current.1 } fn result(&mut self, token: Token, span: Span) -> Result<Token, Unwind> { self.span = span; Ok(token) } pub(crate) fn scan(&mut self) -> Result<Token, Unwind> { if self.at_eof() { return self.result(Token::EOF, self.len()..self.len()); } if self.at_whitespace() { while self.at_whitespace() { self.next(); } return self.scan(); } if self.at_special() { let start = self.next(); return self.result(Token::SIGIL, start..self.pos()); } if self.at_digit(10) { return self.scan_number(); } if self.at_str("---") { let start = self.consume("---"); while !self.at_str("---") { if self.at_eof() { return self.result(Token::EOF, self.len()..self.len()); } else { self.next(); } } self.consume("---"); return self.result(Token::BLOCK_COMMENT, start..self.pos()); } if self.at_str("--") { let start = self.consume("--"); while !self.at_newline() { self.next(); } return self.result(Token::COMMENT, start..self.pos()); } if self.at_str(r#"""""#) { let start = self.consume(r#"""""#); while !self.at_str(r#"""""#) { self.next(); if self.at_str("\\") { self.next(); self.next(); } } self.consume(r#"""""#); return self.result(Token::BLOCK_STRING, start..self.pos()); } if self.at_str(r#"""#) { let start = self.consume(r#"""#); while !self.at_str(r#"""#) { if self.at_str("\\") { self.next(); self.next(); } else { self.next(); } } self.consume(r#"""#); return self.result(Token::STRING, start..self.pos()); } if self.at_word() { let start = self.next(); loop { while self.at_word() { self.next(); } if self.at_char(':') { let pos = self.next(); if self.at_char(':') { self.reset(pos); } else { return self.result(Token::KEYWORD, start..self.pos()); } } if self.at_char('.') { let pos = self.next(); if self.at_word() { continue; } else { self.reset(pos); } } return self.result(Token::WORD, start..self.pos()); } } assert!(self.at_sigil()); let start = self.next(); while self.at_sigil() { self.next(); } return self.result(Token::SIGIL, start..self.pos()); } fn scan_number(&mut self) -> Result<Token, Unwind> { let start = self.next(); if self.at_char('x') || self.at_char('X') { self.next(); while self.at_word() { self.next(); } return self.result(Token::HEX_INTEGER, start..self.pos()); } if self.at_char('b') || self.at_char('B') { self.next(); while self.at_word() { self.next(); } return self.result(Token::BIN_INTEGER, start..self.pos()); } while self.at_digit(10) || self.at_char('_') { self.next(); } let dot = self.at_char('.'); if dot { let p = self.pos(); self.next(); if self.at_whitespace() { self.reset(p); return self.result(Token::DEC_INTEGER, start..self.pos()); } while self.at_digit(10) || self.at_char('_') { self.next(); } } let single = self.at_char('f') || self.at_char('F'); let double = self.at_char('e') || self.at_char('E'); if single || double { self.next(); if self.at_char('+') || self.at_char('-') { self.next(); } while self.at_word() { self.next(); } if single { return self.result(Token::SINGLE_FLOAT, start..self.pos()); } else { return self.result(Token::DOUBLE_FLOAT, start..self.pos()); } } while self.at_word() { self.next(); } if dot { return self.result(Token::DOUBLE_FLOAT, start..self.pos()); } else { return self.result(Token::DEC_INTEGER, start..self.pos()); } } fn at_eof(&self) -> bool { self.pos() >= self.len() } fn at_whitespace(&self) -> bool { !self.at_eof() && self.character().is_whitespace() } fn at_alphanumeric(&self) -> bool { !self.at_eof() && self.character().is_alphanumeric() } fn at_digit(&self, base: u32) -> bool { !self.at_eof() && self.character().is_digit(base) } fn at_newline(&self) -> bool { self.at_char('\n') } fn at_special(&self) -> bool { if self.at_eof() { return false; } let c = self.character(); return c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == '.' || c == ';' || c == '$' || c == '!' || c == '#'; } fn at_terminating(&self) -> bool { self.at_whitespace() || self.at_special() } fn at_word(&self) -> bool { self.at_alphanumeric() || self.at_char('_') } fn at_sigil(&self) -> bool { !(self.at_eof() || self.at_word() || self.at_terminating()) } fn at_char(&self, c: char) -> bool { !self.at_eof() && c == self.character() } fn at_str(&self, target: &str) -> bool { let start = self.pos(); let end = start + target.len(); if self.len() < end { return false; } &self.source[start..end] == target }
fn consume(&mut self, target: &str) -> usize { assert!(self.at_str(target)); let p = self.pos(); self.reset(p + target.len()); return p; } fn reset(&mut self, position: usize) { self.offset = position; self.indices = std::cell::RefCell::new(self.source[position..].char_indices()); self.next(); } }
fn next(&mut self) -> usize { let p = self.pos(); self.current = match self.indices.borrow_mut().next() { Some((p, ch)) => (p + self.offset, ch), None => (self.len(), '.'), }; return p; }
function_block-full_function
[ { "content": "fn _append_context_line(context: &mut String, lineno: usize, line: &str) {\n\n if lineno == 0 {\n\n context.push_str(format!(\" {}\\n\", line).as_str());\n\n } else {\n\n context.push_str(format!(\"{:03} {}\\n\", lineno, line).as_str());\n\n }\n\n}\n", "file_path": "s...
Rust
crates/lib/kajiya-backend/src/shader_compiler.rs
MrBenj4min/kajiya
fdf3a4e11ef0d4bfd5d177396fc9d674b5b8317a
use crate::file::LoadFile; use anyhow::{anyhow, bail, Context, Result}; use bytes::Bytes; use relative_path::RelativePathBuf; use std::{path::PathBuf, sync::Arc}; use turbosloth::*; pub struct CompiledShader { pub name: String, pub spirv: Bytes, } #[derive(Clone, Hash)] pub struct CompileShader { pub path: PathBuf, pub profile: String, } #[async_trait] impl LazyWorker for CompileShader { type Output = Result<CompiledShader>; async fn run(self, ctx: RunContext) -> Self::Output { let ext = self .path .extension() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "".to_string()); let name = self .path .file_stem() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "unknown".to_string()); match ext.as_str() { "glsl" => unimplemented!(), "spv" => { let spirv = LoadFile::new(self.path.clone())?.run(ctx).await?; Ok(CompiledShader { name, spirv }) } "hlsl" => { let file_path = self.path.to_str().unwrap().to_owned(); let source = shader_prepper::process_file( &file_path, &mut ShaderIncludeProvider { ctx }, String::new(), ); let source = source.map_err(|err| anyhow!("{}", err))?; let target_profile = format!("{}_6_4", self.profile); let spirv = compile_generic_shader_hlsl_impl(&name, &source, &target_profile)?; Ok(CompiledShader { name, spirv }) } _ => anyhow::bail!("Unrecognized shader file extension: {}", ext), } } } pub struct RayTracingShader { pub name: String, pub spirv: Bytes, } #[derive(Clone, Hash)] pub struct CompileRayTracingShader { pub path: PathBuf, } #[async_trait] impl LazyWorker for CompileRayTracingShader { type Output = Result<RayTracingShader>; async fn run(self, ctx: RunContext) -> Self::Output { let file_path = self.path.to_str().unwrap().to_owned(); let source = shader_prepper::process_file( &file_path, &mut ShaderIncludeProvider { ctx }, String::new(), ); let source = source.map_err(|err| anyhow!("{}", err))?; let ext = self .path .extension() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "".to_string()); let name = self .path .file_stem() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "unknown".to_string()); match ext.as_str() { "glsl" => unimplemented!(), "hlsl" => { let target_profile = "lib_6_4"; let spirv = compile_generic_shader_hlsl_impl(&name, &source, target_profile)?; Ok(RayTracingShader { name, spirv }) } _ => anyhow::bail!("Unrecognized shader file extension: {}", ext), } } } struct ShaderIncludeProvider { ctx: RunContext, } impl<'a> shader_prepper::IncludeProvider for ShaderIncludeProvider { type IncludeContext = String; fn get_include( &mut self, path: &str, parent_file: &Self::IncludeContext, ) -> std::result::Result< (String, Self::IncludeContext), shader_prepper::BoxedIncludeProviderError, > { let resolved_path = if let Some('/') = path.chars().next() { path.to_owned() } else { let mut folder: RelativePathBuf = parent_file.into(); folder.pop(); folder.join(path).as_str().to_string() }; let blob: Arc<Bytes> = smol::block_on( crate::file::LoadFile::new(&resolved_path) .with_context(|| format!("Failed loading shader include {}", path))? .into_lazy() .eval(&self.ctx), )?; Ok((String::from_utf8(blob.to_vec())?, resolved_path)) } } pub fn get_cs_local_size_from_spirv(spirv: &[u32]) -> Result<[u32; 3]> { let mut loader = rspirv::dr::Loader::new(); rspirv::binary::parse_words(spirv, &mut loader).unwrap(); let module = loader.module(); for inst in module.global_inst_iter() { if inst.class.opcode as u32 == 16 { let local_size = &inst.operands[2..5]; use rspirv::dr::Operand::LiteralInt32; if let [LiteralInt32(x), LiteralInt32(y), LiteralInt32(z)] = *local_size { return Ok([x, y, z]); } else { bail!("Could not parse the ExecutionMode SPIR-V op"); } } } Err(anyhow!("Could not find a ExecutionMode SPIR-V op")) } fn compile_generic_shader_hlsl_impl( name: &str, source: &[shader_prepper::SourceChunk], target_profile: &str, ) -> Result<Bytes> { let mut source_text = String::new(); for s in source { source_text += &s.source; } let t0 = std::time::Instant::now(); let spirv = hassle_rs::compile_hlsl( name, &source_text, "main", target_profile, &[ "-spirv", "-enable-templates", "-fspv-target-env=vulkan1.2", "-WX", "-Ges", ], &[], ) .map_err(|err| anyhow!("{}", err))?; log::trace!("dxc took {:?} for {}", t0.elapsed(), name,); Ok(spirv.into()) }
use crate::file::LoadFile; use anyhow::{anyhow, bail, Context, Result}; use bytes::Bytes; use relative_path::RelativePathBuf; use std::{path::PathBuf, sync::Arc}; use turbosloth::*; pub struct CompiledShader { pub name: String, pub spirv: Bytes, } #[derive(Clone, Hash)] pub struct CompileShader { pub path: PathBuf, pub profile: String, } #[async_trait] impl LazyWorker for CompileShader { type Output = Result<CompiledShader>;
} pub struct RayTracingShader { pub name: String, pub spirv: Bytes, } #[derive(Clone, Hash)] pub struct CompileRayTracingShader { pub path: PathBuf, } #[async_trait] impl LazyWorker for CompileRayTracingShader { type Output = Result<RayTracingShader>; async fn run(self, ctx: RunContext) -> Self::Output { let file_path = self.path.to_str().unwrap().to_owned(); let source = shader_prepper::process_file( &file_path, &mut ShaderIncludeProvider { ctx }, String::new(), ); let source = source.map_err(|err| anyhow!("{}", err))?; let ext = self .path .extension() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "".to_string()); let name = self .path .file_stem() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "unknown".to_string()); match ext.as_str() { "glsl" => unimplemented!(), "hlsl" => { let target_profile = "lib_6_4"; let spirv = compile_generic_shader_hlsl_impl(&name, &source, target_profile)?; Ok(RayTracingShader { name, spirv }) } _ => anyhow::bail!("Unrecognized shader file extension: {}", ext), } } } struct ShaderIncludeProvider { ctx: RunContext, } impl<'a> shader_prepper::IncludeProvider for ShaderIncludeProvider { type IncludeContext = String; fn get_include( &mut self, path: &str, parent_file: &Self::IncludeContext, ) -> std::result::Result< (String, Self::IncludeContext), shader_prepper::BoxedIncludeProviderError, > { let resolved_path = if let Some('/') = path.chars().next() { path.to_owned() } else { let mut folder: RelativePathBuf = parent_file.into(); folder.pop(); folder.join(path).as_str().to_string() }; let blob: Arc<Bytes> = smol::block_on( crate::file::LoadFile::new(&resolved_path) .with_context(|| format!("Failed loading shader include {}", path))? .into_lazy() .eval(&self.ctx), )?; Ok((String::from_utf8(blob.to_vec())?, resolved_path)) } } pub fn get_cs_local_size_from_spirv(spirv: &[u32]) -> Result<[u32; 3]> { let mut loader = rspirv::dr::Loader::new(); rspirv::binary::parse_words(spirv, &mut loader).unwrap(); let module = loader.module(); for inst in module.global_inst_iter() { if inst.class.opcode as u32 == 16 { let local_size = &inst.operands[2..5]; use rspirv::dr::Operand::LiteralInt32; if let [LiteralInt32(x), LiteralInt32(y), LiteralInt32(z)] = *local_size { return Ok([x, y, z]); } else { bail!("Could not parse the ExecutionMode SPIR-V op"); } } } Err(anyhow!("Could not find a ExecutionMode SPIR-V op")) } fn compile_generic_shader_hlsl_impl( name: &str, source: &[shader_prepper::SourceChunk], target_profile: &str, ) -> Result<Bytes> { let mut source_text = String::new(); for s in source { source_text += &s.source; } let t0 = std::time::Instant::now(); let spirv = hassle_rs::compile_hlsl( name, &source_text, "main", target_profile, &[ "-spirv", "-enable-templates", "-fspv-target-env=vulkan1.2", "-WX", "-Ges", ], &[], ) .map_err(|err| anyhow!("{}", err))?; log::trace!("dxc took {:?} for {}", t0.elapsed(), name,); Ok(spirv.into()) }
async fn run(self, ctx: RunContext) -> Self::Output { let ext = self .path .extension() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "".to_string()); let name = self .path .file_stem() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "unknown".to_string()); match ext.as_str() { "glsl" => unimplemented!(), "spv" => { let spirv = LoadFile::new(self.path.clone())?.run(ctx).await?; Ok(CompiledShader { name, spirv }) } "hlsl" => { let file_path = self.path.to_str().unwrap().to_owned(); let source = shader_prepper::process_file( &file_path, &mut ShaderIncludeProvider { ctx }, String::new(), ); let source = source.map_err(|err| anyhow!("{}", err))?; let target_profile = format!("{}_6_4", self.profile); let spirv = compile_generic_shader_hlsl_impl(&name, &source, &target_profile)?; Ok(CompiledShader { name, spirv }) } _ => anyhow::bail!("Unrecognized shader file extension: {}", ext), } }
function_block-full_function
[ { "content": "pub fn normalized_path_from_vfs(path: impl Into<PathBuf>) -> anyhow::Result<PathBuf> {\n\n let path = path.into();\n\n\n\n for (mount_point, mounted_path) in VFS_MOUNT_POINTS.lock().iter() {\n\n if let Ok(rel_path) = path.strip_prefix(mount_point) {\n\n return Ok(mounted_pa...
Rust
physx/src/aggregate.rs
FredrikNoren/physx-rs
92a09a98f3825d52c84d487d0fc575fb8cf04feb
use crate::{ actor::{Actor, ActorMap}, articulation::Articulation, articulation_base::ArticulationBase, articulation_link::ArticulationLink, articulation_reduced_coordinate::ArticulationReducedCoordinate, base::Base, bvh_structure::BvhStructure, owner::Owner, rigid_actor::RigidActor, rigid_dynamic::RigidDynamic, rigid_static::RigidStatic, traits::Class, }; use std::{marker::PhantomData, ptr::null}; use physx_sys::{ PxAggregate_addActor_mut, PxAggregate_addArticulation_mut, PxAggregate_getActors, PxAggregate_getMaxNbActors, PxAggregate_getNbActors, PxAggregate_getSelfCollision, PxAggregate_release_mut, PxAggregate_removeActor_mut, PxAggregate_removeArticulation_mut, }; #[repr(transparent)] pub struct PxAggregate<L, S, D, T, C> where L: ArticulationLink, S: RigidStatic, D: RigidDynamic, T: Articulation, C: ArticulationReducedCoordinate, { obj: physx_sys::PxAggregate, phantom_user_data: PhantomData<(*const L, *const S, *const D, *const T, *const C)>, } impl<L, S, D, T, C> Drop for PxAggregate<L, S, D, T, C> where L: ArticulationLink, S: RigidStatic, D: RigidDynamic, T: Articulation, C: ArticulationReducedCoordinate, { fn drop(&mut self) { unsafe { PxAggregate_release_mut(self.as_mut_ptr()); } } } unsafe impl<L, S, D, T, C> Send for PxAggregate<L, S, D, T, C> where L: ArticulationLink + Send, S: RigidStatic + Send, D: RigidDynamic + Send, T: Articulation + Send, C: ArticulationReducedCoordinate + Send, { } unsafe impl<L, S, D, T, C> Sync for PxAggregate<L, S, D, T, C> where L: ArticulationLink + Sync, S: RigidStatic + Sync, D: RigidDynamic + Sync, T: Articulation + Sync, C: ArticulationReducedCoordinate + Sync, { } unsafe impl<P, L, S, D, T, C> Class<P> for PxAggregate<L, S, D, T, C> where physx_sys::PxAggregate: Class<P>, L: ArticulationLink, S: RigidStatic, D: RigidDynamic, T: Articulation, C: ArticulationReducedCoordinate, { fn as_ptr(&self) -> *const P { self.obj.as_ptr() } fn as_mut_ptr(&mut self) -> *mut P { self.obj.as_mut_ptr() } } impl<L, S, D, T, C> Aggregate for PxAggregate<L, S, D, T, C> where L: ArticulationLink, S: RigidStatic, D: RigidDynamic, T: Articulation, C: ArticulationReducedCoordinate, { type ActorMap = ActorMap<L, S, D>; type ArticulationLink = L; type RigidStatic = S; type RigidDynamic = D; type Articulation = T; type ArticulationReducedCoordinate = C; } pub trait Aggregate: Class<physx_sys::PxAggregate> + Base { type ActorMap: RigidActor; type ArticulationLink: ArticulationLink; type RigidStatic: RigidStatic; type RigidDynamic: RigidDynamic; type Articulation: Articulation; type ArticulationReducedCoordinate: ArticulationReducedCoordinate; unsafe fn from_raw(ptr: *mut physx_sys::PxAggregate) -> Option<Owner<Self>> { Owner::from_raw(ptr as *mut Self) } fn add_articulation_link( &mut self, actor: &mut Self::ArticulationLink, bvh: Option<&BvhStructure>, ) -> bool { unsafe { PxAggregate_addActor_mut( self.as_mut_ptr(), actor.as_mut_ptr(), bvh.map_or(null(), Class::as_ptr), ) } } fn add_rigid_static( &mut self, actor: &mut Self::RigidStatic, bvh: Option<&BvhStructure>, ) -> bool { unsafe { PxAggregate_addActor_mut( self.as_mut_ptr(), actor.as_mut_ptr(), bvh.map_or(null(), Class::as_ptr), ) } } fn add_rigid_dynamic( &mut self, actor: &mut Self::RigidDynamic, bvh: Option<&BvhStructure>, ) -> bool { unsafe { PxAggregate_addActor_mut( self.as_mut_ptr(), actor.as_mut_ptr(), bvh.map_or(null(), Class::as_ptr), ) } } fn add_articulation(&mut self, articulation: &mut Self::Articulation) -> bool { unsafe { PxAggregate_addArticulation_mut(self.as_mut_ptr(), articulation.as_mut_ptr()) } } fn add_articulation_reduced_coordinate( &mut self, articulation: &mut Self::ArticulationReducedCoordinate, ) -> bool { unsafe { PxAggregate_addArticulation_mut(self.as_mut_ptr(), articulation.as_mut_ptr()) } } fn get_actors(&mut self) -> Vec<&mut Self::ActorMap> { let capacity = self.get_nb_actors(); let mut buffer: Vec<&mut Self::ActorMap> = Vec::with_capacity(capacity as usize); unsafe { let len = PxAggregate_getActors( self.as_mut_ptr(), buffer.as_mut_ptr() as *mut *mut physx_sys::PxActor, capacity, 0, ); buffer.set_len(len as usize); } buffer } fn get_max_nb_actors(&self) -> u32 { unsafe { PxAggregate_getMaxNbActors(self.as_ptr()) } } fn get_nb_actors(&self) -> u32 { unsafe { PxAggregate_getNbActors(self.as_ptr()) } } fn get_self_collision(&self) -> bool { unsafe { PxAggregate_getSelfCollision(self.as_ptr()) } } fn remove_actor(&mut self, actor: &mut impl Actor) -> bool { unsafe { PxAggregate_removeActor_mut(self.as_mut_ptr(), actor.as_mut_ptr()) } } fn remove_articulation(&mut self, articulation: &mut impl ArticulationBase) -> bool { unsafe { PxAggregate_removeArticulation_mut(self.as_mut_ptr(), articulation.as_mut_ptr()) } } }
use crate::{ actor::{Actor, ActorMap}, articulation::Articulation, articulation_base::ArticulationBase, articulation_link::ArticulationLink, articulation_reduced_coordinate::ArticulationReducedCoordinate, base::Base, bvh_structure::BvhStructure, owner::Owner, rigid_actor::RigidActor, rigid_dynamic::RigidDynamic, rigid_static::RigidStatic, traits::Class, }; use std::{marker::PhantomData, ptr::null}; use physx_sys::{ PxAggregate_addActor_mut, PxAggregate_addArticulation_mut, PxAggregate_getActors, PxAggregate_getMaxNbActors, PxAggregate_getNbActors, PxAggregate_getSelfCollision, PxAggregate_release_mut, PxAggregate_removeActor_mut, PxAggregate_removeArticulation_mut, }; #[repr(transparent)] pub struct PxAggregate<L, S, D, T, C> where L: ArticulationLink, S: RigidStatic, D: RigidDynamic, T: Articulation, C: ArticulationReducedCoordinate, { obj: physx_sys::PxAggregate, phantom_user_data: PhantomData<(*const L, *const S, *const D, *const T, *const C)>, } impl<L, S, D, T, C> Drop for PxAggregate<L, S, D, T, C> where L: ArticulationLink, S: RigidStatic, D: RigidDynamic, T: Articulation, C: ArticulationReducedCoordinate, { fn drop(&mut self) { unsafe { PxAggregate_release_mut(self.as_mut_ptr()); } } } unsafe impl<L, S, D, T, C> Send for PxAggregate<L, S, D, T, C> where L: ArticulationLink + Send, S: RigidStatic + Send, D: RigidDynamic + Send, T: Articulation + Send, C: ArticulationReducedCoordinate + Send, { } unsafe impl<L, S, D, T, C> Sync for PxAggregate<L, S, D, T, C> where L: ArticulationLink + Sync, S: RigidStatic + Sync, D: RigidDynamic + Sync, T: Articulation + Sync, C: ArticulationReducedCoordinate + Sync, { } unsafe impl<P, L, S, D, T, C> Class<P> for PxAggregate<L, S, D, T, C> where physx_sys::PxAggregate: Class<P>, L: ArticulationLink, S: RigidStatic, D: RigidDynamic, T: Articulation, C: ArticulationReducedCoordinate, { fn as_ptr(&self) -> *const P { self.obj.as_ptr() } fn as_mut_ptr(&mut self) -> *mut P { self.obj.as_mut_ptr() } } impl<L, S, D, T, C> Aggregate for PxAggregate<L, S, D, T, C> where L: ArticulationLink, S: RigidStatic, D: RigidDynamic, T: Articulation, C: ArticulationReducedCoordinate, { type ActorMap = ActorMap<L, S, D>; type ArticulationLink = L; type RigidStatic = S; type RigidDynamic = D; type Articulation = T; type ArticulationReducedCoordinate = C; } pub trait Aggregate: Class<physx_sys::PxAggregate> + Base { type ActorMap: RigidActor; type ArticulationLink: ArticulationLink; type RigidStatic: RigidStatic; type RigidDynamic: RigidDynamic; type Articulation: Articulation; type ArticulationReducedCoordinate: ArticulationReducedCoordinate; unsafe fn from_raw(ptr: *mut physx_sys::PxAggregate) -> Option<Owner<Self>> { Owner::from_raw(ptr as *mut Self) } fn add_articulation_link( &mut self, actor: &mut Self::ArticulationLink, bvh: Option<&BvhStructure>, ) -> bool { unsafe { PxAggregate_addActor_mut( self.as_mut_ptr(), actor.as_mut_ptr(), bvh.map_or(null(), Class::as_ptr), ) } } fn add_rigid_static( &mut self, actor: &mut Self::RigidStatic, bvh: Option<&BvhStructure>, ) -> bool { unsafe { PxAggregate_addActor_mut( self.as_mut_ptr(), actor.as_mut_ptr(), bvh.map_or(null(), Class::as_ptr), ) } } fn add_rigid_dynamic( &mut self, actor: &mut Self::RigidDynamic, bvh: Option<&BvhStructure>, ) -> bool { unsafe { PxAggregate_addActor_mut( self.as_mut_ptr(), actor.as_mut_ptr(), bvh.map_or(null(), Class::as_ptr), ) } } fn add_articulation(&mut self, articulation: &mut Self::Articulation) -> bool { unsafe { PxAggregate_addArticulation_mut(self.as_mut_ptr(), articulation.as_mut_ptr()) } } fn add_articulation_reduced_coordinate( &mut self, articulation: &mut Self::ArticulationReducedCoordinate, ) -> bool { unsafe { PxAggregate_addArticulation_mut(self.as_mut_ptr(), articulation.as_mut_ptr()) } } fn get_actors(&mut self) -> Vec<&mut Self::ActorMap> { let capacity = self.get_nb_actors(); let mut buffer: Vec<&mut Self::ActorMap> = Vec::with_capacity(capacity as usize);
fn get_max_nb_actors(&self) -> u32 { unsafe { PxAggregate_getMaxNbActors(self.as_ptr()) } } fn get_nb_actors(&self) -> u32 { unsafe { PxAggregate_getNbActors(self.as_ptr()) } } fn get_self_collision(&self) -> bool { unsafe { PxAggregate_getSelfCollision(self.as_ptr()) } } fn remove_actor(&mut self, actor: &mut impl Actor) -> bool { unsafe { PxAggregate_removeActor_mut(self.as_mut_ptr(), actor.as_mut_ptr()) } } fn remove_articulation(&mut self, articulation: &mut impl ArticulationBase) -> bool { unsafe { PxAggregate_removeArticulation_mut(self.as_mut_ptr(), articulation.as_mut_ptr()) } } }
unsafe { let len = PxAggregate_getActors( self.as_mut_ptr(), buffer.as_mut_ptr() as *mut *mut physx_sys::PxActor, capacity, 0, ); buffer.set_len(len as usize); } buffer }
function_block-function_prefix_line
[ { "content": "pub fn PxAggregate_addActor_mut(self_: *mut PxAggregate, actor: *mut PxActor, bvhStructure: *const PxBVHStructure, ) -> bool;\n", "file_path": "physx-sys/src/physx_generated.rs", "rank": 0, "score": 550958.7046268866 }, { "content": "pub fn PxAggregate_removeArticulation_mut(se...
Rust
crates/aleph-target-build/src/platform.rs
nathanvoglsam/aleph
00f12548f7f50ade0f60343b6c5001bc0ddde6cd
#[derive(Copy, Clone, PartialEq, Debug)] pub enum Platform { UniversalWindowsGNU, UniversalWindowsMSVC, WindowsGNU, WindowsMSVC, Linux, Android, Unknown, } impl Platform { pub fn print_host_cargo_cfg(self) { match self { Platform::UniversalWindowsGNU => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_gnu"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_universal_windows"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_windows"); } Platform::UniversalWindowsMSVC => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_msvc"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_universal_windows"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_windows"); } Platform::WindowsGNU => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_gnu"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_windows"); } Platform::WindowsMSVC => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_msvc"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_windows"); } Platform::Linux => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_linux"); } Platform::Android => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_android"); } Platform::Unknown => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_unknown"); } } } pub fn print_target_cargo_cfg(self) { match self { Platform::UniversalWindowsGNU => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_gnu"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_windows"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_universal_windows"); } Platform::UniversalWindowsMSVC => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_msvc"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_windows"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_universal_windows"); } Platform::WindowsGNU => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_gnu"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_windows"); } Platform::WindowsMSVC => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_msvc"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_windows"); } Platform::Linux => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_linux"); } Platform::Android => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_android"); } Platform::Unknown => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_unknown"); } } } pub const fn name(self) -> &'static str { match self { Platform::UniversalWindowsGNU => "uwp-gnu", Platform::UniversalWindowsMSVC => "uwp-msvc", Platform::WindowsGNU => "windows-gnu", Platform::WindowsMSVC => "windows-msvc", Platform::Linux => "linux", Platform::Android => "android", Platform::Unknown => "unknown", } } pub const fn pretty_name(self) -> &'static str { match self { Platform::UniversalWindowsGNU => "Universal Windows GNU", Platform::UniversalWindowsMSVC => "Universal Windows MSVC", Platform::WindowsGNU => "Windows GNU", Platform::WindowsMSVC => "Windows MSVC", Platform::Linux => "Linux", Platform::Android => "Android", Platform::Unknown => "Unknown", } } pub const fn is_win32(self) -> bool { match self { Platform::WindowsMSVC | Platform::WindowsGNU => true, _ => false, } } pub const fn is_windows(self) -> bool { match self { Platform::WindowsMSVC | Platform::WindowsGNU | Platform::UniversalWindowsGNU | Platform::UniversalWindowsMSVC => true, _ => false, } } pub const fn is_uwp(self) -> bool { match self { Platform::UniversalWindowsGNU | Platform::UniversalWindowsMSVC => true, _ => false, } } pub const fn is_linux(self) -> bool { match self { Platform::Linux => true, _ => false, } } pub const fn is_msvc(self) -> bool { match self { Platform::WindowsMSVC => true, Platform::UniversalWindowsMSVC => true, _ => false, } } pub const fn is_gnu(self) -> bool { match self { Platform::WindowsGNU => true, Platform::UniversalWindowsGNU => true, _ => false, } } pub const fn is_android(self) -> bool { match self { Platform::Android => true, _ => false, } } pub const fn is_unknown(self) -> bool { match self { Platform::Unknown => true, _ => false, } } } #[inline] pub fn get_platform_from(triple: &str) -> Platform { let target = triple; if target.contains("pc-windows") { if target.contains("msvc") { Platform::WindowsMSVC } else if target.contains("gnu") { Platform::WindowsGNU } else { Platform::Unknown } } else if target.contains("uwp-windows") { if target.contains("msvc") { Platform::UniversalWindowsMSVC } else if target.contains("gnu") { Platform::UniversalWindowsGNU } else { Platform::Unknown } } else if target.contains("android") { Platform::Android } else if target.contains("linux") { Platform::Linux } else { Platform::Unknown } }
#[derive(Copy, Clone, PartialEq, Debug)] pub enum Platform { UniversalWindowsGNU, UniversalWindowsMSVC, WindowsGNU, WindowsMSVC, Linux, Android, Unknown, } impl Platform { pub fn print_host_cargo_cfg(self) { match self { Platform::UniversalWindowsGNU => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_gnu"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_universal_windows"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_windows"); } Platform::UniversalWindowsMSVC => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_msvc"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_universal_windows"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_windows"); } Platform::WindowsGNU => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_gnu"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_windows"); } Platform::WindowsMSVC => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_msvc"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_windows"); } Platform::Linux => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_linux"); } Platform::Android => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_android"); } Platform::Unknown => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_TARGET_is_unknown"); } } } pub fn print_target_cargo_cfg(self) { match self { Platform::UniversalWindowsGNU => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_gnu"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_windows"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_universal_windows"); } Platform::UniversalWindowsMSVC => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_msvc"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_windows"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_universal_windows"); } Platform::WindowsGNU => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_gnu"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_windows"); } Platform::WindowsMSVC => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_msvc"); println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_windows"); } Platform::Linux => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_linux"); } Platform::Android => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_android"); } Platform::Unknown => { println!("cargo:rustc-cfg=ALEPH_BUILD_PLATFORM_HOST_is_unknown"); } } } pub const fn name(self) -> &'static str { match self { Platform::UniversalWindowsGNU => "uwp-gnu", Platform::UniversalWindowsMSVC => "uwp-msvc", Platform::WindowsGNU => "windows-gnu", Platform::WindowsMSVC => "windows-msvc", Platform::Linux => "linux", Platform::Android => "android", Platform::Unknown => "unknown", } } pub const fn pretty_name(self) -> &'static str { match self { Platform::UniversalWindowsGNU => "Universal Windows GNU", Platform::UniversalWindowsMSVC => "Universal Windows MSVC", Platform::WindowsGNU => "Windows GNU", Platform::WindowsMSVC => "Windows MSVC", Platform::Linux => "Linux", Platform::Android => "Android", Platform::Unknown => "Unknown", } } pub const fn is_win32(self) -> bool { match self { Platform::WindowsMSVC | Platform::WindowsGNU => true, _ => false, } } pub const fn is_windows(self) -> bool { match self { Platform::WindowsMSVC | Platform::WindowsGNU | Platform::UniversalWindowsGNU | Platform::UniversalWindowsMSVC => true, _ => false, } } pub const fn is_uwp(self) -> bool { match self { Platform::UniversalWindowsGNU | Platform::UniversalWindowsMSVC => true, _ => false, } } pub const fn is_linux(self) -> bool { match self { Platform::Linux => true, _ => false, } } pub const fn is_msvc(self) -> bool { match self { Platform::WindowsMSVC => true, Platform::UniversalWindowsMSVC => true, _ => false, } } pub cons
} else { Platform::Unknown } } else if target.contains("android") { Platform::Android } else if target.contains("linux") { Platform::Linux } else { Platform::Unknown } }
t fn is_gnu(self) -> bool { match self { Platform::WindowsGNU => true, Platform::UniversalWindowsGNU => true, _ => false, } } pub const fn is_android(self) -> bool { match self { Platform::Android => true, _ => false, } } pub const fn is_unknown(self) -> bool { match self { Platform::Unknown => true, _ => false, } } } #[inline] pub fn get_platform_from(triple: &str) -> Platform { let target = triple; if target.contains("pc-windows") { if target.contains("msvc") { Platform::WindowsMSVC } else if target.contains("gnu") { Platform::WindowsGNU } else { Platform::Unknown } } else if target.contains("uwp-windows") { if target.contains("msvc") { Platform::UniversalWindowsMSVC } else if target.contains("gnu") { Platform::UniversalWindowsGNU
random
[ { "content": "///\n\n/// Gets the vendor string for the current CPU\n\n///\n\n/// # Warning\n\n///\n\n/// At the moment this only works on x86 and x86_64. Otherwise it will just return an \"Unknown CPU\n\n/// Vendor\" string.\n\n///\n\npub fn cpu_vendor() -> &'static str {\n\n CPU_VENDOR_STRING.as_str()\n\n}...
Rust
desktop/src/gui/styles.rs
koompi/koompi-desktop
497a16b68befd3e99cd75169f4d7800312bde2e8
use iced::{button, container, slider, checkbox, pick_list, Color, Vector}; pub const BACKGROUND: Color = Color::from_rgb(238.0 / 255.0, 238.0 / 255.0, 238.0 / 255.0); pub const FOREGROUND: Color = Color::from_rgb(224.0 / 255.0, 224.0 / 255.0, 224.0 / 255.0); pub const HOVERED: Color = Color::from_rgb(66.0 / 255.0, 66.0 / 255.0, 66.0 / 255.0); pub const PRIMARY: Color = Color::from_rgb(12.0 / 255.0, 46.0 / 251.0, 179.0 / 255.0); pub const SECONDARY: Color = Color::from_rgb(112.0 / 255.0, 16.0 / 251.0, 191.0 / 255.0); pub enum CustomButton { Default, Text, Primary, Secondary, Transparent, Selected, Hovered, } impl button::StyleSheet for CustomButton { fn active(&self) -> button::Style { use CustomButton::*; button::Style { text_color: match self { Primary => PRIMARY, Secondary => SECONDARY, Transparent | Selected => Color::WHITE, _ => Color::BLACK, }, background: Some( match self { Default => Color::WHITE, Selected => Color { a: 0.5, ..PRIMARY }, Primary => Color { a: 0.3, ..PRIMARY }, Secondary => Color { a: 0.3, ..SECONDARY }, Hovered => Color { a: 0.3, ..HOVERED }, _ => Color::TRANSPARENT, } .into(), ), border_radius: 7.0, border_color: Color::TRANSPARENT, border_width: 1.0, shadow_offset: match self { Default => Vector::new(0.5, 0.5), _ => Vector::new(0.0, 0.0) }, } } fn hovered(&self) -> button::Style { use CustomButton::*; let active = self.active(); button::Style { background: match self { Transparent => Some(Color { a: 0.3, ..PRIMARY }.into()), Text => Some(Color { a: 0.3, ..HOVERED }.into()), Primary | Secondary | Hovered => Some(active.text_color.into()), _ => active.background, }, text_color: match self { Primary | Secondary | Hovered => Color::WHITE, _ => active.text_color, }, ..active } } } pub enum CustomContainer { Foreground, } impl container::StyleSheet for CustomContainer { fn style(&self) -> container::Style { use CustomContainer::*; container::Style { background: Some(match self { Foreground => FOREGROUND, }.into()), border_radius: 7.0, ..container::Style::default() } } } pub struct CustomSelect; impl pick_list::StyleSheet for CustomSelect { fn menu(&self) -> iced_style::menu::Style { let default = Default::default(); iced_style::menu::Style { selected_background: PRIMARY.into(), ..default } } fn active(&self) -> pick_list::Style { pick_list::Style { text_color: Color::BLACK, background: Color { a: 0.3, ..PRIMARY }.into(), icon_size: 0.5, border_color: PRIMARY, border_radius: 5.0, border_width: 0.0, } } fn hovered(&self) -> pick_list::Style { self.active() } } pub struct CustomSlider; impl slider::StyleSheet for CustomSlider { fn active(&self) -> slider::Style { slider::Style { rail_colors: (Color{ a: 0.5, ..HOVERED }, Color::TRANSPARENT), handle: slider::Handle { shape: slider::HandleShape::Circle { radius: 9.0 }, color: PRIMARY, border_width: 0.0, border_color: Color::TRANSPARENT, }, } } fn hovered(&self) -> slider::Style { self.active() } fn dragging(&self) -> slider::Style { self.hovered() } } pub struct CustomCheckbox; impl checkbox::StyleSheet for CustomCheckbox { fn active(&self, is_checked: bool) -> checkbox::Style { checkbox::Style { background: if is_checked { PRIMARY } else { Color::WHITE }.into(), checkmark_color: Color::WHITE, border_radius: 5.0, border_width: 1.5, border_color: if is_checked { PRIMARY } else { HOVERED }.into(), } } fn hovered(&self, is_checked: bool) -> checkbox::Style { self.active(is_checked) } } pub struct CustomTooltip; impl container::StyleSheet for CustomTooltip { fn style(&self) -> container::Style { container::Style { background: Some(Color::WHITE.into()), ..container::Style::default() } } } pub struct ContainerFill(pub Color); impl container::StyleSheet for ContainerFill { fn style(&self) -> container::Style { container::Style { background: Some(self.0.into()), ..container::Style::default() } } }
use iced::{button, container, slider, checkbox, pick_list, Color, Vector}; pub const BACKGROUND: Color = Color::from_rgb(238.0 / 255.0, 238.0 / 255.0, 238.0 / 255.0); pub const FOREGROUND: Color = Color::from_rgb(224.0 / 255.0, 224.0 / 255.0, 224.0 / 255.0); pub const HOVERED: Color = Color::from_rgb(66.0 / 255.0, 66.0 / 255.0, 66.0 / 255.0); pub const PRIMARY: Color = Color::from_rgb(12.0 / 255.0, 46.0 / 251.0, 179.0 / 255.0); pub const SECONDARY: Color = Color::from_rgb(112.0 / 255.0, 16.0 / 251.0, 191.0 / 255.0); pub enum CustomButton { Default, Text, Primary, Secondary, Transparent, Selected, Hovered, } impl button::StyleSheet for CustomButton { fn active(&self) -> button::Style { use CustomButton::*; button::Style { text_color: match self { Primary => PRIMARY, Secondary => SECONDARY, Transparent | Selected => Color::WHITE, _ => Color::BLACK, }, background: Some( match self { Default => Color::WHITE, Selected => Color { a: 0.5, ..PRIMARY }, Primary => Color { a: 0.3, ..PRIMARY }, Secondary => Color { a: 0.3, ..SECONDARY }, Hovered => Color { a: 0.3, ..HOVERED }, _ => Color::TRANSPARENT, } .into(), ), border_radius: 7.0, border_color: Color::TRANSPARENT, border_width: 1.0, shadow_offset: match self { Default => Vector::new(0.5, 0.5), _ => Vector::new(0.0, 0.0) }, } } fn hovered(&self) -> button::Style { use CustomButton::*; let active = self.active(); button::Style { background: match self { Transparent => Some(Color { a: 0.3, ..PRIMARY }.into()), Text => Some(Color { a: 0.3, ..HOVERED }.into()), Primary | Secondary | Hovered => Some(active.text_color.into()), _ => active.background, }, text_color: match self { Primary | Secondary | Hovered => Color::WHITE, _ => active.text_color, }, ..active } } } pub enum CustomContainer { Foreground, } impl container::StyleSheet for CustomContainer { fn style(&self) -> con
struct ContainerFill(pub Color); impl container::StyleSheet for ContainerFill { fn style(&self) -> container::Style { container::Style { background: Some(self.0.into()), ..container::Style::default() } } }
tainer::Style { use CustomContainer::*; container::Style { background: Some(match self { Foreground => FOREGROUND, }.into()), border_radius: 7.0, ..container::Style::default() } } } pub struct CustomSelect; impl pick_list::StyleSheet for CustomSelect { fn menu(&self) -> iced_style::menu::Style { let default = Default::default(); iced_style::menu::Style { selected_background: PRIMARY.into(), ..default } } fn active(&self) -> pick_list::Style { pick_list::Style { text_color: Color::BLACK, background: Color { a: 0.3, ..PRIMARY }.into(), icon_size: 0.5, border_color: PRIMARY, border_radius: 5.0, border_width: 0.0, } } fn hovered(&self) -> pick_list::Style { self.active() } } pub struct CustomSlider; impl slider::StyleSheet for CustomSlider { fn active(&self) -> slider::Style { slider::Style { rail_colors: (Color{ a: 0.5, ..HOVERED }, Color::TRANSPARENT), handle: slider::Handle { shape: slider::HandleShape::Circle { radius: 9.0 }, color: PRIMARY, border_width: 0.0, border_color: Color::TRANSPARENT, }, } } fn hovered(&self) -> slider::Style { self.active() } fn dragging(&self) -> slider::Style { self.hovered() } } pub struct CustomCheckbox; impl checkbox::StyleSheet for CustomCheckbox { fn active(&self, is_checked: bool) -> checkbox::Style { checkbox::Style { background: if is_checked { PRIMARY } else { Color::WHITE }.into(), checkmark_color: Color::WHITE, border_radius: 5.0, border_width: 1.5, border_color: if is_checked { PRIMARY } else { HOVERED }.into(), } } fn hovered(&self, is_checked: bool) -> checkbox::Style { self.active(is_checked) } } pub struct CustomTooltip; impl container::StyleSheet for CustomTooltip { fn style(&self) -> container::Style { container::Style { background: Some(Color::WHITE.into()), ..container::Style::default() } } } pub
random
[ { "content": "pub fn search() -> Text {\n\n icon('\\u{f002}')\n\n}\n\n\n", "file_path": "panel/src/views/common.rs", "rank": 0, "score": 132919.60925981292 }, { "content": "pub fn wifi() -> Text {\n\n icon('\\u{f1eb}')\n\n}\n", "file_path": "panel/src/views/common.rs", "rank": ...
Rust
src/models.rs
Roba1993/SPE3D
b453ef33a6fc0adfc042784034634aa75e459573
use crate::error::*; use std::sync::atomic::{AtomicUsize, Ordering}; use dlc_decrypter::DlcPackage; use std::sync::{Arc, RwLock, Mutex}; use std::sync::mpsc::{Sender, Receiver}; use std::fs::File; use std::io::prelude::*; use crate::bus::{MessageBus, Message}; use std::thread; static IDCOUNTER: AtomicUsize = AtomicUsize::new(1); pub fn set_idcounter(id: usize) { if id > IDCOUNTER.load(Ordering::Relaxed) { IDCOUNTER.store(id, Ordering::Relaxed); IDCOUNTER.fetch_add(1, Ordering::SeqCst); } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DownloadPackage { id: usize, pub name: String, pub files: Vec<DownloadFile>, } impl DownloadPackage { pub fn new<S: Into<String>>(name: S, files: Vec<DownloadFile>) -> DownloadPackage { DownloadPackage { id: IDCOUNTER.fetch_add(1, Ordering::SeqCst), name: name.into(), files } } pub fn id(&self) -> usize { self.id } } impl From<DlcPackage> for DownloadPackage { fn from(dlc: DlcPackage) -> Self { let files = dlc.files.into_iter().map(|i| { let mut f = DownloadFile::new(); f.url = i.url; f.name = i.name; f.size = i.size.parse().unwrap_or(0); f }).collect(); DownloadPackage::new(dlc.name, files) } } #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DownloadFile { id: usize, pub status: FileStatus, pub hoster: FileHoster, pub name: String, pub url: String, pub size: usize, pub downloaded: usize, pub speed: usize, pub hash: FileHash, pub file_id: String, } impl DownloadFile { pub fn new() -> DownloadFile { DownloadFile { id: IDCOUNTER.fetch_add(1, Ordering::SeqCst), status: FileStatus::Unknown, hoster: FileHoster::Unknown, name: "".to_string(), url: "".to_string(), size: 0, downloaded: 0, speed: 0, hash: FileHash::None, file_id: "".to_string(), } } pub fn default() -> Self { Self::new() } pub fn id(&self) -> usize { self.id } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum FileHoster { Unknown, ShareOnline, Filer } impl Default for FileHoster { fn default() -> Self { FileHoster::Unknown } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Copy)] pub enum FileStatus { Unknown, Offline, Online, DownloadQueue, Downloading, Downloaded, WrongHash, } impl Default for FileStatus { fn default() -> Self { FileStatus::Unknown } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum FileHash { None, Md5(String), } impl FileHash { pub fn md5(&self) -> Option<String> { match self { FileHash::Md5(h) => Some(h.clone()), _ => None } } } impl Default for FileHash { fn default() -> Self { FileHash::None } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct CaptchaResult { pub id: usize, pub file_id: String, pub hoster: String, pub url: String } pub type DownloadList = Vec<DownloadPackage>; #[derive(Clone)] pub struct SmartDownloadList { downloads: Arc<RwLock<DownloadList>>, sender: Arc<Mutex<Sender<Message>>>, receiver: Arc<Mutex<Receiver<Message>>>, } impl SmartDownloadList { pub fn new(bus: &MessageBus) -> Result<SmartDownloadList> { let (sender, receiver) = bus.channel()?; let d_list = SmartDownloadList { downloads: Arc::new(RwLock::new(Vec::new())), sender: Arc::new(Mutex::new(sender)), receiver: Arc::new(Mutex::new(receiver)) }; match d_list.load() { Ok(_) => {}, Err(_) => {println!("Can't read previus status of the download list")} }; let d_list_internal = d_list.clone(); thread::spawn(move || loop { match d_list_internal.handle_msg() { Ok(_) => {} Err(e) => println!("{}", e), } }); Ok(d_list) } pub fn set_status(&self, id: usize, status: &FileStatus) -> Result<()> { { let mut dloads = self.downloads.write()?; match dloads.iter().find(|i| i.id() == id) { Some(_) => { dloads.iter_mut().find(|i| i.id() == id).ok_or("The id didn't exist")?.files.iter_mut().for_each(|i| { i.status = *status; }); }, None => { dloads.iter_mut().for_each(|pck| { if let Some(i) = pck.files.iter_mut().find(|i| i.id() == id) { i.status = *status; } }); } }; } self.publish_update()?; self.save() } pub fn add_downloaded(&self, id: usize, size: usize) -> Result<()> { self.downloads.write()?.iter_mut().for_each(|pck| if let Some(i) = pck.files.iter_mut().find(|f| f.id() == id) { i.downloaded += size; i.speed = size; } ); Ok(()) } pub fn set_downloaded(&self, id: usize, size: usize) -> Result<()> { self.downloads.write()?.iter_mut().for_each(|pck| if let Some(i) = pck.files.iter_mut().find(|f| f.id() == id) { i.downloaded = size; } ); self.publish_update()?; Ok(()) } pub fn add_package(&self, package: DownloadPackage) -> Result<()> { self.downloads.write()?.push(package); self.publish_update()?; self.save() } pub fn remove(&self, id: usize) -> Result<()> { self.downloads.write()?.iter_mut().for_each(|p| p.files.retain(|i| i.id() != id)); self.downloads.write()?.retain(|i| i.id() != id && !i.files.is_empty() ); self.publish_update()?; self.save() } pub fn get_downloads(&self) -> Result<DownloadList> { Ok(self.downloads.read()?.clone()) } pub fn files_status(&self, status: FileStatus) -> Result<Vec<usize>> { let ids = self.downloads.read()?.iter().map(|pck| pck.files.iter() .filter(|i| i.status == status) .map(|i| i.id()).collect::<Vec<usize>>() ).flat_map(|i| i.into_iter()) .collect::<Vec<usize>>(); Ok(ids) } pub fn files_status_hoster(&self, status: FileStatus, hoster: FileHoster) -> Result<Vec<usize>> { let ids = self.downloads.read()?.iter().map(|pck| pck.files.iter() .filter(|i| i.status == status && i.hoster == hoster) .map(|i| i.id()).collect::<Vec<usize>>() ).flat_map(|i| i.into_iter()) .collect::<Vec<usize>>(); Ok(ids) } pub fn get_file(&self, id: &usize) -> Result<DownloadFile> { let file = self.downloads.read()?.iter() .flat_map(|i| i.files.iter()) .find(|i| id == &i.id()).ok_or("The file can't be found")?.clone(); Ok(file.clone()) } pub fn get_package(&self, id: &usize) -> Result<DownloadPackage> { match self.downloads.read()?.iter().find(|i| &i.id() == id) { Some(i) => Ok(i.clone()), None => Ok(self.downloads.read()?.iter().find(|i| i.files.iter().any(|j| &j.id() == id)).ok_or("No download package available")?.clone()) } } pub fn get_high_id(&self) -> Result<usize> { let biggest_child = self.downloads.read()?.iter().map(|pck| pck.files.iter() .map(|i| i.id()).collect::<Vec<usize>>() ).flat_map(|i| i.into_iter()) .collect::<Vec<usize>>(); let biggest_child = biggest_child.iter().max().unwrap_or(&1); let biggest_parent = self.downloads.read()?.iter() .map(|x| x.id()) .collect::<Vec<usize>>(); let biggest_parent = biggest_parent.iter().max().unwrap_or(&1); Ok( if biggest_child > biggest_parent { *biggest_child } else { *biggest_parent } ) } pub fn publish_update(&self) -> Result<()> { self.sender.lock()?.send(Message::DownloadList(self.get_downloads()?))?; Ok(()) } fn handle_msg(&self) -> Result<()> { if let Message::DownloadSpeed((id, size)) = self.receiver.lock()?.recv()? { self.add_downloaded(id, size)?; } Ok(()) } fn save(&self) -> Result<()> { let d_list = ::serde_json::to_string_pretty(&(self.get_high_id()?, self.get_downloads()?))?; let mut file = File::create("./config/status.json")?; file.write_all(&d_list.into_bytes())?; Ok(()) } fn load(&self) -> Result<()> { let file = File::open("./config/status.json")?; let (id, d_list) : (usize, DownloadList) = ::serde_json::from_reader(file)?; crate::models::set_idcounter(id); for mut p in d_list { p.files.iter_mut().for_each(|f| { f.speed = 0; if f.status == FileStatus::Downloading { f.status = FileStatus::DownloadQueue; }; }); self.add_package(p)?; } Ok(()) } }
use crate::error::*; use std::sync::atomic::{AtomicUsize, Ordering}; use dlc_decrypter::DlcPackage; use std::sync::{Arc, RwLock, Mutex}; use std::sync::mpsc::{Sender, Receiver}; use std::fs::File; use std::io::prelude::*; use crate::bus::{MessageBus, Message}; use std::thread; static IDCOUNTER: AtomicUsize = AtomicUsize::new(1); pub fn set_idcounter(id: usize) { if id > IDCOUNTER.load(Ordering::Relaxed) { IDCOUNTER.store(id, Ordering::Relaxed); IDCOUNTER.fetch_add(1, Ordering::SeqCst); } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DownloadPackage { id: usize, pub name: String, pub files: Vec<DownloadFile>, } impl DownloadPackage { pub fn new<S: Into<String>>(name: S, files: Vec<DownloadFile>) -> DownloadPackage { DownloadPackage { id: IDCOUNTER.fetch_add(1, Ordering::SeqCst), name: name.into(), files } } pub fn id(&self) -> usize { self.id } } impl From<DlcPackage> for DownloadPackage { fn from(dlc: DlcPackage) -> Self { let files = dlc.files.into_iter().map(|i| { let mut f = DownloadFile::new(); f.url = i.url; f.name = i.name; f.size = i.size.parse().unwrap_or(0); f }).collect(); DownloadPackage::new(dlc.name, files) } } #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DownloadFile { id: usize, pub status: FileStatus, pub hoster: FileHoster, pub name: String, pub url: String, pub size: usize, pub downloaded: usize, pub speed: usize, pub hash: FileHash, pub file_id: String, } impl DownloadFile { pub fn new() -> DownloadFile { DownloadFile { id: IDCOUNTER.fetch_add(1, Ordering::SeqCst), status: FileStatus::Unknown, hoster: FileHoster::Unknown, name: "".to_string(), url: "".to_string(), size: 0, downloaded: 0, speed: 0, hash: FileHash::None, file_id: "".to_string(), } } pub fn default() -> Self { Self::new() } pub fn id(&self) -> usize { self.id } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum FileHoster { Unknown, ShareOnline, Filer } impl Default for FileHoster { fn default() -> Self { FileHoster::Unknown } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Copy)] pub enum FileStatus { Unknown, Offline, Online, DownloadQueue, Downloading, Downloaded, WrongHash, } impl Default for FileStatus { fn default() -> Self { FileStatus::Unknown } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum FileHash { None, Md5(String), } impl FileHash { pub fn md5(&self) -> Option<String> { match self { FileHash::Md5(h) => Some(h.clone()), _ => None } } } impl Default for FileHash { fn default() -> Self { FileHash::None } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct CaptchaResult { pub id: usize, pub file_id: String, pub hoster: String, pub url: String } pub type DownloadList = Vec<DownloadPackage>; #[derive(Clone)] pub struct SmartDownloadList { downloads: Arc<RwLock<DownloadList>>, sender: Arc<Mutex<Sender<Message>>>, receiver: Arc<Mutex<Receiver<Message>>>, } impl SmartDownloadList { pub fn new(bus: &MessageBus) -> Result<SmartDownloadList> { let (sender, receiver) = bus.channel()?; let d_list = SmartDownloadList { downloads: Arc::new(RwLock::new(Vec::new())), sender: Arc::new(Mutex::new(sender)), receiver: Arc::new(Mutex::new(receiver))
} }); Ok(d_list) } pub fn set_status(&self, id: usize, status: &FileStatus) -> Result<()> { { let mut dloads = self.downloads.write()?; match dloads.iter().find(|i| i.id() == id) { Some(_) => { dloads.iter_mut().find(|i| i.id() == id).ok_or("The id didn't exist")?.files.iter_mut().for_each(|i| { i.status = *status; }); }, None => { dloads.iter_mut().for_each(|pck| { if let Some(i) = pck.files.iter_mut().find(|i| i.id() == id) { i.status = *status; } }); } }; } self.publish_update()?; self.save() } pub fn add_downloaded(&self, id: usize, size: usize) -> Result<()> { self.downloads.write()?.iter_mut().for_each(|pck| if let Some(i) = pck.files.iter_mut().find(|f| f.id() == id) { i.downloaded += size; i.speed = size; } ); Ok(()) } pub fn set_downloaded(&self, id: usize, size: usize) -> Result<()> { self.downloads.write()?.iter_mut().for_each(|pck| if let Some(i) = pck.files.iter_mut().find(|f| f.id() == id) { i.downloaded = size; } ); self.publish_update()?; Ok(()) } pub fn add_package(&self, package: DownloadPackage) -> Result<()> { self.downloads.write()?.push(package); self.publish_update()?; self.save() } pub fn remove(&self, id: usize) -> Result<()> { self.downloads.write()?.iter_mut().for_each(|p| p.files.retain(|i| i.id() != id)); self.downloads.write()?.retain(|i| i.id() != id && !i.files.is_empty() ); self.publish_update()?; self.save() } pub fn get_downloads(&self) -> Result<DownloadList> { Ok(self.downloads.read()?.clone()) } pub fn files_status(&self, status: FileStatus) -> Result<Vec<usize>> { let ids = self.downloads.read()?.iter().map(|pck| pck.files.iter() .filter(|i| i.status == status) .map(|i| i.id()).collect::<Vec<usize>>() ).flat_map(|i| i.into_iter()) .collect::<Vec<usize>>(); Ok(ids) } pub fn files_status_hoster(&self, status: FileStatus, hoster: FileHoster) -> Result<Vec<usize>> { let ids = self.downloads.read()?.iter().map(|pck| pck.files.iter() .filter(|i| i.status == status && i.hoster == hoster) .map(|i| i.id()).collect::<Vec<usize>>() ).flat_map(|i| i.into_iter()) .collect::<Vec<usize>>(); Ok(ids) } pub fn get_file(&self, id: &usize) -> Result<DownloadFile> { let file = self.downloads.read()?.iter() .flat_map(|i| i.files.iter()) .find(|i| id == &i.id()).ok_or("The file can't be found")?.clone(); Ok(file.clone()) } pub fn get_package(&self, id: &usize) -> Result<DownloadPackage> { match self.downloads.read()?.iter().find(|i| &i.id() == id) { Some(i) => Ok(i.clone()), None => Ok(self.downloads.read()?.iter().find(|i| i.files.iter().any(|j| &j.id() == id)).ok_or("No download package available")?.clone()) } } pub fn get_high_id(&self) -> Result<usize> { let biggest_child = self.downloads.read()?.iter().map(|pck| pck.files.iter() .map(|i| i.id()).collect::<Vec<usize>>() ).flat_map(|i| i.into_iter()) .collect::<Vec<usize>>(); let biggest_child = biggest_child.iter().max().unwrap_or(&1); let biggest_parent = self.downloads.read()?.iter() .map(|x| x.id()) .collect::<Vec<usize>>(); let biggest_parent = biggest_parent.iter().max().unwrap_or(&1); Ok( if biggest_child > biggest_parent { *biggest_child } else { *biggest_parent } ) } pub fn publish_update(&self) -> Result<()> { self.sender.lock()?.send(Message::DownloadList(self.get_downloads()?))?; Ok(()) } fn handle_msg(&self) -> Result<()> { if let Message::DownloadSpeed((id, size)) = self.receiver.lock()?.recv()? { self.add_downloaded(id, size)?; } Ok(()) } fn save(&self) -> Result<()> { let d_list = ::serde_json::to_string_pretty(&(self.get_high_id()?, self.get_downloads()?))?; let mut file = File::create("./config/status.json")?; file.write_all(&d_list.into_bytes())?; Ok(()) } fn load(&self) -> Result<()> { let file = File::open("./config/status.json")?; let (id, d_list) : (usize, DownloadList) = ::serde_json::from_reader(file)?; crate::models::set_idcounter(id); for mut p in d_list { p.files.iter_mut().for_each(|f| { f.speed = 0; if f.status == FileStatus::Downloading { f.status = FileStatus::DownloadQueue; }; }); self.add_package(p)?; } Ok(()) } }
}; match d_list.load() { Ok(_) => {}, Err(_) => {println!("Can't read previus status of the download list")} }; let d_list_internal = d_list.clone(); thread::spawn(move || loop { match d_list_internal.handle_msg() { Ok(_) => {} Err(e) => println!("{}", e),
function_block-random_span
[ { "content": "/// Trait to write a stream of data to a file.\n\npub trait FileWriter : Read {\n\n /// Function to write a stream of data, to a file\n\n /// based on the std::io::Read trait. This functions\n\n /// returns as result the hash of the written file.\n\n fn write_to_file<S: Into<String>>(&...
Rust
src/database/meta.rs
eomain/ejdb.rs
43cf24608c5d970f3641d764124122a50438a6e5
use std::iter; use std::ops::Deref; use std::result; use std::slice; use std::str::FromStr; use bson::{Bson, Document, ValueAccessError}; use ejdb_sys; use super::Database; use ejdb_bson::EjdbBsonDocument; use Result; impl Database { pub fn get_metadata(&self) -> Result<DatabaseMetadata> { let doc = unsafe { ejdb_sys::ejdbmeta(self.0) }; if doc.is_null() { return self.last_error("cannot load metadata"); } else { let bson_doc = unsafe { try!(EjdbBsonDocument::from_ptr(doc).to_bson()) }; Ok(DatabaseMetadata(bson_doc)) } } } #[derive(Clone, PartialEq, Debug)] pub struct DatabaseMetadata(Document); impl DatabaseMetadata { #[inline] pub fn into_inner(self) -> Document { self.0 } pub fn file(&self) -> &str { self.0 .get_str("file") .expect("cannot get database file name") } pub fn collections(&self) -> Collections { self.0 .get_array("collections") .expect("cannot get collections metadata") .iter() .map(parse_collection_metadata) } } impl Deref for DatabaseMetadata { type Target = Document; #[inline] fn deref(&self) -> &Document { &self.0 } } pub type Collections<'a> = iter::Map<slice::Iter<'a, Bson>, for<'d> fn(&'d Bson) -> CollectionMetadata<'d>>; fn parse_collection_metadata(bson: &Bson) -> CollectionMetadata { match *bson { Bson::Document(ref doc) => CollectionMetadata(doc), ref something_else => panic!("invalid collections metadata: {}", something_else), } } #[derive(Clone, PartialEq, Debug)] pub struct CollectionMetadata<'a>(&'a Document); impl<'a> CollectionMetadata<'a> { pub fn name(&self) -> &str { self.0.get_str("name").expect("cannot get collection name") } pub fn file(&self) -> &str { self.0 .get_str("file") .expect("cannot get collection file name") } pub fn records(&self) -> u64 { self.0 .get_i64("records") .expect("cannot get collection records count") as u64 } fn options(&self) -> &Document { self.0 .get_document("options") .expect("cannot get collection options") } pub fn buckets(&self) -> u64 { self.options() .get_i64("buckets") .expect("cannot get collection buckets count") as u64 } pub fn cached_records(&self) -> u64 { self.options() .get_i64("cachedrecords") .expect("cannot get collection cached records count") as u64 } pub fn large(&self) -> bool { self.options() .get_bool("large") .expect("cannot get collection large flag") } pub fn compressed(&self) -> bool { self.options() .get_bool("compressed") .expect("cannot get collection compressed flag") } pub fn indices(&self) -> CollectionIndices { self.0 .get_array("indexes") .expect("cannot get collection indices array") .iter() .map(parse_index_metadata) } } impl<'a> Deref for CollectionMetadata<'a> { type Target = Document; #[inline] fn deref(&self) -> &Document { &*self.0 } } pub type CollectionIndices<'a> = iter::Map<slice::Iter<'a, Bson>, for<'d> fn(&'d Bson) -> IndexMetadata<'d>>; fn parse_index_metadata(bson: &Bson) -> IndexMetadata { match *bson { Bson::Document(ref doc) => IndexMetadata(doc), ref something_else => panic!("invalid index metadata: {}", something_else), } } #[derive(Clone, PartialEq, Debug)] pub struct IndexMetadata<'a>(&'a Document); impl<'a> IndexMetadata<'a> { pub fn field(&self) -> &str { self.0.get_str("field").expect("cannot get index field") } pub fn name(&self) -> &str { self.0.get_str("iname").expect("cannot get index name") } pub fn index_type(&self) -> IndexType { self.0 .get_str("type") .expect("cannot get index type") .parse() .expect("invalid index type") } pub fn records(&self) -> Option<u64> { match self.0.get_i64("records") { Ok(n) => Some(n as u64), Err(ValueAccessError::NotPresent) => None, Err(_) => panic!("cannot get index records count"), } } pub fn file(&self) -> Option<&str> { match self.0.get_str("file") { Ok(f) => Some(f), Err(ValueAccessError::NotPresent) => None, Err(_) => panic!("cannot get index file"), } } } impl<'a> Deref for IndexMetadata<'a> { type Target = Document; #[inline] fn deref(&self) -> &Document { &*self.0 } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum IndexType { Lexical, Decimal, Token, } impl FromStr for IndexType { type Err = String; fn from_str(s: &str) -> result::Result<IndexType, String> { match s { "lexical" => Ok(IndexType::Lexical), "decimal" => Ok(IndexType::Decimal), "token" => Ok(IndexType::Token), s => Err(s.into()), } } } #[test] #[ignore] fn test_metadata() { let db = Database::open("db/test").unwrap(); let meta = db.get_metadata().unwrap(); println!("{}", Bson::Document(meta.into_inner())); }
use std::iter; use std::ops::Deref; use std::result; use std::slice; use std::str::FromStr; use bson::{Bson, Document, ValueAccessError}; use ejdb_sys; use super::Database; use ejdb_bson::EjdbBsonDocument; use Result; impl Database { pub fn get_metadata(&self) -> Result<DatabaseMetadata> { let doc = unsafe { ejdb_sys::ejdbmeta(self.0) }; if doc.is_null() { return self.last_error("cannot load metadata"); } else { let bson_doc = unsafe { try!(EjdbBsonDocument::from_ptr(doc).to_bson()) }; Ok(DatabaseMetadata(bson_doc)) } } } #[derive(Clone, PartialEq, Debug)] pub struct DatabaseMetadata(Document); impl DatabaseMetadata { #[inline] pub fn into_inner(self) -> Document { self.0 } pub fn file(&self) -> &str { self.0 .get_str("file") .expect("cannot get database file name") } pub fn collections(&self) -> Collections { self.0 .get_array("collections") .expect("cannot get collections metadata") .iter() .map(parse_collection_metadata) } } impl Deref for DatabaseMetadata { type Target = Document; #[inline] fn deref(&self) -> &Document { &self.0 } } pub type Collections<'a> = iter::Map<slice::Iter<'a, Bson>, for<'d> fn(&'d Bson) -> CollectionMetadata<'d>>; fn parse_collection_metadata(bson: &Bson) -> CollectionMetadata { match *bson { Bson::Document(ref doc) => CollectionMetadata(doc), ref something_else => panic!("invalid collections metadata: {}", something_else), } } #[derive(Clone, PartialEq, Debug)] pub struct CollectionMetadata<'a>(&'a Document); impl<'a> CollectionMetadata<'a> { pub fn name(&self) -> &str { self.0.get_str("name").expect("cannot get collection name") } pub fn file(&self) -> &str { self.0 .get_str("file") .expect("cannot get collection file name") } pub fn records(&self) -> u64 { self.0 .get_i64("records") .expect("cannot get collection records count") as u64 } fn options(&self) -> &Document { self.0 .get_document("options") .expect("cannot get collection options") } pub fn buckets(&self) -> u64 { self.options() .get_i64("buckets") .expect("cannot get collection buckets count") as u64 } pub fn cached_records(&self) -> u64 { self.options() .get_i64("cachedrecords") .expect("cannot get collection cached records count") as u64 } pub fn large(&self) -> bool { self.options() .get_bool("large") .expect("cannot get collection large flag") } pub fn compressed(&self) -> bool { self.options() .get_bool("compressed") .expect("cannot get collection compressed flag") } pub fn indices(&self) -> CollectionIndices { self.0 .get_array("indexes") .expect("cannot get collection indices array") .iter() .map(parse_index_metadata) } } impl<'a> Deref for CollectionMetadata<'a> { type Target = Document; #[inline] fn deref(&self) -> &Document { &*self.0 } } pub type CollectionIndices<'a> = iter::Map<slice::Iter<'a, Bson>, for<'d> fn(&'d Bson) -> IndexMetadata<'d>>; fn parse_index_metadata(bson: &Bson) -> IndexMetadata { match *bson { Bson::Document(ref doc) => IndexMetadata(doc), ref something_else => panic!("invalid index metadata: {}", something_else), } } #[derive(Clone, PartialEq, Debug)] pub struct IndexMetadata<'a>(&'a Document); impl<'a> IndexMetadata<'a> { pub fn field(&self) -> &str { self.0.get_str("field").expect("cannot get index field") } pub fn name(&self) -> &str { self.0.get_str("iname").expect("cannot get index name") } pub fn index_type(&self) -> IndexType { self.0 .get_str("type") .expect("cannot get index type") .parse() .expect("invalid index type") } pub fn records(&self) -> Option<u64> {
} pub fn file(&self) -> Option<&str> { match self.0.get_str("file") { Ok(f) => Some(f), Err(ValueAccessError::NotPresent) => None, Err(_) => panic!("cannot get index file"), } } } impl<'a> Deref for IndexMetadata<'a> { type Target = Document; #[inline] fn deref(&self) -> &Document { &*self.0 } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum IndexType { Lexical, Decimal, Token, } impl FromStr for IndexType { type Err = String; fn from_str(s: &str) -> result::Result<IndexType, String> { match s { "lexical" => Ok(IndexType::Lexical), "decimal" => Ok(IndexType::Decimal), "token" => Ok(IndexType::Token), s => Err(s.into()), } } } #[test] #[ignore] fn test_metadata() { let db = Database::open("db/test").unwrap(); let meta = db.get_metadata().unwrap(); println!("{}", Bson::Document(meta.into_inner())); }
match self.0.get_i64("records") { Ok(n) => Some(n as u64), Err(ValueAccessError::NotPresent) => None, Err(_) => panic!("cannot get index records count"), }
if_condition
[ { "content": "pub trait BsonNumber {\n\n fn to_bson(self) -> Bson;\n\n}\n\n\n\nimpl BsonNumber for f32 {\n\n #[inline]\n\n fn to_bson(self) -> Bson {\n\n Bson::FloatingPoint(self as f64)\n\n }\n\n}\n\n\n\nimpl BsonNumber for f64 {\n\n #[inline]\n\n fn to_bson(self) -> Bson {\n\n ...
Rust
src/coreobjs.rs
mayadata-io/dynservice
3ce44fd53a8986056c85edecefa84c81c87b6e59
use crate::{ common::{ServiceUnregister, DEFAULT_SERVICE_TIMEOUT}, store::{StoreError, TimedLease}, ServiceError, }; use serde::{Deserialize, Serialize}; use snafu::ResultExt; #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Service { name: String, instance_id: String, endpoints: Vec<String>, } impl Service { pub(crate) fn new(options: ServiceConfig) -> Self { Self { name: options.name, instance_id: options.instance_id, endpoints: options.endpoints, } } pub fn name(&self) -> &str { &self.name } pub fn instance_id(&self) -> &str { &self.instance_id } pub fn endpoints(&self) -> &Vec<String> { &self.endpoints } } #[derive(Default, Debug)] pub struct ServiceConfigBuilder { name: Option<String>, instance_id: Option<String>, heartbeat_interval: Option<i64>, endpoints: Option<Vec<String>>, } impl ServiceConfigBuilder { pub fn build(self) -> ServiceConfig { let name = self.name.expect("Service name is mandatory"); let instance_id = self.instance_id.expect("Service instance ID is mandatory"); let heartbeat_interval = self.heartbeat_interval.unwrap_or(DEFAULT_SERVICE_TIMEOUT); let endpoints = self.endpoints.expect("Service endpoints are mandatory"); ServiceConfig { name, instance_id, heartbeat_interval, endpoints, } } pub fn with_name(mut self, name: impl Into<String>) -> Self { self.name = Some(name.into()); self } pub fn with_instance_id(mut self, instance_id: impl Into<String>) -> Self { self.instance_id = Some(instance_id.into()); self } pub fn with_heartbeat_interval(mut self, interval: i64) -> Self { assert!( interval > 0, "Heartbeat interval must be non-negative: {}", interval ); self.heartbeat_interval = Some(interval); self } pub fn with_endpoints<S: AsRef<str>, E: AsRef<[S]>>(mut self, endpoints: E) -> Self { let eps: Vec<String> = endpoints .as_ref() .iter() .map(|e| e.as_ref().to_string()) .collect(); assert!(!eps.is_empty(), "Service must have at least one endpoint"); self.endpoints = Some(eps); self } } #[derive(Debug, Clone)] pub struct ServiceConfig { name: String, instance_id: String, heartbeat_interval: i64, endpoints: Vec<String>, } impl ServiceConfig { pub fn builder() -> ServiceConfigBuilder { ServiceConfigBuilder::default() } pub fn name(&self) -> &str { &self.name } pub fn instance_id(&self) -> &str { &self.instance_id } pub fn heartbeat_interval(&self) -> i64 { self.heartbeat_interval } pub fn endpoints(&self) -> Vec<String> { self.endpoints.clone() } } #[derive(Debug)] pub struct ServiceDescriptor { service: String, instance: String, lease: TimedLease, } impl ServiceDescriptor { pub(crate) fn new(service: &Service, lease: TimedLease) -> Self { Self { service: service.name().to_string(), instance: service.instance_id().to_string(), lease, } } pub async fn send_heartbeat(&mut self) -> Result<(), ServiceError> { match self.lease.keep_alive().await { Err(StoreError::LeaseLost { .. }) => Err(ServiceError::HeartbeatLost { service: self.service.to_string(), instance: self.instance.to_string(), }), Err(e) => Err(ServiceError::HeartbeatError { service: self.service.to_string(), instance: self.instance.to_string(), source: e, }), _ => Ok(()), } } pub async fn unregister(mut self) -> Result<(), ServiceError> { self.lease.revoke().await.context(ServiceUnregister { service: self.service.to_string(), instance: self.instance.to_string(), })?; Ok(()) } pub fn heartbeat_interval(&self) -> i64 { self.lease.ttl() } pub fn service(&self) -> &str { &self.service } pub fn instance(&self) -> &str { &self.instance } }
use crate::{ common::{ServiceUnregister, DEFAULT_SERVICE_TIMEOUT}, store::{StoreError, TimedLease}, ServiceError, }; use serde::{Deserialize, Serialize}; use snafu::ResultExt; #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Service { name: String, instance_id: String, endpoints: Vec<String>, } impl Service { pub(crate) fn new(options: ServiceConfig) -> Self { Self { name: options.name, instance_id: options.instance_id, endpoints: options.endpoints, } } pub fn name(&self) -> &str { &self.name } pub fn instance_id(&self) -> &str { &self.instance_id } pub fn endpoints(&self) -> &Vec<String> { &self.endpoints } } #[derive(Default, Debug)] pub struct ServiceConfigBuilder { name: Option<String>, instance_id: Option<String>, heartbeat_interval: Option<i64>, endpoints: Option<Vec<String>>, } impl ServiceConfigBuilder { pub fn build(self) -> ServiceConfig { let name = self.name.expect("Service name is mandatory"); let instance_id = self.instance_id.expect("Service instance ID is mandatory"); let heartbeat_interval = self.heartbeat_interval.unwrap_or(DEFAULT_SERVICE_TIMEOUT); let endpoints = self.endpoints.expect("Service endpoints are mandatory"); ServiceConfig { name, instance_id, heartbeat_interval, endpoints, } } pub fn with_name(mut self, name: impl Into<String>) -> Self { self.name = Some(name.into()); self } pub fn with_instance_id(mut self, instance_id: impl Into<String>) -> Self { self.instance_id = Some(instance_id.into()); self } pub fn with_heartbeat_interval(mut self, interval: i64) -> Self { assert!( interval > 0, "Heartbeat interval must be non-negative: {}", interval
> i64 { self.lease.ttl() } pub fn service(&self) -> &str { &self.service } pub fn instance(&self) -> &str { &self.instance } }
); self.heartbeat_interval = Some(interval); self } pub fn with_endpoints<S: AsRef<str>, E: AsRef<[S]>>(mut self, endpoints: E) -> Self { let eps: Vec<String> = endpoints .as_ref() .iter() .map(|e| e.as_ref().to_string()) .collect(); assert!(!eps.is_empty(), "Service must have at least one endpoint"); self.endpoints = Some(eps); self } } #[derive(Debug, Clone)] pub struct ServiceConfig { name: String, instance_id: String, heartbeat_interval: i64, endpoints: Vec<String>, } impl ServiceConfig { pub fn builder() -> ServiceConfigBuilder { ServiceConfigBuilder::default() } pub fn name(&self) -> &str { &self.name } pub fn instance_id(&self) -> &str { &self.instance_id } pub fn heartbeat_interval(&self) -> i64 { self.heartbeat_interval } pub fn endpoints(&self) -> Vec<String> { self.endpoints.clone() } } #[derive(Debug)] pub struct ServiceDescriptor { service: String, instance: String, lease: TimedLease, } impl ServiceDescriptor { pub(crate) fn new(service: &Service, lease: TimedLease) -> Self { Self { service: service.name().to_string(), instance: service.instance_id().to_string(), lease, } } pub async fn send_heartbeat(&mut self) -> Result<(), ServiceError> { match self.lease.keep_alive().await { Err(StoreError::LeaseLost { .. }) => Err(ServiceError::HeartbeatLost { service: self.service.to_string(), instance: self.instance.to_string(), }), Err(e) => Err(ServiceError::HeartbeatError { service: self.service.to_string(), instance: self.instance.to_string(), source: e, }), _ => Ok(()), } } pub async fn unregister(mut self) -> Result<(), ServiceError> { self.lease.revoke().await.context(ServiceUnregister { service: self.service.to_string(), instance: self.instance.to_string(), })?; Ok(()) } pub fn heartbeat_interval(&self) -
random
[ { "content": "fn get_container_mount() -> String {\n\n tempdir()\n\n .unwrap()\n\n .into_path()\n\n .as_path()\n\n .to_string_lossy()\n\n .to_string()\n\n}\n\n\n\nimpl Builder {\n\n pub fn new(num_nodes: u32) -> Self {\n\n assert!(\n\n num_nodes > 0 && ...
Rust
src/board.rs
Rejyr/sf21_22
974887cfb655eb48a23b9b425166884194719c00
use std::fmt::Display; use std::ops::ControlFlow; use board_game::board::Board as BoardTrait; use board_game::board::BoardMoves; use board_game::board::Outcome; use board_game::board::Player; use board_game::board::UnitSymmetryBoard; use chess::{BitBoard, Color}; use internal_iterator::Internal; use internal_iterator::InternalIterator; use internal_iterator::IteratorExt; use crate::consts::EMPTY_BB; use crate::consts::{RANKS, START_POS_BLACK, START_POS_WHITE}; use crate::move_gen::Move; use crate::move_gen::MoveGen; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Board { white: BitBoard, black: BitBoard, side_to_move: Color, size: usize, } impl Display for Board { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut white = self.white.0; let mut black = self.black.0; for i in 0..8 { let mut w_rank = ((white & RANKS[7]) >> 56) as u8; let mut b_rank = ((black & RANKS[7]) >> 56) as u8; for _ in 0..8 { let w_sq = w_rank & 1; let b_sq = b_rank & 1; match (w_sq, b_sq) { (0, 0) => f.write_str(" ")?, (1, 0) => f.write_str("♙")?, (0, 1) => f.write_str("♟︎")?, (1, 1) => panic!("Board has two pawns in the same place"), _ => {} } w_rank >>= 1; b_rank >>= 1; } f.write_fmt(format_args!("|{}\n", 8 - i))?; white <<= 8; black <<= 8; } f.write_str("--------*\n")?; f.write_str("abcdefgh\n")?; f.write_str("01234567\n")?; Ok(()) } } impl Board { pub fn new(size: usize) -> Self { assert!(size > 2 && size < 9, "Invalid size, must be 3 to 8"); Board { white: BitBoard(START_POS_WHITE[size - 1]), black: BitBoard(START_POS_BLACK[size - 1]), side_to_move: Color::White, size, } } pub fn pieces(&self, color: Color) -> BitBoard { match color { Color::White => self.white, Color::Black => self.black, } } pub fn pieces_mut(&mut self, color: Color) -> &mut BitBoard { match color { Color::White => &mut self.white, Color::Black => &mut self.black, } } pub fn pieces_to_move(&self) -> BitBoard { self.pieces(self.side_to_move) } pub fn pieces_to_move_mut(&mut self) -> &mut BitBoard { self.pieces_mut(self.side_to_move) } pub fn pieces_not_to_move(&self) -> BitBoard { self.pieces(!self.side_to_move) } pub fn pieces_not_to_move_mut(&mut self) -> &mut BitBoard { self.pieces_mut(!self.side_to_move) } pub fn side_to_move(&self) -> Color { self.side_to_move } pub fn empty(&self) -> BitBoard { !self.occupied() } pub fn occupied(&self) -> BitBoard { self.white | self.black } } impl UnitSymmetryBoard for Board {} impl BoardTrait for Board { type Move = Move; fn next_player(&self) -> board_game::board::Player { match self.side_to_move { Color::White => Player::A, Color::Black => Player::B, } } fn is_available_move(&self, mv: Self::Move) -> bool { MoveGen::new(self).any(|x| x == mv) } fn play(&mut self, mv: Self::Move) { let src_bb = BitBoard::from_square(mv.src()); let dest_bb = BitBoard::from_square(mv.dest()); *self.pieces_to_move_mut() ^= src_bb | dest_bb; *self.pieces_not_to_move_mut() &= !dest_bb; self.side_to_move = !self.side_to_move; } fn outcome(&self) -> Option<board_game::board::Outcome> { if self.white & BitBoard(RANKS[self.size - 1]) != EMPTY_BB { Some(Outcome::WonBy(Player::A)) } else if self.black & BitBoard(RANKS[0]) != EMPTY_BB { Some(Outcome::WonBy(Player::B)) } else if MoveGen::new(self).len() == 0 { Some(Outcome::Draw) } else { None } } fn can_lose_after_move() -> bool { false } } impl<'a> BoardMoves<'a, Board> for Board { type AllMovesIterator = AllMoves; type AvailableMovesIterator = Internal<MoveGen>; fn all_possible_moves() -> Self::AllMovesIterator { AllMoves } fn available_moves(&'a self) -> Self::AvailableMovesIterator { MoveGen::new(self).into_internal() } } #[doc(hidden)] pub struct AllMoves; impl InternalIterator for AllMoves { type Item = Move; fn try_for_each<R, F>(self, mut f: F) -> std::ops::ControlFlow<R> where F: FnMut(Self::Item) -> std::ops::ControlFlow<R>, { for from in chess::ALL_SQUARES { for to in chess::ALL_SQUARES { f(Move::new(from, to))?; } } ControlFlow::Continue(()) } }
use std::fmt::Display; use std::ops::ControlFlow; use board_game::board::Board as BoardTrait; use board_game::board::BoardMoves; use board_game::board::Outcome; use board_game::board::Player; use board_game::board::UnitSymmetryBoard; use chess::{BitBoard, Color}; use internal_iterator::Internal; use internal_iterator::InternalIterator; use internal_iterator::IteratorExt; use crate::consts::EMPTY_BB; use crate::consts::{RANKS, START_POS_BLACK, START_POS_WHITE}; use crate::move_gen::Move; use crate::move_gen::MoveGen; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Board { white: BitBoard, black: BitBoard, side_to_move: Color, size: usize, } impl Display for Board { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut white = self.white.0; let mut black = self.black.0; for i in 0..8 { let mut w_rank = ((white & RANKS[7]) >> 56) as u8; let mut b_rank = ((black & RANKS[7]) >> 56) as u8; for _ in 0..8 { let w_sq = w_rank & 1; let b_sq = b_rank & 1; match (w_sq, b_sq) { (0, 0) => f.write_str(" ")?, (1, 0) => f.write_str("♙")?, (0, 1) => f.write_str("♟︎")?, (1, 1) => panic!("Board has two pawns in the same place"), _ => {} } w_rank >>= 1; b_rank >>= 1; } f.write_fmt(format_args!("|{}\n", 8 - i))?; white <<= 8; black <<= 8; } f.write_str("--------*\n")?; f.write_str("abcdefgh\n")?; f.write_str("01234567\n")?; Ok(()) } } impl Board { pub fn new(size: usize) -> Self { assert!(size > 2 && size < 9, "Invalid size, must be 3 to 8"); Board { white: BitBoard(START_POS_WHITE[size - 1]), black: BitBoard(START_POS_BLACK[size - 1]), side_to_move: Color::White, size, } } pub fn pieces(&self, color: Color) -> BitBoard { match color { Color::White => self.white, Color::Black => self.black, } } pub fn pieces_mut(&mut self, color: Color) -> &mut BitBoard { match color { Color::White => &mut self.white, Color::Black => &mut self.black, } } pub fn pieces_to_move(&self) -> BitBoard { self.pieces(self.side_to_move) } pub fn pieces_to_move_mut(&mut self) -> &mut BitBoard { self.pieces_mut(self.side_to_move) } pub fn pieces_not_to_move(&self) -> BitBoard { self.pieces(!self.side_to_move) } pub fn pieces_not_to_move_mut(&mut self) -> &mut BitBoard { self.pieces_mut(!self.side_to_move) } pub fn side_to_move(&self) -> Color { self.side_to_move } pub fn empty(&self) -> BitBoard { !self.occupied() } pub fn occupied(&self) -> BitBoard { self.white | self.black } } impl UnitSymmetryBoard for Board {} impl BoardTrait for Board { type Move = Move; fn next_player(&self) -> board_game::board::Player { match self.side_to_move { Color::White => Player::A, Color::Black => Player::B, } } fn is_available_move(&self, mv: Self::Move) -> bool { MoveGen::new(self).any(|x| x == mv) } fn play(&mut self, mv: Self::Move) { let src_bb = BitBoard::from_square(mv.src()); let dest_bb = BitBoard::fro
fn outcome(&self) -> Option<board_game::board::Outcome> { if self.white & BitBoard(RANKS[self.size - 1]) != EMPTY_BB { Some(Outcome::WonBy(Player::A)) } else if self.black & BitBoard(RANKS[0]) != EMPTY_BB { Some(Outcome::WonBy(Player::B)) } else if MoveGen::new(self).len() == 0 { Some(Outcome::Draw) } else { None } } fn can_lose_after_move() -> bool { false } } impl<'a> BoardMoves<'a, Board> for Board { type AllMovesIterator = AllMoves; type AvailableMovesIterator = Internal<MoveGen>; fn all_possible_moves() -> Self::AllMovesIterator { AllMoves } fn available_moves(&'a self) -> Self::AvailableMovesIterator { MoveGen::new(self).into_internal() } } #[doc(hidden)] pub struct AllMoves; impl InternalIterator for AllMoves { type Item = Move; fn try_for_each<R, F>(self, mut f: F) -> std::ops::ControlFlow<R> where F: FnMut(Self::Item) -> std::ops::ControlFlow<R>, { for from in chess::ALL_SQUARES { for to in chess::ALL_SQUARES { f(Move::new(from, to))?; } } ControlFlow::Continue(()) } }
m_square(mv.dest()); *self.pieces_to_move_mut() ^= src_bb | dest_bb; *self.pieces_not_to_move_mut() &= !dest_bb; self.side_to_move = !self.side_to_move; }
function_block-function_prefixed
[ { "content": "pub fn inspect_moves(board: &Board) {\n\n if board\n\n .available_moves()\n\n .inspect(|mv| println!(\"{mv}\"))\n\n .count()\n\n == 0\n\n {\n\n println!(\"No moves\");\n\n }\n\n}\n\n\n", "file_path": "src/tests.rs", "rank": 0, "score": 106015...
Rust
amethyst_input/src/gilrs_events_system.rs
niconicoj/amethyst
83fa765987fabb3a5f43e1b2f23381c880d52a6c
use std::{ collections::{hash_map::DefaultHasher, HashMap}, fmt, hash::{Hash, Hasher}, marker::PhantomData, }; use derivative::Derivative; use derive_new::new; use gilrs::{Axis, Button, Event, EventType, GamepadId, Gilrs}; use amethyst_core::{ ecs::prelude::{System, SystemData, World, Write}, shrev::EventChannel, SystemDesc, }; use super::{ controller::{ControllerAxis, ControllerButton, ControllerEvent}, BindingTypes, InputEvent, InputHandler, }; #[derive(Debug)] pub enum GilrsSystemError { ContextInit(String), ControllerSubsystemInit(String), } impl fmt::Display for GilrsSystemError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { GilrsSystemError::ContextInit(ref msg) => { write!(f, "Failed to initialize SDL: {}", msg) } GilrsSystemError::ControllerSubsystemInit(ref msg) => { write!(f, "Failed to initialize SDL controller subsystem: {}", msg) } } } } #[derive(Derivative, Debug, new)] #[derivative(Default(bound = ""))] pub struct GilrsEventsSystemDesc<T> where T: BindingTypes, { marker: PhantomData<T>, } impl<'a, 'b, T> SystemDesc<'a, 'b, GilrsEventsSystem<T>> for GilrsEventsSystemDesc<T> where T: BindingTypes, { fn build(self, world: &mut World) -> GilrsEventsSystem<T> { <GilrsEventsSystem<T> as System<'_>>::SystemData::setup(world); GilrsEventsSystem::new(world) .unwrap_or_else(|e| panic!("Failed to build SdlEventsSystem. Error: {}", e)) } } #[allow(missing_debug_implementations)] pub struct GilrsEventsSystem<T: BindingTypes> { gilrs_handle: Gilrs, opened_controllers: HashMap<GamepadId, u32>, marker: PhantomData<T>, } type GilrsEventsData<'a, T> = ( Write<'a, InputHandler<T>>, Write<'a, EventChannel<InputEvent<T>>>, ); impl<'a, T: BindingTypes> System<'a> for GilrsEventsSystem<T> { type SystemData = GilrsEventsData<'a, T>; fn run(&mut self, (mut handler, mut output): Self::SystemData) { while let Some(Event { id, event, time: _ }) = self.gilrs_handle.next_event() { self.handle_gilrs_event(&id, &event, &mut handler, &mut output); } } } impl<T: BindingTypes> GilrsEventsSystem<T> { pub fn new(world: &mut World) -> Result<Self, GilrsSystemError> { let gilrs_handle: Gilrs = Gilrs::new().unwrap(); GilrsEventsData::<T>::setup(world); let mut sys = GilrsEventsSystem { gilrs_handle, opened_controllers: HashMap::new(), marker: PhantomData, }; let (mut handler, mut output) = GilrsEventsData::fetch(world); sys.initialize_controllers(&mut handler, &mut output); Ok(sys) } fn handle_gilrs_event( &mut self, gamepad_id: &GamepadId, event_type: &EventType, handler: &mut InputHandler<T>, output: &mut EventChannel<InputEvent<T>>, ) { use self::ControllerEvent::*; if let Some(idx) = self.opened_controllers.get(gamepad_id) { match *event_type { EventType::AxisChanged(axis, value, _code) => { handler.send_controller_event( &ControllerAxisMoved { which: *idx, axis: axis.into(), value: value, }, output, ); } EventType::ButtonReleased(button, _code) => { handler.send_controller_event( &ControllerButtonReleased { which: *idx, button: button.into(), }, output, ); } EventType::ButtonPressed(button, _code) => { handler.send_controller_event( &ControllerButtonPressed { which: *idx, button: button.into(), }, output, ); } EventType::Disconnected => { if let Some(idx) = self.close_controller(*gamepad_id) { handler .send_controller_event(&ControllerDisconnected { which: idx }, output); } } EventType::Connected => { if let Some(idx) = self.open_controller(*gamepad_id) { handler.send_controller_event(&ControllerConnected { which: idx }, output); } } _ => {} } } else { match *event_type { EventType::Connected => { if let Some(idx) = self.open_controller(*gamepad_id) { handler.send_controller_event(&ControllerConnected { which: idx }, output); } } _ => {} } } } fn open_controller(&mut self, which: GamepadId) -> Option<u32> { match self.gilrs_handle.connected_gamepad(which) { Some(_) => { let idx = self.my_hash(which) as u32; self.opened_controllers.insert(which, idx); Some(idx) } None => None, } } fn close_controller(&mut self, which: GamepadId) -> Option<u32> { self.opened_controllers.remove(&which) } fn initialize_controllers( &mut self, handler: &mut InputHandler<T>, output: &mut EventChannel<InputEvent<T>>, ) { use crate::controller::ControllerEvent::ControllerConnected; for (_id, gamepad) in self.gilrs_handle.gamepads() { let idx = self.my_hash(gamepad.id()) as u32; self.opened_controllers.insert(gamepad.id(), idx); handler.send_controller_event(&ControllerConnected { which: idx }, output); } } fn my_hash<U>(&self, obj: U) -> u64 where U: Hash, { let mut hasher = DefaultHasher::new(); obj.hash(&mut hasher); hasher.finish() } } impl From<Button> for ControllerButton { fn from(button: Button) -> Self { match button { Button::South => ControllerButton::A, Button::East => ControllerButton::B, Button::West => ControllerButton::X, Button::North => ControllerButton::Y, Button::DPadDown => ControllerButton::DPadDown, Button::DPadLeft => ControllerButton::DPadLeft, Button::DPadRight => ControllerButton::DPadRight, Button::DPadUp => ControllerButton::DPadUp, Button::LeftTrigger => ControllerButton::LeftShoulder, Button::RightTrigger => ControllerButton::RightShoulder, Button::LeftThumb => ControllerButton::LeftStick, Button::RightThumb => ControllerButton::RightStick, Button::Select => ControllerButton::Back, Button::Start => ControllerButton::Start, Button::Mode => ControllerButton::Guide, Button::LeftTrigger2 => ControllerButton::LeftTrigger, Button::RightTrigger2 => ControllerButton::RightTrigger, _ => ControllerButton::Unknown, } } } impl From<Axis> for ControllerAxis { fn from(axis: Axis) -> Self { match axis { Axis::LeftStickX => ControllerAxis::LeftX, Axis::LeftStickY => ControllerAxis::LeftY, Axis::RightStickX => ControllerAxis::RightX, Axis::RightStickY => ControllerAxis::RightY, Axis::LeftZ => ControllerAxis::LeftTrigger, Axis::RightZ => ControllerAxis::RightTrigger, _ => ControllerAxis::Unknown, } } }
use std::{ collections::{hash_map::DefaultHasher, HashMap}, fmt, hash::{Hash, Has
er: PhantomData<T>, } type GilrsEventsData<'a, T> = ( Write<'a, InputHandler<T>>, Write<'a, EventChannel<InputEvent<T>>>, ); impl<'a, T: BindingTypes> System<'a> for GilrsEventsSystem<T> { type SystemData = GilrsEventsData<'a, T>; fn run(&mut self, (mut handler, mut output): Self::SystemData) { while let Some(Event { id, event, time: _ }) = self.gilrs_handle.next_event() { self.handle_gilrs_event(&id, &event, &mut handler, &mut output); } } } impl<T: BindingTypes> GilrsEventsSystem<T> { pub fn new(world: &mut World) -> Result<Self, GilrsSystemError> { let gilrs_handle: Gilrs = Gilrs::new().unwrap(); GilrsEventsData::<T>::setup(world); let mut sys = GilrsEventsSystem { gilrs_handle, opened_controllers: HashMap::new(), marker: PhantomData, }; let (mut handler, mut output) = GilrsEventsData::fetch(world); sys.initialize_controllers(&mut handler, &mut output); Ok(sys) } fn handle_gilrs_event( &mut self, gamepad_id: &GamepadId, event_type: &EventType, handler: &mut InputHandler<T>, output: &mut EventChannel<InputEvent<T>>, ) { use self::ControllerEvent::*; if let Some(idx) = self.opened_controllers.get(gamepad_id) { match *event_type { EventType::AxisChanged(axis, value, _code) => { handler.send_controller_event( &ControllerAxisMoved { which: *idx, axis: axis.into(), value: value, }, output, ); } EventType::ButtonReleased(button, _code) => { handler.send_controller_event( &ControllerButtonReleased { which: *idx, button: button.into(), }, output, ); } EventType::ButtonPressed(button, _code) => { handler.send_controller_event( &ControllerButtonPressed { which: *idx, button: button.into(), }, output, ); } EventType::Disconnected => { if let Some(idx) = self.close_controller(*gamepad_id) { handler .send_controller_event(&ControllerDisconnected { which: idx }, output); } } EventType::Connected => { if let Some(idx) = self.open_controller(*gamepad_id) { handler.send_controller_event(&ControllerConnected { which: idx }, output); } } _ => {} } } else { match *event_type { EventType::Connected => { if let Some(idx) = self.open_controller(*gamepad_id) { handler.send_controller_event(&ControllerConnected { which: idx }, output); } } _ => {} } } } fn open_controller(&mut self, which: GamepadId) -> Option<u32> { match self.gilrs_handle.connected_gamepad(which) { Some(_) => { let idx = self.my_hash(which) as u32; self.opened_controllers.insert(which, idx); Some(idx) } None => None, } } fn close_controller(&mut self, which: GamepadId) -> Option<u32> { self.opened_controllers.remove(&which) } fn initialize_controllers( &mut self, handler: &mut InputHandler<T>, output: &mut EventChannel<InputEvent<T>>, ) { use crate::controller::ControllerEvent::ControllerConnected; for (_id, gamepad) in self.gilrs_handle.gamepads() { let idx = self.my_hash(gamepad.id()) as u32; self.opened_controllers.insert(gamepad.id(), idx); handler.send_controller_event(&ControllerConnected { which: idx }, output); } } fn my_hash<U>(&self, obj: U) -> u64 where U: Hash, { let mut hasher = DefaultHasher::new(); obj.hash(&mut hasher); hasher.finish() } } impl From<Button> for ControllerButton { fn from(button: Button) -> Self { match button { Button::South => ControllerButton::A, Button::East => ControllerButton::B, Button::West => ControllerButton::X, Button::North => ControllerButton::Y, Button::DPadDown => ControllerButton::DPadDown, Button::DPadLeft => ControllerButton::DPadLeft, Button::DPadRight => ControllerButton::DPadRight, Button::DPadUp => ControllerButton::DPadUp, Button::LeftTrigger => ControllerButton::LeftShoulder, Button::RightTrigger => ControllerButton::RightShoulder, Button::LeftThumb => ControllerButton::LeftStick, Button::RightThumb => ControllerButton::RightStick, Button::Select => ControllerButton::Back, Button::Start => ControllerButton::Start, Button::Mode => ControllerButton::Guide, Button::LeftTrigger2 => ControllerButton::LeftTrigger, Button::RightTrigger2 => ControllerButton::RightTrigger, _ => ControllerButton::Unknown, } } } impl From<Axis> for ControllerAxis { fn from(axis: Axis) -> Self { match axis { Axis::LeftStickX => ControllerAxis::LeftX, Axis::LeftStickY => ControllerAxis::LeftY, Axis::RightStickX => ControllerAxis::RightX, Axis::RightStickY => ControllerAxis::RightY, Axis::LeftZ => ControllerAxis::LeftTrigger, Axis::RightZ => ControllerAxis::RightTrigger, _ => ControllerAxis::Unknown, } } }
her}, marker::PhantomData, }; use derivative::Derivative; use derive_new::new; use gilrs::{Axis, Button, Event, EventType, GamepadId, Gilrs}; use amethyst_core::{ ecs::prelude::{System, SystemData, World, Write}, shrev::EventChannel, SystemDesc, }; use super::{ controller::{ControllerAxis, ControllerButton, ControllerEvent}, BindingTypes, InputEvent, InputHandler, }; #[derive(Debug)] pub enum GilrsSystemError { ContextInit(String), ControllerSubsystemInit(String), } impl fmt::Display for GilrsSystemError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { GilrsSystemError::ContextInit(ref msg) => { write!(f, "Failed to initialize SDL: {}", msg) } GilrsSystemError::ControllerSubsystemInit(ref msg) => { write!(f, "Failed to initialize SDL controller subsystem: {}", msg) } } } } #[derive(Derivative, Debug, new)] #[derivative(Default(bound = ""))] pub struct GilrsEventsSystemDesc<T> where T: BindingTypes, { marker: PhantomData<T>, } impl<'a, 'b, T> SystemDesc<'a, 'b, GilrsEventsSystem<T>> for GilrsEventsSystemDesc<T> where T: BindingTypes, { fn build(self, world: &mut World) -> GilrsEventsSystem<T> { <GilrsEventsSystem<T> as System<'_>>::SystemData::setup(world); GilrsEventsSystem::new(world) .unwrap_or_else(|e| panic!("Failed to build SdlEventsSystem. Error: {}", e)) } } #[allow(missing_debug_implementations)] pub struct GilrsEventsSystem<T: BindingTypes> { gilrs_handle: Gilrs, opened_controllers: HashMap<GamepadId, u32>, mark
random
[ { "content": "/// Basic building block of rendering in [RenderingBundle].\n\n///\n\n/// Can be used to register rendering-related systems to the dispatcher,\n\n/// building render graph by registering render targets, adding [RenderableAction]s to them\n\n/// and signalling when the graph has to be rebuild.\n\np...
Rust
src/float/conv.rs
mattico/compiler-builtins
35dec6bd8ab1214078e6284d58e9ba62271e2fb9
use float::Float; use int::{Int, CastInto}; fn int_to_float<I: Int, F: Float>(i: I) -> F where F::Int: CastInto<u32>, F::Int: CastInto<I>, I::UnsignedInt: CastInto<F::Int>, u32: CastInto<F::Int>, { if i == I::ZERO { return F::ZERO; } let two = I::UnsignedInt::ONE + I::UnsignedInt::ONE; let four = two + two; let mant_dig = F::SIGNIFICAND_BITS + 1; let exponent_bias = F::EXPONENT_BIAS; let n = I::BITS; let (s, a) = i.extract_sign(); let mut a = a; let sd = n - a.leading_zeros(); let mut e = sd - 1; if I::BITS < mant_dig { return F::from_parts(s, (e + exponent_bias).cast(), a.cast() << (mant_dig - e - 1)); } a = if sd > mant_dig { /* start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx * finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR * 12345678901234567890123456 * 1 = msb 1 bit * P = bit MANT_DIG-1 bits to the right of 1 * Q = bit MANT_DIG bits to the right of 1 * R = "or" of all bits to the right of Q */ let mant_dig_plus_one = mant_dig + 1; let mant_dig_plus_two = mant_dig + 2; a = if sd == mant_dig_plus_one { a << 1 } else if sd == mant_dig_plus_two { a } else { (a >> (sd - mant_dig_plus_two)) | Int::from_bool((a & I::UnsignedInt::max_value()).wrapping_shl((n + mant_dig_plus_two) - sd) != Int::ZERO) }; /* finish: */ a |= Int::from_bool((a & four) != I::UnsignedInt::ZERO); /* Or P into R */ a += Int::ONE; /* round - this step may add a significant bit */ a >>= 2; /* dump Q and R */ /* a is now rounded to mant_dig or mant_dig+1 bits */ if (a & (I::UnsignedInt::ONE << mant_dig)) != Int::ZERO { a >>= 1; e += 1; } a /* a is now rounded to mant_dig bits */ } else { a.wrapping_shl(mant_dig - sd) /* a is now rounded to mant_dig bits */ }; F::from_parts(s, (e + exponent_bias).cast(), a.cast()) } intrinsics! { #[arm_aeabi_alias = __aeabi_i2f] pub extern "C" fn __floatsisf(i: i32) -> f32 { int_to_float(i) } #[arm_aeabi_alias = __aeabi_i2d] pub extern "C" fn __floatsidf(i: i32) -> f64 { int_to_float(i) } #[use_c_shim_if(all(target_arch = "x86", not(target_env = "msvc")))] #[arm_aeabi_alias = __aeabi_l2d] pub extern "C" fn __floatdidf(i: i64) -> f64 { if cfg!(target_arch = "x86_64") { i as f64 } else { int_to_float(i) } } #[unadjusted_on_win64] pub extern "C" fn __floattisf(i: i128) -> f32 { int_to_float(i) } #[unadjusted_on_win64] pub extern "C" fn __floattidf(i: i128) -> f64 { int_to_float(i) } #[arm_aeabi_alias = __aeabi_ui2f] pub extern "C" fn __floatunsisf(i: u32) -> f32 { int_to_float(i) } #[arm_aeabi_alias = __aeabi_ui2d] pub extern "C" fn __floatunsidf(i: u32) -> f64 { int_to_float(i) } #[use_c_shim_if(all(not(target_env = "msvc"), any(target_arch = "x86", all(not(windows), target_arch = "x86_64"))))] #[arm_aeabi_alias = __aeabi_ul2d] pub extern "C" fn __floatundidf(i: u64) -> f64 { int_to_float(i) } #[unadjusted_on_win64] pub extern "C" fn __floatuntisf(i: u128) -> f32 { int_to_float(i) } #[unadjusted_on_win64] pub extern "C" fn __floatuntidf(i: u128) -> f64 { int_to_float(i) } } #[derive(PartialEq)] enum Sign { Positive, Negative } fn float_to_int<F: Float, I: Int>(f: F) -> I where F::Int: CastInto<u32>, F::Int: CastInto<I>, { let f = f; let fixint_min = I::min_value(); let fixint_max = I::max_value(); let fixint_bits = I::BITS; let fixint_unsigned = fixint_min == I::ZERO; let sign_bit = F::SIGN_MASK; let significand_bits = F::SIGNIFICAND_BITS; let exponent_bias = F::EXPONENT_BIAS; let a_rep = F::repr(f); let a_abs = a_rep & !sign_bit; let sign = if (a_rep & sign_bit) == F::Int::ZERO { Sign::Positive } else { Sign::Negative }; let mut exponent: u32 = (a_abs >> significand_bits).cast(); let significand = (a_abs & F::SIGNIFICAND_MASK) | F::IMPLICIT_BIT; if exponent < exponent_bias || fixint_unsigned && sign == Sign::Negative { return I::ZERO; } exponent -= exponent_bias; if exponent >= (if fixint_unsigned {fixint_bits} else {fixint_bits -1}) { return if sign == Sign::Positive {fixint_max} else {fixint_min} } let r: I = if exponent < significand_bits { (significand >> (significand_bits - exponent)).cast() } else { (significand << (exponent - significand_bits)).cast() }; if sign == Sign::Negative { (!r).wrapping_add(I::ONE) } else { r } } intrinsics! { #[arm_aeabi_alias = __aeabi_f2iz] pub extern "C" fn __fixsfsi(f: f32) -> i32 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_f2lz] pub extern "C" fn __fixsfdi(f: f32) -> i64 { float_to_int(f) } #[unadjusted_on_win64] pub extern "C" fn __fixsfti(f: f32) -> i128 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_d2iz] pub extern "C" fn __fixdfsi(f: f64) -> i32 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_d2lz] pub extern "C" fn __fixdfdi(f: f64) -> i64 { float_to_int(f) } #[unadjusted_on_win64] pub extern "C" fn __fixdfti(f: f64) -> i128 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_f2uiz] pub extern "C" fn __fixunssfsi(f: f32) -> u32 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_f2ulz] pub extern "C" fn __fixunssfdi(f: f32) -> u64 { float_to_int(f) } #[unadjusted_on_win64] pub extern "C" fn __fixunssfti(f: f32) -> u128 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_d2uiz] pub extern "C" fn __fixunsdfsi(f: f64) -> u32 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_d2ulz] pub extern "C" fn __fixunsdfdi(f: f64) -> u64 { float_to_int(f) } #[unadjusted_on_win64] pub extern "C" fn __fixunsdfti(f: f64) -> u128 { float_to_int(f) } }
use float::Float; use int::{Int, CastInto}; fn int_to_float<I: Int, F: Float>(i: I) -> F where F::Int: CastInto<u32>, F::Int: CastInto<I>, I::UnsignedInt: CastInto<F::Int>, u32: CastInto<F::Int>, { if i == I::ZERO { return F::ZERO; } let two = I::UnsignedInt::ONE + I::UnsignedInt::ONE; let four = two + two; let mant_dig = F::SIGNIFICAND_BITS + 1; let exponent_bias = F::EXPONENT_BIAS; let n = I::BITS; let (s, a) = i.extract_sign(); let mut a = a; let sd = n - a.leading_zeros(); let mut e = sd - 1; if I::BITS < mant_dig { return F::from_parts(s, (e + exponent_bias).cast(), a.cast() << (mant_dig - e - 1)); } a = if sd > mant_dig { /* start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx * finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR * 12345678901234567890123456 * 1 = msb 1 bit * P = bit MANT_DIG-1 bits to the right of 1 * Q = bit MANT_DIG bits to the right of 1 * R = "or" of all bits to the right of Q */ let mant_dig_plus_one = mant_dig + 1; let mant_dig_plus_two = mant_dig + 2; a = if sd == mant_dig_plus_one { a << 1 } else if sd == mant_dig
pub extern "C" fn __floatuntidf(i: u128) -> f64 { int_to_float(i) } } #[derive(PartialEq)] enum Sign { Positive, Negative } fn float_to_int<F: Float, I: Int>(f: F) -> I where F::Int: CastInto<u32>, F::Int: CastInto<I>, { let f = f; let fixint_min = I::min_value(); let fixint_max = I::max_value(); let fixint_bits = I::BITS; let fixint_unsigned = fixint_min == I::ZERO; let sign_bit = F::SIGN_MASK; let significand_bits = F::SIGNIFICAND_BITS; let exponent_bias = F::EXPONENT_BIAS; let a_rep = F::repr(f); let a_abs = a_rep & !sign_bit; let sign = if (a_rep & sign_bit) == F::Int::ZERO { Sign::Positive } else { Sign::Negative }; let mut exponent: u32 = (a_abs >> significand_bits).cast(); let significand = (a_abs & F::SIGNIFICAND_MASK) | F::IMPLICIT_BIT; if exponent < exponent_bias || fixint_unsigned && sign == Sign::Negative { return I::ZERO; } exponent -= exponent_bias; if exponent >= (if fixint_unsigned {fixint_bits} else {fixint_bits -1}) { return if sign == Sign::Positive {fixint_max} else {fixint_min} } let r: I = if exponent < significand_bits { (significand >> (significand_bits - exponent)).cast() } else { (significand << (exponent - significand_bits)).cast() }; if sign == Sign::Negative { (!r).wrapping_add(I::ONE) } else { r } } intrinsics! { #[arm_aeabi_alias = __aeabi_f2iz] pub extern "C" fn __fixsfsi(f: f32) -> i32 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_f2lz] pub extern "C" fn __fixsfdi(f: f32) -> i64 { float_to_int(f) } #[unadjusted_on_win64] pub extern "C" fn __fixsfti(f: f32) -> i128 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_d2iz] pub extern "C" fn __fixdfsi(f: f64) -> i32 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_d2lz] pub extern "C" fn __fixdfdi(f: f64) -> i64 { float_to_int(f) } #[unadjusted_on_win64] pub extern "C" fn __fixdfti(f: f64) -> i128 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_f2uiz] pub extern "C" fn __fixunssfsi(f: f32) -> u32 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_f2ulz] pub extern "C" fn __fixunssfdi(f: f32) -> u64 { float_to_int(f) } #[unadjusted_on_win64] pub extern "C" fn __fixunssfti(f: f32) -> u128 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_d2uiz] pub extern "C" fn __fixunsdfsi(f: f64) -> u32 { float_to_int(f) } #[arm_aeabi_alias = __aeabi_d2ulz] pub extern "C" fn __fixunsdfdi(f: f64) -> u64 { float_to_int(f) } #[unadjusted_on_win64] pub extern "C" fn __fixunsdfti(f: f64) -> u128 { float_to_int(f) } }
_plus_two { a } else { (a >> (sd - mant_dig_plus_two)) | Int::from_bool((a & I::UnsignedInt::max_value()).wrapping_shl((n + mant_dig_plus_two) - sd) != Int::ZERO) }; /* finish: */ a |= Int::from_bool((a & four) != I::UnsignedInt::ZERO); /* Or P into R */ a += Int::ONE; /* round - this step may add a significant bit */ a >>= 2; /* dump Q and R */ /* a is now rounded to mant_dig or mant_dig+1 bits */ if (a & (I::UnsignedInt::ONE << mant_dig)) != Int::ZERO { a >>= 1; e += 1; } a /* a is now rounded to mant_dig bits */ } else { a.wrapping_shl(mant_dig - sd) /* a is now rounded to mant_dig bits */ }; F::from_parts(s, (e + exponent_bias).cast(), a.cast()) } intrinsics! { #[arm_aeabi_alias = __aeabi_i2f] pub extern "C" fn __floatsisf(i: i32) -> f32 { int_to_float(i) } #[arm_aeabi_alias = __aeabi_i2d] pub extern "C" fn __floatsidf(i: i32) -> f64 { int_to_float(i) } #[use_c_shim_if(all(target_arch = "x86", not(target_env = "msvc")))] #[arm_aeabi_alias = __aeabi_l2d] pub extern "C" fn __floatdidf(i: i64) -> f64 { if cfg!(target_arch = "x86_64") { i as f64 } else { int_to_float(i) } } #[unadjusted_on_win64] pub extern "C" fn __floattisf(i: i128) -> f32 { int_to_float(i) } #[unadjusted_on_win64] pub extern "C" fn __floattidf(i: i128) -> f64 { int_to_float(i) } #[arm_aeabi_alias = __aeabi_ui2f] pub extern "C" fn __floatunsisf(i: u32) -> f32 { int_to_float(i) } #[arm_aeabi_alias = __aeabi_ui2d] pub extern "C" fn __floatunsidf(i: u32) -> f64 { int_to_float(i) } #[use_c_shim_if(all(not(target_env = "msvc"), any(target_arch = "x86", all(not(windows), target_arch = "x86_64"))))] #[arm_aeabi_alias = __aeabi_ul2d] pub extern "C" fn __floatundidf(i: u64) -> f64 { int_to_float(i) } #[unadjusted_on_win64] pub extern "C" fn __floatuntisf(i: u128) -> f32 { int_to_float(i) } #[unadjusted_on_win64]
random
[ { "content": "#[test]\n\nfn two() {\n\n let mut aligned = Aligned::new([0u8; 8]);;\n\n assert_eq!(mem::align_of_val(&aligned), 4);\n\n let xs = &mut aligned.array;\n\n let n = 2;\n\n let c = 0xdeadbeef;\n\n\n\n unsafe {\n\n __aeabi_memset4(xs.as_mut_ptr(), n, c)\n\n }\n\n\n\n asse...
Rust
kube/src/client/tls.rs
Ka1wa/kube-rs
50acf98ce7513809634d297392663539c06478c2
#[cfg(feature = "native-tls")] pub mod native_tls { use tokio_native_tls::native_tls::{Certificate, Identity, TlsConnector}; use crate::{Error, Result}; const IDENTITY_PASSWORD: &str = " "; pub fn native_tls_connector( identity_pem: Option<&Vec<u8>>, root_cert: Option<&Vec<Vec<u8>>>, accept_invalid: bool, ) -> Result<TlsConnector> { let mut builder = TlsConnector::builder(); if let Some(pem) = identity_pem { let identity = pkcs12_from_pem(pem, IDENTITY_PASSWORD)?; builder.identity( Identity::from_pkcs12(&identity, IDENTITY_PASSWORD) .map_err(|e| Error::SslError(format!("{}", e)))?, ); } if let Some(ders) = root_cert { for der in ders { builder.add_root_certificate( Certificate::from_der(der).map_err(|e| Error::SslError(format!("{}", e)))?, ); } } if accept_invalid { builder.danger_accept_invalid_certs(true); } let connector = builder.build().map_err(|e| Error::SslError(format!("{}", e)))?; Ok(connector) } fn pkcs12_from_pem(pem: &[u8], password: &str) -> Result<Vec<u8>> { use openssl::{pkcs12::Pkcs12, pkey::PKey, x509::X509}; let x509 = X509::from_pem(pem)?; let pkey = PKey::private_key_from_pem(pem)?; let p12 = Pkcs12::builder().build(password, "kubeconfig", &pkey, &x509)?; let der = p12.to_der()?; Ok(der) } } #[cfg(feature = "rustls-tls")] pub mod rustls_tls { use std::sync::Arc; use rustls::{self, Certificate, ClientConfig, ServerCertVerified, ServerCertVerifier}; use webpki::DNSNameRef; use crate::{Error, Result}; pub fn rustls_client_config( identity_pem: Option<&Vec<u8>>, root_cert: Option<&Vec<Vec<u8>>>, accept_invalid: bool, ) -> Result<ClientConfig> { use std::io::Cursor; let mut client_config = ClientConfig::new(); if let Some(buf) = identity_pem { let (key, certs) = { let mut pem = Cursor::new(buf); let certs = rustls_pemfile::certs(&mut pem) .and_then(|certs| { if certs.is_empty() { Err(std::io::Error::new( std::io::ErrorKind::NotFound, "No X.509 Certificates Found", )) } else { Ok(certs.into_iter().map(rustls::Certificate).collect::<Vec<_>>()) } }) .map_err(|_| Error::SslError("No valid certificate was found".into()))?; pem.set_position(0); let mut sk = rustls_pemfile::pkcs8_private_keys(&mut pem) .and_then(|keys| { if keys.is_empty() { Err(std::io::Error::new( std::io::ErrorKind::NotFound, "No PKCS8 Key Found", )) } else { Ok(keys.into_iter().map(rustls::PrivateKey).collect::<Vec<_>>()) } }) .or_else(|_| { pem.set_position(0); rustls_pemfile::rsa_private_keys(&mut pem).and_then(|keys| { if keys.is_empty() { Err(std::io::Error::new( std::io::ErrorKind::NotFound, "No RSA Key Found", )) } else { Ok(keys.into_iter().map(rustls::PrivateKey).collect::<Vec<_>>()) } }) }) .map_err(|_| Error::SslError("No valid private key was found".into()))?; if let (Some(sk), false) = (sk.pop(), certs.is_empty()) { (sk, certs) } else { return Err(Error::SslError("private key or certificate not found".into())); } }; client_config .set_single_client_cert(certs, key) .map_err(|e| Error::SslError(format!("{}", e)))?; } if let Some(ders) = root_cert { for der in ders { client_config .root_store .add(&Certificate(der.to_owned())) .map_err(|e| Error::SslError(format!("{}", e)))?; } } if accept_invalid { client_config .dangerous() .set_certificate_verifier(Arc::new(NoCertificateVerification {})); } Ok(client_config) } struct NoCertificateVerification {} impl ServerCertVerifier for NoCertificateVerification { fn verify_server_cert( &self, _roots: &rustls::RootCertStore, _presented_certs: &[rustls::Certificate], _dns_name: DNSNameRef<'_>, _ocsp: &[u8], ) -> Result<ServerCertVerified, rustls::TLSError> { Ok(ServerCertVerified::assertion()) } } }
#[cfg(feature = "native-tls")] pub mod native_tls { use tokio_native_tls::native_tls::{Certificate, Identity, TlsConnector}; use crate::{Error, Result}; const IDENTITY_PASSWORD: &str = " "; pub fn native_tls_connector( identity_pem: Option<&Vec<u8>>, root_cert: Option<&Vec<Vec<u8>>>, accept_invalid: bool, ) -> Result<TlsConnector> { let mut builder = TlsConnector::builder(); if let Some(pem) = identity_pem { let identity = pkcs12_from_pem(pem, IDENTITY_PASSWORD)?; builder.identity( Identity::from_pkcs12(&identity, IDENTITY_PASSWORD) .map_err(|e| Error::SslError(format!("{}", e)))?, ); } if let Some(ders) = root_cert { for der in ders { builder.add_root_certificate( Certificate::from_der(der).map_err(|e| Error::SslError(format!("{}", e)))?, ); } } if accept_invalid { builder.danger_accept_invalid_certs(true); } let connector = builder.build().map_err(|e| Error::SslError(format!("{}", e)))?; Ok(connector) } fn pkcs12_from_pem(pem: &[u8], password: &str) -> Result<Vec<u8>> { use openssl::{pkcs12::Pkcs12, pkey::PKey, x509::X509}; let x509 = X509::from_pem(pem)?; let pkey = PKey::private_key_from_pem(pem)?; let p12 = Pkcs12::builder().build(password, "kubeconfig", &pkey, &x509)?; let der = p12.to_der()?; Ok(der) } } #[cfg(feature = "rustls-tls")] pub mod rustls_tls { use std::sync::Arc; use rustls::{self, Certificate, ClientConfig, ServerCertVerified, ServerCertVerifier}; use webpki::DNSNameRef; use crate::{Error, Result}; pub fn rustls_client_config( identity_pem: Option<&Vec<u8>>, root_cert: Option<&Vec<Vec<u8>>>, accept_invalid: bool, ) -> Result<ClientConfig> { use std::io::Cursor; let mut client_config = ClientConfig::new(); if let Some(buf) = identity_pem { let (key, certs) = { let mut pem = Cursor::new(buf); let certs = rustls_pemfile::certs(&mut pem) .and_then(|certs| { if certs.is_empty() { Err(std::io::Error::new( std::io::ErrorKind::NotFound, "No X.509 Certificates Found", )) } else { Ok(certs.into_iter().map(rustls::Certificate).collect::<Vec<_>>()) } }) .map_err(|_| Error::SslError("No valid certificate was found".into()))?; pem.set_position(0); let mut sk = rustls_pemfile::pkcs8_private_keys(&mut pem) .and_then(|keys| { if keys.is_empty() { Err(std::io::Error::new( std::io::ErrorKind::NotFound, "No PKCS8 Key Found", )) } else { Ok(keys.into_iter().map(rustls::PrivateKey).collect::<Vec<_>>()) } }) .or_else(|_| { pem.set_position(0); rustls_pemfile::rsa_private_keys(&mut pem).and_then(|keys| { if keys.is_empty() { Err(std::io::Error::new( std::io::ErrorKind::NotFound, "No RSA Key Found", )) } else { Ok(keys.into_iter().map(rustls::PrivateKey).collect::<Vec<_>>()) } }) }) .map_err(|_| Error::SslError("No valid private key was found".into()))?; if let (Some(sk), false) = (sk.pop(), certs.is_empty()) { (sk, certs) } else { return Err(Error::SslError("private key or certificate not found".into())); } }; client_config .set_single_client_cert(certs, key) .map_err(|e| Error::SslError(format!("{}", e)))?; } if let Some(ders) = root_cert { for der in ders { client_config .root_store .add(&Certificate(der.to_owned())) .map_err(|e| Error::SslError(format!("{}", e)))?; } } if accept_invalid { client_config .dangerous() .set_certificate_verifier(Arc::new(NoCertificateVerification {})); } Ok(client_config) } struct NoCertificateVerification {} impl ServerCertVerifier for NoCertificateVerification {
} }
fn verify_server_cert( &self, _roots: &rustls::RootCertStore, _presented_certs: &[rustls::Certificate], _dns_name: DNSNameRef<'_>, _ocsp: &[u8], ) -> Result<ServerCertVerified, rustls::TLSError> { Ok(ServerCertVerified::assertion()) }
function_block-full_function
[ { "content": "/// Returns certification from specified path in cluster.\n\npub fn load_cert() -> Result<Vec<Vec<u8>>> {\n\n Ok(utils::certs(&utils::read_file(SERVICE_CERTFILE)?))\n\n}\n\n\n", "file_path": "kube/src/config/incluster_config.rs", "rank": 0, "score": 250389.20424861487 }, { "...
Rust
rust/agents/kathy/src/kathy.rs
aaronwinter/optics-monorepo
82b74a232b87064456bda20ba5f1171bd2b6fe70
use std::time::Duration; use async_trait::async_trait; use color_eyre::eyre::bail; use ethers::core::types::H256; use optics_core::traits::Replica; use tokio::{task::JoinHandle, time::sleep}; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use color_eyre::Result; use optics_base::{ agent::{AgentCore, OpticsAgent}, decl_agent, }; use optics_core::{traits::Home, Message}; use tracing::instrument::Instrumented; use tracing::{info, Instrument}; use crate::settings::KathySettings as Settings; decl_agent!(Kathy { duration: u64, generator: ChatGenerator, }); impl Kathy { pub fn new(duration: u64, generator: ChatGenerator, core: AgentCore) -> Self { Self { duration, generator, core, } } } #[async_trait] impl OpticsAgent for Kathy { const AGENT_NAME: &'static str = "kathy"; type Settings = Settings; async fn from_settings(settings: Settings) -> Result<Self> { Ok(Self::new( settings.interval.parse().expect("invalid u64"), settings.chat.into(), settings.base.try_into_core(Self::AGENT_NAME).await?, )) } #[tracing::instrument] fn run(&self, name: &str) -> Instrumented<JoinHandle<Result<()>>> { let replica_opt = self.replica_by_name(name); let name = name.to_owned(); let home = self.home(); let mut generator = self.generator.clone(); let duration = Duration::from_secs(self.duration); tokio::spawn(async move { if replica_opt.is_none() { bail!("No replica named {}", name); } let replica = replica_opt.unwrap(); let destination = replica.local_domain(); loop { sleep(duration).await; let msg = generator.gen_chat(); let recipient = generator.gen_recipient(); match msg { Some(body) => { let message = Message { destination, recipient, body, }; info!( target: "outgoing_messages", "Enqueuing message of length {} to {}::{}", length = message.body.len(), destination = message.destination, recipient = message.recipient ); home.dispatch(&message).await?; } _ => { info!("Reached the end of the static message queue. Shutting down."); return Ok(()); } } } }) .in_current_span() } } #[derive(Debug, Clone)] pub enum ChatGenerator { Static { recipient: H256, message: String, }, OrderedList { messages: Vec<String>, counter: usize, }, Random { length: usize, }, Default, } impl Default for ChatGenerator { fn default() -> Self { Self::Default } } impl ChatGenerator { fn rand_string(length: usize) -> String { thread_rng() .sample_iter(&Alphanumeric) .take(length) .map(char::from) .collect() } pub fn gen_recipient(&mut self) -> H256 { match self { ChatGenerator::Default => Default::default(), ChatGenerator::Static { recipient, message: _, } => *recipient, ChatGenerator::OrderedList { messages: _, counter: _, } => Default::default(), ChatGenerator::Random { length: _ } => H256::random(), } } pub fn gen_chat(&mut self) -> Option<Vec<u8>> { match self { ChatGenerator::Default => Some(Default::default()), ChatGenerator::Static { recipient: _, message, } => Some(message.as_bytes().to_vec()), ChatGenerator::OrderedList { messages, counter } => { if *counter >= messages.len() { return None; } let msg = messages[*counter].clone().into(); *counter += 1; Some(msg) } ChatGenerator::Random { length } => Some(Self::rand_string(*length).into()), } } }
use std::time::Duration; use async_trait::async_trait; use color_eyre::eyre::bail; use ethers::core::types::H256; use optics_core::traits::Replica; use tokio::{task::JoinHandle, time::sleep}; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use color_eyre::Result; use optics_base::{ agent::{AgentCore, OpticsAgent}, decl_agent, }; use optics_core::{traits::Home, Message}; use tracing::instrument::Instrumented; use tracing::{info, Instrument}; use crate::settings::KathySettings as Settings; decl_agent!(Kathy { duration: u64, generator: ChatGenerator, }); impl Kathy { pub fn new(duration: u64, generator: ChatGenerator, core: AgentCore) -> Self { Self { duration, generator, core, } } } #[async_trait] impl OpticsAgent for Kathy { const AGENT_NAME: &'static str = "kathy"; type Settings = Settings; async fn from_settings(settings: Settings) -> Result<Self> { Ok(Self::new(
#[tracing::instrument] fn run(&self, name: &str) -> Instrumented<JoinHandle<Result<()>>> { let replica_opt = self.replica_by_name(name); let name = name.to_owned(); let home = self.home(); let mut generator = self.generator.clone(); let duration = Duration::from_secs(self.duration); tokio::spawn(async move { if replica_opt.is_none() { bail!("No replica named {}", name); } let replica = replica_opt.unwrap(); let destination = replica.local_domain(); loop { sleep(duration).await; let msg = generator.gen_chat(); let recipient = generator.gen_recipient(); match msg { Some(body) => { let message = Message { destination, recipient, body, }; info!( target: "outgoing_messages", "Enqueuing message of length {} to {}::{}", length = message.body.len(), destination = message.destination, recipient = message.recipient ); home.dispatch(&message).await?; } _ => { info!("Reached the end of the static message queue. Shutting down."); return Ok(()); } } } }) .in_current_span() } } #[derive(Debug, Clone)] pub enum ChatGenerator { Static { recipient: H256, message: String, }, OrderedList { messages: Vec<String>, counter: usize, }, Random { length: usize, }, Default, } impl Default for ChatGenerator { fn default() -> Self { Self::Default } } impl ChatGenerator { fn rand_string(length: usize) -> String { thread_rng() .sample_iter(&Alphanumeric) .take(length) .map(char::from) .collect() } pub fn gen_recipient(&mut self) -> H256 { match self { ChatGenerator::Default => Default::default(), ChatGenerator::Static { recipient, message: _, } => *recipient, ChatGenerator::OrderedList { messages: _, counter: _, } => Default::default(), ChatGenerator::Random { length: _ } => H256::random(), } } pub fn gen_chat(&mut self) -> Option<Vec<u8>> { match self { ChatGenerator::Default => Some(Default::default()), ChatGenerator::Static { recipient: _, message, } => Some(message.as_bytes().to_vec()), ChatGenerator::OrderedList { messages, counter } => { if *counter >= messages.len() { return None; } let msg = messages[*counter].clone().into(); *counter += 1; Some(msg) } ChatGenerator::Random { length } => Some(Self::rand_string(*length).into()), } } }
settings.interval.parse().expect("invalid u64"), settings.chat.into(), settings.base.try_into_core(Self::AGENT_NAME).await?, )) }
function_block-function_prefix_line
[ { "content": "/// Strips the '0x' prefix off of hex string so it can be deserialized.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `s` - The hex str\n\npub fn strip_0x_prefix(s: &str) -> &str {\n\n if s.len() < 2 || &s[..2] != \"0x\" {\n\n s\n\n } else {\n\n &s[2..]\n\n }\n\n}\n\n\n", "f...
Rust
pallets/template/src/lib.rs
Vietdung113/substrateTemplateNode
a5a9edd4280149de5ad24b4fd5a2b572d647a278
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[cfg(test)] mod mock; #[cfg(test)] mod tests; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; #[frame_support::pallet] pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub trait Config: frame_system::Config { type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet<T>(_); #[pallet::storage] #[pallet::getter(fn current_state)] pub type AccountToBalance<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, u32, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { AccountCreated(T::AccountId), AccountExists(T::AccountId), TransferredCash(T::AccountId, u32, T::AccountId, u32, u32), } #[pallet::error] pub enum Error<T> { NoneValue, StorageOverflow, } #[pallet::call] impl<T: Config> Pallet<T> { #[pallet::weight(10_000 + T::DbWeight::get().writes(1))] pub fn register(origin: OriginFor<T>) -> DispatchResult { let who = ensure_signed(origin)?; if <AccountToBalance<T>>::try_get(&who).is_err() { <AccountToBalance<T>>::insert(&who, 10); Self::deposit_event(Event::AccountCreated(who)); } else { Self::deposit_event(Event::AccountExists(who)); } Ok(()) } #[pallet::weight(10_000 + T::DbWeight::get().writes(1))] pub fn transfer_money(origin: OriginFor<T>, to: T::AccountId, amount: u32) -> DispatchResult { let who = ensure_signed(origin)?; let whoBalance: Result<u32, ()> = <AccountToBalance<T>>::try_get(&who); assert!(whoBalance.is_ok(), "Sender does not have account"); assert!(whoBalance.ok().unwrap() >= amount, "Sender does not have enough money"); let toBalance: Result<u32, ()> = <AccountToBalance<T>>::try_get(&who); assert!(toBalance.is_ok(), "Receiver does not have account"); <AccountToBalance<T>>::try_mutate(&who, |maybe_value| { *maybe_value = *maybe_value - amount; let x: Result<u32, ()> = Ok(*maybe_value); x }); <AccountToBalance<T>>::try_mutate(&to, |maybe_value| { *maybe_value = *maybe_value + amount; let x: Result<u32, ()> = Ok(*maybe_value); x }); let finalWhoBalance = <AccountToBalance<T>>::try_get(&who).ok().unwrap(); let finalToBalance = <AccountToBalance<T>>::try_get(&to).ok().unwrap(); Self::deposit_event(Event::TransferredCash( who, finalWhoBalance, to, finalToBalance, amount )); Ok(()) } } }
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[cfg(test)] mod mock; #[cfg(test)] mod tests; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; #[frame_support::pallet] pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub trait Config: frame_system::Config { type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet<T>(_); #[pallet::storage] #[pallet::getter(fn current_state)] pub type AccountToBalance<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, u32, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { AccountCreated(T::AccountId), AccountExists(T::AccountId), TransferredCash(T::AccountId, u32, T::AccountId, u32, u32), } #[pallet::error] pub enum Error<T> { NoneValue, StorageOverflow, } #[pallet::call] impl<T: Config> Pallet<T> { #[pallet::weight(10_000 + T::DbWeight::get().writes(1))] pub fn register(origin: OriginFor<T>) -> DispatchResult { let who = ensure_signed(origin)?;
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))] pub fn transfer_money(origin: OriginFor<T>, to: T::AccountId, amount: u32) -> DispatchResult { let who = ensure_signed(origin)?; let whoBalance: Result<u32, ()> = <AccountToBalance<T>>::try_get(&who); assert!(whoBalance.is_ok(), "Sender does not have account"); assert!(whoBalance.ok().unwrap() >= amount, "Sender does not have enough money"); let toBalance: Result<u32, ()> = <AccountToBalance<T>>::try_get(&who); assert!(toBalance.is_ok(), "Receiver does not have account"); <AccountToBalance<T>>::try_mutate(&who, |maybe_value| { *maybe_value = *maybe_value - amount; let x: Result<u32, ()> = Ok(*maybe_value); x }); <AccountToBalance<T>>::try_mutate(&to, |maybe_value| { *maybe_value = *maybe_value + amount; let x: Result<u32, ()> = Ok(*maybe_value); x }); let finalWhoBalance = <AccountToBalance<T>>::try_get(&who).ok().unwrap(); let finalToBalance = <AccountToBalance<T>>::try_get(&to).ok().unwrap(); Self::deposit_event(Event::TransferredCash( who, finalWhoBalance, to, finalToBalance, amount )); Ok(()) } } }
if <AccountToBalance<T>>::try_get(&who).is_err() { <AccountToBalance<T>>::insert(&who, 10); Self::deposit_event(Event::AccountCreated(who)); } else { Self::deposit_event(Event::AccountExists(who)); } Ok(()) }
function_block-function_prefix_line
[ { "content": "// Build genesis storage according to the mock runtime.\n\npub fn new_test_ext() -> sp_io::TestExternalities {\n\n\tsystem::GenesisConfig::default().build_storage::<Test>().unwrap().into()\n\n}\n", "file_path": "pallets/template/src/mock.rs", "rank": 1, "score": 118374.5519331848 }, ...
Rust
src/grouped_rects_to_place.rs
chinedufn/rectangle-pack
648774b13ff9af85019eddeb1856e1607191fb8c
use crate::RectToInsert; #[cfg(not(std))] use alloc::collections::BTreeMap as KeyValMap; #[cfg(std)] use std::collections::HashMap as KeyValMap; use alloc::{ collections::{btree_map::Entry, BTreeMap}, vec::Vec, }; use core::{fmt::Debug, hash::Hash}; #[derive(Debug)] pub struct GroupedRectsToPlace<RectToPlaceId, GroupId = ()> where RectToPlaceId: Debug + Hash + Eq + Ord + PartialOrd, GroupId: Debug + Hash + Eq + Ord + PartialOrd, { pub(crate) inbound_id_to_group_ids: KeyValMap<RectToPlaceId, Vec<Group<GroupId, RectToPlaceId>>>, pub(crate) group_id_to_inbound_ids: BTreeMap<Group<GroupId, RectToPlaceId>, Vec<RectToPlaceId>>, pub(crate) rects: KeyValMap<RectToPlaceId, RectToInsert>, } #[derive(Debug, Hash, Eq, PartialEq, Ord, PartialOrd)] pub enum Group<GroupId, RectToPlaceId> where GroupId: Debug + Hash + Eq + PartialEq + Ord + PartialOrd, RectToPlaceId: Debug + Ord + PartialOrd, { Ungrouped(RectToPlaceId), Grouped(GroupId), } impl<RectToPlaceId, GroupId> GroupedRectsToPlace<RectToPlaceId, GroupId> where RectToPlaceId: Debug + Hash + Clone + Eq + Ord + PartialOrd, GroupId: Debug + Hash + Clone + Eq + Ord + PartialOrd, { pub fn new() -> Self { Self { inbound_id_to_group_ids: Default::default(), group_id_to_inbound_ids: Default::default(), rects: Default::default(), } } pub fn push_rect( &mut self, inbound_id: RectToPlaceId, group_ids: Option<Vec<GroupId>>, inbound: RectToInsert, ) { self.rects.insert(inbound_id.clone(), inbound); match group_ids { None => { self.group_id_to_inbound_ids.insert( Group::Ungrouped(inbound_id.clone()), vec![inbound_id.clone()], ); self.inbound_id_to_group_ids .insert(inbound_id.clone(), vec![Group::Ungrouped(inbound_id)]); } Some(group_ids) => { self.inbound_id_to_group_ids.insert( inbound_id.clone(), group_ids .clone() .into_iter() .map(|gid| Group::Grouped(gid)) .collect(), ); for group_id in group_ids { match self.group_id_to_inbound_ids.entry(Group::Grouped(group_id)) { Entry::Occupied(mut o) => { o.get_mut().push(inbound_id.clone()); } Entry::Vacant(v) => { v.insert(vec![inbound_id.clone()]); } }; } } }; } } #[cfg(test)] mod tests { use super::*; use crate::RectToInsert; #[test] fn ungrouped_rectangles_use_their_inbound_id_as_their_group_id() { let mut lrg: GroupedRectsToPlace<_, ()> = GroupedRectsToPlace::new(); lrg.push_rect(RectToPlaceId::One, None, RectToInsert::new(10, 10, 1)); assert_eq!( lrg.group_id_to_inbound_ids[&Group::Ungrouped(RectToPlaceId::One)], vec![RectToPlaceId::One] ); } #[test] fn group_id_to_inbound_ids() { let mut lrg = GroupedRectsToPlace::new(); lrg.push_rect( RectToPlaceId::One, Some(vec![0]), RectToInsert::new(10, 10, 1), ); lrg.push_rect( RectToPlaceId::Two, Some(vec![0]), RectToInsert::new(10, 10, 1), ); assert_eq!( lrg.group_id_to_inbound_ids.get(&Group::Grouped(0)).unwrap(), &vec![RectToPlaceId::One, RectToPlaceId::Two] ); } #[test] fn inbound_id_to_group_ids() { let mut lrg = GroupedRectsToPlace::new(); lrg.push_rect( RectToPlaceId::One, Some(vec![0, 1]), RectToInsert::new(10, 10, 1), ); lrg.push_rect(RectToPlaceId::Two, None, RectToInsert::new(10, 10, 1)); assert_eq!( lrg.inbound_id_to_group_ids[&RectToPlaceId::One], vec![Group::Grouped(0), Group::Grouped(1)] ); assert_eq!( lrg.inbound_id_to_group_ids[&RectToPlaceId::Two], vec![Group::Ungrouped(RectToPlaceId::Two)] ); } #[test] fn store_the_inbound_rectangle() { let mut lrg = GroupedRectsToPlace::new(); lrg.push_rect( RectToPlaceId::One, Some(vec![0, 1]), RectToInsert::new(10, 10, 1), ); assert_eq!(lrg.rects[&RectToPlaceId::One], RectToInsert::new(10, 10, 1)); } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] enum RectToPlaceId { One, Two, } }
use crate::RectToInsert; #[cfg(not(std))] use alloc::collections::BTreeMap as KeyValMap; #[cfg(std)] use std::collections::HashMap as KeyValMap; use alloc::{ collections::{btree_map::Entry, BTreeMap}, vec::Vec, }; use core::{fmt::Debug, hash::Hash}; #[derive(Debug)] pub struct GroupedRectsToPlace<RectToPlaceId, GroupId = ()> where RectToPlaceId: Debug + Hash + Eq + Ord + PartialOrd, GroupId: Debug + Hash + Eq + Ord + PartialOrd, { pub(crate) inbound_id_to_group_ids: KeyValMap<RectToPlaceId, Vec<Group<GroupId, RectToPlaceId>>>, pub(crate) group_id_to_inbound_ids: BTreeMap<Group<GroupId, RectToPlaceId>, Vec<RectToPlaceId>>, pub(crate) rects: KeyValMap<RectToPlaceId, RectToInsert>, } #[derive(Debug, Hash, Eq, PartialEq, Ord, PartialOrd)] pub enum Group<GroupId, RectToPlaceId> where GroupId: Debug + Hash + Eq + PartialEq + Ord + PartialOrd, RectToPlaceId: Debug + Ord + PartialOrd, { Ungrouped(RectToPlaceId), Grouped(GroupId), } impl<RectToPlaceId, GroupId> GroupedRectsToPlace<RectToPlaceId, GroupId> where RectToPlaceId: Debug + Hash + Clone + Eq + Ord + PartialOrd, GroupId: Debug + Hash + Clone + Eq + Ord + PartialOrd, { pub fn new() -> Self { Self { inbound_id_to_group_ids: Default::default(), group_id_to_inbound_ids: Default::default(), rects: Default::default(), } } pub fn push_rect( &mut self, inbound_id: RectToPlaceId, group_ids: Option<Vec<GroupId>>, inbound: RectToInsert, ) { self.rects.insert(inbound_id.clone(), inbound); match group_ids { None => { self.group_id_to_inbound_ids.insert( Group::Ungrouped(inbound_id.clone()), vec![inbound_id.clone()], ); self.inbound_id_to_group_ids .insert(inbound_id.clone(), vec![Group::Ungrouped(inbound_id)]); } Some(group_ids) => { self.inbound_id_to_group_ids.insert( inbound_id.clone(), group_ids .clone() .into_iter() .map(|gid| Group::Grouped(gid)) .collect(), ); for group_id in group_ids { match self.group_id_to_inbound_ids.entry(Group::Grouped(group_id)) { Entry::Occupied(mut o) => { o.get_mut().push(inbound_id.clone()); } Entry::Vacant(v) => { v.insert(vec![inbound_id.clone()]); } }; } } }; } } #[cfg(test)] mod tests { use super::*; use crate::RectToInsert; #[test] fn ungrouped_rectangles_use_their_inbound_id_as_their_group_id() { let mut lrg: GroupedRectsToPlace<_, ()> = GroupedRectsToPlace::new(); lrg.push_rect(RectToPlaceId::One, None, RectToInsert::new(10, 10, 1)); assert_eq!( lrg.group_id_to_inbound_ids[&Group::Ungrouped(RectToPlaceId::One)], vec![RectToPlaceId::One] ); } #[test] fn group_id_to_inbound_ids() { let mut lrg = GroupedRectsToPlace::new(); lrg.push_rect( RectToPlaceId::One, Some(vec![0]), RectToInsert::new(10, 10, 1), ); lrg.push_rect( RectToPlaceId::Two, Some(vec![0]), RectToInsert::new(10, 10, 1), ); assert_eq!( lrg.group_id_to_inbound_ids.get(&Group::Grouped(0)).unwrap(), &vec![RectToPlaceId::One, RectToPlaceId::Two] ); } #[test] fn inbound_id_to_group_ids() { let mut lrg = GroupedRectsToPlace::new(); lrg.push_rect( RectToPlaceId::One, Some(vec![0, 1]), RectToInsert::new(10, 10, 1), ); lrg.push_rect(RectToPlaceId::Two, None, RectToInsert::new(10, 10, 1)); assert_eq!( lrg.inbound_id_to_group_ids[&RectToPlaceId::One], vec![Group::Grouped(0), Group::Grouped(1)] ); assert_eq!( lrg.inbound_id_to_group_ids[&RectToPlaceId::Two], vec![Group::Ungrouped(RectToPlaceId::Two)] ); } #[test]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] enum RectToPlaceId { One, Two, } }
fn store_the_inbound_rectangle() { let mut lrg = GroupedRectsToPlace::new(); lrg.push_rect( RectToPlaceId::One, Some(vec![0, 1]), RectToInsert::new(10, 10, 1), ); assert_eq!(lrg.rects[&RectToPlaceId::One], RectToInsert::new(10, 10, 1)); }
function_block-full_function
[ { "content": "/// Determine how to fit a set of incoming rectangles (2d or 3d) into a set of target bins.\n\n///\n\n/// ## Example\n\n///\n\n/// ```\n\n/// //! A basic example of packing rectangles into target bins\n\n///\n\n/// use rectangle_pack::{\n\n/// GroupedRectsToPlace,\n\n/// RectToInsert,\n\n/...
Rust
src/controllers/time.rs
gopalsgs/rustRocket
ef8e8e45ae3d0a3131b0024b66ee2b8322d56235
use std::f64; use rand::Rng; use super::Actions; use game_state::GameState; use geometry::{Advance, Position, Point}; use models::{Bullet, Enemy, Particle, Vector}; use util; const BULLETS_PER_SECOND: f64 = 100.0; const BULLET_RATE: f64 = 1.0 / BULLETS_PER_SECOND; const ENEMY_SPAWNS_PER_SECOND: f64 = 1.0; const ENEMY_SPAWN_RATE: f64 = 1.0 / ENEMY_SPAWNS_PER_SECOND; const TRAIL_PARTICLES_PER_SECOND: f64 = 20.0; const TRAIL_PARTICLE_RATE: f64 = 1.0 / TRAIL_PARTICLES_PER_SECOND; const ADVANCE_SPEED: f64 = 200.0; const BULLET_SPEED: f64 = 500.0; const ENEMY_SPEED: f64 = 100.0; const ROTATE_SPEED: f64 = 2.0 * f64::consts::PI; const PLAYER_GRACE_AREA: f64 = 200.0; pub struct TimeController<T: Rng> { rng: T, current_time: f64, last_tail_particle: f64, last_shoot: f64, last_spawned_enemy: f64 } impl<T: Rng> TimeController<T> { pub fn new(rng: T) -> TimeController<T> { TimeController { rng, current_time: 0.0, last_tail_particle: 0.0, last_shoot: 0.0, last_spawned_enemy: 0.0 } } pub fn update_seconds(&mut self, dt: f64, actions: &Actions, state: &mut GameState) { self.current_time += dt; if actions.rotate_left { *state.world.player.direction_mut() += -ROTATE_SPEED * dt; } if actions.rotate_right { *state.world.player.direction_mut() += ROTATE_SPEED * dt; }; let speed = if actions.boost { 2.0 * ADVANCE_SPEED } else { ADVANCE_SPEED }; state.world.player.advance_wrapping(dt * speed, state.world.size); for particle in &mut state.world.particles { particle.update(dt); } util::fast_retain(&mut state.world.particles, |p| p.ttl > 0.0); if self.current_time - self.last_tail_particle > TRAIL_PARTICLE_RATE { self.last_tail_particle = self.current_time; state.world.particles.push(Particle::new(state.world.player.vector.clone().invert(), 0.5)); } if actions.shoot && self.current_time - self.last_shoot > BULLET_RATE { self.last_shoot = self.current_time; state.world.bullets.push(Bullet::new(Vector::new(state.world.player.front(), state.world.player.direction()))); } for bullet in &mut state.world.bullets { bullet.update(dt * BULLET_SPEED); } { let size = &state.world.size; util::fast_retain(&mut state.world.bullets, |b| size.contains(b.position())); } if self.current_time - self.last_spawned_enemy > ENEMY_SPAWN_RATE { self.last_spawned_enemy = self.current_time; let player_pos: &Vector = &state.world.player.vector; let mut enemy_pos; loop { enemy_pos = Vector::random(&mut self.rng, state.world.size); if enemy_pos.position != player_pos.position { break; } } if enemy_pos.position.intersect_circle(&player_pos.position, PLAYER_GRACE_AREA) { let length: f64 = enemy_pos.position.squared_distance_to(&player_pos.position).sqrt(); let dp: Point = enemy_pos.position - player_pos.position; enemy_pos.position = player_pos.position + dp / length * PLAYER_GRACE_AREA; } let new_enemy = Enemy::new(enemy_pos); state.world.enemies.push(new_enemy); } for enemy in &mut state.world.enemies { enemy.update(dt * ENEMY_SPEED, state.world.player.position()); } } }
use std::f64; use rand::Rng; use super::Actions; use game_state::GameState; use geometry::{Advance, Position, Point}; use models::{Bullet, Enemy, Particle, Vector}; use util; const BULLETS_PER_SECOND: f64 = 100.0; const BULLET_RATE: f64 = 1.0 / BULLETS_PER_SECOND; const ENEMY_SPAWNS_PER_SECOND: f64 = 1.0; const ENEMY_SPAWN_RATE: f64 = 1.0 / ENEMY_SPAWNS_PER_SECOND; const TRAIL_PARTICLES_PER_SECOND: f64 = 20.0; const TRAIL_PARTICLE_RATE: f64 = 1.0 / TRAIL_PARTICLES_PER_SECOND; const ADVANCE_SPEED: f64 = 200.0; const BULLET_SPEED: f64 = 500.0; const ENEMY_SPEED: f64 = 100.0; const ROTATE_SPEED: f64 = 2.0 * f64::consts::PI; const PLAYER_GRACE_AREA: f64 = 200.0; pub struct TimeController<T: Rng> { rng: T, current_time: f64, last_tail_particle: f64, last_shoot: f64, last_spawned_enemy: f64 } impl<T: Rng> TimeController<T> {
pub fn update_seconds(&mut self, dt: f64, actions: &Actions, state: &mut GameState) { self.current_time += dt; if actions.rotate_left { *state.world.player.direction_mut() += -ROTATE_SPEED * dt; } if actions.rotate_right { *state.world.player.direction_mut() += ROTATE_SPEED * dt; }; let speed = if actions.boost { 2.0 * ADVANCE_SPEED } else { ADVANCE_SPEED }; state.world.player.advance_wrapping(dt * speed, state.world.size); for particle in &mut state.world.particles { particle.update(dt); } util::fast_retain(&mut state.world.particles, |p| p.ttl > 0.0); if self.current_time - self.last_tail_particle > TRAIL_PARTICLE_RATE { self.last_tail_particle = self.current_time; state.world.particles.push(Particle::new(state.world.player.vector.clone().invert(), 0.5)); } if actions.shoot && self.current_time - self.last_shoot > BULLET_RATE { self.last_shoot = self.current_time; state.world.bullets.push(Bullet::new(Vector::new(state.world.player.front(), state.world.player.direction()))); } for bullet in &mut state.world.bullets { bullet.update(dt * BULLET_SPEED); } { let size = &state.world.size; util::fast_retain(&mut state.world.bullets, |b| size.contains(b.position())); } if self.current_time - self.last_spawned_enemy > ENEMY_SPAWN_RATE { self.last_spawned_enemy = self.current_time; let player_pos: &Vector = &state.world.player.vector; let mut enemy_pos; loop { enemy_pos = Vector::random(&mut self.rng, state.world.size); if enemy_pos.position != player_pos.position { break; } } if enemy_pos.position.intersect_circle(&player_pos.position, PLAYER_GRACE_AREA) { let length: f64 = enemy_pos.position.squared_distance_to(&player_pos.position).sqrt(); let dp: Point = enemy_pos.position - player_pos.position; enemy_pos.position = player_pos.position + dp / length * PLAYER_GRACE_AREA; } let new_enemy = Enemy::new(enemy_pos); state.world.enemies.push(new_enemy); } for enemy in &mut state.world.enemies { enemy.update(dt * ENEMY_SPEED, state.world.player.position()); } } }
pub fn new(rng: T) -> TimeController<T> { TimeController { rng, current_time: 0.0, last_tail_particle: 0.0, last_shoot: 0.0, last_spawned_enemy: 0.0 } }
function_block-full_function
[ { "content": "/// Generates a new explosion of the given intensity at the given position.\n\n/// This works best with values between 5 and 25\n\npub fn make_explosion(particles: &mut Vec<Particle>, position: &Point, intensity: u8) {\n\n use itertools_num;\n\n for rotation in itertools_num::linspace(0.0, 2...
Rust
calyx/src/passes/compile_control.rs
yoonachang/futil
2ef8c89ac3e8c398f9db42c28ec8d495ee0a45e2
use crate::errors::Error; use crate::lang::{ ast, component::Component, context::Context, structure_builder::ASTBuilder, }; use crate::passes::visitor::{Action, Named, VisResult, Visitor}; use crate::{add_wires, guard, port, structure}; use ast::{Control, Enable, GuardExpr}; use std::collections::HashMap; use std::convert::TryInto; #[derive(Default)] pub struct CompileControl {} impl Named for CompileControl { fn name() -> &'static str { "compile-control" } fn description() -> &'static str { "Compile away all control language constructs into structure" } } impl Visitor for CompileControl { fn finish_if( &mut self, cif: &ast::If, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let if_group: ast::Id = st.namegen.gen_name("if").into(); let if_group_node = st.insert_group(&if_group, HashMap::new())?; let cond_group_node = st.get_node_by_name(&cif.cond)?; let cond = cif.port.get_edge(st)?; let (true_group, false_group) = match (&*cif.tbranch, &*cif.fbranch) { (Control::Enable { data: t }, Control::Enable { data: f }) => { Ok((&t.comp, &f.comp)) } _ => Err(Error::MalformedControl( "Both branches of an if must be an enable.".to_string(), )), }?; let true_group_node = st.get_node_by_name(true_group)?; let false_group_node = st.get_node_by_name(false_group)?; structure!( st, &ctx, let cond_computed = prim std_reg(1); let cond_stored = prim std_reg(1); let signal_const = constant(1, 1); let signal_off = constant(0, 1); let done_reg = prim std_reg(1); ); let cond_go = !guard!(st; cond_computed["out"]); let is_cond_computed = guard!(st; cond_group_node["go"]) & guard!(st; cond_group_node["done"]); let true_turn = guard!(st; cond_computed["out"]) & guard!(st; cond_stored["out"]); let true_go = !guard!(st; true_group_node["done"]) & true_turn.clone(); let false_turn = guard!(st; cond_computed["out"]) & !guard!(st; cond_stored["out"]); let false_go = !guard!(st; false_group_node["done"]) & false_turn.clone(); let done_guard = (true_turn & guard!(st; true_group_node["done"])) | (false_turn & guard!(st; false_group_node["done"])); let done_reg_high = guard!(st; done_reg["out"]); add_wires!( st, Some(if_group.clone()), cond_group_node["go"] = cond_go ? (signal_const.clone()); cond_computed["in"] = is_cond_computed ? (signal_const.clone()); cond_computed["write_en"] = is_cond_computed ? (signal_const.clone()); cond_stored["in"] = is_cond_computed ? (cond.clone()); cond_stored["write_en"] = is_cond_computed ? (cond); true_group_node["go"] = true_go ? (signal_const.clone()); false_group_node["go"] = false_go ? (signal_const.clone()); done_reg["in"] = done_guard ? (signal_const.clone()); done_reg["write_en"] = done_guard ? (signal_const.clone()); if_group_node["done"] = done_reg_high ? (signal_const.clone()); ); add_wires!( st, None, done_reg["in"] = done_reg_high ? (signal_off.clone()); done_reg["write_en"] = done_reg_high ? (signal_const.clone()); cond_computed["in"] = done_reg_high ? (signal_off.clone()); cond_computed["write_en"] = done_reg_high ? (signal_const.clone()); cond_stored["in"] = done_reg_high ? (signal_off); cond_stored["write_en"] = done_reg_high ? (signal_const); ); Ok(Action::Change(Control::enable(if_group))) } fn finish_while( &mut self, ctrl: &ast::While, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let while_group = st.namegen.gen_name("while").into(); let while_group_node = st.insert_group(&while_group, HashMap::new())?; let cond_group_node = st.get_node_by_name(&ctrl.cond)?; let cond = ctrl.port.get_edge(&*st)?; let body_group = match &*ctrl.body { Control::Enable { data } => Ok(&data.comp), _ => Err(Error::MalformedControl( "The body of a while must be an enable.".to_string(), )), }?; let body_group_node = st.get_node_by_name(body_group)?; structure!(st, &ctx, let cond_computed = prim std_reg(1); let cond_stored = prim std_reg(1); let done_reg = prim std_reg(1); let signal_on = constant(1, 1); let signal_off = constant(0, 1); ); let cond_go = !guard!(st; cond_computed["out"]); let is_cond_computed = guard!(st; cond_group_node["go"]) & guard!(st; cond_group_node["done"]); let body_go = guard!(st; cond_stored["out"]) & guard!(st; cond_computed["out"]) & !guard!(st; body_group_node["done"]); let cond_recompute = guard!(st; cond_stored["out"]) & guard!(st; cond_computed["out"]) & guard!(st; body_group_node["done"]); let is_cond_false = guard!(st; cond_computed["out"]) & !guard!(st; cond_stored["out"]); let done_reg_high = guard!(st; done_reg["out"]); add_wires!(st, Some(while_group.clone()), cond_group_node["go"] = cond_go ? (signal_on.clone()); cond_computed["in"] = is_cond_computed ? (signal_on.clone()); cond_computed["write_en"] = is_cond_computed ? (signal_on.clone()); cond_stored["in"] = is_cond_computed ? (cond); cond_stored["write_en"] = is_cond_computed ? (signal_on.clone()); body_group_node["go"] = body_go ? (signal_on.clone()); cond_computed["in"] = cond_recompute ? (signal_off.clone()); cond_computed["write_en"] = cond_recompute ? (signal_on.clone()); done_reg["in"] = is_cond_false ? (signal_on.clone()); done_reg["write_en"] = is_cond_false ? (signal_on.clone()); while_group_node["done"] = done_reg_high ? (signal_on.clone()); cond_computed["in"] = is_cond_false ? (signal_off.clone()); cond_computed["write_en"] = is_cond_false ? (signal_on.clone()); ); add_wires!(st, None, done_reg["in"] = done_reg_high ? (signal_off); done_reg["write_en"] = done_reg_high ? (signal_on); ); Ok(Action::Change(Control::enable(while_group))) } fn finish_seq( &mut self, s: &ast::Seq, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let seq_group: ast::Id = st.namegen.gen_name("seq").into(); let seq_group_node = st.insert_group(&seq_group, HashMap::new())?; let fsm_size = 32; structure!(st, &ctx, let fsm = prim std_reg(fsm_size); let signal_on = constant(1, 1); ); for (idx, con) in s.stmts.iter().enumerate() { match con { Control::Enable { data: Enable { comp: group_name }, } => { let my_idx: u64 = idx.try_into().unwrap(); /* group[go] = fsm.out == idx & !group[done] ? 1 */ let group = st.get_node_by_name(&group_name)?; structure!(st, &ctx, let fsm_cur_state = constant(my_idx, fsm_size); let fsm_nxt_state = constant(my_idx + 1, fsm_size); ); let group_go = (guard!(st; fsm["out"]) .eq(st.to_guard(fsm_cur_state.clone()))) & !guard!(st; group["done"]); let group_done = (guard!(st; fsm["out"]) .eq(st.to_guard(fsm_cur_state.clone()))) & guard!(st; group["done"]); add_wires!(st, Some(seq_group.clone()), group["go"] = group_go ? (signal_on.clone()); fsm["in"] = group_done ? (fsm_nxt_state.clone()); fsm["write_en"] = group_done ? (signal_on.clone()); ); } _ => { return Err(Error::MalformedControl( "Cannot compile non-group statement inside sequence" .to_string(), )) } } } let final_state_val: u64 = s.stmts.len().try_into().unwrap(); structure!(st, &ctx, let reset_val = constant(0, fsm_size); let fsm_final_state = constant(final_state_val, fsm_size); ); let seq_done = guard!(st; fsm["out"]).eq(st.to_guard(fsm_final_state)); add_wires!(st, Some(seq_group.clone()), seq_group_node["done"] = seq_done ? (signal_on.clone()); ); add_wires!(st, None, fsm["in"] = seq_done ? (reset_val); fsm["write_en"] = seq_done ? (signal_on); ); Ok(Action::Change(Control::enable(seq_group))) } fn finish_par( &mut self, s: &ast::Par, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let par_group: ast::Id = st.namegen.gen_name("par").into(); let par_group_idx = st.insert_group(&par_group, HashMap::new())?; let mut par_group_done: Vec<GuardExpr> = Vec::with_capacity(s.stmts.len()); let mut par_done_regs = Vec::with_capacity(s.stmts.len()); structure!(st, &ctx, let signal_on = constant(1, 1); let signal_off = constant(0, 1); let par_reset = prim std_reg(1); ); for con in s.stmts.iter() { match con { Control::Enable { data: Enable { comp: group_name }, } => { let group_idx = st.get_node_by_name(&group_name)?; structure!(st, &ctx, let par_done_reg = prim std_reg(1); ); let group_go = !(guard!(st; par_done_reg["out"]) | guard!(st; group_idx["done"])); let group_done = guard!(st; group_idx["done"]); add_wires!(st, Some(par_group.clone()), group_idx["go"] = group_go ? (signal_on.clone()); par_done_reg["in"] = group_done ? (signal_on.clone()); par_done_reg["write_en"] = group_done ? (signal_on.clone()); ); par_done_regs.push(par_done_reg); par_group_done.push(guard!(st; par_done_reg["out"])); } _ => { return Err(Error::MalformedControl( "Cannot compile non-group statement inside sequence" .to_string(), )) } } } let par_done = GuardExpr::and_vec(par_group_done); let par_reset_out = guard!(st; par_reset["out"]); add_wires!(st, Some(par_group.clone()), par_reset["in"] = par_done ? (signal_on.clone()); par_reset["write_en"] = par_done ? (signal_on.clone()); par_group_idx["done"] = par_reset_out ? (signal_on.clone()); ); add_wires!(st, None, par_reset["in"] = par_reset_out ? (signal_off.clone()); par_reset["write_en"] = par_reset_out ? (signal_on.clone()); ); for par_done_reg in par_done_regs { add_wires!(st, None, par_done_reg["in"] = par_reset_out ? (signal_off.clone()); par_done_reg["write_en"] = par_reset_out ? (signal_on.clone()); ); } Ok(Action::Change(Control::enable(par_group))) } }
use crate::errors::Error; use crate::lang::{ ast, component::Component, context::Context, structure_builder::ASTBuilder, }; use crate::passes::visitor::{Action, Named, VisResult, Visitor}; use crate::{add_wires, guard, port, structure}; use ast::{Control, Enable, GuardExpr}; use std::collections::HashMap; use std::convert::TryInto; #[derive(Default)] pub struct CompileControl {} impl Named for CompileControl { fn name() -> &'static str { "compile-control" } fn description() -> &'static str { "Compile away all control language constructs into structure" } } impl Visitor for CompileControl { fn finish_if( &mut self, cif: &ast::If, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let if_group: ast::Id = st.namegen.gen_name("if").into(); let if_group_node = st.insert_group(&if_group, HashMap::new())?; let cond_group_node = st.get_node_by_name(&cif.cond)?; let cond = cif.port.get_edge(st)?; let (true_group, false_group) = match (&*cif.tbranch, &*cif.fbranch) { (Control::Enable { data: t }, Control::Enable { data: f }) => { Ok((&t.comp, &f.comp)) } _ => Err(Error::MalformedControl( "Both branches of an if must be an enable.".to_string(), )), }?; let true_group_node = st.get_node_by_name(true_group)?; let false_group_node = st.get_node_by_name(false_group)?; structure!( st, &ctx, let cond_computed = prim std_reg(1); let cond_stored = prim std_reg(1); let signal_const = constant(1, 1); let signal_off = constant(0, 1); let done_reg = prim std_reg(1); ); let cond_go = !guard!(st; cond_computed["out"]); let is_cond_computed = guard!(st; cond_group_node["go"]) & guard!(st; cond_group_node["done"]); let true_turn = guard!(st; cond_computed["out"]) & guard!(st; cond_stored["out"]); let true_go = !guard!(st; true_group_node["done"]) & true_turn.clone(); let false_turn = guard!(st; cond_computed["out"]) & !guard!(st; cond_stored["out"]); let false_go = !guard!(st; false_group_node["done"]) & false_turn.clone(); let done_guard = (true_turn & guard!(st; true_group_node["done"])) | (false_turn & guard!(st; false_group_node["done"])); let done_reg_high = guard!(st; done_reg["out"]); add_wires!( st, Some(if_group.clone()), cond_group_node["go"] = cond_go ? (signal_const.clone()); cond_computed["in"] = is_cond_computed ? (signal_const.clone()); cond_computed["write_en"] = is_cond_computed ? (signal_const.clone()); cond_stored["in"] = is_cond_computed ? (cond.clone()); cond_stored["write_en"] = is_cond_computed ? (cond); true_group_node["go"] = true_go ? (signal_const.clone()); false_group_node["go"] = false_go ? (signal_const.clone()); done_reg["in"] = done_guard ? (signal_const.clone()); done_reg["write_en"] = done_guard ? (signal_const.clone()); if_group_node["done"] = done_reg_high ? (signal_const.clone()); ); add_wires!( st, None, done_reg["in"] = done_reg_high ? (signal_off.clone()); done_reg["write_en"] = done_reg_high ? (signal_const.clone()); cond_computed["in"] = done_reg_high ? (signal_off.clone()); cond_computed["write_en"] = done_reg_high ? (signal_const.clone()); cond_stored["in"] = done_reg_high ? (signal_off); cond_stored["write_en"] = done_reg_high ? (signal_const); ); Ok(Action::Change(Control::enable(if_group))) } fn finish_while( &mut self, ctrl: &ast::While, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let while_group = st.namegen.gen_name("while").into(); let while_group_node = st.insert_group(&while_group, HashMap::new())?; let cond_group_node = st.get_node_by_name(&ctrl.cond)?; let cond = ctrl.port.get_edge(&*st)?; let body_group = match &*ctrl.body { Control::Enable { data } => Ok(&data.comp), _ => Err(Error::MalformedControl( "The body of a while must be an enable.".to_string(), )), }?; let body_group_node = st.get_node_by_name(body_group)?; structure!(st, &ctx, let cond_computed = prim std_reg(1); let cond_stored = prim std_reg(1); let done_reg = prim std_reg(1); let signal_on = constant(1, 1); let signal_off = constant(0, 1); ); let cond_go = !guard!(st; cond_computed["out"]); let is_cond_computed = guard!(st; cond_group_node["go"]) & guard!(st; cond_group_node["done"]); let body_go = guard!(st; cond_stored["out"]) & guard!(st; cond_computed["out"]) & !guard!(st; body_group_node["done"]); let cond_recompute = guard!(st; cond_stored["out"]) & guard!(st; cond_computed["out"]) & guard!(st; body_group_node["done"]); let is_cond_false = guard!(st; cond_computed["out"]) & !guard!(st; cond_stored["out"]); let done_reg_high = guard!(st; done_reg["out"]); add_wires!(st, Some(while_group.clone()), cond_group_node["go"] = cond_go ? (signal_on.clone()); cond_computed["in"] = is_cond_computed ? (signal_on.clone()); cond_computed["write_en"] = is_cond_computed ? (signal_on.clone()); cond_stored["in"] = is_cond_computed ? (cond); cond_stored["write_en"] = is_cond_computed ? (signal_on.clone()); body_group_node["go"] = body_go ? (signal_on.clone()); cond_computed["in"] = cond_recompute ? (signal_off.clone()); cond_computed["write_en"] = cond_recompute ? (signal_on.clone()); done_reg["in"] = is_cond_false ? (signal_on.clone()); done_reg["write_en"] = is_cond_false ? (signal_on.clone()); while_group_node["done"] = done_reg_high ? (signal_on.clone()); cond_computed["in"] = is_cond_false ? (signal_off.clone()); cond_computed["write_en"] = is_cond_false ? (signal_on.clone()); ); add_wires!(st, None, done_reg["in"] = done_reg_high ? (signal_off); done_reg["write_en"] = done_reg_high ? (signal_on); ); Ok(Action::Change(Control::enable(while_group))) } fn finish_seq( &mut self, s: &ast::Seq, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let seq_group: ast::Id = st.namegen.gen_name("seq").into(); let seq_group_node = st.insert_group(&seq_group, HashMap::new())?; let fsm_size = 32; structure!(st, &ctx, let fsm = prim std_reg(fsm_size); let signal_on = constant(1, 1); ); for (idx, con) in s.stmts.iter().enumerate() { match con { Control::Enable { data: Enable { comp: group_name }, } => { let my_idx: u64 = idx.try_into().unwrap(); /* group[go] = fsm.out == idx & !group[done] ? 1 */ let group = st.get_node_by_name(&group_name)?; structure!(st, &ctx, let fsm_cur_state = constant(my_idx, fsm_size); let fsm_nxt_state = constant(my_idx + 1, fsm_size); ); let group_go = (guard!(st; fsm["out"]) .eq(st.to_guard(fsm_cur_state.clone()))) & !guard!(st; group["done"]); let group_done = (guard!(st; fsm["out"]) .eq(st.to_guard(fsm_cur_state.clone()))) & guard!(st; group["done"]); add_wires!(st, Some(seq_group.clone()), group["go"] = group_go ? (signal_on.clone()); fsm["in"] = group_done ? (fsm_nxt_state.clone()); fsm["write_en"] = group_done ? (signal_on.clone()); ); } _ => { return Err(Error::MalformedControl( "Cannot compile non-group statement inside sequence" .to_string(), )) } } } let final_state_val: u64 = s.stmts.len().try_into().unwrap(); structure!(st, &ctx, let reset_val = constant(0, fsm_size); let fsm_final_state = constant(final_state_val, fsm_size); ); let seq_done = guard!(st; fsm["out"]).eq(st.to_guard(fsm_final_state)); add_wires!(st, Some(seq_group.clone()), seq_group_node["done"] = seq_done ? (signal_on.clone()); ); add_wires!(st, None, fsm["in"] = seq_done ? (reset_val); fsm["write_en"] = seq_done ? (signal_on); ); Ok(Action::Change(Control::enable(seq_group))) }
}
fn finish_par( &mut self, s: &ast::Par, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let par_group: ast::Id = st.namegen.gen_name("par").into(); let par_group_idx = st.insert_group(&par_group, HashMap::new())?; let mut par_group_done: Vec<GuardExpr> = Vec::with_capacity(s.stmts.len()); let mut par_done_regs = Vec::with_capacity(s.stmts.len()); structure!(st, &ctx, let signal_on = constant(1, 1); let signal_off = constant(0, 1); let par_reset = prim std_reg(1); ); for con in s.stmts.iter() { match con { Control::Enable { data: Enable { comp: group_name }, } => { let group_idx = st.get_node_by_name(&group_name)?; structure!(st, &ctx, let par_done_reg = prim std_reg(1); ); let group_go = !(guard!(st; par_done_reg["out"]) | guard!(st; group_idx["done"])); let group_done = guard!(st; group_idx["done"]); add_wires!(st, Some(par_group.clone()), group_idx["go"] = group_go ? (signal_on.clone()); par_done_reg["in"] = group_done ? (signal_on.clone()); par_done_reg["write_en"] = group_done ? (signal_on.clone()); ); par_done_regs.push(par_done_reg); par_group_done.push(guard!(st; par_done_reg["out"])); } _ => { return Err(Error::MalformedControl( "Cannot compile non-group statement inside sequence" .to_string(), )) } } } let par_done = GuardExpr::and_vec(par_group_done); let par_reset_out = guard!(st; par_reset["out"]); add_wires!(st, Some(par_group.clone()), par_reset["in"] = par_done ? (signal_on.clone()); par_reset["write_en"] = par_done ? (signal_on.clone()); par_group_idx["done"] = par_reset_out ? (signal_on.clone()); ); add_wires!(st, None, par_reset["in"] = par_reset_out ? (signal_off.clone()); par_reset["write_en"] = par_reset_out ? (signal_on.clone()); ); for par_done_reg in par_done_regs { add_wires!(st, None, par_done_reg["in"] = par_reset_out ? (signal_off.clone()); par_done_reg["write_en"] = par_reset_out ? (signal_on.clone()); ); } Ok(Action::Change(Control::enable(par_group))) }
function_block-full_function
[ { "content": "/// Given a StructureGraph `st`, this function inlines assignments\n\n/// to `x[hole]` into any uses of `x[hole]` in a GuardExpr. This works\n\n/// in 2 passes over the edges. The first pass only considers assignments\n\n/// into `x[hole]` and builds up a mapping from `x[hole] -> (edge index, guar...
Rust
src/online/registry/github_registry.rs
SierraSoftworks/git-tool
961f0d7b2a9dfc58c2346571e09f4cf8b7851c01
use super::*; use crate::errors; use serde::Deserialize; pub struct GitHubRegistry; impl GitHubRegistry { async fn get(&self, core: &Core, url: &str) -> Result<reqwest::Response, errors::Error> { let uri: reqwest::Url = url.parse().map_err(|e| { errors::system_with_internal( &format!("Unable to parse GitHub API URL '{}'.", url), "Please report this error to us by opening a ticket in GitHub.", e, ) })?; #[allow(unused_mut)] let mut req = reqwest::Request::new(reqwest::Method::GET, uri); req.headers_mut().append( "User-Agent", version!("Git-Tool/").parse().map_err(|e| { errors::system_with_internal( &format!( "Unable to parse Git-Tool user agent header {}.", version!("Git-Tool/") ), "Please report this error to us by opening a ticket in GitHub.", e, ) })?, ); #[cfg(test)] { if let Ok(token) = std::env::var("GITHUB_TOKEN") { req.headers_mut().append( "Authorization", format!("token {}", token).parse().map_err(|e| { errors::system_with_internal( "Unable to parse GITHUB_TOKEN authorization header.", "Please report this error to us by opening a ticket in GitHub.", e, ) })?, ); } } core.http_client().request(req).await } } #[async_trait::async_trait] impl Registry for GitHubRegistry { async fn get_entries(&self, core: &Core) -> Result<Vec<String>, Error> { let resp = self.get(core, "https://api.github.com/repos/SierraSoftworks/git-tool/git/trees/main?recursive=true").await?; match resp.status() { http::StatusCode::OK => { let tree: GitHubTree = resp.json().await?; let mut entries: Vec<String> = Vec::new(); let prefix = "registry/"; let suffix = ".yaml"; for node in tree.tree { if node.node_type == "blob" && node.path.starts_with(prefix) && node.path.ends_with(suffix) { let len = node.path.len(); let name: String = node.path[prefix.len()..(len - suffix.len())].into(); entries.push(name); } } Ok(entries) } http::StatusCode::TOO_MANY_REQUESTS | http::StatusCode::FORBIDDEN => { let inner_error = errors::reqwest::ResponseError::with_body(resp).await; Err(errors::user_with_internal( "GitHub has rate limited requests from your IP address.", "Please wait until GitHub removes this rate limit before trying again.", inner_error, )) } status => { let inner_error = errors::reqwest::ResponseError::with_body(resp).await; Err(errors::system_with_internal( &format!("Received an HTTP {} response from GitHub when attempting to list items in the Git-Tool registry.", status), "Please read the error message below and decide if there is something you can do to fix the problem, or report it to us on GitHub.", inner_error)) } } } async fn get_entry(&self, core: &Core, id: &str) -> Result<Entry, Error> { let resp = self .get( core, &format!( "https://raw.githubusercontent.com/SierraSoftworks/git-tool/main/registry/{}.yaml", id ), ) .await?; match resp.status() { http::StatusCode::OK => { let body = resp.bytes().await?; let entity = serde_yaml::from_slice(&body)?; Ok(entity) }, http::StatusCode::NOT_FOUND => { Err(errors::user( &format!("Could not find {} in the Git-Tool registry.", id), "Please make sure that you've selected a configuration entry which exists in the registry. You can check this with `git-tool config list`.")) }, http::StatusCode::TOO_MANY_REQUESTS | http::StatusCode::FORBIDDEN => { let inner_error = errors::reqwest::ResponseError::with_body(resp).await; Err(errors::user_with_internal( "GitHub has rate limited requests from your IP address.", "Please wait until GitHub removes this rate limit before trying again.", inner_error)) }, status => { let inner_error = errors::reqwest::ResponseError::with_body(resp).await; Err(errors::system_with_internal( &format!("Received an HTTP {} response from GitHub when attempting to fetch /registry/{}.yaml.", status, id), "Please read the error message below and decide if there is something you can do to fix the problem, or report it to us on GitHub.", inner_error)) } } } } #[derive(Debug, Deserialize, Clone)] struct GitHubTree { pub tree: Vec<GitHubTreeNode>, pub truncated: bool, } #[derive(Debug, Deserialize, Clone)] struct GitHubTreeNode { #[serde(rename = "type")] pub node_type: String, pub path: String, } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn get_entries() { let core = Core::builder().build(); let registry = GitHubRegistry; let entries = registry.get_entries(&core).await.unwrap(); assert_ne!(entries.len(), 0); assert!(entries.iter().any(|i| i == "apps/bash")); } #[tokio::test] async fn get_entry() { let core = Core::builder().build(); let registry = GitHubRegistry; let entry = registry.get_entry(&core, "apps/bash").await.unwrap(); assert_eq!(entry.name, "Bash"); } }
use super::*; use crate::errors; use serde::Deserialize; pub struct GitHubRegistry; impl GitHubRegistry { async fn get(&self, core: &Core, url: &str) -> Result<reqwest::Response, errors::Error> { let uri: reqwest::Url = url.parse().map_err(|e| { errors::system_with_internal( &format!("Unable to parse GitHub API URL '{}'.", url), "Please report this error to us by opening a ticket in GitHub.", e, ) })?; #[allow(unused_mut)] let mut req = reqwest::Request::new(reqwest::Method::GET, uri); req.headers_mut().append( "User-Agent", version!("Git-Tool/").parse().map_err(|e| { errors::system_with_internal( &format!( "Unable to parse Git-Tool user agent header {}.", version!("Git-Tool/") ), "Please report this error to us by opening a ticket in GitHub.", e, ) })?, ); #[cfg(test)] { if let Ok(token) = std::env::var("GITHUB_TOKEN") { req.headers_mut().append( "Authorization", format!("token {}", token).parse().map_err(|e| { errors::system_with_internal( "Unable to parse GITHUB_TOKEN authorization header.", "Please report this error to us by opening a ticket in GitHub.", e, ) })?, ); } } core.http_client().request(req).await } } #[async_trait::async_trait] impl Registry for GitHubRegistry { async fn get_entries(&self, core: &Core) -> Result<Vec<String>, Error> { let resp = self.get(core, "https://api.github.com/repos/SierraSoftworks/git-tool/git/trees/main?recursive=true").await?; match resp.status() { http::StatusCode::OK => { let tree: GitHubTree = resp.json().awai
async fn get_entry(&self, core: &Core, id: &str) -> Result<Entry, Error> { let resp = self .get( core, &format!( "https://raw.githubusercontent.com/SierraSoftworks/git-tool/main/registry/{}.yaml", id ), ) .await?; match resp.status() { http::StatusCode::OK => { let body = resp.bytes().await?; let entity = serde_yaml::from_slice(&body)?; Ok(entity) }, http::StatusCode::NOT_FOUND => { Err(errors::user( &format!("Could not find {} in the Git-Tool registry.", id), "Please make sure that you've selected a configuration entry which exists in the registry. You can check this with `git-tool config list`.")) }, http::StatusCode::TOO_MANY_REQUESTS | http::StatusCode::FORBIDDEN => { let inner_error = errors::reqwest::ResponseError::with_body(resp).await; Err(errors::user_with_internal( "GitHub has rate limited requests from your IP address.", "Please wait until GitHub removes this rate limit before trying again.", inner_error)) }, status => { let inner_error = errors::reqwest::ResponseError::with_body(resp).await; Err(errors::system_with_internal( &format!("Received an HTTP {} response from GitHub when attempting to fetch /registry/{}.yaml.", status, id), "Please read the error message below and decide if there is something you can do to fix the problem, or report it to us on GitHub.", inner_error)) } } } } #[derive(Debug, Deserialize, Clone)] struct GitHubTree { pub tree: Vec<GitHubTreeNode>, pub truncated: bool, } #[derive(Debug, Deserialize, Clone)] struct GitHubTreeNode { #[serde(rename = "type")] pub node_type: String, pub path: String, } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn get_entries() { let core = Core::builder().build(); let registry = GitHubRegistry; let entries = registry.get_entries(&core).await.unwrap(); assert_ne!(entries.len(), 0); assert!(entries.iter().any(|i| i == "apps/bash")); } #[tokio::test] async fn get_entry() { let core = Core::builder().build(); let registry = GitHubRegistry; let entry = registry.get_entry(&core, "apps/bash").await.unwrap(); assert_eq!(entry.name, "Bash"); } }
t?; let mut entries: Vec<String> = Vec::new(); let prefix = "registry/"; let suffix = ".yaml"; for node in tree.tree { if node.node_type == "blob" && node.path.starts_with(prefix) && node.path.ends_with(suffix) { let len = node.path.len(); let name: String = node.path[prefix.len()..(len - suffix.len())].into(); entries.push(name); } } Ok(entries) } http::StatusCode::TOO_MANY_REQUESTS | http::StatusCode::FORBIDDEN => { let inner_error = errors::reqwest::ResponseError::with_body(resp).await; Err(errors::user_with_internal( "GitHub has rate limited requests from your IP address.", "Please wait until GitHub removes this rate limit before trying again.", inner_error, )) } status => { let inner_error = errors::reqwest::ResponseError::with_body(resp).await; Err(errors::system_with_internal( &format!("Received an HTTP {} response from GitHub when attempting to list items in the Git-Tool registry.", status), "Please read the error message below and decide if there is something you can do to fix the problem, or report it to us on GitHub.", inner_error)) } } }
function_block-function_prefixed
[ { "content": "pub fn render(tmpl: &str, context: Value) -> Result<String, errors::Error> {\n\n template(tmpl, context).map_err(|e| errors::user_with_internal(\n\n format!(\"We couldn't render your template '{}'.\", tmpl).as_str(),\n\n \"Check that your template follows the Go template syntax he...
Rust
onion_lib/src/api_protocol/messages/mod.rs
leonbeckmann/voip-onion-routing
06e86d957c01cf83e7095ff966c24a0fd99a2ff0
use std::convert::{TryFrom, TryInto}; use std::net::IpAddr; /* * Onion Message Header [size: u16, type: u16] * Direction: Incoming, Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionMessageHeader { pub size: u16, pub msg_type: u16, } impl OnionMessageHeader { pub fn new(size: u16, msg_type: u16) -> Self { assert!(size as usize >= Self::hdr_size()); Self { size, msg_type } } pub const fn hdr_size() -> usize { 4 } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.size.to_be_bytes().to_vec()); v.append(&mut self.msg_type.to_be_bytes().to_vec()); v } } impl TryFrom<&[u8; Self::hdr_size()]> for OnionMessageHeader { type Error = anyhow::Error; fn try_from(raw: &[u8; Self::hdr_size()]) -> Result<Self, Self::Error> { let hdr = Self { size: u16::from_be_bytes(raw[0..2].try_into().unwrap()), msg_type: u16::from_be_bytes(raw[2..4].try_into().unwrap()), }; if (hdr.size as usize) >= OnionMessageHeader::hdr_size() { Ok(hdr) } else { Err(anyhow::Error::msg( "Given packet size in OnionMessageHeader less than sizeof OnionMessageHeader", )) } } } /* * Onion Tunnel Build [reserved: u15, ip_version: u1, onion_port: u16, ip_addr: u32/u128, key: [u8]] * Direction: Incoming */ #[derive(Clone, Debug, PartialEq)] pub struct OnionTunnelBuild { _reserved_v: u16, pub onion_port: u16, pub ip: IpAddr, pub host_key: Vec<u8>, } impl OnionTunnelBuild { pub fn new(ip: IpAddr, onion_port: u16, host_key: Vec<u8>) -> Self { Self { _reserved_v: if ip.is_ipv6() { 1 } else { 0 }, onion_port, ip, host_key, } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self._reserved_v.to_be_bytes().to_vec()); v.append(&mut self.onion_port.to_be_bytes().to_vec()); match self.ip { IpAddr::V4(v4) => { v.append(&mut v4.octets().to_vec()); } IpAddr::V6(v6) => { v.append(&mut v6.octets().to_vec()); } } v.extend(&self.host_key); v } } impl TryFrom<Vec<u8>> for Box<OnionTunnelBuild> { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() < 4 { return Err(anyhow::Error::msg( "Cannot parse OnionTunnelBuild: Invalid number of bytes", )); } let reserved_v = u16::from_be_bytes(raw[0..2].try_into().unwrap()); let onion_port = u16::from_be_bytes(raw[2..4].try_into().unwrap()); let (ip, host_key) = match (1 & reserved_v) == 1 { true => { if raw.len() < 20 { return Err(anyhow::Error::msg( "Cannot parse OnionTunnelBuild: Invalid number of bytes", )); } let mut ip_buf = [0u8; 16]; ip_buf.copy_from_slice(&raw[4..20]); (IpAddr::from(ip_buf), raw[20..].to_vec()) } false => { if raw.len() < 8 { return Err(anyhow::Error::msg( "Cannot parse OnionTunnelBuild: Invalid number of bytes", )); } let mut ip_buf = [0u8; 4]; ip_buf.copy_from_slice(&raw[4..8]); (IpAddr::from(ip_buf), raw[8..].to_vec()) } }; Ok(Box::new(OnionTunnelBuild { _reserved_v: reserved_v, onion_port, ip, host_key, })) } } /* * Onion Tunnel Ready [tunnel_id: u32, host_key: [u8]] * Direction: Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionTunnelReady { pub tunnel_id: u32, pub host_key: Vec<u8>, } impl OnionTunnelReady { pub fn new(tunnel_id: u32, host_key: Vec<u8>) -> Self { Self { tunnel_id, host_key, } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.tunnel_id.to_be_bytes().to_vec()); v.extend(&self.host_key); v } } impl TryFrom<Vec<u8>> for Box<OnionTunnelReady> { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() < 4 { return Err(anyhow::Error::msg( "Cannot parse OnionTunnelReady: Invalid number of bytes", )); } Ok(Box::new(OnionTunnelReady { tunnel_id: u32::from_be_bytes(raw[0..4].try_into().unwrap()), host_key: raw[4..].to_vec(), })) } } /* * Onion Tunnel Incoming [tunnel_id: u32] * Direction: Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionTunnelIncoming { pub tunnel_id: u32, } impl OnionTunnelIncoming { pub fn new(tunnel_id: u32) -> Self { Self { tunnel_id } } pub fn to_be_vec(&self) -> Vec<u8> { self.tunnel_id.to_be_bytes().to_vec() } const fn packet_size() -> usize { 4 } } impl TryFrom<Vec<u8>> for OnionTunnelIncoming { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() != Self::packet_size() { Err(anyhow::Error::msg( "Cannot parse OnionTunnelIncoming: Invalid number of bytes", )) } else { Ok(Self { tunnel_id: u32::from_be_bytes(raw[0..4].try_into().unwrap()), }) } } } /* * Onion Tunnel Destroy [tunnel_id: u32] * Direction: Incoming */ #[derive(Debug, PartialEq)] pub struct OnionTunnelDestroy { pub tunnel_id: u32, } impl OnionTunnelDestroy { pub fn new(tunnel_id: u32) -> Self { Self { tunnel_id } } pub fn to_be_vec(&self) -> Vec<u8> { self.tunnel_id.to_be_bytes().to_vec() } const fn packet_size() -> usize { 4 } } impl TryFrom<Vec<u8>> for OnionTunnelDestroy { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() != Self::packet_size() { Err(anyhow::Error::msg( "Cannot parse OnionTunnelDestroy: Invalid number of bytes", )) } else { Ok(Self { tunnel_id: u32::from_be_bytes(raw[0..4].try_into().unwrap()), }) } } } /* * Onion Tunnel Data [tunnel_id: u32, data: Vec<u8>] * Direction: Incoming, Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionTunnelData { pub tunnel_id: u32, pub data: Vec<u8>, } impl OnionTunnelData { pub fn new(tunnel_id: u32, data: Vec<u8>) -> Self { Self { tunnel_id, data } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.tunnel_id.to_be_bytes().to_vec()); v.extend(&self.data); v } } impl TryFrom<Vec<u8>> for Box<OnionTunnelData> { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() < 4 { Err(anyhow::Error::msg( "Cannot parse OnionTunnelData: Invalid number of bytes", )) } else { Ok(Box::new(OnionTunnelData { tunnel_id: u32::from_be_bytes(raw[0..4].try_into().unwrap()), data: raw[4..].to_vec(), })) } } } /* * Onion Tunnel Error [request_type: u16, reserved: u16, tunnel_id: u32] * Direction: Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionError { pub request_type: u16, _reserved: u16, pub tunnel_id: u32, } impl OnionError { pub fn new(request_type: u16, tunnel_id: u32) -> Self { Self { request_type, _reserved: 0, tunnel_id, } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.request_type.to_be_bytes().to_vec()); v.append(&mut self._reserved.to_be_bytes().to_vec()); v.append(&mut self.tunnel_id.to_be_bytes().to_vec()); v } const fn packet_size() -> usize { 8 } } impl TryFrom<Vec<u8>> for OnionError { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() != Self::packet_size() { Err(anyhow::Error::msg( "Cannot parse OnionError: Invalid number of bytes", )) } else { Ok(Self { request_type: u16::from_be_bytes(raw[0..2].try_into().unwrap()), _reserved: 0, tunnel_id: u32::from_be_bytes(raw[4..8].try_into().unwrap()), }) } } } /* * Onion Tunnel Data [cover_size: 16, reserved: u16] * Direction: Incoming */ #[derive(Debug, PartialEq)] pub struct OnionCover { pub cover_size: u16, _reserved: u16, } impl OnionCover { pub fn new(cover_size: u16) -> Self { Self { cover_size, _reserved: 0, } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.cover_size.to_be_bytes().to_vec()); v.append(&mut self._reserved.to_be_bytes().to_vec()); v } const fn packet_size() -> usize { 4 } } impl TryFrom<Vec<u8>> for OnionCover { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() != Self::packet_size() { Err(anyhow::Error::msg( "Cannot parse OnionCover: Invalid number of bytes", )) } else { Ok(Self { cover_size: u16::from_be_bytes(raw[0..2].try_into().unwrap()), _reserved: 0, }) } } } #[cfg(test)] mod tests { use crate::api_protocol::messages::{ OnionCover, OnionError, OnionMessageHeader, OnionTunnelBuild, OnionTunnelData, OnionTunnelDestroy, OnionTunnelIncoming, OnionTunnelReady, }; use crate::api_protocol::{ONION_TUNNEL_BUILD, ONION_TUNNEL_DATA}; use std::convert::{TryFrom, TryInto}; use std::net::IpAddr; use std::str::FromStr; #[test] fn unit_test_only_messages() { let hdr = OnionMessageHeader::new(25, ONION_TUNNEL_DATA); let mut hdr_raw: [u8; 4] = hdr.to_be_vec().try_into().unwrap(); let hdr2 = OnionMessageHeader::try_from(&hdr_raw).unwrap(); assert_eq!(hdr, hdr2); hdr_raw[0] = 0; hdr_raw[1] = 2; OnionMessageHeader::try_from(&hdr_raw).unwrap_err(); let ip_addr = IpAddr::from_str("127.0.0.1").unwrap(); let build_v4 = OnionTunnelBuild::new(ip_addr, 1234, "key".as_bytes().to_vec()); let build2 = Box::<OnionTunnelBuild>::try_from(build_v4.to_be_vec()).unwrap(); assert_eq!(Box::new(build_v4.clone()), build2); let ip_addr = IpAddr::from_str("::1").unwrap(); let build_v6 = OnionTunnelBuild::new(ip_addr, 1234, "key".as_bytes().to_vec()); let build2 = Box::<OnionTunnelBuild>::try_from(build_v6.to_be_vec()).unwrap(); assert_eq!(Box::new(build_v6.clone()), build2); Box::<OnionTunnelBuild>::try_from(vec![0, 1, 2]).unwrap_err(); let mut build_v4_invalid = build_v4.to_be_vec(); build_v4_invalid.truncate(7); let mut build_v6_invalid = build_v6.to_be_vec(); build_v6_invalid.truncate(19); Box::<OnionTunnelBuild>::try_from(build_v4_invalid).unwrap_err(); Box::<OnionTunnelBuild>::try_from(build_v6_invalid).unwrap_err(); let ready = OnionTunnelReady::new(1025, "key".as_bytes().to_vec()); let ready2 = Box::<OnionTunnelReady>::try_from(ready.to_be_vec()).unwrap(); assert_eq!(Box::new(ready), ready2); Box::<OnionTunnelReady>::try_from(vec![0, 1, 2]).unwrap_err(); let incoming = OnionTunnelIncoming::new(1025); let incoming2 = OnionTunnelIncoming::try_from(incoming.to_be_vec()).unwrap(); assert_eq!(incoming, incoming2); OnionTunnelIncoming::try_from(vec![0, 1, 2]).unwrap_err(); let destroy = OnionTunnelDestroy::new(1025); let destroy2 = OnionTunnelDestroy::try_from(destroy.to_be_vec()).unwrap(); assert_eq!(destroy, destroy2); let data = OnionTunnelData::new(1025, "Data".as_bytes().to_vec()); let data2 = Box::<OnionTunnelData>::try_from(data.to_be_vec()).unwrap(); assert_eq!(Box::new(data), data2); Box::<OnionTunnelData>::try_from(vec![0, 1, 2]).unwrap_err(); let error = OnionError::new(ONION_TUNNEL_BUILD, 0); let error2 = OnionError::try_from(error.to_be_vec()).unwrap(); assert_eq!(error, error2); OnionError::try_from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]).unwrap_err(); let cover = OnionCover::new(1025); let cover2 = OnionCover::try_from(cover.to_be_vec()).unwrap(); assert_eq!(cover, cover2); OnionCover::try_from(vec![0, 1, 2, 3, 4]).unwrap_err(); } }
use std::convert::{TryFrom, TryInto}; use std::net::IpAddr; /* * Onion Message Header [size: u16, type: u16] * Direction: Incoming, Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionMessageHeader { pub size: u16, pub msg_type: u16, } impl OnionMessageHeader { pub fn new(size: u16, msg_type: u16) -> Self { assert!(size as usize >= Self::hdr_size()); Self { size, msg_type } } pub const fn hdr_size() -> usize { 4 } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.size.to_be_bytes().to_vec()); v.append(&mut self.msg_type.to_be_bytes().to_vec()); v } } impl TryFrom<&[u8; Self::hdr_size()]> for OnionMessageHeader { type Error = anyhow::Error; fn try_from(raw: &[u8; Self::hdr_size()]) -> Result<Self, Self::Error> { let hdr = Self { size: u16::from_be_bytes(raw[0..2].try_into().unwrap()), msg_type: u16::from_be_bytes(raw[2..4].try_into().unwrap()), }; if (hdr.size as usize) >= OnionMessageHeader::hdr_size() { Ok(hdr) } else { Err(anyhow::Error::msg( "Given packet size in OnionMessageHeader less than sizeof OnionMessageHeader", )) } } } /* * Onion Tunnel Build [reserved: u15, ip_version: u1, onion_port: u16, ip_addr: u32/u128, key: [u8]] * Direction: Incoming */ #[derive(Clone, Debug, PartialEq)] pub struct OnionTunnelBuild { _reserved_v: u16, pub onion_port: u16, pub ip: IpAddr, pub host_key: Vec<u8>, } impl OnionTunnelBuild { pub fn new(ip: IpAddr, onion_port: u16, host_key: Vec<u8>) -> Self { Self { _reserved_v: if ip.is_ipv6() { 1 } else { 0 }, onion_port, ip, host_key, } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self._reserved_v.to_be_bytes().to_vec()); v.append(&mut self.onion_port.to_be_bytes().to_vec()); match self.ip { IpAddr::V4(v4) => { v.append(&mut v4.octets().to_vec()); } IpAddr::V6(v6) => { v.append(&mut v6.octets().to_vec()); } } v.extend(&self.host_key); v } } impl TryFrom<Vec<u8>> for Box<OnionTunnelBuild> { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() < 4 { return Err(anyhow::Error::msg( "Cannot parse OnionTunnelBuild: Invalid number of bytes", )); } let reserved_v = u16::from_be_bytes(raw[0..2].try_into().unwrap()); let onion_port = u16::from_be_bytes(raw[2..4].try_into().unwrap()); let (ip, host_key) = match (1 & reserved_v) == 1 { true => { if raw.len() < 20 { return Err(anyhow::Error::msg( "Cannot parse OnionTunnelBuild: Invalid number of bytes", )); } let mut ip_buf = [0u8; 16]; ip_buf.copy_from_slice(&raw[4..20]); (IpAddr::from(ip_buf), raw[20..].to_vec()) } false => { if raw.len() < 8 { return Err(anyhow::Error::msg( "Cannot parse OnionTunnelBuild: Invalid number of bytes", )); } let mut ip_buf = [0u8; 4]; ip_buf.copy_from_slice(&raw[4..8]); (IpAddr::from(ip_buf), raw[8..].to_vec()) } }; Ok(Box::new(OnionTunnelBuild { _reserved_v: reserved_v, onion_port, ip, host_key, })) } } /* * Onion Tunnel Ready [tunnel_id: u32, host_key: [u8]] * Direction: Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionTunnelReady { pub tunnel_id: u32, pub host_key: Vec<u8>, } impl OnionTunnelReady { pub fn new(tunnel_id: u32, host_key: Vec<u8>) -> Self { Self { tunnel_id, host_key, } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.tunnel_id.to_be_bytes().to_vec()); v.extend(&self.host_key); v } } impl TryFrom<Vec<u8>> for Box<OnionTunnelReady> { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() < 4 { return Err(anyhow::Error::msg( "Cannot parse OnionTunnelReady: Invalid number of bytes", )); } Ok(Box::new(OnionTunnelReady { tunnel_id: u32::from_be_bytes(raw[0..4].try_into().unwrap()), host_key: raw[4..].to_vec(), })) } } /* * Onion Tunnel Incoming [tunnel_id: u32] * Direction: Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionTunnelIncoming { pub tunnel_id: u32, } impl OnionTunnelIncoming { pub fn new(tunnel_id: u32) -> Self { Self { tunnel_id } } pub fn to_be_vec(&self) -> Vec<u8> { self.tunnel_id.to_be_bytes().to_vec() } const fn packet_size() -> usize { 4 } } impl TryFrom<Vec<u8>> for OnionTunnelIncoming { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() != Self::packet_size() { Err(anyhow::Error::msg( "Cannot parse OnionTunnelIncoming: Invalid number of bytes", )) } else { Ok(Self { tunnel_id: u32::from_be_bytes(raw[0..4].try_into().unwrap()), }) } } } /* * Onion Tunnel Destroy [tunnel_id: u32] * Direction: Incoming */ #[derive(Debug, PartialEq)] pub struct OnionTunnelDestroy { pub tunnel_id: u32, } impl OnionTunnelDestroy { pub fn new(tunnel_id: u32) -> Self { Self { tunnel_id } } pub fn to_be_vec(&self) -> Vec<u8> { self.tunnel_id.to_be_bytes().to_vec() } const fn packet_size() -> usize { 4 } } impl TryFrom<Vec<u8>> for OnionTunnelDestroy { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() != Self::packet_size() { Err(anyhow::Error::msg( "Cannot parse OnionTunnelDestroy: Invalid number of bytes", )) } else { Ok(Self { tunnel_id: u32::from_be_bytes(raw[0..4].try_into().unwrap()), }) } } } /* * Onion Tunnel Data [tunnel_id: u32, data: Vec<u8>] * Direction: Incoming, Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionTunnelData { pub tunnel_id: u32, pub data: Vec<u8>, } impl OnionTunnelData { pub fn new(tunnel_id: u32, data: Vec<u8>) -> Self { Self { tunnel_id, data } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.tunnel_id.to_be_bytes().to_vec()); v.extend(&self.data); v } } impl TryFrom<Vec<u8>> for Box<OnionTunnelData> { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() < 4 { Err(anyhow::Error::msg( "Cannot parse OnionTunnelData: Invalid number of bytes", )) } else { Ok(Box::new(OnionTunnelData { tunnel_id: u32::from_be_bytes(raw[0..4].try_into().unwrap()), data: raw[4..].to_vec(), })) } } } /* * Onion Tunnel Error [request_type: u16, reserved: u16, tunnel_id: u32] * Direction: Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionError { pub request_type: u16, _reserved: u16, pub tunnel_id: u32, } impl OnionError { pub fn new(request_type: u16, tunnel_id: u32) -> Self { Self { request_type, _reserved: 0, tunnel_id, } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.request_type.to_be_bytes().to_vec()); v.append(&mut self._reserved.to_be_bytes().to_vec()); v.append(&mut self.tunnel_id.to_be_bytes().to_vec()); v } const fn packet_size() -> usize { 8 } } impl TryFrom<Vec<u8>> for OnionError { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() != Self::packet_size() { Err(anyhow::Error::msg( "Cannot parse OnionError: Invalid number of bytes", )) } else { Ok(Self { request_type: u16::from_be_bytes(raw[0..2].try_into().unwrap()), _reserved: 0, tunnel_id: u32::from_be_bytes(raw[4..8].try_into().unwrap()), }) } } } /* * Onion Tunnel Data [cover_size: 16, reserved: u16] * Direction: Incoming */ #[derive(Debug, PartialEq)] pub struct OnionCover { pub cover_size: u16, _reserved: u16, } impl OnionCover { pub fn new(cover_size: u16) -> Self { Self { cover_size, _reserved: 0, } } pub fn to_be_vec(&self) -> Vec<u8> { let mut v = vec![]; v.append(&mut self.cover_size.to_be_bytes().to_vec()); v.append(&mut self._reserved.to_be_bytes().to_vec()); v } const fn packet_size() -> usize { 4 } } impl TryFrom<Vec<u8>> for OnionCover { type Error = anyhow::Error; fn try_from(raw: Vec<u8>) -> Result<Self, Self::Error> { if raw.len() != Self::packet_size() { Err(anyhow::Error::msg( "Cannot parse OnionCover: Invalid number of bytes", )) } else { Ok(Self { cover_size: u16::from_be_bytes(raw[0..2].try_into().unwrap()), _reserved: 0, }) } } } #[cfg(test)] mod tests { use crate::api_protocol::messages::{ OnionCover, OnionError, OnionMessageHeader, OnionTunnelBuild, OnionTunnelData, OnionTunnelDestroy, OnionTunnelIncoming, OnionTunnelReady, }; use crate::api_protocol::{ONION_TUNNEL_BUILD, ONION_TUNNEL_DATA}; use std::convert::{TryFrom, TryInto}; use std::net::IpAddr; use std::str::FromStr; #[test]
}
fn unit_test_only_messages() { let hdr = OnionMessageHeader::new(25, ONION_TUNNEL_DATA); let mut hdr_raw: [u8; 4] = hdr.to_be_vec().try_into().unwrap(); let hdr2 = OnionMessageHeader::try_from(&hdr_raw).unwrap(); assert_eq!(hdr, hdr2); hdr_raw[0] = 0; hdr_raw[1] = 2; OnionMessageHeader::try_from(&hdr_raw).unwrap_err(); let ip_addr = IpAddr::from_str("127.0.0.1").unwrap(); let build_v4 = OnionTunnelBuild::new(ip_addr, 1234, "key".as_bytes().to_vec()); let build2 = Box::<OnionTunnelBuild>::try_from(build_v4.to_be_vec()).unwrap(); assert_eq!(Box::new(build_v4.clone()), build2); let ip_addr = IpAddr::from_str("::1").unwrap(); let build_v6 = OnionTunnelBuild::new(ip_addr, 1234, "key".as_bytes().to_vec()); let build2 = Box::<OnionTunnelBuild>::try_from(build_v6.to_be_vec()).unwrap(); assert_eq!(Box::new(build_v6.clone()), build2); Box::<OnionTunnelBuild>::try_from(vec![0, 1, 2]).unwrap_err(); let mut build_v4_invalid = build_v4.to_be_vec(); build_v4_invalid.truncate(7); let mut build_v6_invalid = build_v6.to_be_vec(); build_v6_invalid.truncate(19); Box::<OnionTunnelBuild>::try_from(build_v4_invalid).unwrap_err(); Box::<OnionTunnelBuild>::try_from(build_v6_invalid).unwrap_err(); let ready = OnionTunnelReady::new(1025, "key".as_bytes().to_vec()); let ready2 = Box::<OnionTunnelReady>::try_from(ready.to_be_vec()).unwrap(); assert_eq!(Box::new(ready), ready2); Box::<OnionTunnelReady>::try_from(vec![0, 1, 2]).unwrap_err(); let incoming = OnionTunnelIncoming::new(1025); let incoming2 = OnionTunnelIncoming::try_from(incoming.to_be_vec()).unwrap(); assert_eq!(incoming, incoming2); OnionTunnelIncoming::try_from(vec![0, 1, 2]).unwrap_err(); let destroy = OnionTunnelDestroy::new(1025); let destroy2 = OnionTunnelDestroy::try_from(destroy.to_be_vec()).unwrap(); assert_eq!(destroy, destroy2); let data = OnionTunnelData::new(1025, "Data".as_bytes().to_vec()); let data2 = Box::<OnionTunnelData>::try_from(data.to_be_vec()).unwrap(); assert_eq!(Box::new(data), data2); Box::<OnionTunnelData>::try_from(vec![0, 1, 2]).unwrap_err(); let error = OnionError::new(ONION_TUNNEL_BUILD, 0); let error2 = OnionError::try_from(error.to_be_vec()).unwrap(); assert_eq!(error, error2); OnionError::try_from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]).unwrap_err(); let cover = OnionCover::new(1025); let cover2 = OnionCover::try_from(cover.to_be_vec()).unwrap(); assert_eq!(cover, cover2); OnionCover::try_from(vec![0, 1, 2, 3, 4]).unwrap_err(); }
function_block-full_function
[ { "content": "fn write_msg(msg_type: u16, data: Vec<u8>, stream: &mut TcpStream) {\n\n let hdr = OnionMessageHeader::new(\n\n (data.len() + OnionMessageHeader::hdr_size()) as u16,\n\n msg_type,\n\n )\n\n .to_be_vec();\n\n\n\n stream.write_all(hdr.as_slice()).unwrap();\n\n stream.wri...
Rust
noodles-bam/src/bai/reader.rs
MaltheSR/noodles
8530af08ced193795480ea8ee2667fe8af82bd92
use std::{ convert::TryFrom, io::{self, Read}, }; use byteorder::{LittleEndian, ReadBytesExt}; use noodles_bgzf as bgzf; use noodles_csi::index::reference_sequence::{bin::Chunk, Metadata}; use super::{ index::{reference_sequence, ReferenceSequence}, Bin, Index, MAGIC_NUMBER, }; pub struct Reader<R> { inner: R, } impl<R> Reader<R> where R: Read, { pub fn new(inner: R) -> Self { Self { inner } } pub fn read_header(&mut self) -> io::Result<()> { read_magic(&mut self.inner) } pub fn read_index(&mut self) -> io::Result<Index> { let references = read_references(&mut self.inner)?; let n_no_coor = read_unplaced_unmapped_record_count(&mut self.inner)?; Ok(Index::new(references, n_no_coor)) } } fn read_magic<R>(reader: &mut R) -> io::Result<()> where R: Read, { let mut magic = [0; 4]; reader.read_exact(&mut magic)?; if magic == MAGIC_NUMBER { Ok(()) } else { Err(io::Error::new( io::ErrorKind::InvalidData, "invalid BAI header", )) } } fn read_references<R>(reader: &mut R) -> io::Result<Vec<ReferenceSequence>> where R: Read, { let n_ref = reader.read_u32::<LittleEndian>().and_then(|n| { usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) })?; let mut references = Vec::with_capacity(n_ref); for _ in 0..n_ref { let (bins, metadata) = read_bins(reader)?; let intervals = read_intervals(reader)?; references.push(ReferenceSequence::new(bins, intervals, metadata)); } Ok(references) } fn read_bins<R>(reader: &mut R) -> io::Result<(Vec<Bin>, Option<Metadata>)> where R: Read, { use reference_sequence::bin::METADATA_ID; let n_bin = reader.read_u32::<LittleEndian>().and_then(|n| { usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) })?; let mut bins = Vec::with_capacity(n_bin); let mut metadata = None; for _ in 0..n_bin { let id = reader.read_u32::<LittleEndian>()?; if id == METADATA_ID { metadata = read_metadata(reader).map(Some)?; } else { let chunks = read_chunks(reader)?; let bin = Bin::new(id, chunks); bins.push(bin); } } Ok((bins, metadata)) } fn read_chunks<R>(reader: &mut R) -> io::Result<Vec<Chunk>> where R: Read, { let n_chunk = reader.read_u32::<LittleEndian>().and_then(|n| { usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) })?; let mut chunks = Vec::with_capacity(n_chunk); for _ in 0..n_chunk { let chunk_beg = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; let chunk_end = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; chunks.push(Chunk::new(chunk_beg, chunk_end)); } Ok(chunks) } fn read_intervals<R>(reader: &mut R) -> io::Result<Vec<bgzf::VirtualPosition>> where R: Read, { let n_intv = reader.read_u32::<LittleEndian>().and_then(|n| { usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) })?; let mut intervals = Vec::with_capacity(n_intv); for _ in 0..n_intv { let ioffset = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; intervals.push(ioffset); } Ok(intervals) } fn read_metadata<R>(reader: &mut R) -> io::Result<Metadata> where R: Read, { use reference_sequence::bin::METADATA_CHUNK_COUNT; let n_chunk = reader.read_u32::<LittleEndian>()?; if n_chunk != METADATA_CHUNK_COUNT { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "invalid metadata pseudo-bin chunk count: expected {}, got {}", METADATA_CHUNK_COUNT, n_chunk ), )); } let ref_beg = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; let ref_end = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; let n_mapped = reader.read_u64::<LittleEndian>()?; let n_unmapped = reader.read_u64::<LittleEndian>()?; Ok(Metadata::new(ref_beg, ref_end, n_mapped, n_unmapped)) } fn read_unplaced_unmapped_record_count<R>(reader: &mut R) -> io::Result<Option<u64>> where R: Read, { match reader.read_u64::<LittleEndian>() { Ok(n) => Ok(Some(n)), Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(None), Err(e) => Err(e), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_magic() { let data = b"BAI\x01"; let mut reader = &data[..]; assert!(read_magic(&mut reader).is_ok()); } #[test] fn test_read_magic_with_invalid_magic_number() { let data = []; let mut reader = &data[..]; assert!(matches!( read_magic(&mut reader), Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof )); let data = b"BAI"; let mut reader = &data[..]; assert!(matches!( read_magic(&mut reader), Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof )); let data = b"MThd"; let mut reader = &data[..]; assert!(matches!( read_magic(&mut reader), Err(ref e) if e.kind() == io::ErrorKind::InvalidData )); } #[test] fn test_read_metadata() -> io::Result<()> { let data = [ 0x02, 0x00, 0x00, 0x00, 0x62, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3d, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let mut reader = &data[..]; let actual = read_metadata(&mut reader)?; let expected = Metadata::new( bgzf::VirtualPosition::from(610), bgzf::VirtualPosition::from(1597), 55, 0, ); assert_eq!(actual, expected); Ok(()) } #[test] fn test_read_unplaced_unmapped_record_count() -> io::Result<()> { let data = []; let mut reader = &data[..]; assert_eq!(read_unplaced_unmapped_record_count(&mut reader)?, None); let data = [0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; let mut reader = &data[..]; assert_eq!(read_unplaced_unmapped_record_count(&mut reader)?, Some(8)); Ok(()) } }
use std::{ convert::TryFrom, io::{self, Read}, }; use byteorder::{LittleEndian, ReadBytesExt}; use noodles_bgzf as bgzf; use noodles_csi::index::reference_sequence::{bin::Chunk, Metadata}; use super::{ index::{reference_sequence, ReferenceSequence}, Bin, Index, MAGIC_NUMBER, }; pub struct Reader<R> { inner: R, } impl<R> Reader<R> where R: Read, { pub fn new(inner: R) -> Self { Self { inner } } pub fn read_header(&mut self) -> io::Result<()> { read_magic(&mut self.inner) } pub fn read_index(&mut self) -> io::Result<Index> { let references = read_references(&mut self.inner)?; let n_no_coor = read_unplaced_unmapped_record_count(&mut self.inner)?; Ok(Index::new(references, n_no_coor)) } } fn read_magic<R>(reader: &mut R) -> io::Result<()> where R: Read, { let mut magic = [0; 4]; reader.read_exact(&mut magic)?; if magic == MAGIC_NUMBER { Ok(()) } else { Err(io::Error::new( io::ErrorKind::InvalidData, "invalid BAI header", )) } } fn read_references<R>(reader: &mut R) -> io::Result<Vec<ReferenceSequence>> where R: Read, { let n_ref = reader.read_u32::<LittleEndian>().and_then(|n| { usize::try_from(n).map_err(|e| io::Error::new(io
let intervals = read_intervals(reader)?; references.push(ReferenceSequence::new(bins, intervals, metadata)); } Ok(references) } fn read_bins<R>(reader: &mut R) -> io::Result<(Vec<Bin>, Option<Metadata>)> where R: Read, { use reference_sequence::bin::METADATA_ID; let n_bin = reader.read_u32::<LittleEndian>().and_then(|n| { usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) })?; let mut bins = Vec::with_capacity(n_bin); let mut metadata = None; for _ in 0..n_bin { let id = reader.read_u32::<LittleEndian>()?; if id == METADATA_ID { metadata = read_metadata(reader).map(Some)?; } else { let chunks = read_chunks(reader)?; let bin = Bin::new(id, chunks); bins.push(bin); } } Ok((bins, metadata)) } fn read_chunks<R>(reader: &mut R) -> io::Result<Vec<Chunk>> where R: Read, { let n_chunk = reader.read_u32::<LittleEndian>().and_then(|n| { usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) })?; let mut chunks = Vec::with_capacity(n_chunk); for _ in 0..n_chunk { let chunk_beg = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; let chunk_end = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; chunks.push(Chunk::new(chunk_beg, chunk_end)); } Ok(chunks) } fn read_intervals<R>(reader: &mut R) -> io::Result<Vec<bgzf::VirtualPosition>> where R: Read, { let n_intv = reader.read_u32::<LittleEndian>().and_then(|n| { usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) })?; let mut intervals = Vec::with_capacity(n_intv); for _ in 0..n_intv { let ioffset = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; intervals.push(ioffset); } Ok(intervals) } fn read_metadata<R>(reader: &mut R) -> io::Result<Metadata> where R: Read, { use reference_sequence::bin::METADATA_CHUNK_COUNT; let n_chunk = reader.read_u32::<LittleEndian>()?; if n_chunk != METADATA_CHUNK_COUNT { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( "invalid metadata pseudo-bin chunk count: expected {}, got {}", METADATA_CHUNK_COUNT, n_chunk ), )); } let ref_beg = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; let ref_end = reader .read_u64::<LittleEndian>() .map(bgzf::VirtualPosition::from)?; let n_mapped = reader.read_u64::<LittleEndian>()?; let n_unmapped = reader.read_u64::<LittleEndian>()?; Ok(Metadata::new(ref_beg, ref_end, n_mapped, n_unmapped)) } fn read_unplaced_unmapped_record_count<R>(reader: &mut R) -> io::Result<Option<u64>> where R: Read, { match reader.read_u64::<LittleEndian>() { Ok(n) => Ok(Some(n)), Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(None), Err(e) => Err(e), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_magic() { let data = b"BAI\x01"; let mut reader = &data[..]; assert!(read_magic(&mut reader).is_ok()); } #[test] fn test_read_magic_with_invalid_magic_number() { let data = []; let mut reader = &data[..]; assert!(matches!( read_magic(&mut reader), Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof )); let data = b"BAI"; let mut reader = &data[..]; assert!(matches!( read_magic(&mut reader), Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof )); let data = b"MThd"; let mut reader = &data[..]; assert!(matches!( read_magic(&mut reader), Err(ref e) if e.kind() == io::ErrorKind::InvalidData )); } #[test] fn test_read_metadata() -> io::Result<()> { let data = [ 0x02, 0x00, 0x00, 0x00, 0x62, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3d, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let mut reader = &data[..]; let actual = read_metadata(&mut reader)?; let expected = Metadata::new( bgzf::VirtualPosition::from(610), bgzf::VirtualPosition::from(1597), 55, 0, ); assert_eq!(actual, expected); Ok(()) } #[test] fn test_read_unplaced_unmapped_record_count() -> io::Result<()> { let data = []; let mut reader = &data[..]; assert_eq!(read_unplaced_unmapped_record_count(&mut reader)?, None); let data = [0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; let mut reader = &data[..]; assert_eq!(read_unplaced_unmapped_record_count(&mut reader)?, Some(8)); Ok(()) } }
::ErrorKind::InvalidData, e)) })?; let mut references = Vec::with_capacity(n_ref); for _ in 0..n_ref { let (bins, metadata) = read_bins(reader)?;
function_block-random_span
[ { "content": "fn read_header<R>(reader: &mut R) -> io::Result<index::Header>\n\nwhere\n\n R: Read,\n\n{\n\n let format = reader.read_i32::<LittleEndian>().and_then(|n| {\n\n Format::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))\n\n })?;\n\n\n\n let col_seq = reader.re...
Rust
imxrt1062-pac/imxrt1062-semc/src/bmcr1.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register BMCR1"] pub type R = crate::R<u32, super::BMCR1>; #[doc = "Writer for register BMCR1"] pub type W = crate::W<u32, super::BMCR1>; #[doc = "Register BMCR1 `reset()`'s with value 0"] impl crate::ResetValue for super::BMCR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `WQOS`"] pub type WQOS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WQOS`"] pub struct WQOS_W<'a> { w: &'a mut W, } impl<'a> WQOS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `WAGE`"] pub type WAGE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WAGE`"] pub struct WAGE_W<'a> { w: &'a mut W, } impl<'a> WAGE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `WPH`"] pub type WPH_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WPH`"] pub struct WPH_W<'a> { w: &'a mut W, } impl<'a> WPH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8); self.w } } #[doc = "Reader of field `WRWS`"] pub type WRWS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WRWS`"] pub struct WRWS_W<'a> { w: &'a mut W, } impl<'a> WRWS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `WBR`"] pub type WBR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WBR`"] pub struct WBR_W<'a> { w: &'a mut W, } impl<'a> WBR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 24)) | (((value as u32) & 0xff) << 24); self.w } } impl R { #[doc = "Bits 0:3 - Weight of QoS"] #[inline(always)] pub fn wqos(&self) -> WQOS_R { WQOS_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - Weight of Aging"] #[inline(always)] pub fn wage(&self) -> WAGE_R { WAGE_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:15 - Weight of Page Hit"] #[inline(always)] pub fn wph(&self) -> WPH_R { WPH_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:23 - Weight of Read/Write switch"] #[inline(always)] pub fn wrws(&self) -> WRWS_R { WRWS_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 24:31 - Weight of Bank Rotation"] #[inline(always)] pub fn wbr(&self) -> WBR_R { WBR_R::new(((self.bits >> 24) & 0xff) as u8) } } impl W { #[doc = "Bits 0:3 - Weight of QoS"] #[inline(always)] pub fn wqos(&mut self) -> WQOS_W { WQOS_W { w: self } } #[doc = "Bits 4:7 - Weight of Aging"] #[inline(always)] pub fn wage(&mut self) -> WAGE_W { WAGE_W { w: self } } #[doc = "Bits 8:15 - Weight of Page Hit"] #[inline(always)] pub fn wph(&mut self) -> WPH_W { WPH_W { w: self } } #[doc = "Bits 16:23 - Weight of Read/Write switch"] #[inline(always)] pub fn wrws(&mut self) -> WRWS_W { WRWS_W { w: self } } #[doc = "Bits 24:31 - Weight of Bank Rotation"] #[inline(always)] pub fn wbr(&mut self) -> WBR_W { WBR_W { w: self } } }
#[doc = "Reader of register BMCR1"] pub type R = crate::R<u32, super::BMCR1>; #[doc = "Writer for register BMCR1"] pub type W = crate::W<u32, super::BMCR1>; #[doc = "Register BMCR1 `reset()`'s with value 0"] impl crate::ResetValue for super::BMCR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `WQOS`"] pub type WQOS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WQOS`"] pub struct WQOS_W<'a> { w: &'a mut W, } impl<'a> WQOS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `WAGE`"] pub type WAGE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WAGE`"] pub struct WAGE_W<'a> { w: &'a mut W, } impl<'a> WAGE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `WPH`"] pub type WPH_R = crate::R<u8, u8>; #[d
] #[inline(always)] pub fn wbr(&self) -> WBR_R { WBR_R::new(((self.bits >> 24) & 0xff) as u8) } } impl W { #[doc = "Bits 0:3 - Weight of QoS"] #[inline(always)] pub fn wqos(&mut self) -> WQOS_W { WQOS_W { w: self } } #[doc = "Bits 4:7 - Weight of Aging"] #[inline(always)] pub fn wage(&mut self) -> WAGE_W { WAGE_W { w: self } } #[doc = "Bits 8:15 - Weight of Page Hit"] #[inline(always)] pub fn wph(&mut self) -> WPH_W { WPH_W { w: self } } #[doc = "Bits 16:23 - Weight of Read/Write switch"] #[inline(always)] pub fn wrws(&mut self) -> WRWS_W { WRWS_W { w: self } } #[doc = "Bits 24:31 - Weight of Bank Rotation"] #[inline(always)] pub fn wbr(&mut self) -> WBR_W { WBR_W { w: self } } }
oc = "Write proxy for field `WPH`"] pub struct WPH_W<'a> { w: &'a mut W, } impl<'a> WPH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8); self.w } } #[doc = "Reader of field `WRWS`"] pub type WRWS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WRWS`"] pub struct WRWS_W<'a> { w: &'a mut W, } impl<'a> WRWS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `WBR`"] pub type WBR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WBR`"] pub struct WBR_W<'a> { w: &'a mut W, } impl<'a> WBR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 24)) | (((value as u32) & 0xff) << 24); self.w } } impl R { #[doc = "Bits 0:3 - Weight of QoS"] #[inline(always)] pub fn wqos(&self) -> WQOS_R { WQOS_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - Weight of Aging"] #[inline(always)] pub fn wage(&self) -> WAGE_R { WAGE_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:15 - Weight of Page Hit"] #[inline(always)] pub fn wph(&self) -> WPH_R { WPH_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:23 - Weight of Read/Write switch"] #[inline(always)] pub fn wrws(&self) -> WRWS_R { WRWS_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 24:31 - Weight of Bank Rotation"
random
[ { "content": "/// Migrate the `lib.rs` of the PAC subscrate, adding\n\n/// our necessary header to the top of the file.\n\nfn write_lib<R: Read>(crate_path: &Path, mut src: R) {\n\n static LIB_PRELUDE: &str = r#\"#![deny(warnings)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(clippy::all)]\n\n#![no_std]\n\...
Rust
src/git.rs
jhzn/purs
574971936795c484acf3d3785c6ed6bbbc15ee13
use ansi_term::Colour::{Cyan, Green, Purple, Red}; use ansi_term::{ANSIGenericString, ANSIStrings}; use git2::{self, Repository, StatusOptions}; use std::fmt; pub struct Info { detailed: bool, head_description: Option<String>, current_action: Option<String>, index_change: usize, conflicted: usize, working_tree_modified: usize, untracked: usize, origin_ahead: usize, origin_behind: usize, } impl fmt::Display for Info { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut out = vec![]; if let Some(hash) = &self.head_description { out.push(Red.paint(format!("{}", hash))); } if self.detailed { if self.origin_ahead > 0 { out.push(Cyan.paint(format!("↑ {}", self.origin_ahead))); } if self.origin_behind > 0 { out.push(Cyan.paint(format!("↓ {}", self.origin_behind))); } if self.index_change == 0 && self.working_tree_modified == 0 && self.conflicted == 0 && self.untracked == 0 { out.push(Green.paint("✔")); } else { if self.index_change > 0 { out.push(Green.paint(format!("♦ {}", self.index_change))); } if self.conflicted > 0 { out.push(Red.paint(format!("✖ {}", self.conflicted))); } if self.working_tree_modified > 0 { out.push(ANSIGenericString::from(format!( "✚ {}", self.working_tree_modified ))); } if self.untracked > 0 { out.push(ANSIGenericString::from("…")); } } } else { if self.index_change > 0 || self.working_tree_modified > 0 || self.conflicted > 0 || self.untracked > 0 { out.push(Red.bold().paint("*")); } } if let Some(action) = &self.current_action { out.push(Purple.paint(format!(" {}", action))); } write!(f, "({})", ANSIStrings(&out).to_string()) } } pub fn get_status(r: &Repository, detailed: bool) -> Option<Info> { let (index_change, wt_change, conflicted, untracked) = count_files_statuses(r).unwrap_or((0,0,0,0)); let (ahead, behind) = get_ahead_behind(r).unwrap_or((0, 0)); Some(Info { detailed, head_description: get_head_shortname(r), current_action: get_action(r), conflicted, index_change, working_tree_modified: wt_change, untracked, origin_ahead: ahead, origin_behind: behind, }) } fn get_ahead_behind(r: &Repository) -> Option<(usize, usize)> { let head = r.head().ok()?; if !head.is_branch() { return None; } let head_name = head.shorthand()?; let head_branch = r.find_branch(head_name, git2::BranchType::Local).ok()?; let upstream = head_branch.upstream().ok()?; let head_oid = head.target()?; let upstream_oid = upstream.get().target()?; r.graph_ahead_behind(head_oid, upstream_oid).ok() } fn get_head_shortname(r: &Repository) -> Option<String> { let head = r.head().ok()?; if let Some(shorthand) = head.shorthand() { if shorthand != "HEAD" { return Some(shorthand.to_string()); } } let object = head.peel(git2::ObjectType::Commit).ok()?; let short_id = object.short_id().ok()?; Some(format!( ":{}", short_id.iter().map(|ch| *ch as char).collect::<String>() )) } fn count_files_statuses(r: &Repository) -> Option<(usize, usize, usize, usize)> { let mut opts = StatusOptions::new(); opts.include_untracked(true); fn count_files(statuses: &git2::Statuses<'_>, status: git2::Status) -> usize { statuses .iter() .filter(|entry| entry.status().intersects(status)) .count() } let statuses = r.statuses(Some(&mut opts)).ok()?; Some(( count_files( &statuses, git2::Status::INDEX_NEW | git2::Status::INDEX_MODIFIED | git2::Status::INDEX_DELETED | git2::Status::INDEX_RENAMED | git2::Status::INDEX_TYPECHANGE, ), count_files( &statuses, git2::Status::WT_MODIFIED | git2::Status::WT_DELETED | git2::Status::WT_TYPECHANGE | git2::Status::WT_RENAMED, ), count_files(&statuses, git2::Status::CONFLICTED), count_files(&statuses, git2::Status::WT_NEW), )) } fn get_action(r: &Repository) -> Option<String> { let gitdir = r.path(); for tmp in &[ gitdir.join("rebase-apply"), gitdir.join("rebase"), gitdir.join("..").join(".dotest"), ] { if tmp.join("rebasing").exists() { return Some("rebase".to_string()); } if tmp.join("applying").exists() { return Some("am".to_string()); } if tmp.exists() { return Some("am/rebase".to_string()); } } for tmp in &[ gitdir.join("rebase-merge").join("interactive"), gitdir.join(".dotest-merge").join("interactive"), ] { if tmp.exists() { return Some("rebase-i".to_string()); } } for tmp in &[gitdir.join("rebase-merge"), gitdir.join(".dotest-merge")] { if tmp.exists() { return Some("rebase-m".to_string()); } } if gitdir.join("MERGE_HEAD").exists() { return Some("merge".to_string()); } if gitdir.join("BISECT_LOG").exists() { return Some("bisect".to_string()); } if gitdir.join("CHERRY_PICK_HEAD").exists() { if gitdir.join("sequencer").exists() { return Some("cherry-seq".to_string()); } else { return Some("cherry".to_string()); } } if gitdir.join("sequencer").exists() { return Some("cherry-or-revert".to_string()); } None }
use ansi_term::Colour::{Cyan, Green, Purple, Red}; use ansi_term::{ANSIGenericString, ANSIStrings}; use git2::{self, Repository, StatusOptions}; use std::fmt; pub struct Info { detailed: bool, head_description: Option<String>, current_action: Option<String>, index_change: usize, conflicted: usize, working_tree_modified: usize, untracked: usize, origin_ahead: usize, origin_behind: usize, } impl fmt::Display for Info { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut out = vec![]; if let Some(hash) = &self.head_description { out.push(Red.paint(format!("{}", hash))); } if self.detailed { if self.origin_ahead > 0 { out.push(Cyan.paint(format!("↑ {}", self.origin_ahead))); } if self.origin_behind > 0 { out.push(Cyan.paint(format!("↓ {}", self.origin_behind))); } if self.index_change == 0 && self.working_tree_modified == 0 && self.conflicted == 0 && self.untracked == 0 { out.push(Green.paint("✔")); } else { if self.index_change > 0 { out.push(Green.paint(format!("♦ {}", self.index_change))); } if self.conflicted > 0 { out.push(Red.paint(format!("✖ {}", self.conflicted))); } if self.working_tree_modified > 0 { out.push(ANSIGenericString::from(format!( "✚ {}", self.working_tree_modified ))); } if self.untracked > 0 { out.push(ANSIGenericString::from("…")); } } } else { if self.index_change > 0 || self.working_tree_modified > 0 || self.conflicted > 0 || self.untracked > 0 { out.push(Red.bold().paint("*")); } } if let Some(action) = &self.current_action { out.push(Purple.paint(format!(" {}", action))); } write!(f, "({})", ANSIStrings(&out).to_string()) } } pub fn get_status(r: &Repository, detailed: bool) -> Option<Info> { let (index_change, wt_change, conflicted, untracked) = count_files_statuses(r).unwrap_or((0,0,0,0)); let (ahead, behind) = get_ahead_behind(r).unwrap_or((0, 0)); Some(Info { detailed, head_description: get_head_shortname(r), current_action: get_action(r), conflicted, index_change, working_tree_modified: wt_change, untracked, origin_ahead: ahead, origin_behind: behind, }) } fn get_ahead_behind(r: &Repository) -> Option<(usize, usize)> { let head = r.head().ok()?; if !head.is_branch() { return None; } let head_name = head.shorthand()?; let head_branch = r.find_branch(head_name, git2::BranchType::Local).ok()?; let upstream = head_branch.upstream().ok()?; let head_oid = head.target()?; let upstream_oid = upstream.get().target()?; r.graph_ahead_behind(head_oid, upstream_oid).ok() } fn get_head_shortname(r: &Repository) -> Option<String> { let head = r.head().ok()?; if let Some(shorthand) = head.shorthand() { if shorthand != "HEAD" { return Some(shorthand.to_string()); } } let object = head.peel(git2::ObjectType::Commit).ok()?; let short_id = object.short_id().ok()?; Some(format!( ":{}", short_id.iter().map(|ch| *ch as char).collect::<String>() )) } fn count_files_statuses(r: &Repository) -> Option<(usize, usize, usize, usize)> { let mut opts = StatusOptions::new(); opts.include_untracked(true); fn count_files(statuses: &git2::Statuses<'_>, status: git2::Status) -> usize { statuses .iter() .filter(|entry| entry.status().intersects(status)) .count() } let statuses = r.statuses(Some(&mut opts)).ok()?; Some(( count_files( &statuses, git2::Status::INDEX_NEW | git2::Status::INDEX_MODIFIED | git2::Status::INDEX_DELETED | git2::Status::INDEX_RENAMED | git2::Status::INDEX_TYPECHANGE, ), count_files( &statuses, git2::Status::WT_MODIFIED | git2::Status::WT_DELETED | git2::Status::WT_TYPECHANGE | git2::Status::WT_RENAMED, ), count_files(&statuses, git2::Status::CONFLICTED), count_files(&statuses, git2::Status::WT_NEW), )) }
fn get_action(r: &Repository) -> Option<String> { let gitdir = r.path(); for tmp in &[ gitdir.join("rebase-apply"), gitdir.join("rebase"), gitdir.join("..").join(".dotest"), ] { if tmp.join("rebasing").exists() { return Some("rebase".to_string()); } if tmp.join("applying").exists() { return Some("am".to_string()); } if tmp.exists() { return Some("am/rebase".to_string()); } } for tmp in &[ gitdir.join("rebase-merge").join("interactive"), gitdir.join(".dotest-merge").join("interactive"), ] { if tmp.exists() { return Some("rebase-i".to_string()); } } for tmp in &[gitdir.join("rebase-merge"), gitdir.join(".dotest-merge")] { if tmp.exists() { return Some("rebase-m".to_string()); } } if gitdir.join("MERGE_HEAD").exists() { return Some("merge".to_string()); } if gitdir.join("BISECT_LOG").exists() { return Some("bisect".to_string()); } if gitdir.join("CHERRY_PICK_HEAD").exists() { if gitdir.join("sequencer").exists() { return Some("cherry-seq".to_string()); } else { return Some("cherry".to_string()); } } if gitdir.join("sequencer").exists() { return Some("cherry-or-revert".to_string()); } None }
function_block-full_function
[ { "content": "pub fn cli_arguments<'a>() -> App<'a, 'a> {\n\n let v = &[\n\n Arg::with_name(\"git-detailed\")\n\n .long(\"git-detailed\")\n\n .help(\"Prints detailed git status\"),\n\n Arg::with_name(\"shortened-path\")\n\n .long(\"shortened-path\")\n\n ...
Rust
src/app/widgets/tag.rs
AngelOfSol/art-organize
ed4ad1d936a585a80e9f98b672d7875edb553f5d
use db::{ commands::{AttachCategory, EditTag}, Db, Tag, TagId, }; use imgui::{im_str, Selectable, StyleColor, Ui}; use super::{category, combo_box, confirm::confirm_delete_popup, date}; pub fn view(tag_id: TagId, db: &Db, ui: &Ui<'_>) { let tag = &db[tag_id]; ui.text_wrapped(&im_str!("Name: {}", tag.name)); ui.text_wrapped(&im_str!("Description: {}", tag.description)); date::view("Date Added", &tag.added, ui); if let Some(category_id) = db.category_for_tag(tag_id) { category::link(ui, &db[category_id]); } } pub enum EditTagResponse { None, Delete, Edit(EditTag), AttachCategory(AttachCategory), } pub fn edit(tag_id: TagId, db: &Db, ui: &Ui<'_>) -> EditTagResponse { let tag = &db[tag_id]; let mut buf = tag.name.clone().into(); ui.input_text(im_str!("Name"), &mut buf) .resize_buffer(true) .build(); if ui.is_item_deactivated_after_edit() { return EditTagResponse::Edit(EditTag { id: tag_id, data: Tag { name: buf.to_string(), ..tag.clone() }, }); } let mut buf = tag.description.clone().into(); ui.input_text_multiline(im_str!("Description"), &mut buf, [0.0, 100.0]) .resize_buffer(true) .build(); if ui.is_item_deactivated_after_edit() { return EditTagResponse::Edit(EditTag { id: tag_id, data: Tag { description: buf.to_string(), ..tag.clone() }, }); } if let Some(added) = date::edit(im_str!("Date Added"), &tag.added, ui) { return EditTagResponse::Edit(EditTag { id: tag_id, data: Tag { added, ..tag.clone() }, }); } let x = std::iter::once(None).chain(db.categories().map(|(id, _)| Some(id))); if let Some(new_id) = combo_box( ui, &im_str!("Category"), x, &db.category_for_tag(tag_id), |id| match id { Some(category_id) => im_str!("{}", &db[category_id].name), None => Default::default(), }, ) { return EditTagResponse::AttachCategory(AttachCategory { src: tag_id, dest: new_id, }); } if ui.button(im_str!("Delete")) { ui.open_popup(im_str!("Confirm Delete")); } if confirm_delete_popup(ui) { EditTagResponse::Delete } else { EditTagResponse::None } } pub enum ItemViewResponse { None, Add, AddNegated, Open, } pub fn item_view(ui: &Ui, db: &Db, tag_id: TagId) -> ItemViewResponse { item_view_with_count(ui, db, tag_id, db.pieces_for_tag(tag_id).count()) } pub fn item_view_with_count(ui: &Ui, db: &Db, tag_id: TagId, count: usize) -> ItemViewResponse { let tag = &db[tag_id]; let button_size = [ ui.calc_text_size(&im_str!("+"))[0], ui.text_line_height_with_spacing(), ]; let label = im_str!("{}", tag.name); let _id = ui.push_id(&label); if Selectable::new(im_str!("+")).size(button_size).build(ui) { return ItemViewResponse::Add; } if ui.is_item_hovered() { ui.tooltip_text(&im_str!("Unimplemented.")); } ui.same_line(); if Selectable::new(im_str!("!")).size(button_size).build(ui) { return ItemViewResponse::AddNegated; } if ui.is_item_hovered() { ui.tooltip_text(&im_str!("Unimplemented.")); } ui.same_line(); let result = { let color = if let Some(category_id) = db.category_for_tag(tag_id) { db[category_id].raw_color() } else { ui.style_color(StyleColor::Text) }; let _color = ui.push_style_color(StyleColor::Text, color); if Selectable::new(&label) .size([0.0, ui.text_line_height_with_spacing()]) .build(ui) { ItemViewResponse::Open } else { ItemViewResponse::None } }; if ui.is_item_hovered() && tag.description.chars().any(|c| !c.is_whitespace()) { ui.tooltip(|| ui.text(&im_str!("{}", tag.description))); } ui.same_line(); ui.text_colored([0.4, 0.4, 0.4, 1.0], &im_str!("{}", count)); result } pub enum InPieceViewResponse { None, Open, Remove, } pub fn in_piece_view(ui: &Ui, db: &Db, tag_id: TagId) -> InPieceViewResponse { let tag = &db[tag_id]; let button_size = [ui.text_line_height_with_spacing(); 2]; let label = im_str!("{}", tag.name); let _id = ui.push_id(&label); if Selectable::new(im_str!("-")).size(button_size).build(ui) { return InPieceViewResponse::Remove; } ui.same_line(); let color = if let Some(category_id) = db.category_for_tag(tag_id) { db[category_id].raw_color() } else { ui.style_color(StyleColor::Text) }; let result = { let _color = ui.push_style_color(StyleColor::Text, color); if Selectable::new(&label).build(ui) { InPieceViewResponse::Open } else { InPieceViewResponse::None } }; if ui.is_item_hovered() && tag.description.chars().any(|c| !c.is_whitespace()) { ui.tooltip(|| ui.text(&im_str!("{}", tag.description))); } result }
use db::{ commands::{AttachCategory, EditTag}, Db, Tag, TagId, }; use imgui::{im_str, Selectable, StyleColor, Ui}; use super::{category, combo_box, confirm::confirm_delete_popup, date}; pub fn view(tag_id: TagId, db: &Db, ui: &Ui<'_>) { let tag = &db[tag_id]; ui.text_wrapped(&im_str!("Name: {}", tag.name)); ui.text_wrapped(&im_str!("Description: {}", tag.description)); date::view("Date Added", &tag.added, ui); if let Some(category_id) = db.category_for_tag(tag_id) { category::link(ui, &db[category_id]); } } pub enum EditTagResponse { None, Delete, Edit(EditTag), AttachCategory(AttachCategory), } pub fn edit(tag_id: TagId, db: &Db, ui: &Ui<'_>) -> EditTagResponse { let tag = &db[tag_id]; let mut buf = tag.name.clone().into(); ui.input_text(im_str!("Name"), &mut buf) .resize_buffer(true) .build(); if ui.is_item_deactivated_after_edit() { return EditTagResponse::Edit(EditTag { id: tag_id, data: Tag { name: buf.to_string(), ..tag.clone() }, }); } let mut buf = tag.description.clone().into(); ui.input_text_multiline(im_str!("Description"), &mut buf, [0.0, 100.0]) .resize_buffer(true) .build(); if ui.is_item_deactivated_after_edit() { return EditTagResponse::Edit(EditTag { id: tag_id, data: Tag { description: buf.to_string(), ..tag.clone() }, }); } if let Some(added) = date::edit(im_str!("Date Added"), &tag.added, ui) { return EditTagResponse::Edit(EditTag { id: tag_id, data: Tag { added, ..tag.clone() }, }); } let x = std::iter::once(None).chain(db.categories().map(|(id, _)| Some(id))); if let Some(new_id) =
{ return EditTagResponse::AttachCategory(AttachCategory { src: tag_id, dest: new_id, }); } if ui.button(im_str!("Delete")) { ui.open_popup(im_str!("Confirm Delete")); } if confirm_delete_popup(ui) { EditTagResponse::Delete } else { EditTagResponse::None } } pub enum ItemViewResponse { None, Add, AddNegated, Open, } pub fn item_view(ui: &Ui, db: &Db, tag_id: TagId) -> ItemViewResponse { item_view_with_count(ui, db, tag_id, db.pieces_for_tag(tag_id).count()) } pub fn item_view_with_count(ui: &Ui, db: &Db, tag_id: TagId, count: usize) -> ItemViewResponse { let tag = &db[tag_id]; let button_size = [ ui.calc_text_size(&im_str!("+"))[0], ui.text_line_height_with_spacing(), ]; let label = im_str!("{}", tag.name); let _id = ui.push_id(&label); if Selectable::new(im_str!("+")).size(button_size).build(ui) { return ItemViewResponse::Add; } if ui.is_item_hovered() { ui.tooltip_text(&im_str!("Unimplemented.")); } ui.same_line(); if Selectable::new(im_str!("!")).size(button_size).build(ui) { return ItemViewResponse::AddNegated; } if ui.is_item_hovered() { ui.tooltip_text(&im_str!("Unimplemented.")); } ui.same_line(); let result = { let color = if let Some(category_id) = db.category_for_tag(tag_id) { db[category_id].raw_color() } else { ui.style_color(StyleColor::Text) }; let _color = ui.push_style_color(StyleColor::Text, color); if Selectable::new(&label) .size([0.0, ui.text_line_height_with_spacing()]) .build(ui) { ItemViewResponse::Open } else { ItemViewResponse::None } }; if ui.is_item_hovered() && tag.description.chars().any(|c| !c.is_whitespace()) { ui.tooltip(|| ui.text(&im_str!("{}", tag.description))); } ui.same_line(); ui.text_colored([0.4, 0.4, 0.4, 1.0], &im_str!("{}", count)); result } pub enum InPieceViewResponse { None, Open, Remove, } pub fn in_piece_view(ui: &Ui, db: &Db, tag_id: TagId) -> InPieceViewResponse { let tag = &db[tag_id]; let button_size = [ui.text_line_height_with_spacing(); 2]; let label = im_str!("{}", tag.name); let _id = ui.push_id(&label); if Selectable::new(im_str!("-")).size(button_size).build(ui) { return InPieceViewResponse::Remove; } ui.same_line(); let color = if let Some(category_id) = db.category_for_tag(tag_id) { db[category_id].raw_color() } else { ui.style_color(StyleColor::Text) }; let result = { let _color = ui.push_style_color(StyleColor::Text, color); if Selectable::new(&label).build(ui) { InPieceViewResponse::Open } else { InPieceViewResponse::None } }; if ui.is_item_hovered() && tag.description.chars().any(|c| !c.is_whitespace()) { ui.tooltip(|| ui.text(&im_str!("{}", tag.description))); } result }
combo_box( ui, &im_str!("Category"), x, &db.category_for_tag(tag_id), |id| match id { Some(category_id) => im_str!("{}", &db[category_id].name), None => Default::default(), }, )
call_expression
[ { "content": "pub fn view_tags(piece_id: PieceId, db: &Db, ui: &Ui<'_>) -> Option<(TagId, ItemViewResponse)> {\n\n for category_id in db\n\n .tags_for_piece(piece_id)\n\n .flat_map(|tag| db.category_for_tag(tag))\n\n .sorted_by_key(|category_id| &db[category_id].name)\n\n .dedup()...
Rust
src/writer/string_buffer.rs
efharkin/swc2dot
f08a38e7ae18344c4b9da8730ada01050ac2c496
#[derive(Clone, Debug)] pub struct StringBuffer { buf: String, empty_buf: String, has_been_written_to: bool, indent_level: u8, line_width: u32, cursor_position: u32, } impl StringBuffer { pub fn new(leading_newline: bool, indent: Indent, capacity: usize) -> StringBuffer { let mut buf = String::with_capacity((32 + INDENT_SIZE * indent.first) as usize + capacity); if leading_newline { buf.push_str("\n"); } buf.push_str(&get_indent(indent.first)); let string_buffer = StringBuffer { buf: buf, empty_buf: "".to_string(), has_been_written_to: false, indent_level: indent.main, line_width: 80, cursor_position: (INDENT_SIZE * indent.first) as u32, }; string_buffer.assert_cursor_is_within_line(); return string_buffer; } pub fn push_str(&mut self, string: &str) { self.has_been_written_to = true; self.weak_push_str(string); } pub fn newline(&mut self) { self.buf.push_str("\n"); self.buf.push_str(&get_indent(self.indent_level)); self.cursor_position = self.newline_cursor_position(); self.assert_cursor_is_within_line(); } pub fn weak_push_str(&mut self, string: &str) { if (string.len() > self.remaining_space_on_line() as usize) & (self.cursor_position > self.newline_cursor_position()) | (self.remaining_space_on_line() <= 0) { if !string.starts_with("\n") { self.newline(); } } self.buf.push_str(string); self.cursor_position += string.len() as u32; } pub fn to_string(&self) -> String { if self.has_been_written_to { let mut result = self.buf.clone(); result.shrink_to_fit(); result } else { self.empty_buf.clone() } } pub fn len(&self) -> usize { if self.has_been_written_to { self.buf.len() } else { self.empty_buf.len() } } #[inline] fn newline_cursor_position(&self) -> u32 { (self.indent_level * INDENT_SIZE) as u32 } #[inline] fn remaining_space_on_line(&self) -> i32 { (self.line_width as i64 - self.cursor_position as i64) as i32 } #[inline] fn assert_cursor_is_within_line(&self) { assert!( self.cursor_position <= self.line_width, "Cursor position {} greater than line width {}.", self.cursor_position, self.line_width ); } } impl AsRef<String> for StringBuffer { fn as_ref(&self) -> &String { if self.has_been_written_to { &self.buf } else { &self.empty_buf } } } impl AsRef<str> for StringBuffer { fn as_ref(&self) -> &str { if self.has_been_written_to { &self.buf } else { &self.empty_buf } } } #[cfg(test)] mod string_buffer_tests { use super::*; #[test] fn returns_empty_if_push_str_is_never_called() { let string = StringBuffer::new(true, Indent::flat(5), 32); assert_eq!("".to_string(), string.to_string()) } #[test] fn returns_indented_if_push_str_is_called() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.push_str("something"); assert_eq!(" something".to_string(), string.to_string()); } #[test] fn returns_newline_if_push_str_is_called() { let mut string = StringBuffer::new(true, Indent::flat(0), 32); string.push_str("something"); assert_eq!("\nsomething".to_string(), string.to_string()); } fn compare_str_ref(a: &str, b: &str) -> bool { a == b } #[test] fn asref_str_empty_if_push_str_is_never_called() { let string = StringBuffer::new(true, Indent::flat(5), 32); if !compare_str_ref(string.as_ref(), "") { panic!("Failed"); } } #[test] fn asref_str_indented_if_push_str_is_called() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.push_str("something"); if !compare_str_ref(string.as_ref(), " something") { panic!("Failed"); } } #[test] fn asref_str_newline_if_push_str_is_called() { let mut string = StringBuffer::new(true, Indent::flat(0), 32); string.push_str("something"); if !compare_str_ref(string.as_ref(), "\nsomething") { panic!("Failed"); } } #[test] fn hard_wrap_short_line_without_indent() { let mut string = StringBuffer::new(false, Indent::flat(0), 32); string.line_width = 4; string.push_str("123"); string.push_str("456"); assert_eq!("123\n456".to_string(), string.to_string()); } #[test] fn hard_wrap_full_line_without_indent() { let mut string = StringBuffer::new(false, Indent::flat(0), 32); string.line_width = 4; string.push_str("1234"); string.push_str("5678"); assert_eq!("1234\n5678".to_string(), string.to_string()); } #[test] fn hard_wrap_short_line_with_indent() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.line_width = 8; string.push_str("123"); string.push_str("456"); assert_eq!(" 123\n 456".to_string(), string.to_string()); } #[test] fn hard_wrap_full_line_with_indent() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.line_width = 8; string.push_str("1234"); string.push_str("5678"); assert_eq!(" 1234\n 5678".to_string(), string.to_string()); } #[test] fn hard_wrap_long_line_without_indent() { let mut string = StringBuffer::new(false, Indent::flat(0), 32); string.line_width = 4; string.push_str("12345"); string.push_str("678"); assert_eq!("12345\n678".to_string(), string.to_string()); } #[test] fn hard_wrap_long_second_line_with_indent() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.line_width = 8; string.push_str("123"); string.push_str("456789"); string.push_str("0"); assert_eq!(" 123\n 456789\n 0".to_string(), string.to_string()); } } /* pub enum Indent { /// Set the indent of the first line to a different level than subsequent lines. /// /// `AbsoluteFirstLine(first_line_level, subsequent_lines)` AbsoluteFirstLine(u8, u8), /// Set the indent level of the first line relative to subsequent lines. /// /// `RelativeFirstLine(relative_first_line_level, subsequent_lines)` /// /// # Note /// /// `RelativeFirstLine(-1, 1)` is equivalent to `AbsoluteFirstLine(0, 1)`. RelativeFirstLine(i8, u8), /// All lines are indented to the same level. Flat(u8) } */ #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Indent { pub first: u8, pub main: u8 } impl Indent { pub fn absolute_first_line(first_line_level: u8, main_indent_level: u8) -> Indent { Indent{ first: first_line_level, main: main_indent_level } } pub fn relative_first_line(first_line_level: i8, main_indent_level: u8) -> Indent { if (first_line_level as i32) + (main_indent_level as i32) < 0 { panic!( "Minimum allowed relative first line indent level for main indent level {} is -{}, got {}", main_indent_level, main_indent_level, first_line_level ); } Indent { first: (main_indent_level as i16 + first_line_level as i16) as u8, main: main_indent_level } } pub fn flat(indent_level: u8) -> Indent { Indent { first: indent_level, main: indent_level } } pub fn zero() -> Indent { Indent { first: 0, main: 0 } } } #[cfg(test)] mod indent_tests { use super::*; #[test] fn zero() { let indent = Indent::zero(); assert_eq!(indent.first, 0); assert_eq!(indent.main, 0); } #[test] fn flat() { for indent_level in [0, 4, 89, 223].iter() { let indent = Indent::flat(*indent_level); assert_eq!(indent.first, *indent_level); assert_eq!(indent.main, *indent_level); } } #[test] fn absolute_first_line() { for (first_indent_level, main_indent_level) in [(0, 0), (0, 8), (43, 0), (76, 20)].iter() { let indent = Indent::absolute_first_line(*first_indent_level, *main_indent_level); assert_eq!(indent.first, *first_indent_level); assert_eq!(indent.main, *main_indent_level); } } #[test] fn relative_first_line() { for (first_indent_level, main_indent_level) in [(0, 0), (-2, 5), (7, 9)].iter() { let indent = Indent::relative_first_line(*first_indent_level, *main_indent_level); assert_eq!( indent.first, (*first_indent_level + (*main_indent_level as i8)) as u8 ); assert_eq!(indent.main, *main_indent_level as u8); } } #[test] #[should_panic] fn invalid_relative_first_line_panics() { let indent = Indent::relative_first_line(-2, 1); println!("Expected invalid relative indent with negative first line to panic, got {:?} indent instead", indent); } } static INDENT_SIZE: u8 = 4; pub fn get_indent(level: u8) -> String { let mut buf = String::with_capacity((level * INDENT_SIZE) as usize); for _ in 0..level { buf.push_str(" "); } return buf; }
#[derive(Clone, Debug)] pub struct StringBuffer { buf: String, empty_buf: String, has_been_written_to: bool, indent_level: u8, line_width: u32, cursor_position: u32, } impl StringBuffer { pub fn new(leading_newline: bool, indent: Indent, capacity: usize) -> StringBuffer { let mut buf = String::with_capacity((32 + INDENT_SIZE * indent.first) as usize + capacity); if leading_newline { buf.push_str("\n"); } buf.push_str(&get_indent(indent.first)); let string_buffer = StringBuffer { buf: buf, empty_buf: "".to_string(), has_been_written_to: false, indent_level: indent.main, line_width: 80, cursor_position: (INDENT_SIZE * indent.first) as u32, }; string_buffer.assert_cursor_is_within_line(); return string_buffer; } pub fn push_str(&mut self, string: &str) { self.has_been_written_to = true; self.weak_push_str(string); } pub fn newline(&mut self) { self.buf.push_str("\n"); self.buf.push_str(&get_indent(self.indent_level)); self.cursor_position = self.newline_cursor_position(); self.assert_cursor_is_within_line(); } pub fn weak_push_str(&mut self, string: &str) { if (string.len() > self.remaining_space_on_line() as usize) & (self.cursor_position > self.newline_cursor_position()) | (self.remaining_space_on_line() <= 0) { if !string.starts_with("\n") { self.newline(); } } self.buf.push_str(string); self.cursor_position += string.len() as u32; } pub fn to_string(&self) -> String { if self.has_been_written_to { let mut result = self.buf.clone(); result.shrink_to_fit(); result } else { self.empty_buf.clone() } } pub fn len(&self) -> usize { if self.has_been_written_to { self.buf.len() } else { self.empty_buf.len() } } #[inline] fn newline_cursor_position(&self) -> u32 { (self.indent_level * INDENT_SIZE) as u32 } #[inline] fn remaining_space_on_line(&self) -> i32 { (self.line_width as i64 - self.cursor_position as i64) as i32 } #[inline] fn assert_cursor_is_within_line(&self) { assert!( self.cursor_position <= self.line_width, "Cursor position {} greater than line width {}.", self.cursor_position, self.line_width ); } } impl AsRef<String> for StringBuffer { fn as_ref(&self) -> &String { if self.has_been_written_to { &self.buf } else { &self.empty_buf } } } impl AsRef<str> for StringBuffer { fn as_ref(&self) -> &str { if self.has_been_written_to { &self.buf } else { &self.empty_buf } } } #[cfg(test)] mod string_buffer_tests { use super::*; #[test] fn returns_empty_if_push_str_is_never_called() { let string = StringBuffer::new(true, Indent::flat(5), 32); assert_eq!("".to_string(), string.to_string()) } #[test] fn returns_indented_if_push_str_is_called() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.push_str("something"); assert_eq!(" something".to_string(), string.to_string()); } #[test] fn returns_newline_if_push_str_is_called() { let mut string = StringBuffer::new(true, Indent::flat(0), 32); string.push_str("something"); assert_eq!("\nsomething".to_string(), string.to_string()); } fn compare_str_ref(a: &str, b: &str) -> bool { a == b } #[test] fn asref_str_empty_if_push_str_is_never_called() { let string = StringBuffer::new(true, Indent::flat(5), 32); if !compare_str_ref(string.as_ref(), "") { panic!("Failed"); } } #[test] fn asref_str_indented_if_push_str_is_called() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.push_str("something"); if !compare_str_ref(string.as_ref(), " something") { panic!("Failed"); } } #[test] fn asref_str_newline_if_push_str_is_called() { let mut string = StringBuffer::new(true, Indent::flat(0), 32); string.push_str("something"); if !compare_str_ref(string.as_ref(), "\nsomething") { panic!("Failed"); } } #[test] fn hard_wrap_short_line_without_indent() { let mut string = StringBuffer::new(false, Indent::flat(0), 32); string.line_width = 4; string.push_str("123"); string.push_str("456"); assert_eq!("123\n456".to_string(), string.to_string()); } #[test] fn hard_wrap_full_line_without_indent() { let mut string = StringBuffer::new(false, Indent::flat(0), 32); string.line_width = 4; string.push_str("1234"); string.push_str("5678"); assert_eq!("1234\n5678".to_string(), string.to_string()); } #[test] fn hard_wrap_short_line_with_indent() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.line_width = 8; string.push_str("123"); string.push_str("456"); assert_eq!(" 123\n 456".to_string(), string.to_string()); } #[test] fn hard_wrap_full_line_with_indent() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.line_width = 8; string.push_str("1234"); string.push_str("5678"); assert_eq!(" 1234\n 5678".to_string(), string.to_string()); } #[test] fn hard_wrap_long_line_without_indent() { let mut string = StringBuffer::new(false, Inden
} #[test] fn hard_wrap_long_second_line_with_indent() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.line_width = 8; string.push_str("123"); string.push_str("456789"); string.push_str("0"); assert_eq!(" 123\n 456789\n 0".to_string(), string.to_string()); } } /* pub enum Indent { /// Set the indent of the first line to a different level than subsequent lines. /// /// `AbsoluteFirstLine(first_line_level, subsequent_lines)` AbsoluteFirstLine(u8, u8), /// Set the indent level of the first line relative to subsequent lines. /// /// `RelativeFirstLine(relative_first_line_level, subsequent_lines)` /// /// # Note /// /// `RelativeFirstLine(-1, 1)` is equivalent to `AbsoluteFirstLine(0, 1)`. RelativeFirstLine(i8, u8), /// All lines are indented to the same level. Flat(u8) } */ #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Indent { pub first: u8, pub main: u8 } impl Indent { pub fn absolute_first_line(first_line_level: u8, main_indent_level: u8) -> Indent { Indent{ first: first_line_level, main: main_indent_level } } pub fn relative_first_line(first_line_level: i8, main_indent_level: u8) -> Indent { if (first_line_level as i32) + (main_indent_level as i32) < 0 { panic!( "Minimum allowed relative first line indent level for main indent level {} is -{}, got {}", main_indent_level, main_indent_level, first_line_level ); } Indent { first: (main_indent_level as i16 + first_line_level as i16) as u8, main: main_indent_level } } pub fn flat(indent_level: u8) -> Indent { Indent { first: indent_level, main: indent_level } } pub fn zero() -> Indent { Indent { first: 0, main: 0 } } } #[cfg(test)] mod indent_tests { use super::*; #[test] fn zero() { let indent = Indent::zero(); assert_eq!(indent.first, 0); assert_eq!(indent.main, 0); } #[test] fn flat() { for indent_level in [0, 4, 89, 223].iter() { let indent = Indent::flat(*indent_level); assert_eq!(indent.first, *indent_level); assert_eq!(indent.main, *indent_level); } } #[test] fn absolute_first_line() { for (first_indent_level, main_indent_level) in [(0, 0), (0, 8), (43, 0), (76, 20)].iter() { let indent = Indent::absolute_first_line(*first_indent_level, *main_indent_level); assert_eq!(indent.first, *first_indent_level); assert_eq!(indent.main, *main_indent_level); } } #[test] fn relative_first_line() { for (first_indent_level, main_indent_level) in [(0, 0), (-2, 5), (7, 9)].iter() { let indent = Indent::relative_first_line(*first_indent_level, *main_indent_level); assert_eq!( indent.first, (*first_indent_level + (*main_indent_level as i8)) as u8 ); assert_eq!(indent.main, *main_indent_level as u8); } } #[test] #[should_panic] fn invalid_relative_first_line_panics() { let indent = Indent::relative_first_line(-2, 1); println!("Expected invalid relative indent with negative first line to panic, got {:?} indent instead", indent); } } static INDENT_SIZE: u8 = 4; pub fn get_indent(level: u8) -> String { let mut buf = String::with_capacity((level * INDENT_SIZE) as usize); for _ in 0..level { buf.push_str(" "); } return buf; }
t::flat(0), 32); string.line_width = 4; string.push_str("12345"); string.push_str("678"); assert_eq!("12345\n678".to_string(), string.to_string());
function_block-random_span
[ { "content": "fn parse_line(line: String) -> Result<SWCLine, String> {\n\n let trimmed_line = line.trim(); // Remove leading and trailing whitespace.\n\n\n\n let parse_result: SWCLine;\n\n if trimmed_line.is_empty() {\n\n // Line is empty.\n\n parse_result = SWCLine::Blank;\n\n } else...
Rust
src/lib.rs
kyclark/excel2txt-rust
a573b3fa0cd5017d80866b1365f8edb2875c3cb8
extern crate clap; extern crate csv; extern crate regex; extern crate tempdir; use calamine::{open_workbook, Reader, Xlsx}; use clap::{App, Arg}; use csv::WriterBuilder; use regex::Regex; use std::error::Error; use std::fs::{self, DirBuilder}; use std::path::{Path, PathBuf}; type MyResult<T> = Result<T, Box<dyn Error>>; #[derive(Debug)] pub struct Config { files: Vec<String>, outdir: String, delimiter: u8, normalize: bool, make_dirs: bool, } pub fn get_args() -> MyResult<Config> { let matches = App::new("excel2txt") .version("0.1.0") .author("Ken Youens-Clark <kyclark@gmail.com>") .about("Export Excel workbooks into delimited text files") .arg( Arg::with_name("file") .short("f") .long("file") .value_name("FILE") .help("File input") .required(true) .min_values(1), ) .arg( Arg::with_name("outdir") .short("o") .long("outdir") .value_name("DIR") .default_value("out") .help("Output directory"), ) .arg( Arg::with_name("delimiter") .short("d") .long("delimiter") .value_name("DELIM") .default_value("\t") .help("Delimiter for output files"), ) .arg( Arg::with_name("normalize") .short("n") .long("normalize") .help("Normalize headers"), ) .arg( Arg::with_name("make_dirs") .short("m") .long("mkdirs") .help("Make output directory for each input file"), ) .get_matches(); let files = matches.values_of_lossy("file").unwrap(); let bad: Vec<String> = files.iter().cloned().filter(|f| !is_file(f)).collect(); if !bad.is_empty() { let msg = format!( "Invalid file{}: {}", if bad.len() == 1 { "" } else { "s" }, bad.join(", ") ); return Err(From::from(msg)); } Ok(Config { files: files, outdir: matches.value_of("outdir").unwrap().to_string(), delimiter: *matches .value_of("delimiter") .unwrap() .as_bytes() .first() .unwrap(), normalize: matches.is_present("normalize"), make_dirs: matches.is_present("make_dirs"), }) } pub fn run(config: Config) -> MyResult<()> { for (fnum, file) in config.files.into_iter().enumerate() { let path = Path::new(&file); let basename = path.file_stem().expect("basename"); let stem = normalize(&basename.to_string_lossy().to_string()); println!("{}: {}", fnum + 1, basename.to_string_lossy()); let mut out_dir = PathBuf::from(&config.outdir); if config.make_dirs { out_dir.push(&stem) } if !out_dir.is_dir() { DirBuilder::new().recursive(true).create(&out_dir)?; } let mut excel: Xlsx<_> = open_workbook(file)?; let sheets = excel.sheet_names().to_owned(); for sheet in sheets { let ext = if config.delimiter == 44 { "csv" } else { "txt" }; let out_file = format!("{}__{}.{}", &stem, normalize(&sheet), ext); let out_path = &out_dir.join(out_file); let mut wtr = WriterBuilder::new() .delimiter(config.delimiter) .from_path(out_path)?; println!("\tSheet '{}' -> '{}'", sheet, out_path.display()); if let Some(Ok(r)) = excel.worksheet_range(&sheet) { for (rnum, row) in r.rows().enumerate() { let vals = row .into_iter() .map(|f| format!("{}", f)) .map(|f| if rnum == 0 { normalize(&f) } else { f }) .collect::<Vec<String>>(); wtr.write_record(&vals)?; } } wtr.flush()?; } } Ok(()) } fn normalize(val: &String) -> String { let mut new = val.to_string(); let camel = Regex::new(r"(.*)([a-z])([A-Z].*)").unwrap(); loop { if let Some(cap) = camel.captures(&new) { new = format!("{}{}_{}", &cap[1], &cap[2], &cap[3]); } else { break; } } let spaces = Regex::new(r"[\s]+").unwrap(); let non_alphanum = Regex::new(r"[^a-z0-9_]").unwrap(); let mult_underbar = Regex::new(r"[_]+").unwrap(); new = new.to_ascii_lowercase(); new = spaces.replace_all(&new.to_string(), "_").to_string(); new = non_alphanum.replace_all(&new.to_string(), "").to_string(); mult_underbar.replace_all(&new.to_string(), "_").to_string() } fn is_file(path: &String) -> bool { if let Ok(meta) = fs::metadata(path) { return meta.is_file(); } else { return false; } } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; use tempdir::TempDir; #[test] fn test_normalize() { assert_eq!(normalize(&"".to_string()), ""); assert_eq!(normalize(&"ABC".to_string()), "abc"); assert_eq!(normalize(&"ABC DEF".to_string()), "abc_def"); assert_eq!(normalize(&"foo-b*!a,r".to_string()), "foobar"); assert_eq!(normalize(&"Foo Bar".to_string()), "foo_bar"); assert_eq!(normalize(&"Foo / Bar".to_string()), "foo_bar"); assert_eq!(normalize(&"Foo (Bar)".to_string()), "foo_bar"); assert_eq!(normalize(&"FooBarBAZ".to_string()), "foo_bar_baz"); } #[test] fn test_1() { let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let file = manifest_dir.join(PathBuf::from("tests/test1.xlsx")); if let Ok(tmp_dir) = TempDir::new("test") { let outdir = &tmp_dir.path().display().to_string(); let conf = Config { files: vec![file.display().to_string()], outdir: outdir.to_string(), delimiter: 9, normalize: false, make_dirs: false, }; let _res = match run(conf) { Ok(_) => { let expected_dir = PathBuf::from(outdir); assert!(expected_dir.is_dir()); let expected_file = expected_dir.join("test1__sheet1.txt"); assert!(expected_file.is_file()); let contents = fs::read_to_string(expected_file).ok().unwrap(); let lines: Vec<&str> = contents.split("\n").collect(); assert_eq!(lines[0], "name\trank\tserial_number"); assert_eq!(lines[1], "Ed\tCaptain\t12345"); assert_eq!(lines[2], "Jorge\tMajor\t98765"); } Err(x) => panic!("{:?}", x), }; } } #[test] fn test_2() { let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let file = manifest_dir.join(PathBuf::from("tests/Test 2.xlsx")); if let Ok(tmp_dir) = TempDir::new("test") { let outdir = &tmp_dir.path().display().to_string(); let conf = Config { files: vec![file.display().to_string()], outdir: outdir.to_string(), delimiter: 44, normalize: true, make_dirs: true, }; let _res = match run(conf) { Ok(_) => { let expected_dir = PathBuf::from(tmp_dir.path().join("test_2")); assert!(expected_dir.is_dir()); let expected_file = expected_dir.join("test_2__sheet1.csv"); assert!(expected_file.is_file()); let contents = fs::read_to_string(expected_file).ok().unwrap(); let lines: Vec<&str> = contents.split("\n").collect(); assert_eq!(lines[0], "ice_cream_flavor,peoples_rank"); assert_eq!(lines[1], "chocolate,1"); assert_eq!(lines[2], "vanilla,2"); assert_eq!(lines[3], "stravberry,3"); } Err(x) => panic!("{:?}", x), }; } } }
extern crate clap; extern crate csv; extern crate regex; extern crate tempdir; use calamine::{open_workbook, Reader, Xlsx}; use clap::{App, Arg}; use csv::WriterBuilder; use regex::Regex; use std::error::Error; use std::fs::{self, DirBuilder}; use std::path::{Path, PathBuf}; type MyResult<T> = Result<T, Box<dyn Error>>; #[derive(Debug)] pub struct Config { files: Vec<String>, outdir: String, delimiter: u8, normalize: bool, make_dirs: bool, } pub fn get_args() -> MyResult<Config> { let matches = App::new("excel2txt") .version("0.1.0") .author("Ken Youens-Clark <kyclark@gmail.com>") .about("Export Excel workbooks into delimited text files") .arg( Arg::with_name("file") .short("f") .long("file") .value_name("FILE") .help("File input") .required(true) .min_values(1), ) .arg( Arg::with_name("outdir") .short("o") .long("outdir") .value_name("DIR") .default_value("out") .help("Output directory"), ) .arg( Arg::with_name("delimiter") .short("d") .long("delimiter") .value_name("DELIM") .default_value("\t") .help("Delimiter for output files"), ) .arg( Arg::with_name("normalize") .short("n") .long("normalize") .help("Normalize headers"), ) .arg( Arg::with_name("make_dirs") .short("m") .long("mkdirs") .help("Make output directory for each input file"), ) .get_matches(); let files = matches.values_of_lossy("file").unwrap(); let bad: Vec<String> = files.iter().cloned().filter(|f| !is_file(f)).collect(); if !bad.is_empty() { let msg = format!( "Invalid file{}: {}", if bad.len() == 1 { "" } else { "s" }, bad.join(", ") ); return Err(From::from(msg)); } Ok(Config { files: files, outdir: matches.value_of("outdir").unwrap().to_string(), delimiter: *matches .value_of("delimiter") .unwrap() .as_bytes() .first() .unwrap(), normalize: matches.is_present("normalize"), make_dirs: matches.is_present("make_dirs"), }) } pub fn run(config: Config) -> MyResult<()> { for (fnum, file) in config.files.into_iter().enumerate() { let path = Path::new(&file); let basename = path.file_stem().expect("basename"); let stem = normalize(&basename.to_string_lossy().to_string()); println!("{}: {}", fnum + 1, basename.to_string_lossy()); let mut out_dir = PathBuf::from(&config.outdir); if config.make_dirs { out_dir.push(&stem) } if !out_dir.is_dir() { DirBuilder::new().recursive(true).create(&out_dir)?; } let mut excel: Xlsx<_> = open_workbook(file)?; let sheets = excel.sheet_names().to_owned(); for sheet in sheets { let ext = if config.delimiter == 44 { "csv" } else { "txt" }; let out_file = format!("{}__{}.{}", &stem, normalize(&sheet), ext); let out_path = &out_dir.join(out_file); let mut wtr = WriterBuilder::new() .delimiter(config.delimiter) .from_path(out_path)?; println!("\tSheet '{}' -> '{}'", sheet, out_path.display()); if let Some(Ok(r)) = excel.worksheet_range(&sheet) { for (rnum, row) in r.rows().enumerate() { let vals = row .into_iter() .map(|f| format!("{}", f)) .map(|f| if rnum == 0 { normalize(&f) } else { f }) .collect::<Vec<String>>(); wtr.write_record(&vals)?; } } wtr.flush()?; } } Ok(()) } fn normalize(val: &String) -> String { let mut new = val.to_string(); let camel = Regex::new(r"(.*)([a-z])([A-Z].*)").unwrap(); loop { if let Some(cap) = camel.captures(&new) { new = format!("{}{}_{}", &cap[1], &cap[2], &cap[3]); } else { break; } } let spaces = Regex::new(r"[\s]+").unwrap(); let non_alphanum = Regex::new(r"[^a-z0-9_]").unwrap(); let mult_underbar = Regex::new(r"[_]+").unwrap(); new = new.to_ascii_lowercase(); new = spaces.replace_all(&new.to_string(), "_").to_string(); new = non_alphanum.replace_all(&new.to_string(), "").to_string(); mult_underbar.replace_all(&new.to_string(), "_").to_string() } fn is_file(path: &String) -> bool { if let Ok(meta) = fs::metadata(path) { return meta.is_file(); } else { return false; } } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; use tempdir::TempDir; #[test] fn test_normalize() { assert_eq!(normalize(&"".to_string()), ""); assert_eq!(normalize(&"ABC".to_string()), "abc"); assert_eq!(normalize(&"ABC DEF".to_string()), "abc_def"); assert_eq!(normalize(&"foo-b*!a,r".to_string()), "foobar"); assert_eq!(normalize(&"Foo Bar".to_string()), "foo_bar"); assert_eq!(normalize(&"Foo / Bar".to_string()), "foo_bar"); assert_eq!(normalize(&"Foo (Bar)".to_string()), "foo_bar"); assert_eq!(normalize(&"FooBarBAZ".to_string()), "foo_bar_baz"); } #[test] fn test_1() { let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let file = manifest_dir.join(PathBuf::from("tests/test1.xlsx")); if let Ok(tmp_dir) = TempDir::new("test") { let outdir = &tmp_dir.path().display().
#[test] fn test_2() { let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let file = manifest_dir.join(PathBuf::from("tests/Test 2.xlsx")); if let Ok(tmp_dir) = TempDir::new("test") { let outdir = &tmp_dir.path().display().to_string(); let conf = Config { files: vec![file.display().to_string()], outdir: outdir.to_string(), delimiter: 44, normalize: true, make_dirs: true, }; let _res = match run(conf) { Ok(_) => { let expected_dir = PathBuf::from(tmp_dir.path().join("test_2")); assert!(expected_dir.is_dir()); let expected_file = expected_dir.join("test_2__sheet1.csv"); assert!(expected_file.is_file()); let contents = fs::read_to_string(expected_file).ok().unwrap(); let lines: Vec<&str> = contents.split("\n").collect(); assert_eq!(lines[0], "ice_cream_flavor,peoples_rank"); assert_eq!(lines[1], "chocolate,1"); assert_eq!(lines[2], "vanilla,2"); assert_eq!(lines[3], "stravberry,3"); } Err(x) => panic!("{:?}", x), }; } } }
to_string(); let conf = Config { files: vec![file.display().to_string()], outdir: outdir.to_string(), delimiter: 9, normalize: false, make_dirs: false, }; let _res = match run(conf) { Ok(_) => { let expected_dir = PathBuf::from(outdir); assert!(expected_dir.is_dir()); let expected_file = expected_dir.join("test1__sheet1.txt"); assert!(expected_file.is_file()); let contents = fs::read_to_string(expected_file).ok().unwrap(); let lines: Vec<&str> = contents.split("\n").collect(); assert_eq!(lines[0], "name\trank\tserial_number"); assert_eq!(lines[1], "Ed\tCaptain\t12345"); assert_eq!(lines[2], "Jorge\tMajor\t98765"); } Err(x) => panic!("{:?}", x), }; } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let config = match excel2txt::get_args() {\n\n Ok(c) => c,\n\n Err(e) => {\n\n println!(\"Error: {}\", e);\n\n process::exit(1);\n\n }\n\n };\n\n\n\n if let Err(e) = excel2txt::run(config) {\n\n println!(\"Error: {}\", e);\...
Rust
src/mapper.rs
whitfin/efflux
fe756d76cedb962abcd1934285b9d58e6b00d48c
use crate::context::{Context, Offset}; use crate::io::Lifecycle; pub trait Mapper { fn setup(&mut self, _ctx: &mut Context) {} fn map(&mut self, key: usize, value: &[u8], ctx: &mut Context) { ctx.write(key.to_string().as_bytes(), value); } fn cleanup(&mut self, _ctx: &mut Context) {} } impl<M> Mapper for M where M: FnMut(usize, &[u8], &mut Context), { #[inline] fn map(&mut self, key: usize, value: &[u8], ctx: &mut Context) { self(key, value, ctx) } } pub(crate) struct MapperLifecycle<M> where M: Mapper, { mapper: M, } impl<M> MapperLifecycle<M> where M: Mapper, { pub(crate) fn new(mapper: M) -> Self { Self { mapper } } } impl<M> Lifecycle for MapperLifecycle<M> where M: Mapper, { #[inline] fn on_start(&mut self, ctx: &mut Context) { ctx.insert(Offset::new()); self.mapper.setup(ctx); } #[inline] fn on_entry(&mut self, input: &[u8], ctx: &mut Context) { let offset = { ctx.get_mut::<Offset>().unwrap().shift(input.len() + 2) }; self.mapper.map(offset, input, ctx); } #[inline] fn on_end(&mut self, ctx: &mut Context) { self.mapper.cleanup(ctx); } } #[cfg(test)] mod tests { use super::*; use crate::context::Contextual; use crate::io::Lifecycle; #[test] fn test_mapper_lifecycle() { let mut ctx = Context::new(); let mut mapper = MapperLifecycle::new(TestMapper); mapper.on_start(&mut ctx); { let mut vet = |input: &[u8], expected: usize| { mapper.on_entry(input, &mut ctx); let pair = ctx.get::<TestPair>(); assert!(pair.is_some()); let pair = pair.unwrap(); assert_eq!(pair.0, expected); assert_eq!(pair.1, input); }; vet(b"first_input_line", 18); vet(b"second_input_line", 37); vet(b"third_input_line", 55); } mapper.on_end(&mut ctx); } struct TestPair(usize, Vec<u8>); impl Contextual for TestPair {} struct TestMapper; impl Mapper for TestMapper { fn map(&mut self, key: usize, val: &[u8], ctx: &mut Context) { ctx.insert(TestPair(key, val.to_vec())); } } }
use crate::context::{Context, Offset}; use crate::io::Lifecycle; pub trait Mapper { fn setup(&mut self, _ctx: &mut Context) {} fn map(&mut self, key: usize, value: &[u8], ctx: &mut Context) { ctx.write(key.to_string().as_bytes(), value); } fn cleanup(&mut self, _ctx: &mut Context) {} } impl<M> Mapper for M where M: FnMut(usize, &[u8], &mut Context), { #[inline] fn map(&mut self, key: usize, value: &[u8], ctx: &mut Context) { self(key, value, ctx) } } pub(crate) struct MapperLifecycle<M> where M: Mapper, { mapper: M, } impl<M> MapperLifecycle<M> where M: Mapper, { pub(crate) fn new(mapper: M) -> Self { Self { mapper } } } impl<M> Lifecycle for MapperLifecycle<M> where M: Mapper, { #[inline] fn on_start(&mut self, ctx: &mut Context) { ctx.insert(Offset::new()); self.mapper.setup(ctx); } #[inline] fn on_entry(&mut self, input: &[u8], ctx: &mut Context) { let offset = { ctx.get_mut::<Offset>().unwrap().shift(input.len() + 2) }; self.mapper.map(offset, input, ctx); } #[inline] fn on_end(&mut self, ctx: &mut Context) { self.mapper.cleanup(ctx); } } #[cfg(test)] mod tests { use super::*; use crate::context::Contextual; use crate::io::Lifecycle; #[test] fn test_mapper_lifecycle() { let mut ctx = Context::new(); let mut mapper = MapperLifecycle::new(TestMapper); mapper.on_start(&mut ctx); { let mut vet = |input: &[u8], expected: usize| { mapper.on_entry(input, &mut ctx); let pair = ctx.get::<TestPair>(); assert!(pair.is_some());
}; vet(b"first_input_line", 18); vet(b"second_input_line", 37); vet(b"third_input_line", 55); } mapper.on_end(&mut ctx); } struct TestPair(usize, Vec<u8>); impl Contextual for TestPair {} struct TestMapper; impl Mapper for TestMapper { fn map(&mut self, key: usize, val: &[u8], ctx: &mut Context) { ctx.insert(TestPair(key, val.to_vec())); } } }
let pair = pair.unwrap(); assert_eq!(pair.0, expected); assert_eq!(pair.1, input);
random
[ { "content": "/// Marker trait to represent types which can be added to a `Context`.\n\npub trait Contextual: Any {}\n\n\n\n// all internal contextual types\n\nimpl Contextual for Configuration {}\n\nimpl Contextual for Delimiters {}\n\nimpl Contextual for Offset {}\n\n\n\n/// Context structure to represent a H...
Rust
src/main.rs
erikbrinkman/stats
f709428cd7a8e734b67f32693678ed269b384fa7
use std::f64; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Read, StdinLock, StdoutLock, Write}; use std::iter; use clap::{crate_version, App, Arg, ArgGroup, ArgMatches}; use inc_stats::{Mode, Percentiles, SummStats}; fn parse_command_line<'a>() -> ArgMatches<'a> { App::new("stats") .version(crate_version!()) .author("Erik Brinkman <erik.brinkman@gmail.com>") .about("Compute summary statistics of streams of numbers") .arg(Arg::with_name("count") .short("c") .long("count") .help("Print count")) .arg(Arg::with_name("min") .long("min") .help("Print min")) .arg(Arg::with_name("max") .long("max") .help("Print max")) .arg(Arg::with_name("mean") .short("m") .long("mean") .help("Print mean")) .arg(Arg::with_name("sum") .long("sum") .help("Print sum")) .arg(Arg::with_name("stddev") .short("s") .long("stddev") .help("Print sample standard deviation")) .arg(Arg::with_name("var") .short("v") .long("var") .help("Print sample variance")) .arg(Arg::with_name("stderr") .long("stderr") .help("Print standard error")) .arg(Arg::with_name("median") .long("median") .help("Print median (Note: computing median takes O(n) space")) .arg(Arg::with_name("percentiles") .short("p") .long("percentiles") .takes_value(true) .use_delimiter(true) .help("Print arbitrary percentiles. The argument should be a comma delimited list of floats in [0, 100] (Note: computing any percentile takes O(n) space)")) .arg(Arg::with_name("mode") .long("mode") .help("Print mode (Note: computing mode takes O(n) space")) .arg(Arg::with_name("mode-count") .long("mode-count") .help("Print the number of times the mode occured (Note: computing mode takes O(n) space")) .arg(Arg::with_name("distinct") .long("distinct") .help("Print the number of distinct values (Note: computing mode takes O(n) space")) .arg(Arg::with_name("distinct-nan") .long("distinct-nan") .help("Print the number of distinct values treading all NaNs as distinct (Note: computing mode takes O(n) space")) .group(ArgGroup::with_name("format").args(&["tsv", "json"])) .arg(Arg::with_name("tsv") .short("t") .long("tsv") .help("Output as tsv. This will force tsv output even if only one statistics is requested.")) .arg(Arg::with_name("json") .short("j") .long("json") .help("Output as compressed json")) .arg(Arg::with_name("input") .short("i") .long("input") .value_name("file") .default_value("-") .help("Take input from file")) .arg(Arg::with_name("output") .short("o") .long("output") .value_name("file") .default_value("-") .help("Write output to file")) .get_matches() } enum StatsReader<'a> { Stdin(StdinLock<'a>), File(BufReader<File>), } impl<'a> Read for StatsReader<'a> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self { StatsReader::Stdin(lock) => lock.read(buf), StatsReader::File(file) => file.read(buf), } } } impl<'a> BufRead for StatsReader<'a> { fn fill_buf(&mut self) -> io::Result<&[u8]> { match self { StatsReader::Stdin(lock) => lock.fill_buf(), StatsReader::File(file) => file.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { StatsReader::Stdin(lock) => lock.consume(amt), StatsReader::File(file) => file.consume(amt), } } } enum StatsWriter<'a> { Stdout(StdoutLock<'a>), File(BufWriter<File>), } impl<'a> Write for StatsWriter<'a> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { match self { StatsWriter::Stdout(lock) => lock.write(buf), StatsWriter::File(file) => file.write(buf), } } fn flush(&mut self) -> io::Result<()> { match self { StatsWriter::Stdout(lock) => lock.flush(), StatsWriter::File(file) => file.flush(), } } } fn main() { let matches = parse_command_line(); let stdin = io::stdin(); let input = match matches.value_of("input") { Some("-") => StatsReader::Stdin(stdin.lock()), Some(file_name) => StatsReader::File(BufReader::new( File::open(file_name) .unwrap_or_else(|_| panic!("File \"{}\" does not exist", file_name)), )), None => unreachable!(), }; let stdout = io::stdout(); let mut output = match matches.value_of("output") { Some("-") => StatsWriter::Stdout(stdout.lock()), Some(file_name) => { StatsWriter::File(BufWriter::new(File::open(file_name).unwrap_or_else(|_| { panic!("Couldn't open file \"{}\" for writing", file_name) }))) } None => unreachable!(), }; let mut stats = SummStats::new(); let mut percs = Percentiles::new(); let mut mode = Mode::new(); let add_mode = ["mode", "mode-count", "distinct", "distinct-nan"] .iter() .any(|s| matches.is_present(s)); let add_percs = ["percentiles", "median"] .iter() .any(|s| matches.is_present(s)); let add_stats = [ "count", "min", "max", "mean", "sum", "stddev", "var", "stderr", ] .iter() .any(|s| matches.is_present(s)) || !(add_mode && add_percs); for line in input.lines() { for token in line .expect("Couldn't read from file") .split(char::is_whitespace) .filter(|s| !s.is_empty()) { let num: f64 = token .parse() .unwrap_or_else(|_| panic!("Could not parse \"{}\" as float", token)); if add_mode { mode.add(num); } if add_percs { percs.add(num); } if add_stats { stats.add(num); } } } let results = compute_results(&matches, &stats, &mut percs, &mode); if matches.is_present("tsv") { write_tsv(&results, &mut output); } else if matches.is_present("json") { write_json(&results, &mut output); } else if results.len() == 1 { let (_, val) = results[0]; writeln!(output, "{}", val).expect("couldn't write to output"); } else { write_tsv(&results, &mut output); } } fn compute_results( matches: &ArgMatches, stats: &SummStats<f64>, percs: &mut Percentiles<f64>, mode: &Mode<f64>, ) -> Vec<(String, f64)> { let mut results = Vec::new(); if matches.is_present("count") { results.push((String::from("count"), stats.count() as f64)); } if matches.is_present("min") { results.push((String::from("min"), stats.min().unwrap_or(f64::NAN))); } if matches.is_present("max") { results.push((String::from("max"), stats.max().unwrap_or(f64::NAN))); } if matches.is_present("mean") { results.push((String::from("mean"), stats.mean().unwrap_or(f64::NAN))); } if matches.is_present("sum") { results.push((String::from("sum"), stats.sum())); } if matches.is_present("stddev") { results.push(( String::from("stddev"), stats.standard_deviation().unwrap_or(f64::NAN), )); } if matches.is_present("var") { results.push((String::from("var"), stats.variance().unwrap_or(f64::NAN))); } if matches.is_present("stderr") { results.push(( String::from("stderr"), stats.standard_error().unwrap_or(f64::NAN), )); } if matches.is_present("percentiles") { let percentiles: Vec<f64> = matches .values_of("percentiles") .unwrap() .map(|p| { p.parse::<f64>() .unwrap_or_else(|_| panic!("Could not parse \"{}\" as float", p)) }) .collect(); let vals = match percs.percentiles(percentiles.iter().map(|p| p / 100.0)) { Err(_) => panic!("percentiles must between 0 and 100: {:?}", percentiles), Ok(None) => iter::repeat(f64::NAN).take(percentiles.len()).collect(), Ok(Some(pvals)) => pvals, }; for (perc, val) in percentiles.iter().zip(vals) { results.push((format!("{}%", perc), val)); } } if matches.is_present("median") { results.push((String::from("median"), percs.median().unwrap_or(f64::NAN))); } if matches.is_present("mode") { results.push((String::from("mode"), mode.mode().unwrap_or(f64::NAN))); } if matches.is_present("mode-count") { results.push((String::from("mode #"), mode.mode_count() as f64)); } if matches.is_present("distinct") { results.push((String::from("distinct"), mode.count_distinct() as f64)); } if matches.is_present("distinct-nan") { results.push(( String::from("distinct (NaN)"), mode.count_distinct_nan() as f64, )); } if results.is_empty() { results.push((String::from("count"), stats.count() as f64)); results.push((String::from("min"), stats.min().unwrap_or(f64::NAN))); results.push((String::from("max"), stats.max().unwrap_or(f64::NAN))); results.push((String::from("mean"), stats.mean().unwrap_or(f64::NAN))); results.push(( String::from("stddev"), stats.standard_deviation().unwrap_or(f64::NAN), )); } results } fn write_tsv(results: &[(String, f64)], output: &mut impl Write) { for &(ref name, ref val) in results { writeln!(output, "{}\t{}", name, val).expect("couldn't write to output"); } } fn write_json(results: &[(String, f64)], output: &mut impl Write) { write!(output, "{{").expect("couldn't write to output"); let mut iter = results.iter(); let &(ref name, ref val) = iter.next().unwrap(); write!(output, "\"{}\":{}", name, val).expect("couldn't write to output"); for &(ref name, ref val) in iter { write!(output, ",\"{}\":{}", name, val).expect("couldn't write to output"); } writeln!(output, "}}").expect("couldn't write to output"); }
use std::f64; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Read, StdinLock, StdoutLock, Write}; use std::iter; use clap::{crate_version, App, Arg, ArgGroup, ArgMatches}; use inc_stats::{Mode, Percentiles, SummStats}; fn parse_command_line<'a>() -> ArgMatches<'a> { App::new("stats") .version(crate_version!()) .author("Erik Brinkman <erik.brinkman@gmail.com>") .about("Compute summary statistics of streams of numbers") .arg(Arg::with_name("count") .short("c") .long("count") .help("Print count")) .arg(Arg::with_name("min") .long("min") .help("Print min")) .arg(Arg::with_name("max") .long("max") .help("Print max")) .arg(Arg::with_name("mean") .short("m") .long("mean") .help("Print mean")) .arg(Arg::with_name("sum") .long("sum") .help("Print sum")) .arg(Arg::with_name("stddev") .short("s") .long("stddev") .help("Print sample standard deviation")) .arg(Arg::with_name("var") .short("v") .long("var") .help("Print sample variance")) .arg(Arg::with_name("stderr") .long("stderr") .help("Print standard error")) .arg(Arg::with_name("median") .long("median") .help("Print median (Note: computing median takes O(n) space")) .arg(Arg::with_name("percentiles") .short("p") .long("percentiles") .takes_value(true) .use_delimiter(true) .help("Print arbitrary percentiles. The argument should be a comma delimited list of floats in [0, 100] (Note: computing any percentile takes O(n) space)")) .arg(Arg::with_name("mode") .long("mode") .help("Print mode (Note: computing mode takes O(n) space")) .arg(Arg::with_name("mode-coun
stats: &SummStats<f64>, percs: &mut Percentiles<f64>, mode: &Mode<f64>, ) -> Vec<(String, f64)> { let mut results = Vec::new(); if matches.is_present("count") { results.push((String::from("count"), stats.count() as f64)); } if matches.is_present("min") { results.push((String::from("min"), stats.min().unwrap_or(f64::NAN))); } if matches.is_present("max") { results.push((String::from("max"), stats.max().unwrap_or(f64::NAN))); } if matches.is_present("mean") { results.push((String::from("mean"), stats.mean().unwrap_or(f64::NAN))); } if matches.is_present("sum") { results.push((String::from("sum"), stats.sum())); } if matches.is_present("stddev") { results.push(( String::from("stddev"), stats.standard_deviation().unwrap_or(f64::NAN), )); } if matches.is_present("var") { results.push((String::from("var"), stats.variance().unwrap_or(f64::NAN))); } if matches.is_present("stderr") { results.push(( String::from("stderr"), stats.standard_error().unwrap_or(f64::NAN), )); } if matches.is_present("percentiles") { let percentiles: Vec<f64> = matches .values_of("percentiles") .unwrap() .map(|p| { p.parse::<f64>() .unwrap_or_else(|_| panic!("Could not parse \"{}\" as float", p)) }) .collect(); let vals = match percs.percentiles(percentiles.iter().map(|p| p / 100.0)) { Err(_) => panic!("percentiles must between 0 and 100: {:?}", percentiles), Ok(None) => iter::repeat(f64::NAN).take(percentiles.len()).collect(), Ok(Some(pvals)) => pvals, }; for (perc, val) in percentiles.iter().zip(vals) { results.push((format!("{}%", perc), val)); } } if matches.is_present("median") { results.push((String::from("median"), percs.median().unwrap_or(f64::NAN))); } if matches.is_present("mode") { results.push((String::from("mode"), mode.mode().unwrap_or(f64::NAN))); } if matches.is_present("mode-count") { results.push((String::from("mode #"), mode.mode_count() as f64)); } if matches.is_present("distinct") { results.push((String::from("distinct"), mode.count_distinct() as f64)); } if matches.is_present("distinct-nan") { results.push(( String::from("distinct (NaN)"), mode.count_distinct_nan() as f64, )); } if results.is_empty() { results.push((String::from("count"), stats.count() as f64)); results.push((String::from("min"), stats.min().unwrap_or(f64::NAN))); results.push((String::from("max"), stats.max().unwrap_or(f64::NAN))); results.push((String::from("mean"), stats.mean().unwrap_or(f64::NAN))); results.push(( String::from("stddev"), stats.standard_deviation().unwrap_or(f64::NAN), )); } results } fn write_tsv(results: &[(String, f64)], output: &mut impl Write) { for &(ref name, ref val) in results { writeln!(output, "{}\t{}", name, val).expect("couldn't write to output"); } } fn write_json(results: &[(String, f64)], output: &mut impl Write) { write!(output, "{{").expect("couldn't write to output"); let mut iter = results.iter(); let &(ref name, ref val) = iter.next().unwrap(); write!(output, "\"{}\":{}", name, val).expect("couldn't write to output"); for &(ref name, ref val) in iter { write!(output, ",\"{}\":{}", name, val).expect("couldn't write to output"); } writeln!(output, "}}").expect("couldn't write to output"); }
t") .long("mode-count") .help("Print the number of times the mode occured (Note: computing mode takes O(n) space")) .arg(Arg::with_name("distinct") .long("distinct") .help("Print the number of distinct values (Note: computing mode takes O(n) space")) .arg(Arg::with_name("distinct-nan") .long("distinct-nan") .help("Print the number of distinct values treading all NaNs as distinct (Note: computing mode takes O(n) space")) .group(ArgGroup::with_name("format").args(&["tsv", "json"])) .arg(Arg::with_name("tsv") .short("t") .long("tsv") .help("Output as tsv. This will force tsv output even if only one statistics is requested.")) .arg(Arg::with_name("json") .short("j") .long("json") .help("Output as compressed json")) .arg(Arg::with_name("input") .short("i") .long("input") .value_name("file") .default_value("-") .help("Take input from file")) .arg(Arg::with_name("output") .short("o") .long("output") .value_name("file") .default_value("-") .help("Write output to file")) .get_matches() } enum StatsReader<'a> { Stdin(StdinLock<'a>), File(BufReader<File>), } impl<'a> Read for StatsReader<'a> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self { StatsReader::Stdin(lock) => lock.read(buf), StatsReader::File(file) => file.read(buf), } } } impl<'a> BufRead for StatsReader<'a> { fn fill_buf(&mut self) -> io::Result<&[u8]> { match self { StatsReader::Stdin(lock) => lock.fill_buf(), StatsReader::File(file) => file.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { StatsReader::Stdin(lock) => lock.consume(amt), StatsReader::File(file) => file.consume(amt), } } } enum StatsWriter<'a> { Stdout(StdoutLock<'a>), File(BufWriter<File>), } impl<'a> Write for StatsWriter<'a> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { match self { StatsWriter::Stdout(lock) => lock.write(buf), StatsWriter::File(file) => file.write(buf), } } fn flush(&mut self) -> io::Result<()> { match self { StatsWriter::Stdout(lock) => lock.flush(), StatsWriter::File(file) => file.flush(), } } } fn main() { let matches = parse_command_line(); let stdin = io::stdin(); let input = match matches.value_of("input") { Some("-") => StatsReader::Stdin(stdin.lock()), Some(file_name) => StatsReader::File(BufReader::new( File::open(file_name) .unwrap_or_else(|_| panic!("File \"{}\" does not exist", file_name)), )), None => unreachable!(), }; let stdout = io::stdout(); let mut output = match matches.value_of("output") { Some("-") => StatsWriter::Stdout(stdout.lock()), Some(file_name) => { StatsWriter::File(BufWriter::new(File::open(file_name).unwrap_or_else(|_| { panic!("Couldn't open file \"{}\" for writing", file_name) }))) } None => unreachable!(), }; let mut stats = SummStats::new(); let mut percs = Percentiles::new(); let mut mode = Mode::new(); let add_mode = ["mode", "mode-count", "distinct", "distinct-nan"] .iter() .any(|s| matches.is_present(s)); let add_percs = ["percentiles", "median"] .iter() .any(|s| matches.is_present(s)); let add_stats = [ "count", "min", "max", "mean", "sum", "stddev", "var", "stderr", ] .iter() .any(|s| matches.is_present(s)) || !(add_mode && add_percs); for line in input.lines() { for token in line .expect("Couldn't read from file") .split(char::is_whitespace) .filter(|s| !s.is_empty()) { let num: f64 = token .parse() .unwrap_or_else(|_| panic!("Could not parse \"{}\" as float", token)); if add_mode { mode.add(num); } if add_percs { percs.add(num); } if add_stats { stats.add(num); } } } let results = compute_results(&matches, &stats, &mut percs, &mode); if matches.is_present("tsv") { write_tsv(&results, &mut output); } else if matches.is_present("json") { write_json(&results, &mut output); } else if results.len() == 1 { let (_, val) = results[0]; writeln!(output, "{}", val).expect("couldn't write to output"); } else { write_tsv(&results, &mut output); } } fn compute_results( matches: &ArgMatches,
random
[ { "content": "/// Get the mean of a set of data\n\n///\n\n/// This method takes constant space and linear time.\n\n///\n\n/// # Examples:\n\n///\n\n/// ```\n\n/// let mean: f64 = inc_stats::mean(&[2.0, 4.0]).unwrap();\n\n/// assert!((3.0 - mean).abs() < 1.0e-6);\n\n/// ```\n\npub fn mean<T, V, I>(data: I) -> Op...
Rust
src/volume/storage/redis/redis.rs
isgasho/zbox
752c2739f883f416e27e9c342552ff1f9838c0e6
use std::fmt::{self, Debug}; use std::sync::Mutex; use redis::{Client, Commands, Connection}; use base::crypto::{Crypto, Key}; use base::IntoRef; use error::{Error, Result}; use trans::Eid; use volume::address::Span; use volume::storage::Storable; use volume::BLK_SIZE; #[inline] fn super_blk_key(suffix: u64) -> String { format!("super_blk:{}", suffix) } #[inline] fn wal_key(id: &Eid) -> String { format!("wal:{}", id.to_string()) } #[inline] fn addr_key(id: &Eid) -> String { format!("address:{}", id.to_string()) } #[inline] fn blk_key(blk_idx: usize) -> String { format!("block:{}", blk_idx) } pub struct RedisStorage { client: Client, conn: Option<Mutex<Connection>>, } impl RedisStorage { pub fn new(path: &str) -> Result<Self> { let url = if path.starts_with("+unix+") { format!("redis+unix:///{}", &path[6..]) } else { format!("redis://{}", path) }; let client = Client::open(url.as_str())?; Ok(RedisStorage { client, conn: None }) } fn get_bytes(&self, key: &str) -> Result<Vec<u8>> { match self.conn { Some(ref conn) => { let conn = conn.lock().unwrap(); if !conn.exists::<&str, bool>(key)? { return Err(Error::NotFound); } let ret = conn.get(key)?; Ok(ret) } None => unreachable!(), } } fn set_bytes(&self, key: &str, val: &[u8]) -> Result<()> { match self.conn { Some(ref conn) => { let conn = conn.lock().unwrap(); conn.set(key, val)?; Ok(()) } None => unreachable!(), } } fn del(&self, key: &str) -> Result<()> { match self.conn { Some(ref conn) => { let conn = conn.lock().unwrap(); conn.del(key)?; Ok(()) } None => unreachable!(), } } } impl Storable for RedisStorage { fn exists(&self) -> Result<bool> { let conn = self.client.get_connection()?; let key = super_blk_key(0); conn.exists::<&str, bool>(&key).map_err(Error::from) } fn connect(&mut self) -> Result<()> { let conn = self.client.get_connection()?; self.conn = Some(Mutex::new(conn)); Ok(()) } #[inline] fn init(&mut self, _crypto: Crypto, _key: Key) -> Result<()> { Ok(()) } #[inline] fn open(&mut self, _crypto: Crypto, _key: Key) -> Result<()> { Ok(()) } fn get_super_block(&mut self, suffix: u64) -> Result<Vec<u8>> { let key = super_blk_key(suffix); self.get_bytes(&key) } fn put_super_block(&mut self, super_blk: &[u8], suffix: u64) -> Result<()> { let key = super_blk_key(suffix); self.set_bytes(&key, super_blk) } fn get_wal(&mut self, id: &Eid) -> Result<Vec<u8>> { let key = wal_key(id); self.get_bytes(&key) } fn put_wal(&mut self, id: &Eid, wal: &[u8]) -> Result<()> { let key = wal_key(id); self.set_bytes(&key, wal) } fn del_wal(&mut self, id: &Eid) -> Result<()> { let key = wal_key(id); self.del(&key) } fn get_address(&mut self, id: &Eid) -> Result<Vec<u8>> { let key = addr_key(id); self.get_bytes(&key) } fn put_address(&mut self, id: &Eid, addr: &[u8]) -> Result<()> { let key = addr_key(id); self.set_bytes(&key, addr) } fn del_address(&mut self, id: &Eid) -> Result<()> { let key = addr_key(id); self.del(&key) } fn get_blocks(&mut self, dst: &mut [u8], span: Span) -> Result<()> { let mut read = 0; for blk_idx in span { let key = blk_key(blk_idx); let blk = self.get_bytes(&key)?; assert_eq!(blk.len(), BLK_SIZE); dst[read..read + BLK_SIZE].copy_from_slice(&blk); read += BLK_SIZE; } Ok(()) } fn put_blocks(&mut self, span: Span, mut blks: &[u8]) -> Result<()> { for blk_idx in span { let key = blk_key(blk_idx); self.set_bytes(&key, &blks[..BLK_SIZE])?; blks = &blks[BLK_SIZE..]; } Ok(()) } fn del_blocks(&mut self, span: Span) -> Result<()> { for blk_idx in span { let key = blk_key(blk_idx); self.del(&key)?; } Ok(()) } #[inline] fn flush(&mut self) -> Result<()> { Ok(()) } } impl Debug for RedisStorage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("RedisStorage").finish() } } impl IntoRef for RedisStorage {} #[cfg(test)] mod tests { use super::*; use base::init_env; #[test] fn redis_storage() { init_env(); let mut rs = RedisStorage::new("127.0.0.1").unwrap(); rs.connect().unwrap(); rs.init(Crypto::default(), Key::new_empty()).unwrap(); let id = Eid::new(); let buf = vec![1, 2, 3]; let blks = vec![42u8; BLK_SIZE * 3]; let mut dst = vec![0u8; BLK_SIZE * 3]; rs.put_super_block(&buf, 0).unwrap(); let s = rs.get_super_block(0).unwrap(); assert_eq!(&s[..], &buf[..]); rs.put_wal(&id, &buf).unwrap(); let s = rs.get_wal(&id).unwrap(); assert_eq!(&s[..], &buf[..]); rs.del_wal(&id).unwrap(); assert_eq!(rs.get_wal(&id).unwrap_err(), Error::NotFound); rs.put_address(&id, &buf).unwrap(); let s = rs.get_address(&id).unwrap(); assert_eq!(&s[..], &buf[..]); rs.del_address(&id).unwrap(); assert_eq!(rs.get_address(&id).unwrap_err(), Error::NotFound); let span = Span::new(0, 3); rs.put_blocks(span, &blks).unwrap(); rs.get_blocks(&mut dst, span).unwrap(); assert_eq!(&dst[..], &blks[..]); rs.del_blocks(Span::new(1, 2)).unwrap(); assert_eq!( rs.get_blocks(&mut dst, Span::new(0, 3)).unwrap_err(), Error::NotFound ); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(1, 1)) .unwrap_err(), Error::NotFound ); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(2, 1)) .unwrap_err(), Error::NotFound ); drop(rs); let mut rs = RedisStorage::new("127.0.0.1").unwrap(); rs.connect().unwrap(); rs.open(Crypto::default(), Key::new_empty()).unwrap(); rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(0, 1)) .unwrap(); assert_eq!(&dst[..BLK_SIZE], &blks[..BLK_SIZE]); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(1, 1)) .unwrap_err(), Error::NotFound ); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(2, 1)) .unwrap_err(), Error::NotFound ); } }
use std::fmt::{self, Debug}; use std::sync::Mutex; use redis::{Client, Commands, Connection}; use base::crypto::{Crypto, Key}; use base::IntoRef; use error::{Error, Result}; use trans::Eid; use volume::address::Span; use volume::storage::Storable; use volume::BLK_SIZE; #[inline] fn super_blk_key(suffix: u64) -> String { format!("super_blk:{}", suffix) } #[inline] fn wal_key(id: &Eid) -> String { format!("wal:{}", id.to_string()) } #[inline] fn addr_key(id: &Eid) -> String { format!("address:{}", id.to_string()) } #[inline] fn blk_key(blk_idx: usize) -> String { format!("block:{}", blk_idx) } pub struct RedisStorage { client: Client, conn: Option<Mutex<Connection>>, } impl RedisStorage { pub fn new(path: &str) -> Result<Self> { let url = if path.starts_with("+unix+") { format!("redis+unix:///{}", &path[6..]) } else { format!("redis://{}", path) }; let client = Client::open(url.as_str())?; Ok(RedisStorage { client, conn: None }) } fn get_bytes(&self, key: &str) -> Result<Vec<u8>> { match self.conn { Some(ref conn) => { let conn = conn.lock().unwrap(); if !conn.exists::<&str, bool>(key)? { return Err(Error::NotFound); } let ret = conn.get(key)?; Ok(ret) } None => unreachable!(), } } fn set_bytes(&self, key: &str, val: &[u8]) -> Result<()> { match self.conn { Some(ref conn) => { let conn = conn.lock().unwrap(); conn.set(key, val)?; Ok(()) } None => unreachable!(), } } fn del(&self, key: &str) -> Result<()> { match self.conn { Some(ref conn) => { let conn = conn.lock().unwrap(); conn.del(key)?; Ok(()) } None => unreachable!(), } } } impl Storable for RedisStorage { fn exists(&self) -> Result<bool> { let conn = self.client.get_connection()?; let key = super_blk_key(0); conn.exists::<&str, bool>(&key).map_err(Error::from) } fn connect(&mut self) -> Result<()> { let conn = self.client.get_connection()?; self.conn = Some(Mutex::new(conn)); Ok(()) } #[inline] fn init(&mut self, _crypto: Crypto, _key: Key) -> Result<()> { Ok(()) } #[inline] fn open(&mut self, _crypto: Crypto, _key: Key) -> Result<()> { Ok(()) } fn get_super_block(&mut self, suffix: u64) -> Result<Vec<u8>> { let key = super_blk_key(suffix); self.get_bytes(&key) } fn put_super_block(&mut self, super_blk: &[u8], suffix: u64) -> Result<()> { let key = super_blk_key(suffix); self.set_bytes(&key, super_blk) } fn get_wal(&mut self, id: &Eid) -> Result<Vec<u8>> { let key = wal_key(id); self.get_bytes(&key) } fn put_wal(&mut self, id: &Eid, wal: &[u8]) -> Result<()> { let key = wal_key(id); self.set_bytes(&key, wal) } fn del_wal(&mut self, id: &Eid) -> Result<()> { let key = wal_key(id); self.del(&key) } fn get_address(&mut self, id: &Eid) -> Result<Vec<u8>> { let key = addr_key(id); self.get_bytes(&key) } fn put_address(&mut self, id: &Eid, addr: &[u8]) -> Result<()> { let key = addr_key(id); self.set_bytes(&key, addr) } fn del_address(&mut self, id: &Eid) -> Result<()> { let key = addr_key(id); self.del(&key) } fn get_blocks(&mut self, dst: &mut [u8], span: Span) -> Result<()> { let mut read = 0; for blk_idx in span { let key = blk_key(blk_idx); let blk = self.get_bytes(&key)?; assert_eq!(blk.len(), BLK_SIZE); dst[read..read + BLK_SIZE].copy_from_slice(&blk); read += BLK_SIZE; } Ok(()) } fn put_blocks(&mut self, span: Span, mut blks: &[u8]) -> Result<()> { for blk_idx in span { let key = blk_key(blk_idx); self.set_bytes(&key, &blks[..BLK_SIZE])?; blks = &blks[BLK_SIZE..]; } Ok(()) } fn del_blocks(&mut self, span: Span) -> Result<()> { for blk_idx in span { let key = blk_key(blk_idx); self.del(&key)?; } Ok(()) } #[inline] fn flush(&mut self) -> Result<()> { Ok(()) } } impl Debug for RedisStorage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("RedisStorage").finish() } } impl IntoRef for RedisStorage {} #[cfg(test)] mod tests { use super::*; use base::init_env; #[test] fn redis_storage() { init_env(); let mut rs = RedisStorage::new("127.0.0.1").unwrap(); rs.connect().unwrap(); rs.init(Crypto::default(), Key::new_empty()).unwrap(); let id = Eid::new(); let buf = vec![1, 2, 3]; let blks = vec![42u8; BLK_SIZE * 3]; let mut dst = vec![0u8; BLK_SIZE * 3]; rs.put_super_block(&buf, 0).unwrap(); let s = rs.get_super_block(0).unwrap(); assert_eq!(&s[..], &buf[..]); rs.put_wal(&id, &buf).unwrap(); let s = rs.get_wal(&id).unwrap(); assert_eq!(&s[..], &buf[..]); rs.del_wal(&id).unwrap(); assert_eq!(rs.get_wal(&id).unwrap_err(), Error::NotFound); rs.put_address(&id, &buf).unwrap(); let s = rs.get_address(&id).unwrap(); assert_eq!(&s[..], &buf[..]); rs.del_address(&id).unwrap(); assert_eq!(rs.get_address(&id).unwrap_err(), Error::NotFound); let span = Span::new(0, 3); rs.put_blocks(span, &blks).unwrap(); rs.get_blocks(&mut dst, span).unwrap(); assert_eq!(&dst[..], &blks[..]); rs.del_blocks(Span::new(1, 2)).unwrap(); assert_eq!( rs.get_blocks(&mut dst, Span::new(0, 3)).unwrap_err(),
}
Error::NotFound ); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(1, 1)) .unwrap_err(), Error::NotFound ); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(2, 1)) .unwrap_err(), Error::NotFound ); drop(rs); let mut rs = RedisStorage::new("127.0.0.1").unwrap(); rs.connect().unwrap(); rs.open(Crypto::default(), Key::new_empty()).unwrap(); rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(0, 1)) .unwrap(); assert_eq!(&dst[..BLK_SIZE], &blks[..BLK_SIZE]); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(1, 1)) .unwrap_err(), Error::NotFound ); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(2, 1)) .unwrap_err(), Error::NotFound ); }
function_block-function_prefix_line
[ { "content": "pub fn random_buf(buf: &mut [u8]) {\n\n unsafe {\n\n randombytes_buf(buf.as_mut_ptr(), buf.len());\n\n }\n\n}\n\n\n", "file_path": "tests/common/crypto.rs", "rank": 0, "score": 387509.8669507819 }, { "content": "pub fn random_slice(buf: &[u8]) -> (usize, &[u8]) {\n...
Rust
crates/holochain_zome_types/src/dna_def.rs
guillemcordoba/holochain
fa4acd2067176757327328446368b1e09bfa2a34
use super::zome; use crate::prelude::*; #[cfg(feature = "full-dna-def")] use crate::zome::error::ZomeError; #[cfg(feature = "full-dna-def")] use holo_hash::*; pub type IntegrityZomes = Vec<(ZomeName, zome::IntegrityZomeDef)>; pub type CoordinatorZomes = Vec<(ZomeName, zome::CoordinatorZomeDef)>; pub type Uid = String; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, SerializedBytes)] #[cfg_attr(feature = "full-dna-def", derive(derive_builder::Builder))] #[cfg_attr(feature = "full-dna-def", builder(public))] pub struct DnaDef { #[cfg_attr( feature = "full-dna-def", builder(default = "\"Generated DnaDef\".to_string()") )] pub name: String, pub uid: String, #[cfg_attr(feature = "full-dna-def", builder(default = "().try_into().unwrap()"))] pub properties: SerializedBytes, #[cfg_attr(feature = "full-dna-def", builder(default = "Timestamp::now()"))] pub origin_time: Timestamp, pub integrity_zomes: IntegrityZomes, pub coordinator_zomes: CoordinatorZomes, } #[derive(Serialize, Debug, PartialEq, Eq)] struct DnaDefHash<'a> { name: &'a String, uid: &'a String, properties: &'a SerializedBytes, integrity_zomes: &'a IntegrityZomes, } #[cfg(feature = "test_utils")] impl DnaDef { pub fn unique_from_zomes( integrity: Vec<IntegrityZome>, coordinator: Vec<CoordinatorZome>, ) -> DnaDef { let integrity = integrity.into_iter().map(|z| z.into_inner()).collect(); let coordinator = coordinator.into_iter().map(|z| z.into_inner()).collect(); DnaDefBuilder::default() .integrity_zomes(integrity) .coordinator_zomes(coordinator) .random_uid() .build() .unwrap() } } impl DnaDef { pub fn all_zomes(&self) -> impl Iterator<Item = (&ZomeName, &zome::ZomeDef)> { self.integrity_zomes .iter() .map(|(n, def)| (n, def.as_any_zome_def())) .chain( self.coordinator_zomes .iter() .map(|(n, def)| (n, def.as_any_zome_def())), ) } } #[cfg(feature = "full-dna-def")] impl DnaDef { pub fn get_integrity_zome( &self, zome_name: &ZomeName, ) -> Result<zome::IntegrityZome, ZomeError> { self.integrity_zomes .iter() .find(|(name, _)| name == zome_name) .cloned() .map(|(name, def)| IntegrityZome::new(name, def)) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) } pub fn is_integrity_zome(&self, zome_name: &ZomeName) -> bool { self.integrity_zomes .iter() .any(|(name, _)| name == zome_name) } pub fn get_coordinator_zome( &self, zome_name: &ZomeName, ) -> Result<zome::CoordinatorZome, ZomeError> { self.coordinator_zomes .iter() .find(|(name, _)| name == zome_name) .cloned() .map(|(name, def)| CoordinatorZome::new(name, def)) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) } pub fn get_zome(&self, zome_name: &ZomeName) -> Result<zome::Zome, ZomeError> { self.integrity_zomes .iter() .find(|(name, _)| name == zome_name) .cloned() .map(|(name, def)| Zome::new(name, def.erase_type())) .or_else(|| { self.coordinator_zomes .iter() .find(|(name, _)| name == zome_name) .cloned() .map(|(name, def)| Zome::new(name, def.erase_type())) }) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) } pub fn get_all_coordinators(&self) -> Vec<zome::CoordinatorZome> { self.coordinator_zomes .iter() .cloned() .map(|(name, def)| CoordinatorZome::new(name, def)) .collect() } pub fn get_wasm_zome(&self, zome_name: &ZomeName) -> Result<&zome::WasmZome, ZomeError> { self.all_zomes() .find(|(name, _)| *name == zome_name) .map(|(_, def)| def) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) .and_then(|def| { if let ZomeDef::Wasm(wasm_zome) = def { Ok(wasm_zome) } else { Err(ZomeError::NonWasmZome(zome_name.clone())) } }) } pub fn modify_phenotype(&self, uid: Uid, properties: SerializedBytes) -> Self { let mut clone = self.clone(); clone.properties = properties; clone.uid = uid; clone } } #[cfg(feature = "full-dna-def")] pub fn random_uid() -> String { nanoid::nanoid!() } #[cfg(feature = "full-dna-def")] impl DnaDefBuilder { pub fn random_uid(&mut self) -> &mut Self { self.uid = Some(random_uid()); self } } #[cfg(feature = "full-dna-def")] pub type DnaDefHashed = HoloHashed<DnaDef>; #[cfg(feature = "full-dna-def")] impl HashableContent for DnaDef { type HashType = holo_hash::hash_type::Dna; fn hash_type(&self) -> Self::HashType { holo_hash::hash_type::Dna::new() } fn hashable_content(&self) -> HashableContentBytes { let hash = DnaDefHash { name: &self.name, uid: &self.uid, properties: &self.properties, integrity_zomes: &self.integrity_zomes, }; HashableContentBytes::Content( holochain_serialized_bytes::UnsafeBytes::from( holochain_serialized_bytes::encode(&hash) .expect("Could not serialize HashableContent"), ) .into(), ) } }
use super::zome; use crate::prelude::*; #[cfg(feature = "full-dna-def")] use crate::zome::error::ZomeError; #[cfg(feature = "full-dna-def")] use holo_hash::*; pub type IntegrityZomes = Vec<(ZomeName, zome::IntegrityZomeDef)>; pub type CoordinatorZomes = Vec<(ZomeName, zome::CoordinatorZomeDef)>; pub type Uid = String; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, SerializedBytes)] #[cfg_attr(feature = "full-dna-def", derive(derive_builder::Builder))] #[cfg_attr(feature = "full-dna-def", builder(public))] pub struct DnaDef { #[cfg_attr( feature = "full-dna-def", builder(default = "\"Generated DnaDef\".to_string()") )] pub name: String, pub uid: String, #[cfg_attr(feature = "full-dna-def", builder(default = "().try_into().unwrap()"))] pub properties: SerializedBytes, #[cfg_attr(feature = "full-dna-def", builder(default = "Timestamp::now()"))] pub origin_time: Timestamp, pub integrity_zomes: IntegrityZomes, pub coordinator_zomes: CoordinatorZomes, } #[derive(Serialize, Debug, PartialEq, Eq)] struct DnaDefHash<'a> { name: &'a String, uid: &'a String, properties: &'a SerializedBytes, integrity_zomes: &'a IntegrityZomes, } #[cfg(feature = "test_utils")] impl DnaDef { pub fn unique_from_zomes( integrity: Vec<IntegrityZome>, coordinator: Vec<CoordinatorZome>, ) -> DnaDef { let integrity = integrity.into_iter().map(|z| z.into_inner()).collect(); let coordinator = coordinator.into_iter().map(|z| z.into_inner()).collect(); DnaDefBuilder::default() .integrity_zomes(integrity) .coordinator_zomes(coordinator) .random_uid() .build() .unwrap() } } impl DnaDef { pub fn all_zomes(&self) -> impl Iterator<Item = (&ZomeName, &zome::ZomeDef)> { self.integrity_zomes .iter() .map(|(n, def)| (n, def.as_any_zome_def())) .chain( self.coordinator_zomes .iter() .map(|(n, def)| (n, def.as_any_zome_def())), ) } } #[cfg(feature = "full-dna-def")] impl DnaDef { pub fn get_integrity_zome( &self, zome_name: &ZomeName, ) -> Result<zome::IntegrityZome, ZomeError> { self.integrity_zomes .iter() .find(|(name, _)| name == zome_name) .cloned() .map(|(name, def)| IntegrityZome::new(name, def)) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) } pub fn is_integrity_zome(&self, zome_name: &ZomeName) -> bool { self.integrity_zomes .iter() .any(|(name, _)| name == zome_name) } pub fn get_coordinator_zome( &self, zome_name: &ZomeName, ) -> Result<zome::CoordinatorZome, ZomeError> { self.coordinator_zomes .iter() .find(|(name, _)| name == zome_name) .cloned() .map(|(name, def)| CoordinatorZome::new(name, def)) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) } pub fn get_zome(&self, zome_name: &ZomeName) -> Result<zome::Zome, ZomeError> { self.integrity_zomes .iter() .find(|(name, _)| name == zome_name) .cloned() .map(|(name, def)| Zome::new(name, def.erase_type())) .or_else(|| { self.coordinator_zomes .iter() .find(|(name, _)| name == zome_name) .cloned() .map(|(name, def)| Zome::new(name, def.erase_type())) }) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) } pub fn get_all_coordinators(&self) -> Vec<zome::CoordinatorZome> { self.coordinator_zomes .iter() .cloned() .map(|(name, def)| CoordinatorZome::new(name, def)) .collect() } pub fn get_wasm_zome(&self, zome_name: &ZomeName) -> Result<&zome::WasmZome, ZomeError> { sel
pub fn modify_phenotype(&self, uid: Uid, properties: SerializedBytes) -> Self { let mut clone = self.clone(); clone.properties = properties; clone.uid = uid; clone } } #[cfg(feature = "full-dna-def")] pub fn random_uid() -> String { nanoid::nanoid!() } #[cfg(feature = "full-dna-def")] impl DnaDefBuilder { pub fn random_uid(&mut self) -> &mut Self { self.uid = Some(random_uid()); self } } #[cfg(feature = "full-dna-def")] pub type DnaDefHashed = HoloHashed<DnaDef>; #[cfg(feature = "full-dna-def")] impl HashableContent for DnaDef { type HashType = holo_hash::hash_type::Dna; fn hash_type(&self) -> Self::HashType { holo_hash::hash_type::Dna::new() } fn hashable_content(&self) -> HashableContentBytes { let hash = DnaDefHash { name: &self.name, uid: &self.uid, properties: &self.properties, integrity_zomes: &self.integrity_zomes, }; HashableContentBytes::Content( holochain_serialized_bytes::UnsafeBytes::from( holochain_serialized_bytes::encode(&hash) .expect("Could not serialize HashableContent"), ) .into(), ) } }
f.all_zomes() .find(|(name, _)| *name == zome_name) .map(|(_, def)| def) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) .and_then(|def| { if let ZomeDef::Wasm(wasm_zome) = def { Ok(wasm_zome) } else { Err(ZomeError::NonWasmZome(zome_name.clone())) } }) }
function_block-function_prefixed
[]
Rust
benches/hashmap.rs
junghan0611/node-replication
c06f653051987a8bbc097486f1f815bd9787cb81
#![allow(dead_code)] #![feature(test)] use std::collections::HashMap; use std::fmt::Debug; use std::marker::Sync; use rand::seq::SliceRandom; use rand::{distributions::Distribution, Rng, RngCore}; use zipf::ZipfDistribution; use node_replication::Dispatch; use node_replication::Replica; mod hashmap_comparisons; mod mkbench; mod utils; use hashmap_comparisons::*; use mkbench::ReplicaTrait; use utils::benchmark::*; use utils::topology::ThreadMapping; use utils::Operation; #[cfg(feature = "smokebench")] pub const INITIAL_CAPACITY: usize = 1 << 22; #[cfg(not(feature = "smokebench"))] pub const INITIAL_CAPACITY: usize = 1 << 26; #[cfg(feature = "smokebench")] pub const KEY_SPACE: usize = 5_000_000; #[cfg(not(feature = "smokebench"))] pub const KEY_SPACE: usize = 50_000_000; pub const UNIFORM: &'static str = "uniform"; #[cfg(feature = "smokebench")] pub const NOP: usize = 2_500_000; #[cfg(not(feature = "smokebench"))] pub const NOP: usize = 25_000_000; #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum OpWr { Put(u64, u64), } #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum OpRd { Get(u64), } #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum OpConcurrent { Get(u64), Put(u64, u64), } #[derive(Debug, Clone)] pub struct NrHashMap { storage: HashMap<u64, u64>, } impl NrHashMap { pub fn put(&mut self, key: u64, val: u64) { self.storage.insert(key, val); } pub fn get(&self, key: u64) -> Option<u64> { self.storage.get(&key).map(|v| *v) } } impl Default for NrHashMap { fn default() -> NrHashMap { let mut storage = HashMap::with_capacity(INITIAL_CAPACITY); for i in 0..INITIAL_CAPACITY { storage.insert(i as u64, (i + 1) as u64); } NrHashMap { storage } } } impl Dispatch for NrHashMap { type ReadOperation = OpRd; type WriteOperation = OpWr; type Response = Result<Option<u64>, ()>; fn dispatch(&self, op: Self::ReadOperation) -> Self::Response { match op { OpRd::Get(key) => return Ok(self.get(key)), } } fn dispatch_mut(&mut self, op: Self::WriteOperation) -> Self::Response { match op { OpWr::Put(key, val) => { self.put(key, val); Ok(None) } } } } pub fn generate_operations( nop: usize, write_ratio: usize, span: usize, distribution: &'static str, ) -> Vec<Operation<OpRd, OpWr>> { assert!(distribution == "skewed" || distribution == "uniform"); let mut ops = Vec::with_capacity(nop); let skewed = distribution == "skewed"; let mut t_rng = rand::thread_rng(); let zipf = ZipfDistribution::new(span, 1.03).unwrap(); for idx in 0..nop { let id = if skewed { zipf.sample(&mut t_rng) as u64 } else { t_rng.gen_range(0, span as u64) }; if idx % 100 < write_ratio { ops.push(Operation::WriteOperation(OpWr::Put(id, t_rng.next_u64()))); } else { ops.push(Operation::ReadOperation(OpRd::Get(id))); } } ops.shuffle(&mut t_rng); ops } pub fn generate_operations_concurrent( nop: usize, write_ratio: usize, span: usize, distribution: &'static str, ) -> Vec<Operation<OpConcurrent, ()>> { assert!(distribution == "skewed" || distribution == "uniform"); let mut ops = Vec::with_capacity(nop); let skewed = distribution == "skewed"; let mut t_rng = rand::thread_rng(); let zipf = ZipfDistribution::new(span, 1.03).unwrap(); for idx in 0..nop { let id = if skewed { zipf.sample(&mut t_rng) as u64 } else { t_rng.gen_range(0, span as u64) }; if idx % 100 < write_ratio { ops.push(Operation::ReadOperation(OpConcurrent::Put( id, t_rng.next_u64(), ))); } else { ops.push(Operation::ReadOperation(OpConcurrent::Get(id))); } } ops.shuffle(&mut t_rng); ops } fn hashmap_single_threaded(c: &mut TestHarness) { const LOG_SIZE_BYTES: usize = 2 * 1024 * 1024; const NOP: usize = 1000; const KEY_SPACE: usize = 10_000; const UNIFORM: &'static str = "uniform"; const WRITE_RATIO: usize = 10; let ops = generate_operations(NOP, WRITE_RATIO, KEY_SPACE, UNIFORM); mkbench::baseline_comparison::<Replica<NrHashMap>>(c, "hashmap", ops, LOG_SIZE_BYTES); } fn hashmap_scale_out<R>(c: &mut TestHarness, name: &str, write_ratio: usize) where R: ReplicaTrait + Send + Sync + 'static, R::D: Send, R::D: Dispatch<ReadOperation = OpRd>, R::D: Dispatch<WriteOperation = OpWr>, <R::D as Dispatch>::WriteOperation: Send + Sync, <R::D as Dispatch>::ReadOperation: Send + Sync, <R::D as Dispatch>::Response: Sync + Send + Debug, { let ops = generate_operations(NOP, write_ratio, KEY_SPACE, UNIFORM); let bench_name = format!("{}-scaleout-wr{}", name, write_ratio); mkbench::ScaleBenchBuilder::<R>::new(ops) .thread_defaults() .update_batch(128) .log_size(32 * 1024 * 1024) .replica_strategy(mkbench::ReplicaStrategy::One) .replica_strategy(mkbench::ReplicaStrategy::Socket) .thread_mapping(ThreadMapping::Interleave) .log_strategy(mkbench::LogStrategy::One) .configure( c, &bench_name, |_cid, rid, _log, replica, op, _batch_size| match op { Operation::ReadOperation(op) => { replica.exec_ro(*op, rid); } Operation::WriteOperation(op) => { replica.exec(*op, rid); } }, ); } fn partitioned_hashmap_scale_out(c: &mut TestHarness, name: &str, write_ratio: usize) { let ops = generate_operations(NOP, write_ratio, KEY_SPACE, UNIFORM); let bench_name = format!("{}-scaleout-wr{}", name, write_ratio); mkbench::ScaleBenchBuilder::<Partitioner<NrHashMap>>::new(ops) .thread_defaults() .replica_strategy(mkbench::ReplicaStrategy::PerThread) .thread_mapping(ThreadMapping::Interleave) .log_strategy(mkbench::LogStrategy::One) .update_batch(128) .configure( c, &bench_name, |_cid, rid, _log, replica, op, _batch_size| match op { Operation::ReadOperation(op) => { replica.exec_ro(*op, rid).unwrap(); } Operation::WriteOperation(op) => { replica.exec(*op, rid).unwrap(); } }, ); } fn concurrent_ds_scale_out<T>(c: &mut TestHarness, name: &str, write_ratio: usize) where T: Dispatch<ReadOperation = OpConcurrent>, T: Dispatch<WriteOperation = ()>, T: 'static, T: Dispatch + Sync + Default + Send, <T as Dispatch>::Response: Send + Sync + Debug, { let ops = generate_operations_concurrent(NOP, write_ratio, KEY_SPACE, UNIFORM); let bench_name = format!("{}-scaleout-wr{}", name, write_ratio); mkbench::ScaleBenchBuilder::<ConcurrentDs<T>>::new(ops) .thread_defaults() .replica_strategy(mkbench::ReplicaStrategy::One) .update_batch(128) .thread_mapping(ThreadMapping::Interleave) .log_strategy(mkbench::LogStrategy::One) .configure( c, &bench_name, |_cid, rid, _log, replica, op, _batch_size| match op { Operation::ReadOperation(op) => { replica.exec_ro(*op, rid); } Operation::WriteOperation(op) => { replica.exec(*op, rid); } }, ); } fn main() { let _r = env_logger::try_init(); if cfg!(feature = "smokebench") { log::warn!("Running with feature 'smokebench' may not get the desired results"); } utils::disable_dvfs(); let mut harness = Default::default(); let write_ratios = vec![0, 10, 20, 40, 60, 80, 100]; unsafe { urcu_sys::rcu_init(); } hashmap_single_threaded(&mut harness); for write_ratio in write_ratios.into_iter() { hashmap_scale_out::<Replica<NrHashMap>>(&mut harness, "hashmap", write_ratio); #[cfg(feature = "cmp")] { partitioned_hashmap_scale_out(&mut harness, "partitioned-hashmap", write_ratio); concurrent_ds_scale_out::<CHashMapWrapper>(&mut harness, "chashmap", write_ratio); concurrent_ds_scale_out::<StdWrapper>(&mut harness, "std", write_ratio); concurrent_ds_scale_out::<FlurryWrapper>(&mut harness, "flurry", write_ratio); concurrent_ds_scale_out::<RcuHashMap>(&mut harness, "urcu", write_ratio); concurrent_ds_scale_out::<DashWrapper>(&mut harness, "dashmap", write_ratio); } } }
#![allow(dead_code)] #![feature(test)] use std::collections::HashMap; use std::fmt::Debug; use std::marker::Sync; use rand::seq::SliceRandom; use rand::{distributions::Distribution, Rng, RngCore}; use zipf::ZipfDistribution; use node_replication::Dispatch; use node_replication::Replica; mod hashmap_comparisons; mod mkbench; mod utils; use hashmap_comparisons::*; use mkbench::ReplicaTrait; use utils::benchmark::*; use utils::topology::ThreadMapping; use utils::Operation; #[cfg(feature = "smokebench")] pub const INITIAL_CAPACITY: usize = 1 << 22; #[cfg(not(feature = "smokebench"))] pub const INITIAL_CAPACITY: usize = 1 << 26; #[cfg(feature = "smokebench")] pub const KEY_SPACE: usize = 5_000_000; #[cfg(not(feature = "smokebench"))] pub const KEY_SPACE: usize = 50_000_000; pub const UNIFORM: &'static str = "uniform"; #[cfg(feature = "smokebench")] pub const NOP: usize = 2_500_000; #[cfg(not(feature = "smokebench"))] pub const NOP: usize = 25_000_000; #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum OpWr { Put(u64, u64), } #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum OpRd { Get(u64), } #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum OpConcurrent { Get(u64), Put(u64, u64), } #[derive(Debug, Clone)] pub struct NrHashMap { storage: HashMap<u64, u64>, } impl NrHashMap { pub fn put(&mut self, key: u64, val: u64) { self.storage.insert(key, val); } pub fn get(&self, key: u64) -> Option<u64> { self.storage.get(&key).map(|v| *v) } } impl Default for NrHashMap { fn default() -> NrHashMap { let mut storage = HashMap::with_capacity(INITIAL_CAPACITY); for i in 0..INITIAL_CAPACITY { storage.insert(i as u64, (i + 1) as u64); } NrHashMap { storage } } } impl Dispatch for NrHashMap { type ReadOperation = OpRd; type WriteOperation = OpWr; type Response = Result<Option<u64>, ()>; fn dispatch(&self, op: Self::ReadOperation) -> Self::Response { match op { OpRd::Get(key) => return Ok(self.get(key)), } } fn dispatch_mut(&mut self, op: Self::WriteOperation) -> Self::Response { match op { OpWr::Put(key, val) => { self.put(key, val); Ok(None) } } } } pub fn generate_operations( nop: usize, write_ratio: usize, span: usize, distribution: &'static str, ) -> Vec<Operation<OpRd, OpWr>> { assert!(distribution == "skewed" || distribution == "uniform"); let mut ops = Vec::with_capacity(nop); let skewed = distribution == "skewed"; let mut t_rng = rand::thread_rng(); let zipf = ZipfDistribution::new(span, 1.03).unwrap(); for idx in 0..nop { let id = if skewed { zipf.sample(&mut t_rng) as u64 } else { t_rng.gen_range(0, span as u64) }; if idx % 100 < write_ratio { ops.push(Operation::WriteOperation(OpWr::Put(id, t_rng.next_u64()))); } else { ops.push(Operation::ReadOperation(OpRd::Get(id))); } } ops.shuffle(&mut t_rng); ops } pub fn generate_operations_concurrent( nop: usize, write_ratio: usize, span: usize, distribution: &'static str, ) -> Vec<Operation<OpConcurrent, ()>> { assert!(distribution == "skewed" || distribution == "uniform"); let mut ops = Vec::with_capacity(nop); let skewed = distribution == "skewed"; let mut t_rng = rand::thread_rng(); let zipf = ZipfDistribution::new(span, 1.03).unwrap(); for idx in 0..nop { let id = if skewed { zipf.sample(&mut t_rng) as u64 } else { t_rng.gen_range(0, span as u64) }; if idx % 100 < write_ratio { ops.push(Operation::ReadOperation(OpConcurrent::Put( id, t_rng.next_u64(), ))); } else { ops.push(Operation::ReadOperation(OpConcurrent::Get(id))); } } ops.shuffle(&mut t_rng); ops } fn hashmap_single_threaded(c: &mut TestHarness) { const LOG_SIZE_BYTES: usize = 2 * 1024 * 1024; const NOP: usize = 1000; const KEY_SPACE: usize = 10_000; const UNIFORM: &'static str = "uniform"; const WRITE_RATIO: usize = 10; let ops = generate_operations(NOP, WRITE_RATIO, KEY_SPACE, UNIFORM); mkbench::baseline_comparison::<Replica<NrHashMap>>(c, "hashmap", ops, LOG_SIZE_BYTES); } fn hashmap_scale_out<R>(c: &mut TestHarness, name: &str, write_ratio: usize) where R: ReplicaTrait + Send + Sync + 'static, R::D: Send, R::D: Dispatch<ReadOperation = OpRd>, R::D: Dispatch<WriteOperation = OpWr>, <R::D as Dispatch>::WriteOperation: Send + Sync, <R::D as Dispatch>::ReadOperation: Send + Sync, <R::D as Dispatch>::Response: Sync + Send + Debug, { let ops = generate_operations(NOP, write_ratio, KEY_SPACE, UNIFORM); let bench_name = format!("{}-scaleout-wr{}", name, write_ratio); mkbench::ScaleBenchBuilder::<R>::new(ops) .thread_defaults() .update_batch(128) .log_size(32 * 1024 * 1024) .replica_strategy(mkbench::ReplicaStrategy::One) .replica_strategy(mkbench::ReplicaStrategy::Socket) .thread_mapping(ThreadMapping::Interleave) .log_strategy(mkbench::LogStrategy::One) .configure( c, &bench_name, |_cid, rid, _log, replica, op, _batch_size|
, ); } fn partitioned_hashmap_scale_out(c: &mut TestHarness, name: &str, write_ratio: usize) { let ops = generate_operations(NOP, write_ratio, KEY_SPACE, UNIFORM); let bench_name = format!("{}-scaleout-wr{}", name, write_ratio); mkbench::ScaleBenchBuilder::<Partitioner<NrHashMap>>::new(ops) .thread_defaults() .replica_strategy(mkbench::ReplicaStrategy::PerThread) .thread_mapping(ThreadMapping::Interleave) .log_strategy(mkbench::LogStrategy::One) .update_batch(128) .configure( c, &bench_name, |_cid, rid, _log, replica, op, _batch_size| match op { Operation::ReadOperation(op) => { replica.exec_ro(*op, rid).unwrap(); } Operation::WriteOperation(op) => { replica.exec(*op, rid).unwrap(); } }, ); } fn concurrent_ds_scale_out<T>(c: &mut TestHarness, name: &str, write_ratio: usize) where T: Dispatch<ReadOperation = OpConcurrent>, T: Dispatch<WriteOperation = ()>, T: 'static, T: Dispatch + Sync + Default + Send, <T as Dispatch>::Response: Send + Sync + Debug, { let ops = generate_operations_concurrent(NOP, write_ratio, KEY_SPACE, UNIFORM); let bench_name = format!("{}-scaleout-wr{}", name, write_ratio); mkbench::ScaleBenchBuilder::<ConcurrentDs<T>>::new(ops) .thread_defaults() .replica_strategy(mkbench::ReplicaStrategy::One) .update_batch(128) .thread_mapping(ThreadMapping::Interleave) .log_strategy(mkbench::LogStrategy::One) .configure( c, &bench_name, |_cid, rid, _log, replica, op, _batch_size| match op { Operation::ReadOperation(op) => { replica.exec_ro(*op, rid); } Operation::WriteOperation(op) => { replica.exec(*op, rid); } }, ); } fn main() { let _r = env_logger::try_init(); if cfg!(feature = "smokebench") { log::warn!("Running with feature 'smokebench' may not get the desired results"); } utils::disable_dvfs(); let mut harness = Default::default(); let write_ratios = vec![0, 10, 20, 40, 60, 80, 100]; unsafe { urcu_sys::rcu_init(); } hashmap_single_threaded(&mut harness); for write_ratio in write_ratios.into_iter() { hashmap_scale_out::<Replica<NrHashMap>>(&mut harness, "hashmap", write_ratio); #[cfg(feature = "cmp")] { partitioned_hashmap_scale_out(&mut harness, "partitioned-hashmap", write_ratio); concurrent_ds_scale_out::<CHashMapWrapper>(&mut harness, "chashmap", write_ratio); concurrent_ds_scale_out::<StdWrapper>(&mut harness, "std", write_ratio); concurrent_ds_scale_out::<FlurryWrapper>(&mut harness, "flurry", write_ratio); concurrent_ds_scale_out::<RcuHashMap>(&mut harness, "urcu", write_ratio); concurrent_ds_scale_out::<DashWrapper>(&mut harness, "dashmap", write_ratio); } } }
match op { Operation::ReadOperation(op) => { replica.exec_ro(*op, rid); } Operation::WriteOperation(op) => { replica.exec(*op, rid); } }
if_condition
[ { "content": "fn concurrent_ds_nr_scale_out<R>(c: &mut TestHarness, name: &str, write_ratio: usize)\n\nwhere\n\n R: ReplicaTrait + Send + Sync + 'static,\n\n R::D: Send,\n\n R::D: Dispatch<ReadOperation = SkipListConcurrent>,\n\n R::D: Dispatch<WriteOperation = OpWr>,\n\n <R::D as Dispatch>::Writ...
Rust
src/gen/generate.rs
warpwm/lule
dd429596aa32895bd19ba814951ba1fda65275c3
use rand::prelude::*; use crate::scheme::*; pub fn gen_main_six(col: &Vec<pastel::Color>) -> Vec<pastel::Color> { let mut colors = col.clone(); colors.retain(|x| x.to_lab().l > 20.0); colors.retain(|x| x.to_lab().l < 80.0); colors.sort_by_key(|c| (c.to_lch().l) as i32); colors.reverse(); let mut i = 0; while colors.len() < 6 { colors.push(pastel::Color::complementary(&colors[i])); i = i +1; } let mut main_colors: Vec<pastel::Color> = Vec::new(); for i in 0..6 { main_colors.push(colors[i].clone()) } main_colors.sort_by_key(|c| (c.to_lch().c) as i32); main_colors.reverse(); main_colors } pub fn get_black_white(ac: &pastel::Color, black_mix: f64, white_mix: f64, theme: bool) -> (pastel::Color, pastel::Color) { let black = pastel::Color::from_rgb(0,0,0); let white = pastel::Color::from_rgb(255,255,255); let dark = black.mix::<pastel::RGBA<f64>>(&ac, pastel::Fraction::from(black_mix)); let light = white.mix::<pastel::RGBA<f64>>(&ac, pastel::Fraction::from(white_mix)); if theme { (dark, light) } else { (light, dark) } } pub fn get_two_grays(ac: &pastel::Color, mix: f64, theme: bool) -> (pastel::Color, pastel::Color) { let darker = pastel::Color::from_rgb(100,100,100); let lighter = pastel::Color::from_rgb(170,170,170); let dark = darker.mix::<pastel::RGBA<f64>>(&ac, pastel::Fraction::from(mix)); let light = lighter.mix::<pastel::RGBA<f64>>(&ac, pastel::Fraction::from(mix)); if theme { (dark, light) } else { (light, dark) } } pub fn gen_prime_six(colors: Vec<pastel::Color>, mix: f64, theme: bool) -> Vec<pastel::Color> { let mut second_colors: Vec<pastel::Color> = Vec::new(); for col in colors.iter() { let new_col = if theme { col.lighten(mix) } else { col.darken(mix) }; second_colors.push(new_col) } second_colors } pub fn gen_second_six(colors: Vec<pastel::Color>, mix: f64, theme: bool) -> Vec<pastel::Color> { let mut second_colors: Vec<pastel::Color> = Vec::new(); for col in colors.iter() { let new_col = if ! theme { col.lighten(mix) } else { col.darken(mix) }; second_colors.push(new_col) } second_colors } pub fn gen_shades(colors: Vec<&pastel::Color>, number: u8) -> Vec<pastel::Color>{ let mut color_scale = pastel::ColorScale::empty(); let mut gradients: Vec<pastel::Color> = Vec::new(); for (i, color) in colors.iter().enumerate() { let position = pastel::Fraction::from(i as f64 / (colors.len() as f64 - 1.0)); color_scale.add_stop(color.clone().clone(), position); } let mix = Box::new(|c1: &pastel::Color, c2: &pastel::Color, f: pastel::Fraction| c1.mix::<pastel::Lab>(c2, f)); let count = number + 2; for i in 0..count { let position = pastel::Fraction::from(i as f64 / (count as f64 - 1.0)); let color = color_scale.sample(position, &mix).expect("gradient color"); if i == 0 || i == count-1 { continue; } gradients.push(color) } gradients } pub fn gen_gradients(ac: pastel::Color, col0: pastel::Color, col15: pastel::Color, black: pastel::Color, white: pastel::Color) -> Vec<pastel::Color> { let mut gradients: Vec<pastel::Color> = Vec::new(); gradients.push(black.clone()); let blacks = gen_shades(vec![&black, &col0], 3); gradients.extend(blacks); let middle = gen_shades(vec![&col0, &ac, &col15], 16); gradients.extend(middle); let whites = gen_shades(vec![&col15, &white], 3); gradients.extend(whites); gradients.push(white.clone()); gradients } pub fn get_all_colors(scheme: &mut SCHEME) -> Vec<pastel::Color> { let theme = if scheme.theme().as_ref().unwrap_or(&"dark".to_string()) == "light" { false } else { true }; let mut palette: Vec<pastel::Color> = Vec::new(); if let Some(ref cols) = scheme.pigments() { for c in cols.iter() { palette.push(pastel::Color::from_hex(c)); } } let main = gen_main_six(&palette); let mut black = pastel::Color::from_rgb(0,0,0); let mut white = pastel::Color::from_rgb(255,255,255); if !theme { white = pastel::Color::from_rgb(0,0,0); black = pastel::Color::from_rgb(255,255,255); } let prime = gen_prime_six(main.clone(), 0.1, theme); let acc = prime.get(0).unwrap().clone(); let (col0, col15) = get_black_white(&acc, 0.08, 0.12, theme); let (col7, col8) = get_two_grays(&acc, 0.2, theme); let second = gen_second_six(main.clone(), 0.1, theme); let gradients = gen_gradients(acc.clone(), col0.clone(), col15.clone(), black, white); let mut colors: Vec<pastel::Color> = Vec::new(); colors.push(col0.clone()); colors.extend(prime); colors.push(col7); colors.push(col8); colors.extend(second); colors.push(col15.clone()); for _ in 0..18 { let rng: &mut dyn RngCore = &mut thread_rng(); let hue = rng.gen::<f64>() * 360.0; let saturation = 0.2 + 0.6 * rng.gen::<f64>(); let lightness = 0.3 + 0.4 * rng.gen::<f64>(); colors.extend( gen_shades(vec![&col0, &pastel::Color::from_hsl(hue, saturation, lightness), &col15], 12) ); } colors.extend(gradients); colors }
use rand::prelude::*; use crate::scheme::*; pub fn gen_main_six(col: &Vec<pastel::Color>) -> Vec<pastel::Color> { let mut colors = col.clone(); colors.retain(|x| x.to_lab().l > 20.0); colors.retain(|x| x.to_lab().l < 80.0); colors.sort_by_key(|c| (c.to_lch().l) as i32); colors.reverse(); let mut i = 0; while colors.len() < 6 { colors.push(pastel::Color::complementary(&colors[i])); i = i +1; } let mut main_colors: Vec<pastel::Color> = Vec::new(); for i in 0..6 { main_colors.push(colors[i].clone()) } main_colors.sort_by_key(|c| (c.to_lch().c) as i32); main_colors.reverse(); main_colors } pub fn get_black_white(ac: &pastel::Color, black_mix: f64, white_mix: f64, theme: bool) -> (pastel::Color, pastel::Color) { let black = pastel::Color::from_rgb(0,0,0); let white = pastel::Color::from_rgb(255,255,255); let dark = black.mix::<pastel::RGBA<f64>>(&ac, pastel::Fraction::from(black_mix)); let light = white.mix::<pastel::RGBA<f64>>(&ac, pastel::Fraction::from(white_mix)); if theme { (dark, light) } else { (light, dark) } } pub fn get_two_grays(ac: &pastel::Color, mix: f64, theme: bool) -> (pastel::Color, pastel::Color) { let darker = pastel::Color::from_rgb(100,100,100); let lighter = pastel::Color::from_rgb(170,170,170); let dark = darker.mix::<pastel::RGBA<f64>>(&ac, pastel::Fraction::from(mix)); let light = lighter.mix::<pastel::RGBA<f64>>(&ac, pastel::Fraction::from(mix)); if theme { (dark, light) } else { (light, dark) } } pub fn gen_prime_six(colors: Vec<pastel::Color>, mix: f64, theme: bool) -> Vec<pastel::Color> { let mut second_colors: Vec<pastel::Color> = Vec::new(); for col in colors.iter() { let new_col = if theme { col.lighten(mix) } else { col.darken(mix) }; second_colors.push(new_col) } second_colors } pub fn gen_second_six(colors: Vec<pastel::Color>, mix: f64, theme: bool) -> Vec<pastel::Color> { let mut second_colors: Vec<pastel::Color> = Vec::new(); for col in colors.iter() { let new_col = if ! theme { col.lighten(mix) } else { col.darken(mix) }; second_colors.push(new_col) } second_colors } pub fn gen_shades(colors: Vec<&pastel::Color>, number: u8) -> Vec<pastel::Color>{ let mut color_scale = pastel::ColorScale::empty(); let mut gradients: Vec<pastel::Color> = Vec::new(); for (i, color) in colors.iter().enumerate() { let position = pastel::Fraction::from(i as f64 / (colors.len() as f64 - 1.0)); color_scale.add_stop(color.clone().clone(), position); } let mix = Box::new(|c1: &pastel::Color, c2: &pastel::Color, f: pastel::Fraction| c1.mix::<pastel::Lab>(c2, f)); let count = number + 2; for i in 0..count { let position = pastel::Fraction::from(i as f64 / (count as f64 - 1.0)); let color = color_scale.sample(position, &mix).expect("gradient color"); if i == 0 || i == count-1 { continue; } gradients.push(color) } gradients } pub fn gen_gradients(ac: pastel::Color, col0: pastel::Color, col15: pastel::Color, black: pastel::Color, white: pastel::Color) -> Vec<pastel::Color> { let mut gradients: Vec<pastel::Color> = Vec::new(); gradients.push(black.clone()); let blacks = gen_shades(vec![&black, &col0], 3); gradients.extend(blacks); let middle = gen_shades(vec![&col0, &ac, &col15], 16); gradients.extend(middle); let whites = gen_shades(vec![&col15, &white], 3); gradients.extend(whites); gradients.push(white.clone()); gradients } pub fn get_all_colors(scheme: &mut SCHEME) -> Vec<pastel::Color> { let theme = if scheme.theme().as_ref().unwrap_or(&"dark".to_string()) == "light" { false } else { true }; let mut palette: Vec<pastel::Color> = Vec::new(); if l
et Some(ref cols) = scheme.pigments() { for c in cols.iter() { palette.push(pastel::Color::from_hex(c)); } } let main = gen_main_six(&palette); let mut black = pastel::Color::from_rgb(0,0,0); let mut white = pastel::Color::from_rgb(255,255,255); if !theme { white = pastel::Color::from_rgb(0,0,0); black = pastel::Color::from_rgb(255,255,255); } let prime = gen_prime_six(main.clone(), 0.1, theme); let acc = prime.get(0).unwrap().clone(); let (col0, col15) = get_black_white(&acc, 0.08, 0.12, theme); let (col7, col8) = get_two_grays(&acc, 0.2, theme); let second = gen_second_six(main.clone(), 0.1, theme); let gradients = gen_gradients(acc.clone(), col0.clone(), col15.clone(), black, white); let mut colors: Vec<pastel::Color> = Vec::new(); colors.push(col0.clone()); colors.extend(prime); colors.push(col7); colors.push(col8); colors.extend(second); colors.push(col15.clone()); for _ in 0..18 { let rng: &mut dyn RngCore = &mut thread_rng(); let hue = rng.gen::<f64>() * 360.0; let saturation = 0.2 + 0.6 * rng.gen::<f64>(); let lightness = 0.3 + 0.4 * rng.gen::<f64>(); colors.extend( gen_shades(vec![&col0, &pastel::Color::from_hsl(hue, saturation, lightness), &col15], 12) ); } colors.extend(gradients); colors }
function_block-function_prefixed
[ { "content": "pub fn write_colors(scheme: &mut SCHEME, old: bool) -> Result<()> {\n\n if old {\n\n if let Some(cachepath) = scheme.cache().clone() {\n\n let mut palette_temp = PathBuf::from(&cachepath); palette_temp.push(\"palette\");\n\n scheme.set_pigments(Some(text::lines_to_v...
Rust
contracts/terranames_auction/src/state.rs
jonls/terranames-contracts
13f50b1d396c26391f43478b06f72b220978e4ab
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Addr, Order, StdError, StdResult, Storage, Uint128}; use cosmwasm_storage::{ bucket, bucket_read, singleton, singleton_read, }; use terranames::auction::{ seconds_from_deposit, deposit_from_seconds_ceil, deposit_from_seconds_floor, }; use terranames::utils::{Timedelta, Timestamp}; pub static CONFIG_KEY: &[u8] = b"config"; pub static NAME_STATE_PREFIX: &[u8] = b"name"; const DEFAULT_LIMIT: u32 = 10; const MAX_LIMIT: u32 = 30; fn calc_range_start_str(start_after: Option<&str>) -> Option<Vec<u8>> { start_after.map(|s| { let mut v: Vec<u8> = s.into(); v.push(0); v }) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub collector_addr: Addr, pub stable_denom: String, pub min_lease_secs: Timedelta, pub max_lease_secs: Timedelta, pub counter_delay_secs: Timedelta, pub transition_delay_secs: Timedelta, pub bid_delay_secs: Timedelta, } pub fn read_config(storage: &dyn Storage) -> StdResult<Config> { singleton_read(storage, CONFIG_KEY).load() } #[must_use] pub fn store_config( storage: &mut dyn Storage, config: &Config, ) -> StdResult<()> { singleton(storage, CONFIG_KEY).save(config) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct NameState { pub owner: Addr, pub controller: Option<Addr>, pub transition_reference_time: Timestamp, pub rate: Uint128, pub begin_time: Timestamp, pub begin_deposit: Uint128, pub previous_owner: Option<Addr>, pub previous_transition_reference_time: Timestamp, } impl NameState { pub fn seconds_spent_since_bid(&self, current_time: Timestamp) -> Option<Timedelta> { current_time.checked_sub(self.begin_time).ok() } pub fn seconds_spent_since_transition(&self, current_time: Timestamp) -> Option<Timedelta> { current_time.checked_sub(self.transition_reference_time).ok() } pub fn counter_delay_end(&self, config: &Config) -> Timestamp { self.begin_time + config.counter_delay_secs } pub fn transition_delay_end(&self, config: &Config) -> Timestamp { if self.transition_reference_time.is_zero() { self.begin_time } else { self.transition_reference_time + config.counter_delay_secs + config.transition_delay_secs } } pub fn bid_delay_end(&self, config: &Config) -> Timestamp { let delay = if !self.rate.is_zero() { config.counter_delay_secs + config.bid_delay_secs } else { Timedelta::zero() }; self.begin_time + delay } pub fn max_seconds(&self) -> Option<Timedelta> { seconds_from_deposit(self.begin_deposit, self.rate) } pub fn expire_time(&self) -> Option<Timestamp> { self.max_seconds().map(|max_seconds| self.begin_time + max_seconds) } pub fn current_deposit(&self, current_time: Timestamp) -> Uint128 { let seconds_spent = match self.seconds_spent_since_bid(current_time) { Some(seconds_spent) => seconds_spent, None => return Uint128::zero(), }; let deposit_spent = deposit_from_seconds_ceil(seconds_spent, self.rate); self.begin_deposit - deposit_spent } pub fn max_allowed_deposit(&self, config: &Config, current_time: Timestamp) -> Uint128 { let seconds_spent = match self.seconds_spent_since_bid(current_time) { Some(seconds_spent) => seconds_spent, None => return Uint128::zero(), }; let max_seconds_from_beginning = config.max_lease_secs + seconds_spent; deposit_from_seconds_floor(max_seconds_from_beginning, self.rate) } pub fn owner_status(&self, config: &Config, current_time: Timestamp) -> OwnerStatus { let seconds_spent_since_bid = match self.seconds_spent_since_bid(current_time) { Some(seconds_spent) => seconds_spent, None => return OwnerStatus::Expired { expire_time: Timestamp::zero(), transition_reference_time: self.transition_reference_time, }, }; if let Some(max_seconds) = self.max_seconds() { if seconds_spent_since_bid >= max_seconds { return OwnerStatus::Expired { expire_time: self.begin_time + max_seconds, transition_reference_time: self.transition_reference_time, }; } } let seconds_spent_since_transition = match self.seconds_spent_since_transition(current_time) { Some(seconds_spent) => seconds_spent, None => return OwnerStatus::Expired { expire_time: Timestamp::zero(), transition_reference_time: self.transition_reference_time, }, }; if seconds_spent_since_bid < config.counter_delay_secs { OwnerStatus::CounterDelay { name_owner: self.previous_owner.clone(), bid_owner: self.owner.clone(), transition_reference_time: self.previous_transition_reference_time, } } else if seconds_spent_since_transition < config.counter_delay_secs + config.transition_delay_secs { OwnerStatus::TransitionDelay { owner: self.owner.clone(), transition_reference_time: self.transition_reference_time, } } else { OwnerStatus::Valid { owner: self.owner.clone(), transition_reference_time: self.transition_reference_time, } } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub enum OwnerStatus { CounterDelay { name_owner: Option<Addr>, bid_owner: Addr, transition_reference_time: Timestamp, }, TransitionDelay { owner: Addr, transition_reference_time: Timestamp, }, Valid { owner: Addr, transition_reference_time: Timestamp, }, Expired { expire_time: Timestamp, transition_reference_time: Timestamp, }, } impl OwnerStatus { pub fn can_set_rate(&self, sender: &Addr) -> bool { match self { OwnerStatus::Valid { owner, .. } | OwnerStatus::TransitionDelay { owner, .. } => sender == owner, _ => false, } } pub fn can_transfer_name_owner(&self, sender: &Addr) -> bool { match self { OwnerStatus::Valid { owner, .. } | OwnerStatus::CounterDelay { name_owner: Some(owner), .. } | OwnerStatus::TransitionDelay { owner, .. } => sender == owner, _ => false, } } pub fn can_transfer_bid_owner(&self, sender: &Addr) -> bool { match self { OwnerStatus::CounterDelay { bid_owner, .. } => sender == bid_owner, _ => false, } } pub fn can_set_controller(&self, sender: &Addr) -> bool { match self { OwnerStatus::Valid { owner, .. } | OwnerStatus::CounterDelay { name_owner: Some(owner), .. } | OwnerStatus::TransitionDelay { owner, .. } => sender == owner, _ => false, } } } pub fn read_name_state( storage: &dyn Storage, name: &str, ) -> StdResult<NameState> { bucket_read(storage, NAME_STATE_PREFIX).load(name.as_bytes()) } pub fn read_option_name_state( storage: &dyn Storage, name: &str, ) -> StdResult<Option<NameState>> { bucket_read(storage, NAME_STATE_PREFIX).may_load(name.as_bytes()) } pub fn collect_name_states( storage: &dyn Storage, start_after: Option<&str>, limit: Option<u32>, ) -> StdResult<Vec<(String, NameState)>> { let bucket = bucket_read(storage, NAME_STATE_PREFIX); let start = calc_range_start_str(start_after); let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; bucket.range(start.as_deref(), None, Order::Ascending) .take(limit) .map(|item| { let (key, value) = item?; let key = String::from_utf8(key) .or_else(|_| Err(StdError::generic_err("Invalid utf-8")))?; Ok((key, value)) }) .collect() } #[must_use] pub fn store_name_state( storage: &mut dyn Storage, name: &str, name_info: &NameState, ) -> StdResult<()> { bucket(storage, NAME_STATE_PREFIX).save(name.as_bytes(), name_info) }
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Addr, Order, StdError, StdResult, Storage, Uint128}; use cosmwasm_storage::{ bucket, bucket_read, singleton, singleton_read, }; use terranames::auction::{ seconds_from_deposit, deposit_from_seconds_ceil, deposit_from_seconds_floor, }; use terranames::utils::{Timedelta, Timestamp}; pub static CONFIG_KEY: &[u8] = b"config"; pub static NAME_STATE_PREFIX: &[u8] = b"name"; const DEFAULT_LIMIT: u32 = 10; const MAX_LIMIT: u32 = 30; fn calc_range_start_str(start_after: Option<&str>) -> Option<Vec<u8>> { start_after.map(|s| { let mut v: Vec<u8> = s.into(); v.push(0); v }) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub collector_addr: Addr, pub stable_denom: String, pub min_lease_secs: Timedelta, pub max_lease_secs: Timedelta, pub counter_delay_secs: Timedelta, pub transition_delay_secs: Timedelta, pub bid_delay_secs: Timedelta, } pub fn read_config(storage: &dyn Storage) -> StdResult<Config> { singleton_read(storage, CONFIG_KEY).load() } #[must_use] pub fn store_config( storage: &mut dyn Storage, config: &Config, ) -> St
transition_reference_time: self.transition_reference_time, } } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub enum OwnerStatus { CounterDelay { name_owner: Option<Addr>, bid_owner: Addr, transition_reference_time: Timestamp, }, TransitionDelay { owner: Addr, transition_reference_time: Timestamp, }, Valid { owner: Addr, transition_reference_time: Timestamp, }, Expired { expire_time: Timestamp, transition_reference_time: Timestamp, }, } impl OwnerStatus { pub fn can_set_rate(&self, sender: &Addr) -> bool { match self { OwnerStatus::Valid { owner, .. } | OwnerStatus::TransitionDelay { owner, .. } => sender == owner, _ => false, } } pub fn can_transfer_name_owner(&self, sender: &Addr) -> bool { match self { OwnerStatus::Valid { owner, .. } | OwnerStatus::CounterDelay { name_owner: Some(owner), .. } | OwnerStatus::TransitionDelay { owner, .. } => sender == owner, _ => false, } } pub fn can_transfer_bid_owner(&self, sender: &Addr) -> bool { match self { OwnerStatus::CounterDelay { bid_owner, .. } => sender == bid_owner, _ => false, } } pub fn can_set_controller(&self, sender: &Addr) -> bool { match self { OwnerStatus::Valid { owner, .. } | OwnerStatus::CounterDelay { name_owner: Some(owner), .. } | OwnerStatus::TransitionDelay { owner, .. } => sender == owner, _ => false, } } } pub fn read_name_state( storage: &dyn Storage, name: &str, ) -> StdResult<NameState> { bucket_read(storage, NAME_STATE_PREFIX).load(name.as_bytes()) } pub fn read_option_name_state( storage: &dyn Storage, name: &str, ) -> StdResult<Option<NameState>> { bucket_read(storage, NAME_STATE_PREFIX).may_load(name.as_bytes()) } pub fn collect_name_states( storage: &dyn Storage, start_after: Option<&str>, limit: Option<u32>, ) -> StdResult<Vec<(String, NameState)>> { let bucket = bucket_read(storage, NAME_STATE_PREFIX); let start = calc_range_start_str(start_after); let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; bucket.range(start.as_deref(), None, Order::Ascending) .take(limit) .map(|item| { let (key, value) = item?; let key = String::from_utf8(key) .or_else(|_| Err(StdError::generic_err("Invalid utf-8")))?; Ok((key, value)) }) .collect() } #[must_use] pub fn store_name_state( storage: &mut dyn Storage, name: &str, name_info: &NameState, ) -> StdResult<()> { bucket(storage, NAME_STATE_PREFIX).save(name.as_bytes(), name_info) }
dResult<()> { singleton(storage, CONFIG_KEY).save(config) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct NameState { pub owner: Addr, pub controller: Option<Addr>, pub transition_reference_time: Timestamp, pub rate: Uint128, pub begin_time: Timestamp, pub begin_deposit: Uint128, pub previous_owner: Option<Addr>, pub previous_transition_reference_time: Timestamp, } impl NameState { pub fn seconds_spent_since_bid(&self, current_time: Timestamp) -> Option<Timedelta> { current_time.checked_sub(self.begin_time).ok() } pub fn seconds_spent_since_transition(&self, current_time: Timestamp) -> Option<Timedelta> { current_time.checked_sub(self.transition_reference_time).ok() } pub fn counter_delay_end(&self, config: &Config) -> Timestamp { self.begin_time + config.counter_delay_secs } pub fn transition_delay_end(&self, config: &Config) -> Timestamp { if self.transition_reference_time.is_zero() { self.begin_time } else { self.transition_reference_time + config.counter_delay_secs + config.transition_delay_secs } } pub fn bid_delay_end(&self, config: &Config) -> Timestamp { let delay = if !self.rate.is_zero() { config.counter_delay_secs + config.bid_delay_secs } else { Timedelta::zero() }; self.begin_time + delay } pub fn max_seconds(&self) -> Option<Timedelta> { seconds_from_deposit(self.begin_deposit, self.rate) } pub fn expire_time(&self) -> Option<Timestamp> { self.max_seconds().map(|max_seconds| self.begin_time + max_seconds) } pub fn current_deposit(&self, current_time: Timestamp) -> Uint128 { let seconds_spent = match self.seconds_spent_since_bid(current_time) { Some(seconds_spent) => seconds_spent, None => return Uint128::zero(), }; let deposit_spent = deposit_from_seconds_ceil(seconds_spent, self.rate); self.begin_deposit - deposit_spent } pub fn max_allowed_deposit(&self, config: &Config, current_time: Timestamp) -> Uint128 { let seconds_spent = match self.seconds_spent_since_bid(current_time) { Some(seconds_spent) => seconds_spent, None => return Uint128::zero(), }; let max_seconds_from_beginning = config.max_lease_secs + seconds_spent; deposit_from_seconds_floor(max_seconds_from_beginning, self.rate) } pub fn owner_status(&self, config: &Config, current_time: Timestamp) -> OwnerStatus { let seconds_spent_since_bid = match self.seconds_spent_since_bid(current_time) { Some(seconds_spent) => seconds_spent, None => return OwnerStatus::Expired { expire_time: Timestamp::zero(), transition_reference_time: self.transition_reference_time, }, }; if let Some(max_seconds) = self.max_seconds() { if seconds_spent_since_bid >= max_seconds { return OwnerStatus::Expired { expire_time: self.begin_time + max_seconds, transition_reference_time: self.transition_reference_time, }; } } let seconds_spent_since_transition = match self.seconds_spent_since_transition(current_time) { Some(seconds_spent) => seconds_spent, None => return OwnerStatus::Expired { expire_time: Timestamp::zero(), transition_reference_time: self.transition_reference_time, }, }; if seconds_spent_since_bid < config.counter_delay_secs { OwnerStatus::CounterDelay { name_owner: self.previous_owner.clone(), bid_owner: self.owner.clone(), transition_reference_time: self.previous_transition_reference_time, } } else if seconds_spent_since_transition < config.counter_delay_secs + config.transition_delay_secs { OwnerStatus::TransitionDelay { owner: self.owner.clone(), transition_reference_time: self.transition_reference_time, } } else { OwnerStatus::Valid { owner: self.owner.clone(),
random
[ { "content": "pub fn read_config(storage: &dyn Storage) -> StdResult<Config> {\n\n singleton_read(storage, CONFIG_KEY).load()\n\n}\n\n\n", "file_path": "contracts/terranames_resolver/src/state.rs", "rank": 1, "score": 233558.8203027719 }, { "content": "pub fn read_config(storage: &dyn Sto...
Rust
hive-core/src/lua/shared/kv.rs
hackerer1c/hive
a98ab9a97836f208646df252175283067a398b7b
use super::SharedTable; use mlua::{ExternalError, ExternalResult, FromLua, Lua, ToLua}; use serde::{Serialize, Serializer}; use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use std::sync::Arc; #[derive(Clone, Serialize)] #[serde(untagged)] pub enum SharedTableValue { Nil, Boolean(bool), Integer(i64), Number(f64), String(#[serde(serialize_with = "serialize_slice_as_str")] SmallVec<[u8; 32]>), Table(SharedTable), } fn serialize_slice_as_str<S: Serializer>(slice: &[u8], serializer: S) -> Result<S::Ok, S::Error> { if let Ok(x) = std::str::from_utf8(slice) { serializer.serialize_str(x) } else { serializer.serialize_bytes(slice) } } impl<'lua> FromLua<'lua> for SharedTableValue { fn from_lua(lua_value: mlua::Value<'lua>, lua: &'lua Lua) -> mlua::Result<Self> { use mlua::Value::*; let result = match lua_value { Nil => Self::Nil, Boolean(x) => Self::Boolean(x), Integer(x) => Self::Integer(x), Number(x) => Self::Number(x), String(x) => Self::String(x.as_bytes().into()), Table(x) => Self::Table(self::SharedTable::from_lua_table(lua, x)?), UserData(x) => { if let Ok(x) = x.borrow::<self::SharedTable>() { Self::Table(x.clone()) } else { return Err("invalid table value".to_lua_err()); } } _ => return Err("invalid table value".to_lua_err()), }; Ok(result) } } impl<'a, 'lua> ToLua<'lua> for &'a SharedTableValue { fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { use SharedTableValue::*; let result = match self { Nil => mlua::Value::Nil, Boolean(x) => mlua::Value::Boolean(*x), Integer(x) => mlua::Value::Integer(*x), Number(x) => mlua::Value::Number(*x), String(x) => mlua::Value::String(lua.create_string(x)?), Table(x) => mlua::Value::UserData(lua.create_ser_userdata(x.clone())?), }; Ok(result) } } impl<'lua> ToLua<'lua> for SharedTableValue { fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { use SharedTableValue::*; let result = match self { Nil => mlua::Value::Nil, Boolean(x) => mlua::Value::Boolean(x), Integer(x) => mlua::Value::Integer(x), Number(x) => mlua::Value::Number(x), String(x) => mlua::Value::String(lua.create_string(&x)?), Table(x) => mlua::Value::UserData(lua.create_ser_userdata(x)?), }; Ok(result) } } impl PartialEq for SharedTableValue { fn eq(&self, other: &Self) -> bool { use SharedTableValue::*; match (self, other) { (Nil, Nil) => true, (Nil, _) => false, (Boolean(x), Boolean(y)) => x == y, (Boolean(_), _) => false, (Integer(x), Integer(y)) => x == y, (Integer(x), Number(y)) => *x as f64 == *y, (Integer(_), _) => false, (Number(x), Number(y)) => x == y, (Number(x), Integer(y)) => *x == *y as f64, (Number(_), _) => false, (String(x), String(y)) => x == y, (String(_), _) => false, (Table(x), Table(y)) => Arc::ptr_eq(&x.0, &y.0), (Table(_), _) => false, } } } #[derive(Clone, Serialize)] pub struct SharedTableKey(pub(super) SharedTableValue); #[derive(Debug, thiserror::Error)] #[error("invalid key")] pub struct InvalidKey(()); impl SharedTableKey { pub fn from_value(value: SharedTableValue) -> Result<Self, InvalidKey> { use SharedTableValue::*; match value { Nil => Err(InvalidKey(())), Table(_) => Err(InvalidKey(())), Number(x) if x.is_nan() => Err(InvalidKey(())), Number(x) => { let i = x as i64; if i as f64 == x { Ok(Self(Integer(i))) } else { Ok(Self(value)) } } _ => Ok(Self(value)), } } pub fn to_i64(&self) -> Option<i64> { if let SharedTableValue::Integer(i) = self.0 { Some(i) } else { None } } } impl Hash for SharedTableKey { fn hash<H: Hasher>(&self, state: &mut H) { use SharedTableValue::*; fn canonical_float_bytes(f: f64) -> [u8; 8] { assert!(!f.is_nan()); if f == 0.0 { 0.0f64.to_ne_bytes() } else { f.to_ne_bytes() } } match &self.0 { Boolean(x) => (0u8, x).hash(state), Integer(x) => (1u8, x).hash(state), Number(x) => (2u8, canonical_float_bytes(*x)).hash(state), String(x) => (3u8, x).hash(state), Nil => unreachable!(), Table(_) => unreachable!(), } } } impl PartialEq for SharedTableKey { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl Eq for SharedTableKey {} impl<'lua> FromLua<'lua> for SharedTableKey { fn from_lua(lua_value: mlua::Value<'lua>, lua: &'lua Lua) -> mlua::Result<Self> { Self::from_value(SharedTableValue::from_lua(lua_value, lua)?).to_lua_err() } } impl<'a, 'lua> ToLua<'lua> for &'a SharedTableKey { fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { (&self.0).to_lua(lua) } } impl<'a, 'lua> ToLua<'lua> for SharedTableKey { fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { self.0.to_lua(lua) } }
use super::SharedTable; use mlua::{ExternalError, ExternalResult, FromLua, Lua, ToLua}; use serde::{Serialize, Serializer}; use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use std::sync::Arc; #[derive(Clone, Serialize)] #[serde(untagged)] pub enum SharedTableValue { Nil, Boolean(bool), Integer(i64), Number(f64), String(#[serde(serialize_with = "serialize_slice_as_str")] SmallVec<[u8; 32]>), Table(SharedTable), } fn serialize_slice_as_str<S: Serializer>(slice: &[u8], serializer: S) -> Result<S::Ok, S::Error> { if let Ok(x) = std::str::from_utf8(slice) { serializer.serialize_str(x) } else { serializer.serialize_bytes(slice) } } impl<'lua> FromLua<'lua> for SharedTableValue { fn from_lua(lua_value: mlua::Value<'lua>, lua: &'lua Lua) -> mlua::Result<Self> { use mlua::Value::*; let result = match lua_value { Nil => Self::Nil, Boolean(x) => Self::Boolean(x), Integer(x) => Self::Integer(x), Number(x) => Self::Number(x), String(x) => Self::String(x.as_bytes().into()), Table(x) => Self::Table(self::SharedTable::from_lua_table(lua, x)?), UserData(x) => { if let Ok(x) = x.borrow::<self::SharedTable>() { Self::Table(x.clone()) } else { return Err("invalid table value".to_lua_err()); } } _ => return Err("invalid table value".to_lua_err()), }; Ok(result) } } impl<'a, 'lua> ToLua<'lua> for &'a SharedTableValue {
} impl<'lua> ToLua<'lua> for SharedTableValue { fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { use SharedTableValue::*; let result = match self { Nil => mlua::Value::Nil, Boolean(x) => mlua::Value::Boolean(x), Integer(x) => mlua::Value::Integer(x), Number(x) => mlua::Value::Number(x), String(x) => mlua::Value::String(lua.create_string(&x)?), Table(x) => mlua::Value::UserData(lua.create_ser_userdata(x)?), }; Ok(result) } } impl PartialEq for SharedTableValue { fn eq(&self, other: &Self) -> bool { use SharedTableValue::*; match (self, other) { (Nil, Nil) => true, (Nil, _) => false, (Boolean(x), Boolean(y)) => x == y, (Boolean(_), _) => false, (Integer(x), Integer(y)) => x == y, (Integer(x), Number(y)) => *x as f64 == *y, (Integer(_), _) => false, (Number(x), Number(y)) => x == y, (Number(x), Integer(y)) => *x == *y as f64, (Number(_), _) => false, (String(x), String(y)) => x == y, (String(_), _) => false, (Table(x), Table(y)) => Arc::ptr_eq(&x.0, &y.0), (Table(_), _) => false, } } } #[derive(Clone, Serialize)] pub struct SharedTableKey(pub(super) SharedTableValue); #[derive(Debug, thiserror::Error)] #[error("invalid key")] pub struct InvalidKey(()); impl SharedTableKey { pub fn from_value(value: SharedTableValue) -> Result<Self, InvalidKey> { use SharedTableValue::*; match value { Nil => Err(InvalidKey(())), Table(_) => Err(InvalidKey(())), Number(x) if x.is_nan() => Err(InvalidKey(())), Number(x) => { let i = x as i64; if i as f64 == x { Ok(Self(Integer(i))) } else { Ok(Self(value)) } } _ => Ok(Self(value)), } } pub fn to_i64(&self) -> Option<i64> { if let SharedTableValue::Integer(i) = self.0 { Some(i) } else { None } } } impl Hash for SharedTableKey { fn hash<H: Hasher>(&self, state: &mut H) { use SharedTableValue::*; fn canonical_float_bytes(f: f64) -> [u8; 8] { assert!(!f.is_nan()); if f == 0.0 { 0.0f64.to_ne_bytes() } else { f.to_ne_bytes() } } match &self.0 { Boolean(x) => (0u8, x).hash(state), Integer(x) => (1u8, x).hash(state), Number(x) => (2u8, canonical_float_bytes(*x)).hash(state), String(x) => (3u8, x).hash(state), Nil => unreachable!(), Table(_) => unreachable!(), } } } impl PartialEq for SharedTableKey { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl Eq for SharedTableKey {} impl<'lua> FromLua<'lua> for SharedTableKey { fn from_lua(lua_value: mlua::Value<'lua>, lua: &'lua Lua) -> mlua::Result<Self> { Self::from_value(SharedTableValue::from_lua(lua_value, lua)?).to_lua_err() } } impl<'a, 'lua> ToLua<'lua> for &'a SharedTableKey { fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { (&self.0).to_lua(lua) } } impl<'a, 'lua> ToLua<'lua> for SharedTableKey { fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { self.0.to_lua(lua) } }
fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { use SharedTableValue::*; let result = match self { Nil => mlua::Value::Nil, Boolean(x) => mlua::Value::Boolean(*x), Integer(x) => mlua::Value::Integer(*x), Number(x) => mlua::Value::Number(*x), String(x) => mlua::Value::String(lua.create_string(x)?), Table(x) => mlua::Value::UserData(lua.create_ser_userdata(x.clone())?), }; Ok(result) }
function_block-full_function
[ { "content": "pub fn apply_table_module_patch(lua: &Lua, table_module: Table) -> mlua::Result<()> {\n\n table_module.raw_set(\"dump\", create_fn_table_dump(lua)?)?;\n\n table_module.raw_set(\"insert\", create_fn_table_insert(lua)?)?;\n\n table_module.raw_set(\"scope\", create_fn_table_scope(lua)?)?;\n\n Ok(...
Rust
src/table_properties_rc.rs
hustwp233/rust-rocksdb
bac3ef613692ba783cfe9256cfd2388411c25a6d
use crocksdb_ffi::{DBTablePropertiesCollection, DBTableProperty}; use libc::size_t; use librocksdb_sys as crocksdb_ffi; use std::ops::Deref; use std::slice; use std::str; use crate::table_properties_rc_handles::{ TablePropertiesCollectionHandle, TablePropertiesCollectionIteratorHandle, TablePropertiesHandle, UserCollectedPropertiesHandle, }; pub struct TablePropertiesCollection { handle: TablePropertiesCollectionHandle, } impl TablePropertiesCollection { pub unsafe fn new(ptr: *mut DBTablePropertiesCollection) -> TablePropertiesCollection { assert!(!ptr.is_null()); TablePropertiesCollection { handle: TablePropertiesCollectionHandle::new(ptr), } } pub fn iter(&self) -> TablePropertiesCollectionIter { TablePropertiesCollectionIter::new(self.handle.clone()) } pub fn len(&self) -> usize { unsafe { crocksdb_ffi::crocksdb_table_properties_collection_len(self.handle.ptr()) } } pub fn is_empty(&self) -> bool { self.len() == 0 } } pub struct TablePropertiesCollectionIter { handle: TablePropertiesCollectionIteratorHandle, } impl TablePropertiesCollectionIter { fn new(collection: TablePropertiesCollectionHandle) -> TablePropertiesCollectionIter { TablePropertiesCollectionIter { handle: TablePropertiesCollectionIteratorHandle::new(collection), } } } impl Iterator for TablePropertiesCollectionIter { type Item = (TablePropertiesKey, TableProperties); fn next(&mut self) -> Option<Self::Item> { unsafe { loop { if !crocksdb_ffi::crocksdb_table_properties_collection_iter_valid(self.handle.ptr()) { return None; } let mut keylen: size_t = 0; let key = crocksdb_ffi::crocksdb_table_properties_collection_iter_key( self.handle.ptr(), &mut keylen, ); let props = crocksdb_ffi::crocksdb_table_properties_collection_iter_value( self.handle.ptr(), ); crocksdb_ffi::crocksdb_table_properties_collection_iter_next(self.handle.ptr()); if !props.is_null() { assert!(!key.is_null() && keylen != 0); let key = TablePropertiesKey::new(key, keylen, self.handle.clone()); let props_handle = TablePropertiesHandle::new(props, self.handle.clone()); let val = TableProperties::new(props_handle); return Some((key, val)); } } } } } pub struct TablePropertiesKey { key: *const u8, keylen: size_t, _iter_handle: TablePropertiesCollectionIteratorHandle, } impl TablePropertiesKey { fn new( key: *const u8, keylen: size_t, _iter_handle: TablePropertiesCollectionIteratorHandle, ) -> TablePropertiesKey { unsafe { let bytes = slice::from_raw_parts(key, keylen); assert!(str::from_utf8(bytes).is_ok()); } TablePropertiesKey { key, keylen, _iter_handle, } } } impl Deref for TablePropertiesKey { type Target = str; fn deref(&self) -> &str { unsafe { let bytes = slice::from_raw_parts(self.key, self.keylen); str::from_utf8_unchecked(bytes) } } } pub struct TableProperties { handle: TablePropertiesHandle, } impl TableProperties { fn new(handle: TablePropertiesHandle) -> TableProperties { TableProperties { handle } } fn get_u64(&self, prop: DBTableProperty) -> u64 { unsafe { crocksdb_ffi::crocksdb_table_properties_get_u64(self.handle.ptr(), prop) } } pub fn num_entries(&self) -> u64 { self.get_u64(DBTableProperty::NumEntries) } pub fn user_collected_properties(&self) -> UserCollectedProperties { UserCollectedProperties::new(self.handle.clone()) } } pub struct UserCollectedProperties { handle: UserCollectedPropertiesHandle, } impl UserCollectedProperties { fn new(table_props_handle: TablePropertiesHandle) -> UserCollectedProperties { UserCollectedProperties { handle: UserCollectedPropertiesHandle::new(table_props_handle), } } pub fn get<Q: AsRef<[u8]>>(&self, index: Q) -> Option<&[u8]> { let bytes = index.as_ref(); let mut size = 0; unsafe { let ptr = crocksdb_ffi::crocksdb_user_collected_properties_get( self.handle.ptr(), bytes.as_ptr(), bytes.len(), &mut size, ); if ptr.is_null() { return None; } Some(slice::from_raw_parts(ptr, size)) } } pub fn len(&self) -> usize { unsafe { crocksdb_ffi::crocksdb_user_collected_properties_len(self.handle.ptr()) } } pub fn is_empty(&self) -> bool { self.len() == 0 } }
use crocksdb_ffi::{DBTablePropertiesCollection, DBTableProperty}; use libc::size_t; use librocksdb_sys as crocksdb_ffi; use std::ops::Deref; use std::slice; use std::str; use crate::table_properties_rc_handles::{ TablePropertiesCollectionHandle, TablePropertiesCollectionIteratorHandle, TablePropertiesHandle, UserCollectedPropertiesHandle, }; pub struct TablePropertiesCollection { handle: TablePropertiesCollectionHandle, } impl TablePropertiesCollection { pub unsafe fn new(ptr: *mut DBTablePropertiesCollection) -> TablePropertiesCollection { assert!(!ptr.is_null()); TablePropertiesCollection { handle: TablePropertiesCollectionHandle::new(ptr), } } pub fn iter(&self) -> TablePropertiesCollectionIter { TablePropertiesCollectionIter::new(self.handle.clone()) } pub fn len(&self) -> usize { unsafe { crocksdb_ffi::crocksdb_table_properties_collection_len(self.handle.ptr()) } } pub fn is_empty(&self) -> bool { self.len() == 0 } } pub struct TablePropertiesCollectionIter { handle: TablePropertiesCollectionIteratorHandle, } impl TablePropertiesCollectionIter { fn new(collection: TablePropertiesCollectionHandle) -> TablePropertiesCollectionIter { TablePropertiesCollectionIter { handle: TablePropertiesCollectionIteratorHandle::new(collection), } } } impl Iterator for TablePropertiesCollectionIter { type Item = (TablePropertiesK
e { let ptr = crocksdb_ffi::crocksdb_user_collected_properties_get( self.handle.ptr(), bytes.as_ptr(), bytes.len(), &mut size, ); if ptr.is_null() { return None; } Some(slice::from_raw_parts(ptr, size)) } } pub fn len(&self) -> usize { unsafe { crocksdb_ffi::crocksdb_user_collected_properties_len(self.handle.ptr()) } } pub fn is_empty(&self) -> bool { self.len() == 0 } }
ey, TableProperties); fn next(&mut self) -> Option<Self::Item> { unsafe { loop { if !crocksdb_ffi::crocksdb_table_properties_collection_iter_valid(self.handle.ptr()) { return None; } let mut keylen: size_t = 0; let key = crocksdb_ffi::crocksdb_table_properties_collection_iter_key( self.handle.ptr(), &mut keylen, ); let props = crocksdb_ffi::crocksdb_table_properties_collection_iter_value( self.handle.ptr(), ); crocksdb_ffi::crocksdb_table_properties_collection_iter_next(self.handle.ptr()); if !props.is_null() { assert!(!key.is_null() && keylen != 0); let key = TablePropertiesKey::new(key, keylen, self.handle.clone()); let props_handle = TablePropertiesHandle::new(props, self.handle.clone()); let val = TableProperties::new(props_handle); return Some((key, val)); } } } } } pub struct TablePropertiesKey { key: *const u8, keylen: size_t, _iter_handle: TablePropertiesCollectionIteratorHandle, } impl TablePropertiesKey { fn new( key: *const u8, keylen: size_t, _iter_handle: TablePropertiesCollectionIteratorHandle, ) -> TablePropertiesKey { unsafe { let bytes = slice::from_raw_parts(key, keylen); assert!(str::from_utf8(bytes).is_ok()); } TablePropertiesKey { key, keylen, _iter_handle, } } } impl Deref for TablePropertiesKey { type Target = str; fn deref(&self) -> &str { unsafe { let bytes = slice::from_raw_parts(self.key, self.keylen); str::from_utf8_unchecked(bytes) } } } pub struct TableProperties { handle: TablePropertiesHandle, } impl TableProperties { fn new(handle: TablePropertiesHandle) -> TableProperties { TableProperties { handle } } fn get_u64(&self, prop: DBTableProperty) -> u64 { unsafe { crocksdb_ffi::crocksdb_table_properties_get_u64(self.handle.ptr(), prop) } } pub fn num_entries(&self) -> u64 { self.get_u64(DBTableProperty::NumEntries) } pub fn user_collected_properties(&self) -> UserCollectedProperties { UserCollectedProperties::new(self.handle.clone()) } } pub struct UserCollectedProperties { handle: UserCollectedPropertiesHandle, } impl UserCollectedProperties { fn new(table_props_handle: TablePropertiesHandle) -> UserCollectedProperties { UserCollectedProperties { handle: UserCollectedPropertiesHandle::new(table_props_handle), } } pub fn get<Q: AsRef<[u8]>>(&self, index: Q) -> Option<&[u8]> { let bytes = index.as_ref(); let mut size = 0; unsaf
random
[ { "content": "#[test]\n\npub fn test_iterator() {\n\n let path = tempdir_with_prefix(\"_rust_rocksdb_iteratortest\");\n\n\n\n let k1 = b\"k1\";\n\n let k2 = b\"k2\";\n\n let k3 = b\"k3\";\n\n let k4 = b\"k4\";\n\n let v1 = b\"v1111\";\n\n let v2 = b\"v2222\";\n\n let v3 = b\"v3333\";\n\n...
Rust
src/mesh/pointcloud.rs
elrnv/meshx
8119edab6eb744bc2a7d21577a472de8927e81e5
use crate::attrib::*; use crate::mesh::topology::*; use crate::mesh::{VertexMesh, VertexPositions}; use crate::Real; #[derive(Clone, Debug, PartialEq, Attrib, Intrinsic)] pub struct PointCloud<T: Real> { #[intrinsic(VertexPositions)] pub vertex_positions: IntrinsicAttribute<[T; 3], VertexIndex>, pub vertex_attributes: AttribDict<VertexIndex>, } impl<T: Real> PointCloud<T> { #[inline] pub fn new(verts: Vec<[T; 3]>) -> PointCloud<T> { PointCloud { vertex_positions: IntrinsicAttribute::from_vec(verts), vertex_attributes: AttribDict::new(), } } } impl<T: Real> Default for PointCloud<T> { fn default() -> Self { PointCloud::new(vec![]) } } impl<T: Real> NumVertices for PointCloud<T> { #[inline] fn num_vertices(&self) -> usize { self.vertex_positions.len() } } impl<T: Real, M: VertexMesh<T>> From<&M> for PointCloud<T> { fn from(mesh: &M) -> PointCloud<T> { let vertex_attributes = mesh.attrib_dict::<VertexIndex>().clone(); PointCloud { vertex_positions: IntrinsicAttribute::from_slice(mesh.vertex_positions()), vertex_attributes, } } } impl<T: Real> From<super::PolyMesh<T>> for PointCloud<T> { fn from(polymesh: super::PolyMesh<T>) -> PointCloud<T> { let super::PolyMesh { vertex_positions, vertex_attributes, .. } = polymesh; PointCloud { vertex_positions, vertex_attributes, } } } impl<T: Real> From<super::TriMesh<T>> for PointCloud<T> { fn from(mesh: super::TriMesh<T>) -> PointCloud<T> { let super::TriMesh { vertex_positions, vertex_attributes, .. } = mesh; PointCloud { vertex_positions, vertex_attributes, } } } impl<T: Real> From<super::QuadMesh<T>> for PointCloud<T> { fn from(mesh: super::QuadMesh<T>) -> PointCloud<T> { let super::QuadMesh { vertex_positions, vertex_attributes, .. } = mesh; PointCloud { vertex_positions, vertex_attributes, } } } impl<T: Real> From<super::TetMesh<T>> for PointCloud<T> { fn from(mesh: super::TetMesh<T>) -> PointCloud<T> { let super::TetMesh { vertex_positions, vertex_attributes, .. } = mesh; PointCloud { vertex_positions, vertex_attributes, } } } #[cfg(test)] mod tests { use super::*; #[test] fn pointcloud_test() { let pts = vec![ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], ]; let mut ptcloud = PointCloud::new(pts.clone()); assert_eq!(ptcloud.num_vertices(), 4); for (pt1, pt2) in ptcloud.vertex_position_iter().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } for (pt1, pt2) in ptcloud.vertex_position_iter_mut().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } for (pt1, pt2) in ptcloud.vertex_positions().iter().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } for (pt1, pt2) in ptcloud.vertex_positions_mut().iter().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } } #[test] fn convert_test() { use crate::mesh::{PolyMesh, QuadMesh, TetMesh, TriMesh}; let pts = vec![ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], ]; let ptcloud = PointCloud::new(pts.clone()); let polymesh = PolyMesh::new(pts.clone(), &vec![]); let trimesh = TriMesh::new(pts.clone(), vec![]); let quadmesh = QuadMesh::new(pts.clone(), vec![]); let tetmesh = TetMesh::new(pts.clone(), vec![]); assert_eq!(PointCloud::from(&polymesh), ptcloud); assert_eq!(PointCloud::from(&trimesh), ptcloud); assert_eq!(PointCloud::from(&quadmesh), ptcloud); assert_eq!(PointCloud::from(&tetmesh), ptcloud); assert_eq!(PointCloud::from(polymesh), ptcloud); assert_eq!(PointCloud::from(trimesh), ptcloud); assert_eq!(PointCloud::from(quadmesh), ptcloud); assert_eq!(PointCloud::from(tetmesh), ptcloud); } }
use crate::attrib::*; use crate::mesh::topology::*; use crate::mesh::{VertexMesh, VertexPositions}; use crate::Real; #[derive(Clone, Debug, PartialEq, Attrib, Intrinsic)] pub struct PointCloud<T: Real> { #[intrinsic(VertexPositions)] pub vertex_positions: IntrinsicAttribute<[T; 3], VertexIndex>, pub vertex_attributes: AttribDict<VertexIndex>, } impl<T: Real> PointCloud<T> { #[inline] pub fn new(verts: Vec<[T; 3]>) -> PointCloud<T> { PointCloud { vertex_positions: IntrinsicAttribute::from_vec(verts), vertex_attributes: AttribDict::new(), } } } impl<T: Real> Default for PointCloud<T> { fn default() -> Self { PointCloud::new(vec![]) } } impl<T: Real> NumVertices for PointCloud<T> { #[inline] fn num_vertices(&self) -> usize { self.vertex_positions.len() } } impl<T: Real, M: VertexMesh<T>> From<&M> for PointCloud<T> { fn from(mesh: &M) -> PointCloud<T> { let vertex_attributes = mesh.attrib_dict::<VertexIndex>().clone(); PointCloud { vertex_positions: IntrinsicAttribute::from_slice(mesh.vertex_positions()), vertex_attributes, } } } impl<T: Real> From<super::PolyMesh<T>> for PointCloud<T> { fn from(polymesh: super::PolyMesh<T>) -> PointCloud<T> { let super::PolyMesh { vertex_positions, vertex_attributes, .. } = polymesh; PointCloud { vertex_positions, vertex_attributes, } } } impl<T: Real> From<super::TriMesh<T>> for PointCloud<T> { fn from(mesh: super::TriMesh<T>) -> PointCloud<T> { let super::TriMesh { vertex_positions, vertex_attributes, .. } = mesh; PointCloud { vertex_positions, vertex_attributes, } } } impl<T: Real> From<super::QuadMesh<T>> for PointCloud<T> { fn from(mesh: super::QuadMesh<T>) -> PointCloud<T> { let super::QuadMesh { vertex_positions, vertex_attributes, .. } = mesh; PointCloud { vertex_positions, vertex_attributes, } } } impl<T: Real> From<super::TetMesh<T>> for PointCloud<T> { fn from(mesh: super::TetMesh<T>) -> PointCloud<T> { let super::TetMesh { vertex_positions, vertex_attributes, .. } = mesh; PointCloud { vertex_positions, vertex_attributes, } } } #[cfg(test)] mod tests { use super::*; #[test] fn pointcloud_test() { let pts = vec![ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], ]; let mut ptcloud = PointCloud::new(pts.clone()); assert_eq!(ptcloud.num_vertices(), 4); for (pt1, pt2) in ptcloud.vertex_positio
#[test] fn convert_test() { use crate::mesh::{PolyMesh, QuadMesh, TetMesh, TriMesh}; let pts = vec![ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], ]; let ptcloud = PointCloud::new(pts.clone()); let polymesh = PolyMesh::new(pts.clone(), &vec![]); let trimesh = TriMesh::new(pts.clone(), vec![]); let quadmesh = QuadMesh::new(pts.clone(), vec![]); let tetmesh = TetMesh::new(pts.clone(), vec![]); assert_eq!(PointCloud::from(&polymesh), ptcloud); assert_eq!(PointCloud::from(&trimesh), ptcloud); assert_eq!(PointCloud::from(&quadmesh), ptcloud); assert_eq!(PointCloud::from(&tetmesh), ptcloud); assert_eq!(PointCloud::from(polymesh), ptcloud); assert_eq!(PointCloud::from(trimesh), ptcloud); assert_eq!(PointCloud::from(quadmesh), ptcloud); assert_eq!(PointCloud::from(tetmesh), ptcloud); } }
n_iter().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } for (pt1, pt2) in ptcloud.vertex_position_iter_mut().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } for (pt1, pt2) in ptcloud.vertex_positions().iter().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } for (pt1, pt2) in ptcloud.vertex_positions_mut().iter().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } }
function_block-function_prefixed
[ { "content": "pub fn convert_polymesh_to_obj_format<T: Real>(mesh: &PolyMesh<T>) -> Result<ObjData, Error> {\n\n let position: Vec<[f32; 3]> = mesh\n\n .vertex_position_iter()\n\n .cloned()\n\n .map(|[x, y, z]| {\n\n [\n\n x.to_f32().unwrap(),\n\n ...
Rust
rust/rsmgp-sys/src/testing.rs
memgraph/mage
8c389146dfce35c436e941b04655d9f758351e46
#[cfg(test)] pub mod alloc { use libc::malloc; use std::mem::size_of; use crate::mgp::*; pub(crate) unsafe fn alloc_mgp_type() -> *mut mgp_type { malloc(size_of::<mgp_type>()) as *mut mgp_type } pub(crate) unsafe fn alloc_mgp_value() -> *mut mgp_value { malloc(size_of::<mgp_value>()) as *mut mgp_value } pub(crate) unsafe fn alloc_mgp_list() -> *mut mgp_list { malloc(size_of::<mgp_list>()) as *mut mgp_list } pub(crate) unsafe fn alloc_mgp_map() -> *mut mgp_map { malloc(size_of::<mgp_map>()) as *mut mgp_map } pub(crate) unsafe fn alloc_mgp_map_items_iterator() -> *mut mgp_map_items_iterator { malloc(size_of::<mgp_map_items_iterator>()) as *mut mgp_map_items_iterator } pub(crate) unsafe fn alloc_mgp_vertex() -> *mut mgp_vertex { malloc(size_of::<mgp_vertex>()) as *mut mgp_vertex } pub(crate) unsafe fn alloc_mgp_edge() -> *mut mgp_edge { malloc(size_of::<mgp_edge>()) as *mut mgp_edge } pub(crate) unsafe fn alloc_mgp_path() -> *mut mgp_path { malloc(size_of::<mgp_path>()) as *mut mgp_path } pub(crate) unsafe fn alloc_mgp_date() -> *mut mgp_date { malloc(size_of::<mgp_date>()) as *mut mgp_date } pub(crate) unsafe fn alloc_mgp_local_time() -> *mut mgp_local_time { malloc(size_of::<mgp_local_time>()) as *mut mgp_local_time } pub(crate) unsafe fn alloc_mgp_local_date_time() -> *mut mgp_local_date_time { malloc(size_of::<mgp_local_date_time>()) as *mut mgp_local_date_time } pub(crate) unsafe fn alloc_mgp_duration() -> *mut mgp_duration { malloc(size_of::<mgp_duration>()) as *mut mgp_duration } pub(crate) unsafe fn alloc_mgp_proc() -> *mut mgp_proc { malloc(size_of::<mgp_proc>()) as *mut mgp_proc } pub(crate) unsafe fn alloc_mgp_result_record() -> *mut mgp_result_record { malloc(size_of::<mgp_result_record>()) as *mut mgp_result_record } #[macro_export] macro_rules! mock_mgp_once { ($c_func_name:ident, $rs_return_func:expr) => { let $c_func_name = $c_func_name(); $c_func_name.expect().times(1).returning($rs_return_func); }; } #[macro_export] macro_rules! with_dummy { ($rs_test_func:expr) => { let memgraph = Memgraph::new_default(); $rs_test_func(&memgraph); }; (List, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let list = List::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&list); }; (Map, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let map = Map::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&map); }; (Vertex, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let vertex = Vertex::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&vertex); }; (Edge, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let edge = Edge::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&edge); }; (Path, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let path = Path::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&path); }; (Date, $rs_test_func:expr) => { let date = Date::new(std::ptr::null_mut()); $rs_test_func(&date); }; (LocalTime, $rs_test_func:expr) => { let local_time = LocalTime::new(std::ptr::null_mut()); $rs_test_func(&local_time); }; (LocalDateTime, $rs_test_func:expr) => { let local_date_time = LocalDateTime::new(std::ptr::null_mut()); $rs_test_func(&local_date_time); }; (Duration, $rs_test_func:expr) => { let duration = Duration::new(std::ptr::null_mut()); $rs_test_func(&duration); }; } }
#[cfg(test)] pub mod alloc { use libc::malloc; use std::mem::size_of; use crate::mgp::*; pub(crate) unsafe fn alloc_mgp_type() -> *mut mgp_type { malloc(size_of::<mgp_type>()) as *mut mgp_type } pub(crate) unsafe fn alloc_mgp_value() -> *mut mgp_value { malloc(size_of::<mgp_value>()) as *mut mgp_value } pub(crate) unsafe fn alloc_mgp_list() -> *mut mgp_list { malloc(size_of::<mgp_list>()) as *mut mgp_list } pub(crate) unsafe fn alloc_mgp_map() -> *mut mgp_map { malloc(size_of::<mgp_map>()) as *mut mgp_map } pub(crate) unsafe fn alloc_mgp_map_items_iterator() -> *mut mgp_map_items_iterator { malloc(size_of::<mgp_map_items_iterator>()) as *mut mgp_map_items_iterator } pub(crate) unsafe fn alloc_mgp_vertex() -> *mut mgp_vertex { malloc(size_of::<mgp_vertex>()) as *mut mgp_vertex } pub(crate) unsafe fn alloc_mgp_edge() -> *mut mgp_edge { malloc(size_of::<mgp_edge>()) as *mut mgp_edge } pub(crate) unsafe fn alloc_mgp_path() -> *mut mgp_path {
$c_func_name.expect().times(1).returning($rs_return_func); }; } #[macro_export] macro_rules! with_dummy { ($rs_test_func:expr) => { let memgraph = Memgraph::new_default(); $rs_test_func(&memgraph); }; (List, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let list = List::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&list); }; (Map, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let map = Map::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&map); }; (Vertex, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let vertex = Vertex::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&vertex); }; (Edge, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let edge = Edge::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&edge); }; (Path, $rs_test_func:expr) => { let memgraph = Memgraph::new_default(); let path = Path::new(std::ptr::null_mut(), &memgraph); $rs_test_func(&path); }; (Date, $rs_test_func:expr) => { let date = Date::new(std::ptr::null_mut()); $rs_test_func(&date); }; (LocalTime, $rs_test_func:expr) => { let local_time = LocalTime::new(std::ptr::null_mut()); $rs_test_func(&local_time); }; (LocalDateTime, $rs_test_func:expr) => { let local_date_time = LocalDateTime::new(std::ptr::null_mut()); $rs_test_func(&local_date_time); }; (Duration, $rs_test_func:expr) => { let duration = Duration::new(std::ptr::null_mut()); $rs_test_func(&duration); }; } }
malloc(size_of::<mgp_path>()) as *mut mgp_path } pub(crate) unsafe fn alloc_mgp_date() -> *mut mgp_date { malloc(size_of::<mgp_date>()) as *mut mgp_date } pub(crate) unsafe fn alloc_mgp_local_time() -> *mut mgp_local_time { malloc(size_of::<mgp_local_time>()) as *mut mgp_local_time } pub(crate) unsafe fn alloc_mgp_local_date_time() -> *mut mgp_local_date_time { malloc(size_of::<mgp_local_date_time>()) as *mut mgp_local_date_time } pub(crate) unsafe fn alloc_mgp_duration() -> *mut mgp_duration { malloc(size_of::<mgp_duration>()) as *mut mgp_duration } pub(crate) unsafe fn alloc_mgp_proc() -> *mut mgp_proc { malloc(size_of::<mgp_proc>()) as *mut mgp_proc } pub(crate) unsafe fn alloc_mgp_result_record() -> *mut mgp_result_record { malloc(size_of::<mgp_result_record>()) as *mut mgp_result_record } #[macro_export] macro_rules! mock_mgp_once { ($c_func_name:ident, $rs_return_func:expr) => { let $c_func_name = $c_func_name();
random
[ { "content": "/// Combines the given array of types from left to right to construct [mgp_type]. E.g., if the\n\n/// input is [Type::List, Type::Int], the constructed [mgp_type] is going to be list of integers.\n\nfn resolve_mgp_type(types: &[Type]) -> *mut mgp_type {\n\n unsafe {\n\n let mut mgp_type_...
Rust
whisper/src/bin/whisper-create.rs
GiantPlantsSociety/graphite-rs
d2657ae3ddf110023417ec255f5192ac8fa83bfc
use humansize::{file_size_opts as options, FileSize}; use std::error::Error; use std::fs; use std::path::PathBuf; use std::process::exit; use structopt::StructOpt; use whisper::aggregation::AggregationMethod; use whisper::retention::Retention; use whisper::WhisperBuilder; #[derive(Debug, StructOpt)] #[structopt(name = "whisper-create")] struct Args { #[structopt(long = "overwrite")] overwrite: bool, #[structopt(long = "estimate")] estimate: bool, #[structopt(long = "sparse")] sparse: bool, #[structopt(long = "fallocate")] fallocate: bool, #[structopt(long = "xFilesFactor", default_value = "0.5")] x_files_factor: f32, #[structopt(long = "aggregationMethod", default_value = "average")] aggregation_method: AggregationMethod, #[structopt(name = "path", parse(from_os_str))] path: PathBuf, #[structopt( name = "retentions", help = r#"Specify lengths of time, for example: 60:1440 60 seconds per datapoint, 1440 datapoints = 1 day of retention 15m:8 15 minutes per datapoint, 8 datapoints = 2 hours of retention 1h:7d 1 hour per datapoint, 7 days of retention 12h:2y 12 hours per datapoint, 2 years of retention "#, required = true, min_values = 1 )] retentions: Vec<Retention>, } fn estimate_info(retentions: &[Retention]) { for (i, retention) in retentions.iter().enumerate() { println!( "Archive {}: {} points of {}s precision", i, &retention.points, &retention.seconds_per_point ); } let total_points: usize = retentions.iter().map(|x| x.points as usize).sum(); let size = (whisper::METADATA_SIZE + (retentions.len() * whisper::ARCHIVE_INFO_SIZE) + (total_points * whisper::POINT_SIZE)) as usize; let disk_size = (size as f64 / 4096.0).ceil() as usize * 4096; let custom_options = options::FileSizeOpts { decimal_places: 3, ..options::CONVENTIONAL }; println!(); println!( "Estimated Whisper DB Size: {} ({} bytes on disk with 4k blocks)", size.file_size(&custom_options).unwrap(), disk_size ); println!(); let numbers = [1, 5, 10, 50, 100, 500]; for number in &numbers { println!( "Estimated storage requirement for {}k metrics: {}", number, (number * 1000_usize * disk_size) .file_size(&custom_options) .unwrap() ); } } fn run(args: &Args) -> Result<(), Box<dyn Error>> { if args.estimate { estimate_info(&args.retentions); } else { if args.overwrite && args.path.exists() { println!( "Overwriting existing file: {}", &args.path.to_str().unwrap() ); fs::remove_file(&args.path)?; } WhisperBuilder::default() .add_retentions(&args.retentions) .x_files_factor(args.x_files_factor) .aggregation_method(args.aggregation_method) .sparse(args.sparse) .build(&args.path)?; let size = args.path.metadata()?.len(); println!("Created: {} ({} bytes)", &args.path.to_str().unwrap(), size); } Ok(()) } fn main() { let args = Args::from_args(); if let Err(err) = run(&args) { eprintln!("{}", err); exit(1); } }
use humansize::{file_size_opts as options, FileSize}; use std::error::Error; use std::fs; use std::path::PathBuf; use std::process::exit; use structopt::StructOpt; use whisper::aggregation::AggregationMethod; use whisper::retention::Retention; use whisper::WhisperBuilder; #[derive(Debug, StructOpt)] #[structopt(name = "whisper-create")] struct Args { #[structopt(long = "overwrite")] overwrite: bool, #[structopt(long = "estimate")] estimate: bool, #[structopt(long = "sparse")] sparse: bool, #[structopt(long = "fallocate")] fallocate: bool, #[structopt(long = "xFilesFactor", default_value = "0.5")] x_files_factor: f32, #[structopt(long = "aggregationMethod", default_value = "average")] aggregation_method: AggregationMethod, #[structopt(na
number, (number * 1000_usize * disk_size) .file_size(&custom_options) .unwrap() ); } } fn run(args: &Args) -> Result<(), Box<dyn Error>> { if args.estimate { estimate_info(&args.retentions); } else { if args.overwrite && args.path.exists() { println!( "Overwriting existing file: {}", &args.path.to_str().unwrap() ); fs::remove_file(&args.path)?; } WhisperBuilder::default() .add_retentions(&args.retentions) .x_files_factor(args.x_files_factor) .aggregation_method(args.aggregation_method) .sparse(args.sparse) .build(&args.path)?; let size = args.path.metadata()?.len(); println!("Created: {} ({} bytes)", &args.path.to_str().unwrap(), size); } Ok(()) } fn main() { let args = Args::from_args(); if let Err(err) = run(&args) { eprintln!("{}", err); exit(1); } }
me = "path", parse(from_os_str))] path: PathBuf, #[structopt( name = "retentions", help = r#"Specify lengths of time, for example: 60:1440 60 seconds per datapoint, 1440 datapoints = 1 day of retention 15m:8 15 minutes per datapoint, 8 datapoints = 2 hours of retention 1h:7d 1 hour per datapoint, 7 days of retention 12h:2y 12 hours per datapoint, 2 years of retention "#, required = true, min_values = 1 )] retentions: Vec<Retention>, } fn estimate_info(retentions: &[Retention]) { for (i, retention) in retentions.iter().enumerate() { println!( "Archive {}: {} points of {}s precision", i, &retention.points, &retention.seconds_per_point ); } let total_points: usize = retentions.iter().map(|x| x.points as usize).sum(); let size = (whisper::METADATA_SIZE + (retentions.len() * whisper::ARCHIVE_INFO_SIZE) + (total_points * whisper::POINT_SIZE)) as usize; let disk_size = (size as f64 / 4096.0).ceil() as usize * 4096; let custom_options = options::FileSizeOpts { decimal_places: 3, ..options::CONVENTIONAL }; println!(); println!( "Estimated Whisper DB Size: {} ({} bytes on disk with 4k blocks)", size.file_size(&custom_options).unwrap(), disk_size ); println!(); let numbers = [1, 5, 10, 50, 100, 500]; for number in &numbers { println!( "Estimated storage requirement for {}k metrics: {}",
random
[ { "content": "#[derive(Debug, StructOpt)]\n\n#[structopt(name = \"rrd2whisper\")]\n\nstruct Args {\n\n /// The xFilesFactor to use in the output file. Defaults to the input RRD's xFilesFactor.\n\n #[structopt(long = \"xFilesFactor\")]\n\n x_files_factor: Option<f64>,\n\n\n\n /// The consolidation fu...
Rust
src/main.rs
erikjohnston/matrix-media-store-size
16055e1964c58f2f35bdff1e888e84d963a1c37a
#[macro_use] extern crate clap; extern crate humansize; extern crate linear_map; extern crate rand; extern crate rusqlite; extern crate twox_hash; extern crate walkdir; extern crate indicatif; use humansize::{FileSize, file_size_opts as options}; use clap::{App, Arg}; use linear_map::LinearMap; use rand::Rng; use std::io; use std::io::Read; use std::fs::File; use std::hash::Hasher; use std::collections::BTreeMap; use std::path::PathBuf; use walkdir::WalkDir; fn copy<R: io::Read, W: Hasher>(reader: &mut R, writer: &mut W) -> io::Result<u64> { let mut buf = [0; 64 * 1024]; let mut written = 0; loop { let len = match reader.read(&mut buf) { Ok(0) => return Ok(written), Ok(len) => len, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; writer.write(&buf[..len]); written += len as u64; } } fn to_hash(path: &PathBuf) -> u64 { let mut file = File::open(path).unwrap(); let mut hasher = twox_hash::XxHash::default(); copy(&mut file, &mut hasher).unwrap(); hasher.finish() } fn read_file(path: &PathBuf) -> Vec<u8> { let mut file = File::open(path).unwrap(); let mut vec = Vec::new(); file.read_to_end(&mut vec).unwrap(); vec } fn partition_by<I, F, R>(paths: I, f: F) -> LinearMap<R, Vec<PathBuf>> where I: Iterator<Item=PathBuf>, F: Fn(&PathBuf) -> R, R: Eq { let mut map = LinearMap::with_capacity(paths.size_hint().0); for path in paths { let key = f(&path); map.entry(key).or_insert_with(Vec::new).push(path); } map } const DB_TABLE_SCHEMA: &'static str = r#" CREATE TABLE files ( hash BIGINT NOT NULL, path TEXT NOT NULL, size BIGINT NOT NULL ); "#; fn main() { let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!("\n")) .arg(Arg::with_name("media_directory") .help("The location of the media store") .index(1) .multiple(true) .required(true)) .arg(Arg::with_name("output-db") .short("o") .long("output-db") .help("Where to write SQLite database to") .value_name("FILE") .takes_value(true)) .get_matches(); let paths_to_search = matches.values_of("media_directory").unwrap(); let output_db_path = matches.value_of("output-db"); let db = rusqlite::Connection::open_in_memory().expect("failed to open sqlite db"); db.execute_batch(DB_TABLE_SCHEMA).expect("failed to create db schema"); let mut paths_by_size = BTreeMap::new(); let mut total_files = 0; let mut total_size = 0; let pb = indicatif::ProgressBar::new_spinner(); pb.set_style( indicatif::ProgressStyle::default_spinner() .template("{spinner} Collected metadata for {pos} files [{elapsed}]") ); for path in paths_to_search { for entry in WalkDir::new(path) { let entry = entry.unwrap(); if !entry.file_type().is_file() { continue } let file_size = entry.metadata().unwrap().len() as usize; paths_by_size.entry(file_size).or_insert_with(Vec::new).push(entry.path().to_owned()); total_files += 1; total_size += file_size; pb.inc(1); } } pb.finish(); pb.set_position(total_files); let pb = indicatif::ProgressBar::new(total_files); pb.set_style( indicatif::ProgressStyle::default_bar() .template(" Searching for possible duplicates {bar:40} {pos:>9}/{len:9} [{elapsed}]") ); let mut possible_total_size = 0; let mut possible_duplicates = Vec::new(); for (file_size, paths) in paths_by_size { if paths.len() > 1 { possible_total_size += file_size * paths.len(); possible_duplicates.push((file_size, paths)) } pb.inc(1); } pb.finish(); let mut rng = rand::thread_rng(); rng.shuffle(possible_duplicates.as_mut_slice()); let pb = indicatif::ProgressBar::new(possible_total_size as u64); pb.set_style( indicatif::ProgressStyle::default_bar() .template(" Comparing hashes {bar:40} {bytes:>9}/{total_bytes:9} [{elapsed}]") ); let mut total_wasted_size = 0; for (file_size, paths) in possible_duplicates { if paths.len() == 1 { continue } let by_hash = partition_by(paths.into_iter(), to_hash); for (hash, paths) in by_hash { if paths.len() == 1 { pb.inc(file_size as u64); continue } let by_contents = partition_by(paths.into_iter(), read_file); for (_, paths) in by_contents { if paths.len() == 1 { pb.inc(file_size as u64); continue } for path in &paths { db.execute("INSERT INTO files (hash, path, size) VALUES (?, ?, ?)", &[&(hash as i64), &path.to_str().unwrap(), &(file_size as i64)]).expect("failed to write to db"); } let wasted = file_size * (paths.len() - 1); total_wasted_size += wasted; pb.inc((file_size * paths.len()) as u64); } } } pb.finish(); println!(); println!( "Total wasted size: {} out of {}. Percentage: {:.2}%", total_wasted_size.file_size(options::CONVENTIONAL).unwrap(), total_size.file_size(options::CONVENTIONAL).unwrap(), (total_wasted_size * 100) as f64 / total_size as f64, ); if let Some(path) = output_db_path { let mut disk_db = rusqlite::Connection::open(path).expect("failed to open sqlite db"); let backup = rusqlite::backup::Backup::new(&db, &mut disk_db).expect("failed to create backup"); backup.run_to_completion(5, std::time::Duration::from_millis(0), None).expect("failed to write to disk"); } }
#[macro_use] extern crate clap; extern crate humansize; extern crate linear_map; extern crate rand; extern crate rusqlite; extern crate twox_hash; extern crate walkdir; extern crate indicatif; use humansize::{FileSize, file_size_opts as options}; use clap::{App, Arg}; use linear_map::LinearMap; use rand::Rng; use std::io; use std::io::Read; use std::fs::File; use std::hash::Hasher; use std::collections::BTreeMap; use std::path::PathBuf; use walkdir::WalkDir; fn copy<R: io::Read, W: Hasher>(reader: &mut R, writer: &mut W) -> io::Result<u64> { let mut buf = [0; 64 * 1024]; let mut written = 0; loop { let len = match reader.read(&mut buf) { Ok(0) => return Ok(written), Ok(len) => len, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; writer.write(&buf[..len]); written += len as u64; } } fn to_hash(path: &PathBuf) -> u64 { let mut file = File::open(path).unwrap(); let mut hasher = twox_hash::XxHash::default(); copy(&mut file, &mut hasher).unwrap(); hasher.finish() } fn read_file(path: &PathBuf) -> Vec<u8> { let mut file = File::open(path).unwrap(); let mut vec = Vec::new(); file.read_to_end(&mut vec).unwrap(); vec } fn partition_by<I, F, R>(paths: I, f: F) -> LinearMap<R, Vec<PathBuf>> where I: Iterator<Item=PathBuf>, F: Fn(&PathBuf) -> R, R: Eq { let mut map = LinearMap::with_capacity(paths.size_hint().0); for path in paths { let key = f(&path); map.entry(key).or_insert_with(Vec::new).push(path); } map } const DB_TABLE_SCHEMA: &'static str = r#" CREATE TABLE files ( hash BIGINT NOT NULL, path TEXT NOT NULL, size BIGINT NOT NULL ); "#; fn main() { let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!("\n")) .arg(Arg::with_name("media_directory") .help("The location of the media store") .index(1) .multiple(true) .required(true)) .arg(Arg::with_name("output-db") .short("o") .long("output-db") .help("Where to write SQLite database to") .value_name("FILE") .takes_value(true)) .get_matches(); let paths_to_search = matches.values_of("media_directory").unwrap(); let output_db_path = matches.value_of("output-db"); let db = rusqlite::Connection::open_in_memory().expect("failed to open sqlite db"); db.execute_batch(DB_TABLE_SCHEMA).expect("failed to create db schema"); let mut paths_by_size = BTreeMap::new(); let mut total_files = 0; let mut total_size = 0; let pb = indicatif::ProgressBar::new_spinner(); pb.set_style( indicatif::ProgressStyle::default_spinner() .template("{spinner} Collected metadata for {pos} files [{elapsed}]") ); for path in paths_to_search { for entry in WalkDir::new(path) { let entry = entry.unwrap(); if !entry.file_type().is_file() { continue } let file_size = entry.metadata().unwrap().len() as usize; paths_by_size.entry(file_size).or_insert_with(Vec::new).push(entry.path().to_owned()); total_files += 1; total_size += file_size; pb.inc(1); } } pb.finish(); pb.set_position(total_files); let pb = indicatif::ProgressBar::new(total_files); pb.set_style( indicatif::ProgressStyle::default_bar() .template(" Searching for possible duplicates {bar:40} {pos:>9}/{len:9} [{elapsed}]") ); let mut possible_total_size = 0; let mut possible_duplicates = Vec::new(); for (file_size, paths) in paths_by_size { if paths.len() > 1 { possible_total_size += file_size * paths.len(); possible_duplicates.push((file_size, paths)) } pb.inc(1); } pb.finish(); let mut rng = rand::thread_rng(); rng.shuffle(possible_duplicates.as_mut_slice()); let pb = indicatif::ProgressBar::new(possible_total_size as u64); pb.set_style( indicatif::ProgressStyle::default_bar() .template(" Comparing hashes {bar:40} {bytes:>9}/{total_bytes:9} [{elapsed}]") ); let mut total_wasted_size = 0; for (file_size, paths) in possible_duplicates { if paths.len() == 1 { continue } let by_hash = partition_by(paths.into_iter(), to_hash); for (hash, paths) in by_hash { if paths.len() == 1 { pb.inc(file_size as u64); continue } let by_contents = partition_by(paths.into_iter(), read_file); for (_, paths) in by_contents { if paths.len() == 1 { pb.inc(file_size as u64); continue } for path in &paths { db.execute("INSERT INTO files (hash, path, size) VALUES (?, ?, ?)", &[&(hash as i64), &path.to_str().unwrap(), &(file_size as i64)]).expect("failed to write to db
.len()) as u64); } } } pb.finish(); println!(); println!( "Total wasted size: {} out of {}. Percentage: {:.2}%", total_wasted_size.file_size(options::CONVENTIONAL).unwrap(), total_size.file_size(options::CONVENTIONAL).unwrap(), (total_wasted_size * 100) as f64 / total_size as f64, ); if let Some(path) = output_db_path { let mut disk_db = rusqlite::Connection::open(path).expect("failed to open sqlite db"); let backup = rusqlite::backup::Backup::new(&db, &mut disk_db).expect("failed to create backup"); backup.run_to_completion(5, std::time::Duration::from_millis(0), None).expect("failed to write to disk"); } }
"); } let wasted = file_size * (paths.len() - 1); total_wasted_size += wasted; pb.inc((file_size * paths
random
[]
Rust
src/entities.rs
brooks-builds/improve_skills_by_building_ecs_library_in_rust
d8131b0b6a963456fd4c2ad94382924060847905
pub mod query; pub mod query_entity; use std::{ any::{Any, TypeId}, cell::RefCell, collections::HashMap, rc::Rc, vec, }; use eyre::Result; use crate::custom_errors::CustomErrors; pub type Component = Rc<RefCell<dyn Any>>; pub type Components = HashMap<TypeId, Vec<Option<Component>>>; #[derive(Debug, Default)] pub struct Entities { components: Components, bit_masks: HashMap<TypeId, u32>, map: Vec<u32>, inserting_into_index: usize, } impl Entities { pub fn register_component<T: Any + 'static>(&mut self) { let type_id = TypeId::of::<T>(); let bit_mask = 2u32.pow(self.bit_masks.len() as u32); self.components.insert(type_id, vec![]); self.bit_masks.insert(type_id, bit_mask); } pub fn create_entity(&mut self) -> &mut Self { if let Some((index, _)) = self .map .iter() .enumerate() .find(|(_index, mask)| **mask == 0) { self.inserting_into_index = index; } else { self.components .iter_mut() .for_each(|(_key, components)| components.push(None)); self.map.push(0); self.inserting_into_index = self.map.len() - 1; } self } pub fn with_component(&mut self, data: impl Any) -> Result<&mut Self> { let type_id = data.type_id(); let index = self.inserting_into_index; if let Some(components) = self.components.get_mut(&type_id) { let component = components .get_mut(index) .ok_or(CustomErrors::CreateComponentNeverCalled)?; *component = Some(Rc::new(RefCell::new(data))); let bitmask = self.bit_masks.get(&type_id).unwrap(); self.map[index] |= *bitmask; } else { return Err(CustomErrors::ComponentNotRegistered.into()); } Ok(self) } pub fn get_bitmask(&self, type_id: &TypeId) -> Option<u32> { self.bit_masks.get(type_id).copied() } pub fn delete_component_by_entity_id<T: Any>(&mut self, index: usize) -> Result<()> { let type_id = TypeId::of::<T>(); let mask = if let Some(mask) = self.bit_masks.get(&type_id) { mask } else { return Err(CustomErrors::ComponentNotRegistered.into()); }; if self.has_component(index, *mask) { self.map[index] ^= *mask; } Ok(()) } pub fn add_component_by_entity_id(&mut self, data: impl Any, index: usize) -> Result<()> { let type_id = data.type_id(); let mask = if let Some(mask) = self.bit_masks.get(&type_id) { mask } else { return Err(CustomErrors::ComponentNotRegistered.into()); }; self.map[index] |= *mask; let components = self.components.get_mut(&type_id).unwrap(); components[index] = Some(Rc::new(RefCell::new(data))); Ok(()) } pub fn delete_entity_by_id(&mut self, index: usize) -> Result<()> { if let Some(map) = self.map.get_mut(index) { *map = 0; } else { return Err(CustomErrors::EntityDoesNotExist.into()); } Ok(()) } fn has_component(&self, index: usize, mask: u32) -> bool { self.map[index] & mask == mask } } #[cfg(test)] mod test { use std::any::TypeId; use super::*; #[test] fn register_an_entity() { let mut entities = Entities::default(); entities.register_component::<Health>(); let type_id = TypeId::of::<Health>(); let health_components = entities.components.get(&type_id).unwrap(); assert_eq!(health_components.len(), 0); } #[test] fn bitmask_updated_when_registering_entities() { let mut entities = Entities::default(); entities.register_component::<Health>(); let type_id = TypeId::of::<Health>(); let mask = entities.bit_masks.get(&type_id).unwrap(); assert_eq!(*mask, 1); entities.register_component::<Speed>(); let type_id = TypeId::of::<Speed>(); let mask = entities.bit_masks.get(&type_id).unwrap(); assert_eq!(*mask, 2); } #[test] fn create_entity() { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities.create_entity(); let health = entities.components.get(&TypeId::of::<Health>()).unwrap(); let speed = entities.components.get(&TypeId::of::<Speed>()).unwrap(); assert!(health.len() == speed.len() && health.len() == 1); assert!(health[0].is_none() && speed[0].is_none()); } #[test] fn with_component() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities .create_entity() .with_component(Health(100))? .with_component(Speed(15))?; let first_health = &entities.components.get(&TypeId::of::<Health>()).unwrap()[0]; let wrapped_health = first_health.as_ref().unwrap(); let borrowed_health = wrapped_health.borrow(); let health = borrowed_health.downcast_ref::<Health>().unwrap(); assert_eq!(health.0, 100); Ok(()) } #[test] fn map_is_updated_when_creating_entities() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities .create_entity() .with_component(Health(100))? .with_component(Speed(15))?; let entity_map = entities.map[0]; assert_eq!(entity_map, 3); entities.create_entity().with_component(Speed(15))?; let entity_map = entities.map[1]; assert_eq!(entity_map, 2); Ok(()) } #[test] fn delete_component_by_entity_id() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities .create_entity() .with_component(Health(100))? .with_component(Speed(50))?; entities.delete_component_by_entity_id::<Health>(0)?; assert_eq!(entities.map[0], 2); Ok(()) } #[test] fn add_component_to_entity_by_id() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities.create_entity().with_component(Health(100))?; entities.add_component_by_entity_id(Speed(50), 0)?; assert_eq!(entities.map[0], 3); let speed_type_id = TypeId::of::<Speed>(); let wrapped_speeds = entities.components.get(&speed_type_id).unwrap(); let wrapped_speed = wrapped_speeds[0].as_ref().unwrap(); let borrowed_speed = wrapped_speed.borrow(); let speed = borrowed_speed.downcast_ref::<Speed>().unwrap(); assert_eq!(speed.0, 50); Ok(()) } #[test] fn delete_entity_by_id() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.create_entity().with_component(Health(100))?; entities.delete_entity_by_id(0)?; assert_eq!(entities.map[0], 0); Ok(()) } #[test] fn created_entities_are_inserted_into_deleted_entities_columns() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.create_entity().with_component(Health(100))?; entities.create_entity().with_component(Health(50))?; entities.delete_entity_by_id(0)?; entities.create_entity().with_component(Health(25))?; assert_eq!(entities.map[0], 1); let type_id = TypeId::of::<Health>(); let borrowed_health = &entities.components.get(&type_id).unwrap()[0] .as_ref() .unwrap() .borrow(); let health = borrowed_health.downcast_ref::<Health>().unwrap(); assert_eq!(health.0, 25); Ok(()) } #[test] fn should_not_add_component_back_after_deleting_twice() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<u32>(); entities.register_component::<f32>(); entities .create_entity() .with_component(100_u32)? .with_component(50.0_f32)?; entities.delete_component_by_entity_id::<u32>(0)?; entities.delete_component_by_entity_id::<u32>(0)?; assert_eq!(entities.map[0], 2); Ok(()) } /* Brendon Stanton When you create your second component, inserting_into_index never changes from 0. So when you get to with_component, Health(50) overwrites Health(100) and column 1 in your table never actually gets used. */ #[test] fn inserting_into_index_should_change_when_adding_components() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<f32>(); entities.register_component::<u32>(); let creating_entity = entities.create_entity(); assert_eq!(creating_entity.inserting_into_index, 0); creating_entity .with_component(100.0_f32)? .with_component(10_u32)?; assert_eq!(entities.inserting_into_index, 0); let creating_entity = entities.create_entity(); assert_eq!(creating_entity.inserting_into_index, 1); creating_entity .with_component(110.0_f32)? .with_component(20_u32)?; assert_eq!(entities.inserting_into_index, 1); entities.delete_entity_by_id(0)?; let creating_entity = entities.create_entity(); assert_eq!(creating_entity.inserting_into_index, 0); creating_entity .with_component(100.0_f32)? .with_component(10_u32)?; assert_eq!(entities.inserting_into_index, 0); Ok(()) } struct Health(pub u32); struct Speed(pub u32); }
pub mod query; pub mod query_entity; use std::{ any::{Any, TypeId}, cell::RefCell, collections::HashMap, rc::Rc, vec, }; use eyre::Result; use crate::custom_errors::CustomErrors; pub type Component = Rc<RefCell<dyn Any>>; pub type Components = HashMap<TypeId, Vec<Option<Component>>>; #[derive(Debug, Default)] pub struct Entities { components: Components, bit_masks: HashMap<TypeId, u32>, map: Vec<u32>, inserting_into_index: usize, } impl Entities { pub fn register_component<T: Any + 'static>(&mut self) { let type_id = TypeId::of::<T>(); let bit_mask = 2u32.pow(self.bit_masks.len() as u32); self.components.insert(type_id, vec![]); self.bit_masks.insert(type_id, bit_mask); } pub fn create_entity(&mut self) -> &mut Self { if let Some((index, _)) = self .map .iter() .enumerate() .find(|(_index, mask)| **mask == 0) { self.inserting_into_index = index; } else { self.components .iter_mut() .for_each(|(_key, components)| components.push(None)); self.map.push(0); self.inserting_into_index = self.map.len() - 1; } self } pub fn with_component(&mut self, data: impl Any) -> Result<&mut Self> { let type_id = data.type_id(); let index = self.inserting_into_index;
Ok(self) } pub fn get_bitmask(&self, type_id: &TypeId) -> Option<u32> { self.bit_masks.get(type_id).copied() } pub fn delete_component_by_entity_id<T: Any>(&mut self, index: usize) -> Result<()> { let type_id = TypeId::of::<T>(); let mask = if let Some(mask) = self.bit_masks.get(&type_id) { mask } else { return Err(CustomErrors::ComponentNotRegistered.into()); }; if self.has_component(index, *mask) { self.map[index] ^= *mask; } Ok(()) } pub fn add_component_by_entity_id(&mut self, data: impl Any, index: usize) -> Result<()> { let type_id = data.type_id(); let mask = if let Some(mask) = self.bit_masks.get(&type_id) { mask } else { return Err(CustomErrors::ComponentNotRegistered.into()); }; self.map[index] |= *mask; let components = self.components.get_mut(&type_id).unwrap(); components[index] = Some(Rc::new(RefCell::new(data))); Ok(()) } pub fn delete_entity_by_id(&mut self, index: usize) -> Result<()> { if let Some(map) = self.map.get_mut(index) { *map = 0; } else { return Err(CustomErrors::EntityDoesNotExist.into()); } Ok(()) } fn has_component(&self, index: usize, mask: u32) -> bool { self.map[index] & mask == mask } } #[cfg(test)] mod test { use std::any::TypeId; use super::*; #[test] fn register_an_entity() { let mut entities = Entities::default(); entities.register_component::<Health>(); let type_id = TypeId::of::<Health>(); let health_components = entities.components.get(&type_id).unwrap(); assert_eq!(health_components.len(), 0); } #[test] fn bitmask_updated_when_registering_entities() { let mut entities = Entities::default(); entities.register_component::<Health>(); let type_id = TypeId::of::<Health>(); let mask = entities.bit_masks.get(&type_id).unwrap(); assert_eq!(*mask, 1); entities.register_component::<Speed>(); let type_id = TypeId::of::<Speed>(); let mask = entities.bit_masks.get(&type_id).unwrap(); assert_eq!(*mask, 2); } #[test] fn create_entity() { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities.create_entity(); let health = entities.components.get(&TypeId::of::<Health>()).unwrap(); let speed = entities.components.get(&TypeId::of::<Speed>()).unwrap(); assert!(health.len() == speed.len() && health.len() == 1); assert!(health[0].is_none() && speed[0].is_none()); } #[test] fn with_component() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities .create_entity() .with_component(Health(100))? .with_component(Speed(15))?; let first_health = &entities.components.get(&TypeId::of::<Health>()).unwrap()[0]; let wrapped_health = first_health.as_ref().unwrap(); let borrowed_health = wrapped_health.borrow(); let health = borrowed_health.downcast_ref::<Health>().unwrap(); assert_eq!(health.0, 100); Ok(()) } #[test] fn map_is_updated_when_creating_entities() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities .create_entity() .with_component(Health(100))? .with_component(Speed(15))?; let entity_map = entities.map[0]; assert_eq!(entity_map, 3); entities.create_entity().with_component(Speed(15))?; let entity_map = entities.map[1]; assert_eq!(entity_map, 2); Ok(()) } #[test] fn delete_component_by_entity_id() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities .create_entity() .with_component(Health(100))? .with_component(Speed(50))?; entities.delete_component_by_entity_id::<Health>(0)?; assert_eq!(entities.map[0], 2); Ok(()) } #[test] fn add_component_to_entity_by_id() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.register_component::<Speed>(); entities.create_entity().with_component(Health(100))?; entities.add_component_by_entity_id(Speed(50), 0)?; assert_eq!(entities.map[0], 3); let speed_type_id = TypeId::of::<Speed>(); let wrapped_speeds = entities.components.get(&speed_type_id).unwrap(); let wrapped_speed = wrapped_speeds[0].as_ref().unwrap(); let borrowed_speed = wrapped_speed.borrow(); let speed = borrowed_speed.downcast_ref::<Speed>().unwrap(); assert_eq!(speed.0, 50); Ok(()) } #[test] fn delete_entity_by_id() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.create_entity().with_component(Health(100))?; entities.delete_entity_by_id(0)?; assert_eq!(entities.map[0], 0); Ok(()) } #[test] fn created_entities_are_inserted_into_deleted_entities_columns() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<Health>(); entities.create_entity().with_component(Health(100))?; entities.create_entity().with_component(Health(50))?; entities.delete_entity_by_id(0)?; entities.create_entity().with_component(Health(25))?; assert_eq!(entities.map[0], 1); let type_id = TypeId::of::<Health>(); let borrowed_health = &entities.components.get(&type_id).unwrap()[0] .as_ref() .unwrap() .borrow(); let health = borrowed_health.downcast_ref::<Health>().unwrap(); assert_eq!(health.0, 25); Ok(()) } #[test] fn should_not_add_component_back_after_deleting_twice() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<u32>(); entities.register_component::<f32>(); entities .create_entity() .with_component(100_u32)? .with_component(50.0_f32)?; entities.delete_component_by_entity_id::<u32>(0)?; entities.delete_component_by_entity_id::<u32>(0)?; assert_eq!(entities.map[0], 2); Ok(()) } /* Brendon Stanton When you create your second component, inserting_into_index never changes from 0. So when you get to with_component, Health(50) overwrites Health(100) and column 1 in your table never actually gets used. */ #[test] fn inserting_into_index_should_change_when_adding_components() -> Result<()> { let mut entities = Entities::default(); entities.register_component::<f32>(); entities.register_component::<u32>(); let creating_entity = entities.create_entity(); assert_eq!(creating_entity.inserting_into_index, 0); creating_entity .with_component(100.0_f32)? .with_component(10_u32)?; assert_eq!(entities.inserting_into_index, 0); let creating_entity = entities.create_entity(); assert_eq!(creating_entity.inserting_into_index, 1); creating_entity .with_component(110.0_f32)? .with_component(20_u32)?; assert_eq!(entities.inserting_into_index, 1); entities.delete_entity_by_id(0)?; let creating_entity = entities.create_entity(); assert_eq!(creating_entity.inserting_into_index, 0); creating_entity .with_component(100.0_f32)? .with_component(10_u32)?; assert_eq!(entities.inserting_into_index, 0); Ok(()) } struct Health(pub u32); struct Speed(pub u32); }
if let Some(components) = self.components.get_mut(&type_id) { let component = components .get_mut(index) .ok_or(CustomErrors::CreateComponentNeverCalled)?; *component = Some(Rc::new(RefCell::new(data))); let bitmask = self.bit_masks.get(&type_id).unwrap(); self.map[index] |= *bitmask; } else { return Err(CustomErrors::ComponentNotRegistered.into()); }
if_condition
[ { "content": "struct Health(pub u32);\n\n\n\nimpl Health {\n\n pub fn new(data: u32) -> Self {\n\n Self(data)\n\n }\n\n\n\n pub fn lose_health(&mut self, amount: u32) {\n\n self.0 -= amount;\n\n }\n\n\n\n pub fn print_health(&self) {\n\n println!(\"health: {:?}\", **self);\n\...
Rust
src/main.rs
detedetedetedete/DictWalker
81ebbf52a0e124172b7697a1f8ee0748f98ed60e
extern crate serde_json; extern crate encoding; extern crate fern; extern crate clap; extern crate chrono; extern crate regex; #[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; extern crate serde; extern crate libc; use dict_entry::DictEntry; use std::path::Path; use cli_api::get_args; use std::collections::HashSet; use std::iter::FromIterator; use std::fs::File; use std::io::Write; use training_entry::TrainingEntry; use phoneme_resolvers::DeadEndPhonemeResolver; use phoneme_resolvers::DictionaryPhonemeResolver; use phoneme_resolvers::PhonemeResolver; use phoneme_resolvers::MarkerPhonemeResolver; use phoneme_resolvers::DummyPhonemeResolver; use phoneme_resolvers::TensorflowPhonemeResolver; mod decode; mod dict_entry; mod cli_api; mod logging; mod training_entry; mod phonemes; mod phoneme_resolvers; mod model_def; mod model_runner; fn main() { let matches = get_args(); let dictionary = matches.value_of("dictionary").unwrap(); let mut output_file = match File::create(matches.value_of("output").unwrap()) { Ok(v) => v, Err(e) => { error!("Cannot open file \"{}\" for writing: {}", matches.value_of("output").unwrap(), e); panic!(); } }; let mut phoneme_resolvers: Vec<Box<PhonemeResolver>> = vec![ match matches.value_of("phoneme dictionary") { Some(path) => { match DictionaryPhonemeResolver::load(Path::new(path)) { Ok(v) => Box::new(v), Err(e) => { error!("Failed to instantiate DictionaryPhonemeResolver: \"{}\"", e); panic!(); } } }, None => Box::new(DummyPhonemeResolver::new()) }, match matches.value_of("Seq2Seq model folder") { Some(path) => { let model_folder_path = Path::new(path); match TensorflowPhonemeResolver::load(model_folder_path) { Ok(v) => Box::new(v), Err(e) => { error!("Failed to instantiate DictionaryPhonemeResolver: \"{}\"", e); panic!(); } } }, None => Box::new(DummyPhonemeResolver::new()) }, Box::new(MarkerPhonemeResolver::new()), Box::new(DeadEndPhonemeResolver::new()) ]; let mut entries = match DictEntry::collect_entries( Path::new(dictionary), &HashSet::from_iter(matches.value_of("audio extensions").unwrap().split(",").map(|v| String::from(v))), &HashSet::from_iter(matches.value_of("text extensions").unwrap().split(",").map(|v| String::from(v))) ) { Ok(v) => v, Err(e) => panic!("Failed to collect entries: {:?}", e) }; let t_entries: Vec<TrainingEntry> = entries .drain(0..) .map(|v| TrainingEntry::construct(v, &mut phoneme_resolvers)) .collect(); let json = match serde_json::to_string_pretty(&t_entries) { Ok(v) => v, Err(e) => { error!("Cannot serialize processed entries to JSON: {}", e); panic!(); } }; match output_file.write_all(json.as_bytes()) { Err(e) => { error!("Error during write to file {:?}: {}", output_file, e); panic!(); }, _ => () }; info!("Done."); }
extern crate serde_json; extern crate encoding; extern crate fern; extern crate clap; extern crate chrono; extern crate regex; #[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; extern crate serde; extern crate libc; use dict_entry::DictEntry; use std::path::Path; use cli_api::get_args; use std::collections::HashSet; use std::iter::FromIterator; use std::fs::File; use std::io::Write; use training_entry::TrainingEntry; use phoneme_resolvers::DeadEndPhonemeResolver; use phoneme_resolvers::DictionaryPhonemeResolver; use phoneme_resolvers::PhonemeResolver; use phoneme_resolvers::MarkerPhonemeResolver; use phoneme_resolvers::DummyPhonemeResolver; use phoneme_resolvers::TensorflowPhonemeResolver; mod decode; mod dict_entry; mod cli_api; mod logging; mod training_entry; mod phonemes; mod phoneme_resolvers; mod model_def; mod model_runner; fn main() { let matches = get_args(); let dictionary = matches.value_of("dictionary").unwrap(); let mut output_file = match File::create(matches.value_of("output").unwrap()) { Ok(v) => v, Err(e) => { error!("Cannot open file \"{}\" for writing: {}", matches.value_of("output").unwrap(), e); panic!(); } }; let mut phoneme_resolvers: Vec<Box<PhonemeResolver>> = vec![ match matches.value_of("phoneme dictionary") { Some(path) => { match DictionaryPhonemeResolver::load(Path::new(path)) { Ok(v) => Box::new(v), Err(e) => { error!("Failed to instantiate DictionaryPhonemeResolver: \"{}\"", e); panic!(); } } }, None => Box::new(DummyPhonemeResolver::new()) }, match matches.value_of("Seq2Seq model folder") { Some(path) => { let model_folder_path = Path::new(path); match TensorflowPhonemeResolver::load(model_folder_path) { Ok(v) => Box::new(v), Err(e) => { error!("Failed to instantiate DictionaryPhonemeResolver: \"{}\"", e); panic!(); } } }, None => Box::new(DummyPhonemeResolver::new()) }, Box::new(MarkerPhonemeResolver::new())
in(0..) .map(|v| TrainingEntry::construct(v, &mut phoneme_resolvers)) .collect(); let json = match serde_json::to_string_pretty(&t_entries) { Ok(v) => v, Err(e) => { error!("Cannot serialize processed entries to JSON: {}", e); panic!(); } }; match output_file.write_all(json.as_bytes()) { Err(e) => { error!("Error during write to file {:?}: {}", output_file, e); panic!(); }, _ => () }; info!("Done."); }
, Box::new(DeadEndPhonemeResolver::new()) ]; let mut entries = match DictEntry::collect_entries( Path::new(dictionary), &HashSet::from_iter(matches.value_of("audio extensions").unwrap().split(",").map(|v| String::from(v))), &HashSet::from_iter(matches.value_of("text extensions").unwrap().split(",").map(|v| String::from(v))) ) { Ok(v) => v, Err(e) => panic!("Failed to collect entries: {:?}", e) }; let t_entries: Vec<TrainingEntry> = entries .dra
function_block-random_span
[ { "content": "fn serialize_phoneme_vec<S>(vec: &Vec<Phoneme>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {\n\n let mut str = String::new();\n\n for ph in vec {\n\n str.push_str(&ph.to_string());\n\n }\n\n serializer.serialize_str(&str)\n\n}\n\n\n\nimpl TrainingEntry {\n\n ...
Rust
src/pixel.rs
B-Reif/asefile
4bb33e1398461b3d153d99ab0830bb87f347dce2
use image::{Pixel, Rgba}; use crate::{reader::AseReader, AsepriteParseError, ColorPalette, PixelFormat, Result}; use std::{borrow::Cow, io::Read}; fn read_rgba(chunk: &[u8]) -> Result<Rgba<u8>> { let mut reader = AseReader::new(chunk); let red = reader.byte()?; let green = reader.byte()?; let blue = reader.byte()?; let alpha = reader.byte()?; Ok(Rgba::from_channels(red, green, blue, alpha)) } #[derive(Debug, Clone, Copy)] pub(crate) struct Grayscale { value: u8, alpha: u8, } impl Grayscale { fn new(chunk: &[u8]) -> Result<Self> { let mut reader = AseReader::new(chunk); let value = reader.byte()?; let alpha = reader.byte()?; Ok(Self { value, alpha }) } pub(crate) fn into_rgba(self) -> Rgba<u8> { let Self { value, alpha } = self; Rgba::from_channels(value, value, value, alpha) } } #[derive(Debug, Clone, Copy)] pub(crate) struct Indexed(u8); impl Indexed { pub(crate) fn value(&self) -> u8 { self.0 } pub(crate) fn as_rgba( &self, palette: &ColorPalette, transparent_color_index: u8, layer_is_background: bool, ) -> Option<Rgba<u8>> { let index = self.0; palette.color(index as u32).map(|c| { let alpha = if transparent_color_index == index && !layer_is_background { 0 } else { c.alpha() }; Rgba::from_channels(c.red(), c.green(), c.blue(), alpha) }) } } fn output_size(pixel_format: PixelFormat, expected_pixel_count: usize) -> usize { pixel_format.bytes_per_pixel() * expected_pixel_count } #[derive(Debug)] pub(crate) enum Pixels { Rgba(Vec<Rgba<u8>>), Grayscale(Vec<Grayscale>), Indexed(Vec<Indexed>), } impl Pixels { fn from_bytes(bytes: Vec<u8>, pixel_format: PixelFormat) -> Result<Self> { match pixel_format { PixelFormat::Indexed { .. } => { let pixels = bytes.iter().map(|byte| Indexed(*byte)).collect(); Ok(Self::Indexed(pixels)) } PixelFormat::Grayscale => { if bytes.len() % 2 != 0 { return Err(AsepriteParseError::InvalidInput( "Incorrect length of bytes for Grayscale image data".to_string(), )); } let pixels: Result<Vec<_>> = bytes.chunks_exact(2).map(Grayscale::new).collect(); pixels.map(Self::Grayscale) } PixelFormat::Rgba => { if bytes.len() % 4 != 0 { return Err(AsepriteParseError::InvalidInput( "Incorrect length of bytes for RGBA image data".to_string(), )); } let pixels: Result<Vec<_>> = bytes.chunks_exact(4).map(read_rgba).collect(); pixels.map(Self::Rgba) } } } pub(crate) fn from_raw<T: Read>( reader: AseReader<T>, pixel_format: PixelFormat, expected_pixel_count: usize, ) -> Result<Self> { let expected_output_size = output_size(pixel_format, expected_pixel_count); reader .take_bytes(expected_output_size) .and_then(|bytes| Self::from_bytes(bytes, pixel_format)) } pub(crate) fn from_compressed<T: Read>( reader: AseReader<T>, pixel_format: PixelFormat, expected_pixel_count: usize, ) -> Result<Self> { let expected_output_size = output_size(pixel_format, expected_pixel_count); reader .unzip(expected_output_size) .and_then(|bytes| Self::from_bytes(bytes, pixel_format)) } pub(crate) fn byte_count(&self) -> usize { match self { Pixels::Rgba(v) => v.len() * 4, Pixels::Grayscale(v) => v.len() * 2, Pixels::Indexed(v) => v.len(), } } pub(crate) fn clone_as_image_rgba( &self, index_resolver_data: IndexResolverData<'_>, ) -> Cow<Vec<image::Rgba<u8>>> { match self { Pixels::Rgba(rgba) => Cow::Borrowed(rgba), Pixels::Grayscale(grayscale) => { Cow::Owned(grayscale.iter().map(|gs| gs.into_rgba()).collect()) } Pixels::Indexed(indexed) => { let IndexResolverData { palette, transparent_color_index, layer_is_background, } = index_resolver_data; let palette = palette.expect("Expected a palette when resolving indexed pixels. Should have been caught in validation"); let transparent_color_index = transparent_color_index.expect( "Indexed tilemap pixels in non-indexed pixel format. Should have been caught in validation", ); let resolver = |px: &Indexed| { px.as_rgba(palette, transparent_color_index, layer_is_background) .expect("Indexed pixel out of range. Should have been caught in validation") }; Cow::Owned(indexed.iter().map(resolver).collect()) } } } } pub(crate) struct IndexResolverData<'a> { pub(crate) palette: Option<&'a ColorPalette>, pub(crate) transparent_color_index: Option<u8>, pub(crate) layer_is_background: bool, }
use image::{Pixel, Rgba}; use crate::{reader::AseReader, AsepriteParseError, ColorPalette, PixelFormat, Result}; use std::{borrow::Cow, io::Read}; fn read_rgba(chunk: &[u8]) -> Result<Rgba<u8>> { let mut reader = AseReader::new(chunk); let red = reader.byte()?; let green = reader.byte()?; let blue = reader.byte()?; let alpha = reader.byte()?; Ok(Rgba::from_channels(red, green, blue, alpha)) } #[derive(Debug, Clone, Copy)] pub(crate) struct Grayscale { value: u8, alpha: u8, } impl Grayscale { fn new(chunk: &[u8]) -> Result<Self> { let mut reader = AseReader::new(chunk); let value = reader.byte()?; let alpha = reader.byte()?; Ok(Self { value, alpha }) } pub(crate) fn into_rgba(self) -> Rgba<u8> { let Self { value, alpha } = self; Rgba::from_channels(value, value, value, alpha) } } #[derive(Debug, Clone, Copy)] pub(crate) struct Indexed(u8); impl Indexed { pub(crate) fn value(&self) -> u8 { self.0 } pub(crate) fn as_rgba( &self, palette: &ColorPalette, transparent_color_index: u8, layer_is_background: bool, ) -> Option<Rgba<u8>> { let index = self.0; palette.color(index as u32).map(|c| { let alpha = if transparent_color_index == index && !layer_is_background { 0 } else { c.alpha() }; Rgba::from_channels(c.red(), c.green(), c.blue(), alpha) }) } } fn output_size(pixel_format: PixelFormat, expected_pixel_count: usize) -> usize { pixel_format.bytes_per_pixel() * expected_pixel_count } #[derive(Debug)] pub(crate) enum Pixels { Rgba(Vec<Rgba<u8>>), Grayscale(Vec<Grayscale>), Indexed(Vec<Indexed>), }
let pixels: Result<Vec<_>> = bytes.chunks_exact(2).map(Grayscale::new).collect(); pixels.map(Self::Grayscale) } PixelFormat::Rgba => { if bytes.len() % 4 != 0 { return Err(AsepriteParseError::InvalidInput( "Incorrect length of bytes for RGBA image data".to_string(), )); } let pixels: Result<Vec<_>> = bytes.chunks_exact(4).map(read_rgba).collect(); pixels.map(Self::Rgba) } } } pub(crate) fn from_raw<T: Read>( reader: AseReader<T>, pixel_format: PixelFormat, expected_pixel_count: usize, ) -> Result<Self> { let expected_output_size = output_size(pixel_format, expected_pixel_count); reader .take_bytes(expected_output_size) .and_then(|bytes| Self::from_bytes(bytes, pixel_format)) } pub(crate) fn from_compressed<T: Read>( reader: AseReader<T>, pixel_format: PixelFormat, expected_pixel_count: usize, ) -> Result<Self> { let expected_output_size = output_size(pixel_format, expected_pixel_count); reader .unzip(expected_output_size) .and_then(|bytes| Self::from_bytes(bytes, pixel_format)) } pub(crate) fn byte_count(&self) -> usize { match self { Pixels::Rgba(v) => v.len() * 4, Pixels::Grayscale(v) => v.len() * 2, Pixels::Indexed(v) => v.len(), } } pub(crate) fn clone_as_image_rgba( &self, index_resolver_data: IndexResolverData<'_>, ) -> Cow<Vec<image::Rgba<u8>>> { match self { Pixels::Rgba(rgba) => Cow::Borrowed(rgba), Pixels::Grayscale(grayscale) => { Cow::Owned(grayscale.iter().map(|gs| gs.into_rgba()).collect()) } Pixels::Indexed(indexed) => { let IndexResolverData { palette, transparent_color_index, layer_is_background, } = index_resolver_data; let palette = palette.expect("Expected a palette when resolving indexed pixels. Should have been caught in validation"); let transparent_color_index = transparent_color_index.expect( "Indexed tilemap pixels in non-indexed pixel format. Should have been caught in validation", ); let resolver = |px: &Indexed| { px.as_rgba(palette, transparent_color_index, layer_is_background) .expect("Indexed pixel out of range. Should have been caught in validation") }; Cow::Owned(indexed.iter().map(resolver).collect()) } } } } pub(crate) struct IndexResolverData<'a> { pub(crate) palette: Option<&'a ColorPalette>, pub(crate) transparent_color_index: Option<u8>, pub(crate) layer_is_background: bool, }
impl Pixels { fn from_bytes(bytes: Vec<u8>, pixel_format: PixelFormat) -> Result<Self> { match pixel_format { PixelFormat::Indexed { .. } => { let pixels = bytes.iter().map(|byte| Indexed(*byte)).collect(); Ok(Self::Indexed(pixels)) } PixelFormat::Grayscale => { if bytes.len() % 2 != 0 { return Err(AsepriteParseError::InvalidInput( "Incorrect length of bytes for Grayscale image data".to_string(), )); }
random
[ { "content": "fn parse_pixel_format(color_depth: u16, transparent_color_index: u8) -> Result<PixelFormat> {\n\n match color_depth {\n\n 8 => Ok(PixelFormat::Indexed {\n\n transparent_color_index,\n\n }),\n\n 16 => Ok(PixelFormat::Grayscale),\n\n 32 => Ok(PixelFormat::Rg...
Rust
modbus_server/src/server_status.rs
guozhaohui/modbus_simulator
3707d068a4ea10925a25f489516d9721b67f5ba0
use rand::Rng; use modbus_protocol::exception_code::{Result, Error, ExceptionCode}; use modbus_protocol::coils::Coil; use modbus_protocol::requests::Requests; enum ModbusRegisterType{ Coil = 0x01, DiscreteInput = 0x02, InputRegister = 0x04, HoldingRegister = 0x03, } pub struct StatusInfo { capacity: u16, coils : Vec<Coil>, discrete_inputs: Vec<Coil>, input_registers: Vec<u16>, holding_registers: Vec<u16>, } impl StatusInfo { pub fn create(size: usize) -> StatusInfo { let mut coils = vec![Coil::Off; size]; let discrete_inputs : Vec<Coil> = (0..size).map(|_| Coil::from(rand::thread_rng().gen_bool(0.5))).collect(); let input_registers: Vec<u16> = (0..size).map(|_| rand::thread_rng().gen_range(0..100)).collect(); let holding_registers = vec![0u16; size]; for i in 0..size { coils[i] = Coil::from(rand::thread_rng().gen_bool(0.5)); } StatusInfo{ capacity: size as u16, coils: coils, discrete_inputs: discrete_inputs, input_registers: input_registers, holding_registers: holding_registers} } fn convert_addr_to_index(self: &Self, register_type: ModbusRegisterType, addr: u16) -> Result<u16> { match register_type { ModbusRegisterType::Coil => { if addr > self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(addr - (0 * self.capacity)); } ModbusRegisterType::DiscreteInput => { if addr < self.capacity || addr > 2 * self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(addr - (1 * self.capacity)); } ModbusRegisterType::InputRegister => { if addr < 2 * self.capacity || addr > 3 * self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(addr - (2 * self.capacity)); } ModbusRegisterType::HoldingRegister => { if addr < 3 * self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(addr - (3 * self.capacity)); } } } fn check_range(self: &Self, register_type: ModbusRegisterType, addr: u16, count: u16) -> Result<()> { match register_type { ModbusRegisterType::Coil => { if (addr + count + 1) as usize > self.coils.len() { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(()); } ModbusRegisterType::DiscreteInput => { if (addr + count + 1) as usize > self.discrete_inputs.len() { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(()); } ModbusRegisterType::InputRegister => { if (addr + count + 1) as usize > self.input_registers.len() { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(()); } ModbusRegisterType::HoldingRegister => { if (addr + count + 1) as usize > self.holding_registers.len() { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(()); } } } } impl Requests for StatusInfo { fn read_coils(self: &mut Self, addr: u16, count: u16) -> Result<Vec<Coil>> { let address = self.convert_addr_to_index(ModbusRegisterType::Coil, addr)?; self.check_range(ModbusRegisterType::Coil, address, count)?; let mut coils: Vec<Coil> = vec![Coil::Off; count as usize]; coils.clone_from_slice(&self.coils[(address) as usize..(address+count) as usize]); Ok(coils) } fn read_discrete_inputs(self: &mut Self, addr: u16, count: u16) -> Result<Vec<Coil>> { let address = self.convert_addr_to_index(ModbusRegisterType::DiscreteInput, addr)?; self.check_range(ModbusRegisterType::DiscreteInput, address, count)?; let mut coils: Vec<Coil> = vec![Coil::Off; count as usize]; coils.clone_from_slice(&self.discrete_inputs[address as usize..(address+count) as usize]); Ok(coils) } fn read_holding_registers(self: &mut Self, addr: u16, count: u16) -> Result<Vec<u16>> { let address = self.convert_addr_to_index(ModbusRegisterType::HoldingRegister, addr)?; self.check_range(ModbusRegisterType::HoldingRegister, address, count)?; let mut registers: Vec<u16> = vec![0u16; count as usize]; registers.clone_from_slice(&self.holding_registers[address as usize..(address+count) as usize]); Ok(registers) } fn read_input_registers(self: &mut Self, addr: u16, count: u16) -> Result<Vec<u16>> { let address = self.convert_addr_to_index(ModbusRegisterType::InputRegister, addr)?; self.check_range(ModbusRegisterType::InputRegister, address, count)?; let mut registers: Vec<u16> = vec![0u16; count as usize]; registers.clone_from_slice(&self.input_registers[address as usize..(address+count) as usize]); Ok(registers) } fn write_single_coil(self: &mut Self, addr: u16, value: Coil) -> Result<()> { let address = self.convert_addr_to_index(ModbusRegisterType::Coil, addr)?; self.check_range(ModbusRegisterType::Coil, address, 1)?; self.coils[address as usize] = value; return Ok(()) } fn write_single_register(self: &mut Self, addr: u16, value: u16) -> Result<()> { let address = self.convert_addr_to_index(ModbusRegisterType::HoldingRegister, addr)?; self.check_range(ModbusRegisterType::HoldingRegister, address, 1)?; self.holding_registers[address as usize] = value; return Ok(()) } fn write_multiple_coils(self: &mut Self, addr: u16, values: &[Coil]) -> Result<()> { let address = self.convert_addr_to_index(ModbusRegisterType::Coil, addr)?; let n = values.len(); self.check_range(ModbusRegisterType::Coil, address, n as u16)?; for i in 0..n { self.coils[i + address as usize] = values[i]; } return Ok(()) } fn write_multiple_registers(self: &mut Self, addr: u16, values: &[u16]) -> Result<()> { let address = self.convert_addr_to_index(ModbusRegisterType::HoldingRegister, addr)?; let n = values.len(); self.check_range(ModbusRegisterType::HoldingRegister, address, n as u16)?; for i in 0..n { self.holding_registers[i + address as usize] = values[i]; } return Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_server_initializaion(){ let mut status_info = StatusInfo::create(10usize); match status_info.read_coils(7u16, 2u16) { Ok(_coils) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_discrete_inputs(17u16, 2u16) { Ok(_coils) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_input_registers(26u16, 3u16) { Ok(_registers) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_holding_registers(36u16, 3u16) { Ok(registers) => { assert_eq!(registers, [0u16, 0u16, 0u16]); }, Err(_e) => { assert!(false); }, } } #[test] fn test_server_invalid_param1(){ let mut status_info = StatusInfo::create(10usize); match status_info.read_coils(7u16, 3u16) { Ok(_coils) => { assert!(false); }, Err(_e) => { assert!(true); }, } match status_info.read_holding_registers(37u16, 3u16) { Ok(_registers) => { assert!(false); }, Err(_e) => { assert!(true); }, } } #[test] fn test_server_writeread(){ let mut status_info = StatusInfo::create(10usize); let coils = vec![Coil::On, Coil::Off, Coil::On]; match status_info.write_multiple_coils(6u16, &coils) { Ok(()) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_coils(6u16, 3u16) { Ok(_coils) => { assert_eq!(_coils, coils); }, Err(_e) => { assert!(false); }, } let regs = vec![1u16, 2u16, 3u16]; match status_info.write_multiple_registers(36u16, &regs) { Ok(()) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_holding_registers(36u16, 3u16) { Ok(registers) => { assert_eq!(registers, regs); }, Err(_e) => { assert!(true); }, } } }
use rand::Rng; use modbus_protocol::exception_code::{Result, Error, ExceptionCode}; use modbus_protocol::coils::Coil; use modbus_protocol::requests::Requests; enum ModbusRegisterType{ Coil = 0x01, DiscreteInput = 0x02, InputRegister = 0x04, HoldingRegister = 0x03, } pub struct StatusInfo { capacity: u16, coils : Vec<Coil>, discrete_inputs: Vec<Coil>, input_registers: Vec<u16>, holding_registers: Vec<u16>, } impl StatusInfo { pub fn create(size: usize) -> StatusInfo { let mut coils = vec![Coil::Off; size]; let discrete_inputs : Vec<Coil> = (0..size).map(|_| Coil::from(ran
fn convert_addr_to_index(self: &Self, register_type: ModbusRegisterType, addr: u16) -> Result<u16> { match register_type { ModbusRegisterType::Coil => { if addr > self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(addr - (0 * self.capacity)); } ModbusRegisterType::DiscreteInput => { if addr < self.capacity || addr > 2 * self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(addr - (1 * self.capacity)); } ModbusRegisterType::InputRegister => { if addr < 2 * self.capacity || addr > 3 * self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(addr - (2 * self.capacity)); } ModbusRegisterType::HoldingRegister => { if addr < 3 * self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(addr - (3 * self.capacity)); } } } fn check_range(self: &Self, register_type: ModbusRegisterType, addr: u16, count: u16) -> Result<()> { match register_type { ModbusRegisterType::Coil => { if (addr + count + 1) as usize > self.coils.len() { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(()); } ModbusRegisterType::DiscreteInput => { if (addr + count + 1) as usize > self.discrete_inputs.len() { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(()); } ModbusRegisterType::InputRegister => { if (addr + count + 1) as usize > self.input_registers.len() { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(()); } ModbusRegisterType::HoldingRegister => { if (addr + count + 1) as usize > self.holding_registers.len() { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); } return Ok(()); } } } } impl Requests for StatusInfo { fn read_coils(self: &mut Self, addr: u16, count: u16) -> Result<Vec<Coil>> { let address = self.convert_addr_to_index(ModbusRegisterType::Coil, addr)?; self.check_range(ModbusRegisterType::Coil, address, count)?; let mut coils: Vec<Coil> = vec![Coil::Off; count as usize]; coils.clone_from_slice(&self.coils[(address) as usize..(address+count) as usize]); Ok(coils) } fn read_discrete_inputs(self: &mut Self, addr: u16, count: u16) -> Result<Vec<Coil>> { let address = self.convert_addr_to_index(ModbusRegisterType::DiscreteInput, addr)?; self.check_range(ModbusRegisterType::DiscreteInput, address, count)?; let mut coils: Vec<Coil> = vec![Coil::Off; count as usize]; coils.clone_from_slice(&self.discrete_inputs[address as usize..(address+count) as usize]); Ok(coils) } fn read_holding_registers(self: &mut Self, addr: u16, count: u16) -> Result<Vec<u16>> { let address = self.convert_addr_to_index(ModbusRegisterType::HoldingRegister, addr)?; self.check_range(ModbusRegisterType::HoldingRegister, address, count)?; let mut registers: Vec<u16> = vec![0u16; count as usize]; registers.clone_from_slice(&self.holding_registers[address as usize..(address+count) as usize]); Ok(registers) } fn read_input_registers(self: &mut Self, addr: u16, count: u16) -> Result<Vec<u16>> { let address = self.convert_addr_to_index(ModbusRegisterType::InputRegister, addr)?; self.check_range(ModbusRegisterType::InputRegister, address, count)?; let mut registers: Vec<u16> = vec![0u16; count as usize]; registers.clone_from_slice(&self.input_registers[address as usize..(address+count) as usize]); Ok(registers) } fn write_single_coil(self: &mut Self, addr: u16, value: Coil) -> Result<()> { let address = self.convert_addr_to_index(ModbusRegisterType::Coil, addr)?; self.check_range(ModbusRegisterType::Coil, address, 1)?; self.coils[address as usize] = value; return Ok(()) } fn write_single_register(self: &mut Self, addr: u16, value: u16) -> Result<()> { let address = self.convert_addr_to_index(ModbusRegisterType::HoldingRegister, addr)?; self.check_range(ModbusRegisterType::HoldingRegister, address, 1)?; self.holding_registers[address as usize] = value; return Ok(()) } fn write_multiple_coils(self: &mut Self, addr: u16, values: &[Coil]) -> Result<()> { let address = self.convert_addr_to_index(ModbusRegisterType::Coil, addr)?; let n = values.len(); self.check_range(ModbusRegisterType::Coil, address, n as u16)?; for i in 0..n { self.coils[i + address as usize] = values[i]; } return Ok(()) } fn write_multiple_registers(self: &mut Self, addr: u16, values: &[u16]) -> Result<()> { let address = self.convert_addr_to_index(ModbusRegisterType::HoldingRegister, addr)?; let n = values.len(); self.check_range(ModbusRegisterType::HoldingRegister, address, n as u16)?; for i in 0..n { self.holding_registers[i + address as usize] = values[i]; } return Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_server_initializaion(){ let mut status_info = StatusInfo::create(10usize); match status_info.read_coils(7u16, 2u16) { Ok(_coils) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_discrete_inputs(17u16, 2u16) { Ok(_coils) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_input_registers(26u16, 3u16) { Ok(_registers) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_holding_registers(36u16, 3u16) { Ok(registers) => { assert_eq!(registers, [0u16, 0u16, 0u16]); }, Err(_e) => { assert!(false); }, } } #[test] fn test_server_invalid_param1(){ let mut status_info = StatusInfo::create(10usize); match status_info.read_coils(7u16, 3u16) { Ok(_coils) => { assert!(false); }, Err(_e) => { assert!(true); }, } match status_info.read_holding_registers(37u16, 3u16) { Ok(_registers) => { assert!(false); }, Err(_e) => { assert!(true); }, } } #[test] fn test_server_writeread(){ let mut status_info = StatusInfo::create(10usize); let coils = vec![Coil::On, Coil::Off, Coil::On]; match status_info.write_multiple_coils(6u16, &coils) { Ok(()) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_coils(6u16, 3u16) { Ok(_coils) => { assert_eq!(_coils, coils); }, Err(_e) => { assert!(false); }, } let regs = vec![1u16, 2u16, 3u16]; match status_info.write_multiple_registers(36u16, &regs) { Ok(()) => { assert!(true); }, Err(_e) => { assert!(false); }, } match status_info.read_holding_registers(36u16, 3u16) { Ok(registers) => { assert_eq!(registers, regs); }, Err(_e) => { assert!(true); }, } } }
d::thread_rng().gen_bool(0.5))).collect(); let input_registers: Vec<u16> = (0..size).map(|_| rand::thread_rng().gen_range(0..100)).collect(); let holding_registers = vec![0u16; size]; for i in 0..size { coils[i] = Coil::from(rand::thread_rng().gen_bool(0.5)); } StatusInfo{ capacity: size as u16, coils: coils, discrete_inputs: discrete_inputs, input_registers: input_registers, holding_registers: holding_registers} }
function_block-function_prefixed
[ { "content": "pub fn unpack_bits(bytes: &[u8], count: u16) -> Vec<Coil> {\n\n let mut res = Vec::with_capacity(count as usize);\n\n for i in 0..count {\n\n if (bytes[(i / 8u16) as usize] >> (i % 8)) & 0b1 > 0 {\n\n res.push(Coil::On);\n\n } else {\n\n res.push(Coil::Off...
Rust
src/n64/cpu/cpu.rs
Protowalker/rustendo64
2e6405bfadd923a3ab6c5ace29d2bdf85b0ae3c4
use super::super::Interconnect; use super::opcode::Opcode::*; use super::opcode::RegImmOpcode::*; use super::opcode::SpecialOpcode::*; use super::{cp0, Instruction}; use std::fmt; const NUM_GPR: usize = 32; enum SignExtendResult { Yes, No, } enum WriteLink { Yes, No, } pub struct Cpu { reg_gpr: [u64; NUM_GPR], reg_fpr: [f64; NUM_GPR], reg_pc: u64, reg_hi: u64, reg_lo: u64, reg_llbit: bool, reg_fcr0: u32, reg_fcr31: u32, cp0: cp0::Cp0, delay_slot_pc: Option<u64>, } impl Cpu { pub fn new() -> Cpu { Cpu { reg_gpr: [0; NUM_GPR], reg_fpr: [0.0; NUM_GPR], reg_pc: 0xffff_ffff_bfc0_0000, reg_hi: 0, reg_lo: 0, reg_llbit: false, reg_fcr0: 0, reg_fcr31: 0, cp0: cp0::Cp0::default(), delay_slot_pc: None, } } pub fn current_pc_virt(&self) -> u64 { self.delay_slot_pc.unwrap_or(self.reg_pc) } pub fn current_pc_phys(&self) -> u64 { self.virt_addr_to_phys_addr(self.current_pc_virt()) } pub fn will_execute_from_delay_slot(&self) -> bool { self.delay_slot_pc.is_some() } pub fn step(&mut self, interconnect: &mut Interconnect) { if let Some(pc) = self.delay_slot_pc { let instr = self.read_instruction(interconnect, pc); self.delay_slot_pc = None; self.execute_instruction(interconnect, instr); } else { let instr = self.read_instruction(interconnect, self.reg_pc); self.reg_pc += 4; self.execute_instruction(interconnect, instr); } } fn read_instruction(&self, interconnect: &mut Interconnect, addr: u64) -> Instruction { Instruction(self.read_word(interconnect, addr)) } fn execute_instruction(&mut self, interconnect: &mut Interconnect, instr: Instruction) { match instr.opcode() { Special => { match instr.special_op() { Sll => self.reg_instr(instr, |_, rt, sa| rt << sa), Srl => self.reg_instr(instr, |_, rt, sa| { let rt = rt as u32; (rt >> sa) as u64 }), Sllv => self.reg_instr(instr, |rs, rt, _| { let shift = rs & 0b11111; rt << shift }), Srlv => self.reg_instr(instr, |rs, rt, _| { let rs = rs as u32; let rt = rt as u32; let shift = rs & 0b11111; (rt >> shift) as u64 }), Jr => { let delay_slot_pc = self.reg_pc; self.reg_pc = self.read_reg_gpr(instr.rs()); self.delay_slot_pc = Some(delay_slot_pc); } Multu => { let rs = self.read_reg_gpr(instr.rs()) as u32; let rt = self.read_reg_gpr(instr.rt()) as u32; let res = (rs as u64) * (rt as u64); self.reg_lo = (res as i32) as u64; self.reg_hi = ((res >> 32) as i32) as u64; } Mfhi => { let value = self.reg_hi; self.write_reg_gpr(instr.rd() as usize, value); } Mflo => { let value = self.reg_lo; self.write_reg_gpr(instr.rd() as usize, value); } Addu => self.reg_instr(instr, |rs, rt, _| rs.wrapping_add(rt)), Subu => self.reg_instr(instr, |rs, rt, _| rs.wrapping_sub(rt)), And => self.reg_instr(instr, |rs, rt, _| rs & rt), Or => self.reg_instr(instr, |rs, rt, _| rs | rt), Xor => self.reg_instr(instr, |rs, rt, _| rs ^ rt), Sltu => self.reg_instr(instr, |rs, rt, _| if rs < rt { 1 } else { 0 }), } } RegImm => match instr.reg_imm_op() { Bgezal => { self.branch(instr, WriteLink::Yes, |rs, _| (rs as i64) >= 0); } }, Addi => self.imm_instr(instr, SignExtendResult::Yes, |rs, _, imm_sign_extended| { rs + imm_sign_extended }), Addiu => self.imm_instr(instr, SignExtendResult::Yes, |rs, _, imm_sign_extended| { rs.wrapping_add(imm_sign_extended) }), Andi => self.imm_instr(instr, SignExtendResult::No, |rs, imm, _| rs & imm), Ori => self.imm_instr(instr, SignExtendResult::No, |rs, imm, _| rs | imm), Lui => self.imm_instr(instr, SignExtendResult::Yes, |_, imm, _| imm << 16), Mtc0 => { let data = self.read_reg_gpr(instr.rt()); self.cp0.write_reg(instr.rd(), data); } Beq => { self.branch(instr, WriteLink::No, |rs, rt| rs == rt); } Bne => { self.branch(instr, WriteLink::No, |rs, rt| rs != rt); } Beql => self.branch_likely(instr, |rs, rt| rs == rt), Bnel => self.branch_likely(instr, |rs, rt| rs != rt), Lw => { let base = instr.rs(); let sign_extended_offset = instr.offset_sign_extended(); let virt_addr = self.read_reg_gpr(base).wrapping_add(sign_extended_offset); let mem = (self.read_word(interconnect, virt_addr) as i32) as u64; self.write_reg_gpr(instr.rt(), mem); } Sw => { let base = instr.rs(); let sign_extended_offset = instr.offset_sign_extended(); let virt_addr = self.read_reg_gpr(base).wrapping_add(sign_extended_offset); let mem = self.read_reg_gpr(instr.rt()) as u32; self.write_word(interconnect, virt_addr, mem); } } } fn imm_instr<F>(&mut self, instr: Instruction, sign_extend_result: SignExtendResult, f: F) where F: FnOnce(u64, u64, u64) -> u64, { let rs = self.read_reg_gpr(instr.rs()); let imm = instr.imm() as u64; let imm_sign_extended = instr.imm_sign_extended(); let value = f(rs, imm, imm_sign_extended); let sign_extended_value = (value as i32) as u64; let value = match sign_extend_result { SignExtendResult::Yes => sign_extended_value, _ => value, }; self.write_reg_gpr(instr.rt(), value); } fn reg_instr<F>(&mut self, instr: Instruction, f: F) where F: FnOnce(u64, u64, u32) -> u64, { let rs = self.read_reg_gpr(instr.rs()); let rt = self.read_reg_gpr(instr.rt()); let sa = instr.sa(); let value = f(rs, rt, sa); let sign_extended_value = (value as i32) as u64; self.write_reg_gpr(instr.rd() as usize, sign_extended_value); } fn branch<F>(&mut self, instr: Instruction, write_link: WriteLink, f: F) -> bool where F: FnOnce(u64, u64) -> bool, { let rs = self.read_reg_gpr(instr.rs()); let rt = self.read_reg_gpr(instr.rt()); let is_taken = f(rs, rt); let delay_slot_pc = self.reg_pc; if let WriteLink::Yes = write_link { let link_address = delay_slot_pc + 4; self.write_reg_gpr(31, link_address); } if is_taken { let sign_extended_offset = instr.offset_sign_extended() << 2; self.reg_pc = self.reg_pc.wrapping_add(sign_extended_offset); self.delay_slot_pc = Some(delay_slot_pc); } is_taken } fn branch_likely<F>(&mut self, instr: Instruction, f: F) where F: FnOnce(u64, u64) -> bool, { if !self.branch(instr, WriteLink::No, f) { self.reg_pc = self.reg_pc.wrapping_add(4); } } fn read_word(&self, interconnect: &mut Interconnect, virt_addr: u64) -> u32 { let phys_addr = self.virt_addr_to_phys_addr(virt_addr); interconnect.read_word(phys_addr as u32) } fn write_word(&mut self, interconnect: &mut Interconnect, virt_addr: u64, value: u32) { let phys_addr = self.virt_addr_to_phys_addr(virt_addr); interconnect.write_word(phys_addr as u32, value); } fn virt_addr_to_phys_addr(&self, virt_addr: u64) -> u64 { let addr_bit_values = (virt_addr >> 29) & 0b111; if addr_bit_values == 0b101 { virt_addr - 0xffff_ffff_a000_0000 } else { panic!("Unrecognized virtual address: {:#x}", virt_addr); } } fn write_reg_gpr(&mut self, index: usize, value: u64) { if index != 0 { self.reg_gpr[index] = value; } } fn read_reg_gpr(&self, index: usize) -> u64 { match index { 0 => 0, _ => self.reg_gpr[index], } } } impl fmt::Debug for Cpu { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { const REGS_PER_LINE: usize = 2; const REG_NAMES: [&'static str; NUM_GPR] = [ "r0", "at", "v0", "v1", "a0", "a1", "a2", "a3", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8", "t9", "k0", "k1", "gp", "sp", "s8", "ra", ]; write!(f, "\nCPU General Purpose Registers:")?; for reg_num in 0..NUM_GPR { if (reg_num % REGS_PER_LINE) == 0 { writeln!(f, "")?; } write!( f, "{reg_name}/gpr{num:02}: {value:#018X} ", num = reg_num, reg_name = REG_NAMES[reg_num], value = self.reg_gpr[reg_num], )?; } write!(f, "\n\nCPU Floating Point Registers:")?; for reg_num in 0..NUM_GPR { if (reg_num % REGS_PER_LINE) == 0 { writeln!(f, "")?; } write!( f, "fpr{num:02}: {value:21} ", num = reg_num, value = self.reg_fpr[reg_num] )?; } writeln!(f, "\n\nCPU Special Registers:")?; writeln!( f, "\ reg_pc: {:#018X}\n\ reg_hi: {:#018X}\n\ reg_lo: {:#018X}\n\ reg_llbit: {}\n\ reg_fcr0: {:#010X}\n\ reg_fcr31: {:#010X}\n\ ", self.reg_pc, self.reg_hi, self.reg_lo, self.reg_llbit, self.reg_fcr0, self.reg_fcr31 )?; writeln!(f, "{:#?}", self.cp0) } }
use super::super::Interconnect; use super::opcode::Opcode::*; use super::opcode::RegImmOpcode::*; use super::opcode::SpecialOpcode::*; use super::{cp0, Instruction}; use std::fmt; const NUM_GPR: usize = 32; enum SignExtendResult { Yes, No, } enum WriteLink { Yes, No, } pub struct Cpu { reg_gpr: [u64; NUM_GPR], reg_fpr: [f64; NUM_GPR], reg_pc: u64, reg_hi: u64, reg_lo: u64, reg_llbit: bool, reg_fcr0: u32, reg_fcr31: u32, cp0: cp0::Cp0, delay_slot_pc: Option<u64>, } impl Cpu { pub fn new() -> Cpu { Cpu { reg_gpr: [0; NUM_GPR], reg_fpr: [0.0; NUM_GPR], reg_pc: 0xffff_ffff_bfc0_0000, reg_hi: 0, reg_lo: 0, reg_llbit: false, reg_fcr0: 0, reg_fcr31: 0, cp0: cp0::Cp0::default(), delay_slot_pc: None, } } pub fn current_pc_virt(&self) -> u64 { self.delay_slot_pc.unwrap_or(self.reg_pc) } pub fn current_pc_phys(&self) -> u64 { self.virt_addr_to_phys_addr(self.current_pc_virt()) } pub fn will_execute_from_delay_slot(&self) -> bool { self.delay_slot_pc.is_some() } pub fn step(&mut self, interconnect: &mut Interconnect) {
} fn read_instruction(&self, interconnect: &mut Interconnect, addr: u64) -> Instruction { Instruction(self.read_word(interconnect, addr)) } fn execute_instruction(&mut self, interconnect: &mut Interconnect, instr: Instruction) { match instr.opcode() { Special => { match instr.special_op() { Sll => self.reg_instr(instr, |_, rt, sa| rt << sa), Srl => self.reg_instr(instr, |_, rt, sa| { let rt = rt as u32; (rt >> sa) as u64 }), Sllv => self.reg_instr(instr, |rs, rt, _| { let shift = rs & 0b11111; rt << shift }), Srlv => self.reg_instr(instr, |rs, rt, _| { let rs = rs as u32; let rt = rt as u32; let shift = rs & 0b11111; (rt >> shift) as u64 }), Jr => { let delay_slot_pc = self.reg_pc; self.reg_pc = self.read_reg_gpr(instr.rs()); self.delay_slot_pc = Some(delay_slot_pc); } Multu => { let rs = self.read_reg_gpr(instr.rs()) as u32; let rt = self.read_reg_gpr(instr.rt()) as u32; let res = (rs as u64) * (rt as u64); self.reg_lo = (res as i32) as u64; self.reg_hi = ((res >> 32) as i32) as u64; } Mfhi => { let value = self.reg_hi; self.write_reg_gpr(instr.rd() as usize, value); } Mflo => { let value = self.reg_lo; self.write_reg_gpr(instr.rd() as usize, value); } Addu => self.reg_instr(instr, |rs, rt, _| rs.wrapping_add(rt)), Subu => self.reg_instr(instr, |rs, rt, _| rs.wrapping_sub(rt)), And => self.reg_instr(instr, |rs, rt, _| rs & rt), Or => self.reg_instr(instr, |rs, rt, _| rs | rt), Xor => self.reg_instr(instr, |rs, rt, _| rs ^ rt), Sltu => self.reg_instr(instr, |rs, rt, _| if rs < rt { 1 } else { 0 }), } } RegImm => match instr.reg_imm_op() { Bgezal => { self.branch(instr, WriteLink::Yes, |rs, _| (rs as i64) >= 0); } }, Addi => self.imm_instr(instr, SignExtendResult::Yes, |rs, _, imm_sign_extended| { rs + imm_sign_extended }), Addiu => self.imm_instr(instr, SignExtendResult::Yes, |rs, _, imm_sign_extended| { rs.wrapping_add(imm_sign_extended) }), Andi => self.imm_instr(instr, SignExtendResult::No, |rs, imm, _| rs & imm), Ori => self.imm_instr(instr, SignExtendResult::No, |rs, imm, _| rs | imm), Lui => self.imm_instr(instr, SignExtendResult::Yes, |_, imm, _| imm << 16), Mtc0 => { let data = self.read_reg_gpr(instr.rt()); self.cp0.write_reg(instr.rd(), data); } Beq => { self.branch(instr, WriteLink::No, |rs, rt| rs == rt); } Bne => { self.branch(instr, WriteLink::No, |rs, rt| rs != rt); } Beql => self.branch_likely(instr, |rs, rt| rs == rt), Bnel => self.branch_likely(instr, |rs, rt| rs != rt), Lw => { let base = instr.rs(); let sign_extended_offset = instr.offset_sign_extended(); let virt_addr = self.read_reg_gpr(base).wrapping_add(sign_extended_offset); let mem = (self.read_word(interconnect, virt_addr) as i32) as u64; self.write_reg_gpr(instr.rt(), mem); } Sw => { let base = instr.rs(); let sign_extended_offset = instr.offset_sign_extended(); let virt_addr = self.read_reg_gpr(base).wrapping_add(sign_extended_offset); let mem = self.read_reg_gpr(instr.rt()) as u32; self.write_word(interconnect, virt_addr, mem); } } } fn imm_instr<F>(&mut self, instr: Instruction, sign_extend_result: SignExtendResult, f: F) where F: FnOnce(u64, u64, u64) -> u64, { let rs = self.read_reg_gpr(instr.rs()); let imm = instr.imm() as u64; let imm_sign_extended = instr.imm_sign_extended(); let value = f(rs, imm, imm_sign_extended); let sign_extended_value = (value as i32) as u64; let value = match sign_extend_result { SignExtendResult::Yes => sign_extended_value, _ => value, }; self.write_reg_gpr(instr.rt(), value); } fn reg_instr<F>(&mut self, instr: Instruction, f: F) where F: FnOnce(u64, u64, u32) -> u64, { let rs = self.read_reg_gpr(instr.rs()); let rt = self.read_reg_gpr(instr.rt()); let sa = instr.sa(); let value = f(rs, rt, sa); let sign_extended_value = (value as i32) as u64; self.write_reg_gpr(instr.rd() as usize, sign_extended_value); } fn branch<F>(&mut self, instr: Instruction, write_link: WriteLink, f: F) -> bool where F: FnOnce(u64, u64) -> bool, { let rs = self.read_reg_gpr(instr.rs()); let rt = self.read_reg_gpr(instr.rt()); let is_taken = f(rs, rt); let delay_slot_pc = self.reg_pc; if let WriteLink::Yes = write_link { let link_address = delay_slot_pc + 4; self.write_reg_gpr(31, link_address); } if is_taken { let sign_extended_offset = instr.offset_sign_extended() << 2; self.reg_pc = self.reg_pc.wrapping_add(sign_extended_offset); self.delay_slot_pc = Some(delay_slot_pc); } is_taken } fn branch_likely<F>(&mut self, instr: Instruction, f: F) where F: FnOnce(u64, u64) -> bool, { if !self.branch(instr, WriteLink::No, f) { self.reg_pc = self.reg_pc.wrapping_add(4); } } fn read_word(&self, interconnect: &mut Interconnect, virt_addr: u64) -> u32 { let phys_addr = self.virt_addr_to_phys_addr(virt_addr); interconnect.read_word(phys_addr as u32) } fn write_word(&mut self, interconnect: &mut Interconnect, virt_addr: u64, value: u32) { let phys_addr = self.virt_addr_to_phys_addr(virt_addr); interconnect.write_word(phys_addr as u32, value); } fn virt_addr_to_phys_addr(&self, virt_addr: u64) -> u64 { let addr_bit_values = (virt_addr >> 29) & 0b111; if addr_bit_values == 0b101 { virt_addr - 0xffff_ffff_a000_0000 } else { panic!("Unrecognized virtual address: {:#x}", virt_addr); } } fn write_reg_gpr(&mut self, index: usize, value: u64) { if index != 0 { self.reg_gpr[index] = value; } } fn read_reg_gpr(&self, index: usize) -> u64 { match index { 0 => 0, _ => self.reg_gpr[index], } } } impl fmt::Debug for Cpu { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { const REGS_PER_LINE: usize = 2; const REG_NAMES: [&'static str; NUM_GPR] = [ "r0", "at", "v0", "v1", "a0", "a1", "a2", "a3", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8", "t9", "k0", "k1", "gp", "sp", "s8", "ra", ]; write!(f, "\nCPU General Purpose Registers:")?; for reg_num in 0..NUM_GPR { if (reg_num % REGS_PER_LINE) == 0 { writeln!(f, "")?; } write!( f, "{reg_name}/gpr{num:02}: {value:#018X} ", num = reg_num, reg_name = REG_NAMES[reg_num], value = self.reg_gpr[reg_num], )?; } write!(f, "\n\nCPU Floating Point Registers:")?; for reg_num in 0..NUM_GPR { if (reg_num % REGS_PER_LINE) == 0 { writeln!(f, "")?; } write!( f, "fpr{num:02}: {value:21} ", num = reg_num, value = self.reg_fpr[reg_num] )?; } writeln!(f, "\n\nCPU Special Registers:")?; writeln!( f, "\ reg_pc: {:#018X}\n\ reg_hi: {:#018X}\n\ reg_lo: {:#018X}\n\ reg_llbit: {}\n\ reg_fcr0: {:#010X}\n\ reg_fcr31: {:#010X}\n\ ", self.reg_pc, self.reg_hi, self.reg_lo, self.reg_llbit, self.reg_fcr0, self.reg_fcr31 )?; writeln!(f, "{:#?}", self.cp0) } }
if let Some(pc) = self.delay_slot_pc { let instr = self.read_instruction(interconnect, pc); self.delay_slot_pc = None; self.execute_instruction(interconnect, instr); } else { let instr = self.read_instruction(interconnect, self.reg_pc); self.reg_pc += 4; self.execute_instruction(interconnect, instr); }
if_condition
[ { "content": "pub fn map_addr(addr: u32) -> Addr {\n\n match addr {\n\n PIF_ROM_START..=PIF_ROM_END => Addr::PifRom(addr - PIF_ROM_START),\n\n PIF_RAM_START..=PIF_RAM_END => Addr::PifRam(addr - PIF_RAM_START),\n\n\n\n CART_DOM1_ADDR2_START..=CART_DOM1_ADDR2_END => Addr::CartDom1(addr - C...
Rust
src/signed_url.rs
mysilkway/tame-gcs
e05ff7af85bd8592f98e4deb3a8900a20d0c0152
use crate::{error::Error, signing, types::ObjectIdentifier}; use percent_encoding as perc_enc; use std::borrow::Cow; use url::Url; pub struct UrlSigner<D, S> { digester: D, signer: S, } #[cfg(feature = "signing")] impl UrlSigner<signing::RingDigest, signing::RingSigner> { pub fn with_ring() -> UrlSigner<signing::RingDigest, signing::RingSigner> { UrlSigner::new(signing::RingDigest, signing::RingSigner) } } impl<D, S> UrlSigner<D, S> where D: signing::DigestCalulator, S: signing::Signer, { pub fn new(digester: D, signer: S) -> Self { Self { digester, signer } } pub fn generate<'a, K, OID>( &self, key_provider: &K, id: &OID, optional: SignedUrlOptional<'_>, ) -> Result<Url, Error> where K: signing::KeyProvider, OID: ObjectIdentifier<'a>, { const SEVEN_DAYS: u64 = 7 * 24 * 60 * 60; if optional.duration.as_secs() > SEVEN_DAYS { return Err(Error::TooLongExpiration { requested: optional.duration.as_secs(), max: SEVEN_DAYS, }); } let mut signed_url = Url::parse("https://storage.googleapis.com").map_err(Error::UrlParse)?; let resource_path = format!( "/{}/{}", perc_enc::percent_encode(id.bucket().as_ref(), crate::util::PATH_ENCODE_SET), perc_enc::percent_encode(id.object().as_ref(), crate::util::PATH_ENCODE_SET), ); signed_url.set_path(&resource_path); let mut headers = optional.headers; headers.insert( http::header::HOST, http::header::HeaderValue::from_static("storage.googleapis.com"), ); let headers = { let mut hdrs = Vec::with_capacity(headers.keys_len()); for key in headers.keys() { let vals_size = headers .get_all(key) .iter() .fold(0, |acc, v| acc + v.len() + 1) - 1; let mut key_vals = String::with_capacity(vals_size); for (i, val) in headers.get_all(key).iter().enumerate() { if i > 0 { key_vals.push(','); } key_vals.push_str( val.to_str() .map_err(|_err| Error::OpaqueHeaderValue(val.clone()))?, ); } hdrs.push((key.as_str().to_lowercase(), key_vals)); } hdrs.sort(); hdrs }; let signed_headers = { let signed_size = headers.iter().fold(0, |acc, (name, _)| acc + name.len()) + headers.len() - 1; let mut names = String::with_capacity(signed_size); for (i, name) in headers.iter().map(|(name, _)| name).enumerate() { if i > 0 { names.push(';'); } names.push_str(name); } assert_eq!(signed_size, names.capacity()); names }; let timestamp = time::OffsetDateTime::now_utc(); let request_timestamp = { let year = timestamp.year(); let month = timestamp.month() as u8; let day = timestamp.day(); let hour = timestamp.hour(); let minute = timestamp.minute(); let second = timestamp.second(); format!("{year:04}{month:02}{day:02}T{hour:02}{minute:02}{second:02}Z") }; let datestamp = &request_timestamp[..8]; let credential_scope = format!("{}/{}/storage/goog4_request", datestamp, optional.region); let credential_param = format!("{}/{}", key_provider.authorizer(), credential_scope); let expiration = optional.duration.as_secs().to_string(); let mut query_params = optional.query_params; query_params.extend( [ ("X-Goog-Algorithm", "GOOG4-RSA-SHA256"), ("X-Goog-Credential", &credential_param), ("X-Goog-Date", &request_timestamp), ("X-Goog-Expires", &expiration), ("X-Goog-SignedHeaders", &signed_headers), ] .iter() .map(|(k, v)| (Cow::Borrowed(*k), Cow::Borrowed(*v))), ); query_params.sort(); let canonical_query = { { let mut query_pairs = signed_url.query_pairs_mut(); query_pairs.clear(); for (key, value) in &query_params { query_pairs.append_pair(key, value); } } signed_url.query().unwrap().to_owned() }; let canonical_headers = { let canonical_size = headers .iter() .fold(0, |acc, kv| acc + kv.0.len() + kv.1.len()) + headers.len() * 2; let mut hdrs = String::with_capacity(canonical_size); for (k, v) in &headers { hdrs.push_str(k); hdrs.push(':'); hdrs.push_str(v); hdrs.push('\n'); } assert_eq!(canonical_size, hdrs.capacity()); hdrs }; let canonical_request = format!( "{verb}\n{resource}\n{query}\n{headers}\n{signed_headers}\nUNSIGNED-PAYLOAD", verb = optional.method, resource = resource_path, query = canonical_query, headers = canonical_headers, signed_headers = signed_headers, ); let mut digest = [0u8; 32]; self.digester.digest( signing::DigestAlgorithm::Sha256, canonical_request.as_bytes(), &mut digest, ); let digest_str = crate::util::to_hex(&digest); let string_to_sign = format!( "GOOG4-RSA-SHA256\n{timestamp}\n{scope}\n{hash}", timestamp = request_timestamp, scope = credential_scope, hash = digest_str, ); let signature = self.signer.sign( signing::SigningAlgorithm::RsaSha256, key_provider.key(), string_to_sign.as_bytes(), )?; let signature_str = crate::util::to_hex(&signature); signed_url .query_pairs_mut() .append_pair("X-Goog-Signature", signature_str.as_str()); Ok(signed_url) } } pub struct SignedUrlOptional<'a> { pub method: http::Method, pub duration: std::time::Duration, pub headers: http::HeaderMap, pub region: &'a str, pub query_params: Vec<(Cow<'a, str>, Cow<'a, str>)>, } impl<'a> Default for SignedUrlOptional<'a> { fn default() -> Self { Self { method: http::Method::GET, duration: std::time::Duration::from_secs(60 * 60), headers: http::HeaderMap::default(), region: "auto", query_params: Vec::new(), } } }
use crate::{error::Error, signing, types::ObjectIdentifier}; use percent_encoding as perc_enc; use std::borrow::Cow; use url::Url; pub struct UrlSigner<D, S> { digester: D, signer: S, } #[cfg(feature = "signing")] impl UrlSigner<signing::RingDigest, signing::RingSigner> { pub fn with_ring() -> UrlSigner<signing::RingDigest, signing::RingSigner> { UrlSigner::new(signing::RingDigest, signing::RingSigner) } } impl<D, S> UrlSigner<D, S> where D: signing::DigestCalulator, S: signing::Signer, { pub fn new(digester: D, signer: S) -> Self { Self { digester, signer } } pub fn generate<'a, K, OID>( &self, key_provider: &K, id: &OID, optional: SignedUrlOptional<'_>, ) -> Result<Url, Error> where K: signing::KeyProvider, OID: ObjectIdentifier<'a>, { const SEVEN_DAYS: u64 = 7 * 24 * 60 * 60; if optional.duration.as_secs() > SEVEN_DAYS { return
; } let mut signed_url = Url::parse("https://storage.googleapis.com").map_err(Error::UrlParse)?; let resource_path = format!( "/{}/{}", perc_enc::percent_encode(id.bucket().as_ref(), crate::util::PATH_ENCODE_SET), perc_enc::percent_encode(id.object().as_ref(), crate::util::PATH_ENCODE_SET), ); signed_url.set_path(&resource_path); let mut headers = optional.headers; headers.insert( http::header::HOST, http::header::HeaderValue::from_static("storage.googleapis.com"), ); let headers = { let mut hdrs = Vec::with_capacity(headers.keys_len()); for key in headers.keys() { let vals_size = headers .get_all(key) .iter() .fold(0, |acc, v| acc + v.len() + 1) - 1; let mut key_vals = String::with_capacity(vals_size); for (i, val) in headers.get_all(key).iter().enumerate() { if i > 0 { key_vals.push(','); } key_vals.push_str( val.to_str() .map_err(|_err| Error::OpaqueHeaderValue(val.clone()))?, ); } hdrs.push((key.as_str().to_lowercase(), key_vals)); } hdrs.sort(); hdrs }; let signed_headers = { let signed_size = headers.iter().fold(0, |acc, (name, _)| acc + name.len()) + headers.len() - 1; let mut names = String::with_capacity(signed_size); for (i, name) in headers.iter().map(|(name, _)| name).enumerate() { if i > 0 { names.push(';'); } names.push_str(name); } assert_eq!(signed_size, names.capacity()); names }; let timestamp = time::OffsetDateTime::now_utc(); let request_timestamp = { let year = timestamp.year(); let month = timestamp.month() as u8; let day = timestamp.day(); let hour = timestamp.hour(); let minute = timestamp.minute(); let second = timestamp.second(); format!("{year:04}{month:02}{day:02}T{hour:02}{minute:02}{second:02}Z") }; let datestamp = &request_timestamp[..8]; let credential_scope = format!("{}/{}/storage/goog4_request", datestamp, optional.region); let credential_param = format!("{}/{}", key_provider.authorizer(), credential_scope); let expiration = optional.duration.as_secs().to_string(); let mut query_params = optional.query_params; query_params.extend( [ ("X-Goog-Algorithm", "GOOG4-RSA-SHA256"), ("X-Goog-Credential", &credential_param), ("X-Goog-Date", &request_timestamp), ("X-Goog-Expires", &expiration), ("X-Goog-SignedHeaders", &signed_headers), ] .iter() .map(|(k, v)| (Cow::Borrowed(*k), Cow::Borrowed(*v))), ); query_params.sort(); let canonical_query = { { let mut query_pairs = signed_url.query_pairs_mut(); query_pairs.clear(); for (key, value) in &query_params { query_pairs.append_pair(key, value); } } signed_url.query().unwrap().to_owned() }; let canonical_headers = { let canonical_size = headers .iter() .fold(0, |acc, kv| acc + kv.0.len() + kv.1.len()) + headers.len() * 2; let mut hdrs = String::with_capacity(canonical_size); for (k, v) in &headers { hdrs.push_str(k); hdrs.push(':'); hdrs.push_str(v); hdrs.push('\n'); } assert_eq!(canonical_size, hdrs.capacity()); hdrs }; let canonical_request = format!( "{verb}\n{resource}\n{query}\n{headers}\n{signed_headers}\nUNSIGNED-PAYLOAD", verb = optional.method, resource = resource_path, query = canonical_query, headers = canonical_headers, signed_headers = signed_headers, ); let mut digest = [0u8; 32]; self.digester.digest( signing::DigestAlgorithm::Sha256, canonical_request.as_bytes(), &mut digest, ); let digest_str = crate::util::to_hex(&digest); let string_to_sign = format!( "GOOG4-RSA-SHA256\n{timestamp}\n{scope}\n{hash}", timestamp = request_timestamp, scope = credential_scope, hash = digest_str, ); let signature = self.signer.sign( signing::SigningAlgorithm::RsaSha256, key_provider.key(), string_to_sign.as_bytes(), )?; let signature_str = crate::util::to_hex(&signature); signed_url .query_pairs_mut() .append_pair("X-Goog-Signature", signature_str.as_str()); Ok(signed_url) } } pub struct SignedUrlOptional<'a> { pub method: http::Method, pub duration: std::time::Duration, pub headers: http::HeaderMap, pub region: &'a str, pub query_params: Vec<(Cow<'a, str>, Cow<'a, str>)>, } impl<'a> Default for SignedUrlOptional<'a> { fn default() -> Self { Self { method: http::Method::GET, duration: std::time::Duration::from_secs(60 * 60), headers: http::HeaderMap::default(), region: "auto", query_params: Vec::new(), } } }
Err(Error::TooLongExpiration { requested: optional.duration.as_secs(), max: SEVEN_DAYS, })
call_expression
[ { "content": "/// Used to sign a block of data\n\npub trait Signer {\n\n /// Sign a block of data with the specified algorith, and a private key\n\n fn sign(\n\n &self,\n\n algorithm: SigningAlgorithm,\n\n key: Key<'_>,\n\n data: &[u8],\n\n ) -> Result<Vec<u8>, Error>;\n\n}\...
Rust
remote-trait-object-macro/src/service/dispatcher.rs
junha1/baselink-rs
51480ea1635a7c88ad4a13a76d8133aa9110233f
use super::MacroArgs; use crate::create_env_path; use proc_macro2::{Span, TokenStream as TokenStream2}; pub(super) fn generate_dispatcher( source_trait: &syn::ItemTrait, args: &MacroArgs, ) -> Result<TokenStream2, TokenStream2> { if args.no_skeleton { return Ok(TokenStream2::new()); } let env_path = create_env_path(); let trait_ident = source_trait.ident.clone(); let box_dispatcher_ident = quote::format_ident!("{}BoxDispatcher", trait_ident); let arc_dispatcher_ident = quote::format_ident!("{}ArcDispatcher", trait_ident); let rwlock_dispatcher_ident = quote::format_ident!("{}RwLockDispatcher", trait_ident); let serde_format = &args.serde_format; let mut if_else_clauses = TokenStream2::new(); let mut if_else_clauses_rwlock = TokenStream2::new(); let mut is_this_trait_mutable = false; for item in source_trait.items.iter() { let method = match item { syn::TraitItem::Method(x) => x, non_method => { return Err(syn::Error::new_spanned( non_method, "Service trait must have only methods", ) .to_compile_error()) } }; let id_ident = super::id::id_method_ident(source_trait, method); let mut the_let_pattern = syn::PatTuple { attrs: Vec::new(), paren_token: syn::token::Paren(Span::call_site()), elems: syn::punctuated::Punctuated::new(), }; let mut type_annotation = syn::TypeTuple { paren_token: syn::token::Paren(Span::call_site()), elems: syn::punctuated::Punctuated::new(), }; let mut the_args: syn::punctuated::Punctuated<syn::Expr, syn::token::Comma> = syn::punctuated::Punctuated::new(); let no_self = "All your method must take &self or &mut self (Object safety)"; let mut_self = match method .sig .inputs .first() .ok_or_else(|| syn::Error::new_spanned(method, no_self).to_compile_error())? { syn::FnArg::Typed(_) => { return Err(syn::Error::new_spanned(method, no_self).to_compile_error()) } syn::FnArg::Receiver(syn::Receiver { mutability: Some(_), .. }) => true, _ => false, }; is_this_trait_mutable |= mut_self; for (j, arg_source) in method.sig.inputs.iter().skip(1).enumerate() { let the_iden = quote::format_ident!("a{}", j + 1); the_let_pattern.elems.push(syn::Pat::Ident(syn::PatIdent { attrs: Vec::new(), by_ref: None, mutability: None, ident: the_iden, subpat: None, })); the_let_pattern .elems .push_punct(syn::token::Comma(Span::call_site())); let arg_type = match arg_source { syn::FnArg::Typed(syn::PatType { attrs: _, pat: _, colon_token: _, ty: t, }) => &**t, _ => panic!(), }; if let Some(unrefed_type) = crate::helper::is_ref(arg_type) .map_err(|e| syn::Error::new_spanned(arg_source, &e).to_compile_error())? { type_annotation.elems.push(unrefed_type); } else { type_annotation.elems.push(arg_type.clone()); } type_annotation .elems .push_punct(syn::token::Comma(Span::call_site())); let arg_ident = quote::format_ident!("a{}", j + 1); let the_arg = if crate::helper::is_ref(arg_type) .map_err(|e| syn::Error::new_spanned(arg_source, &e).to_compile_error())? .is_some() { quote! { &#arg_ident } } else { quote! { #arg_ident } }; the_args.push(syn::parse2(the_arg).unwrap()); } let stmt_deserialize = quote! { let #the_let_pattern: #type_annotation = <#serde_format as #env_path::SerdeFormat>::from_slice(args).unwrap(); }; let method_name = method.sig.ident.clone(); let stmt_call = quote! { let result = self.object.#method_name(#the_args); }; let stmt_call_rwlock = if mut_self { quote! { let result = self.object.write().#method_name(#the_args); } } else { quote! { let result = self.object.read().#method_name(#the_args); } }; let the_return = quote! { return <#serde_format as #env_path::SerdeFormat>::to_vec(&result).unwrap(); }; if_else_clauses.extend(quote! { if method == #id_ident.load(#env_path::ID_ORDERING) { #stmt_deserialize #stmt_call #the_return } }); if_else_clauses_rwlock.extend(quote! { if method == #id_ident.load(#env_path::ID_ORDERING) { #stmt_deserialize #stmt_call_rwlock #the_return } }); } if_else_clauses.extend(quote! { panic!("Invalid remote-trait-object call. Fatal Error.") }); if_else_clauses_rwlock.extend(quote! { panic!("Invalid remote-trait-object call. Fatal Error.") }); let box_dispatcher = if is_this_trait_mutable { quote! { #[doc(hidden)] pub struct #box_dispatcher_ident { object: parking_lot::RwLock<Box<dyn #trait_ident>> } impl #box_dispatcher_ident { fn new(object: Box<dyn #trait_ident>) -> Self { Self { object: parking_lot::RwLock::new(object) } } } impl #env_path::Dispatch for #box_dispatcher_ident { fn dispatch_and_call(&self, method: #env_path::MethodId, args: &[u8]) -> Vec<u8> { #if_else_clauses_rwlock } } impl #env_path::IntoSkeleton<dyn #trait_ident> for Box<dyn #trait_ident> { fn into_skeleton(self) -> #env_path::Skeleton { #env_path::create_skeleton(std::sync::Arc::new(#box_dispatcher_ident::new(self))) } } } } else { quote! { #[doc(hidden)] pub struct #box_dispatcher_ident { object: Box<dyn #trait_ident> } impl #box_dispatcher_ident { fn new(object: Box<dyn #trait_ident>) -> Self { Self { object } } } impl #env_path::Dispatch for #box_dispatcher_ident { fn dispatch_and_call(&self, method: #env_path::MethodId, args: &[u8]) -> Vec<u8> { #if_else_clauses } } impl #env_path::IntoSkeleton<dyn #trait_ident> for Box<dyn #trait_ident> { fn into_skeleton(self) -> #env_path::Skeleton { #env_path::create_skeleton(std::sync::Arc::new(#box_dispatcher_ident::new(self))) } } } }; let arc_dispatcher = if is_this_trait_mutable { quote! {} } else { quote! { #[doc(hidden)] pub struct #arc_dispatcher_ident { object: std::sync::Arc<dyn #trait_ident> } impl #arc_dispatcher_ident { fn new(object: std::sync::Arc<dyn #trait_ident>) -> Self { Self { object } } } impl #env_path::Dispatch for #arc_dispatcher_ident { fn dispatch_and_call(&self, method: #env_path::MethodId, args: &[u8]) -> Vec<u8> { #if_else_clauses } } impl #env_path::IntoSkeleton<dyn #trait_ident> for std::sync::Arc<dyn #trait_ident> { fn into_skeleton(self) -> #env_path::Skeleton { #env_path::create_skeleton(std::sync::Arc::new(#arc_dispatcher_ident::new(self))) } } } }; let rwlock_dispatcher = quote! { #[doc(hidden)] pub struct #rwlock_dispatcher_ident { object: std::sync::Arc<parking_lot::RwLock<dyn #trait_ident>> } impl #rwlock_dispatcher_ident { fn new(object: std::sync::Arc<parking_lot::RwLock<dyn #trait_ident>>) -> Self { Self { object } } } impl #env_path::Dispatch for #rwlock_dispatcher_ident { fn dispatch_and_call(&self, method: #env_path::MethodId, args: &[u8]) -> Vec<u8> { #if_else_clauses_rwlock } } impl #env_path::IntoSkeleton<dyn #trait_ident> for std::sync::Arc<parking_lot::RwLock<dyn #trait_ident>> { fn into_skeleton(self) -> #env_path::Skeleton { #env_path::create_skeleton(std::sync::Arc::new(#rwlock_dispatcher_ident::new(self))) } } }; Ok(quote! { #box_dispatcher #arc_dispatcher #rwlock_dispatcher }) }
use super::MacroArgs; use crate::create_env_path; use proc_macro2::{Span, TokenStream as TokenStream2}; pub(super) fn generate_dispatcher( source_trait: &syn::ItemTrait, args: &MacroArgs, ) -> Result<TokenStream2, TokenStream2> { if args.no_skeleton { return Ok(TokenStream2::new()); } let env_path = create_env_path(); let trait_ident = source_trait.ident.clone(); let box_dispatcher_ident = quote::format_ident!("{}BoxDispatcher", trait_ident); let arc_dispatcher_ident = quote::format_ident!("{}ArcDispatcher", trait_ident); let rwlock_dispatcher_ident = quote::format_ident!("{}RwLockDispatcher", trait_ident); let serde_format = &args.serde_format; let mut if_else_clauses = TokenStream2::new(); let mut if_else_clauses_rwlock = TokenStream2::new(); let mut is_this_trait_mutable = false; for item in source_trait.items.iter() { let method = match item { syn::TraitItem::Method(x) => x, non_method => { return Err(syn::Error::new_spanned( non_method, "Service trait must have only methods", ) .to_compile_error()) } }; let id_ident = super::id::id_method_ident(source_trait, method); let mut the_let_pattern = syn::PatTuple { attrs: Vec::new(), paren_token: syn::token::Paren(Span::call_site()), elems: syn::punctuated::Punctuated::new(), }; let mut type_annotation = syn::TypeTuple { paren_token: syn::token::Paren(Span::call_site()), elems: syn::punctuated::Punctuated::new(), }; let mut the_args: syn::punctuated::P
e_annotation.elems.push(arg_type.clone()); } type_annotation .elems .push_punct(syn::token::Comma(Span::call_site())); let arg_ident = quote::format_ident!("a{}", j + 1); let the_arg = if crate::helper::is_ref(arg_type) .map_err(|e| syn::Error::new_spanned(arg_source, &e).to_compile_error())? .is_some() { quote! { &#arg_ident } } else { quote! { #arg_ident } }; the_args.push(syn::parse2(the_arg).unwrap()); } let stmt_deserialize = quote! { let #the_let_pattern: #type_annotation = <#serde_format as #env_path::SerdeFormat>::from_slice(args).unwrap(); }; let method_name = method.sig.ident.clone(); let stmt_call = quote! { let result = self.object.#method_name(#the_args); }; let stmt_call_rwlock = if mut_self { quote! { let result = self.object.write().#method_name(#the_args); } } else { quote! { let result = self.object.read().#method_name(#the_args); } }; let the_return = quote! { return <#serde_format as #env_path::SerdeFormat>::to_vec(&result).unwrap(); }; if_else_clauses.extend(quote! { if method == #id_ident.load(#env_path::ID_ORDERING) { #stmt_deserialize #stmt_call #the_return } }); if_else_clauses_rwlock.extend(quote! { if method == #id_ident.load(#env_path::ID_ORDERING) { #stmt_deserialize #stmt_call_rwlock #the_return } }); } if_else_clauses.extend(quote! { panic!("Invalid remote-trait-object call. Fatal Error.") }); if_else_clauses_rwlock.extend(quote! { panic!("Invalid remote-trait-object call. Fatal Error.") }); let box_dispatcher = if is_this_trait_mutable { quote! { #[doc(hidden)] pub struct #box_dispatcher_ident { object: parking_lot::RwLock<Box<dyn #trait_ident>> } impl #box_dispatcher_ident { fn new(object: Box<dyn #trait_ident>) -> Self { Self { object: parking_lot::RwLock::new(object) } } } impl #env_path::Dispatch for #box_dispatcher_ident { fn dispatch_and_call(&self, method: #env_path::MethodId, args: &[u8]) -> Vec<u8> { #if_else_clauses_rwlock } } impl #env_path::IntoSkeleton<dyn #trait_ident> for Box<dyn #trait_ident> { fn into_skeleton(self) -> #env_path::Skeleton { #env_path::create_skeleton(std::sync::Arc::new(#box_dispatcher_ident::new(self))) } } } } else { quote! { #[doc(hidden)] pub struct #box_dispatcher_ident { object: Box<dyn #trait_ident> } impl #box_dispatcher_ident { fn new(object: Box<dyn #trait_ident>) -> Self { Self { object } } } impl #env_path::Dispatch for #box_dispatcher_ident { fn dispatch_and_call(&self, method: #env_path::MethodId, args: &[u8]) -> Vec<u8> { #if_else_clauses } } impl #env_path::IntoSkeleton<dyn #trait_ident> for Box<dyn #trait_ident> { fn into_skeleton(self) -> #env_path::Skeleton { #env_path::create_skeleton(std::sync::Arc::new(#box_dispatcher_ident::new(self))) } } } }; let arc_dispatcher = if is_this_trait_mutable { quote! {} } else { quote! { #[doc(hidden)] pub struct #arc_dispatcher_ident { object: std::sync::Arc<dyn #trait_ident> } impl #arc_dispatcher_ident { fn new(object: std::sync::Arc<dyn #trait_ident>) -> Self { Self { object } } } impl #env_path::Dispatch for #arc_dispatcher_ident { fn dispatch_and_call(&self, method: #env_path::MethodId, args: &[u8]) -> Vec<u8> { #if_else_clauses } } impl #env_path::IntoSkeleton<dyn #trait_ident> for std::sync::Arc<dyn #trait_ident> { fn into_skeleton(self) -> #env_path::Skeleton { #env_path::create_skeleton(std::sync::Arc::new(#arc_dispatcher_ident::new(self))) } } } }; let rwlock_dispatcher = quote! { #[doc(hidden)] pub struct #rwlock_dispatcher_ident { object: std::sync::Arc<parking_lot::RwLock<dyn #trait_ident>> } impl #rwlock_dispatcher_ident { fn new(object: std::sync::Arc<parking_lot::RwLock<dyn #trait_ident>>) -> Self { Self { object } } } impl #env_path::Dispatch for #rwlock_dispatcher_ident { fn dispatch_and_call(&self, method: #env_path::MethodId, args: &[u8]) -> Vec<u8> { #if_else_clauses_rwlock } } impl #env_path::IntoSkeleton<dyn #trait_ident> for std::sync::Arc<parking_lot::RwLock<dyn #trait_ident>> { fn into_skeleton(self) -> #env_path::Skeleton { #env_path::create_skeleton(std::sync::Arc::new(#rwlock_dispatcher_ident::new(self))) } } }; Ok(quote! { #box_dispatcher #arc_dispatcher #rwlock_dispatcher }) }
unctuated<syn::Expr, syn::token::Comma> = syn::punctuated::Punctuated::new(); let no_self = "All your method must take &self or &mut self (Object safety)"; let mut_self = match method .sig .inputs .first() .ok_or_else(|| syn::Error::new_spanned(method, no_self).to_compile_error())? { syn::FnArg::Typed(_) => { return Err(syn::Error::new_spanned(method, no_self).to_compile_error()) } syn::FnArg::Receiver(syn::Receiver { mutability: Some(_), .. }) => true, _ => false, }; is_this_trait_mutable |= mut_self; for (j, arg_source) in method.sig.inputs.iter().skip(1).enumerate() { let the_iden = quote::format_ident!("a{}", j + 1); the_let_pattern.elems.push(syn::Pat::Ident(syn::PatIdent { attrs: Vec::new(), by_ref: None, mutability: None, ident: the_iden, subpat: None, })); the_let_pattern .elems .push_punct(syn::token::Comma(Span::call_site())); let arg_type = match arg_source { syn::FnArg::Typed(syn::PatType { attrs: _, pat: _, colon_token: _, ty: t, }) => &**t, _ => panic!(), }; if let Some(unrefed_type) = crate::helper::is_ref(arg_type) .map_err(|e| syn::Error::new_spanned(arg_source, &e).to_compile_error())? { type_annotation.elems.push(unrefed_type); } else { typ
random
[ { "content": "fn id_method_entry_ident(the_trait: &syn::ItemTrait, method: &syn::TraitItemMethod) -> Ident {\n\n quote::format_ident!(\"ID_METHOD_ENTRY_{}_{}\", the_trait.ident, method.sig.ident)\n\n}\n\n\n", "file_path": "remote-trait-object-macro/src/service/id.rs", "rank": 0, "score": 147821.7...
Rust
src/response.rs
ghairfield/TinyHTTP
9559caa86bb4afb75e6ca2d5a912469b6f881650
use chrono::{DateTime, Local, TimeZone, Utc}; use std::collections::HashMap; use std::fs::{File, Metadata}; use std::io::prelude::*; use std::path::Path; use std::time::SystemTime; use crate::configuration::CONFIG; use crate::protocol::*; use crate::request; #[derive(Debug, Clone, PartialEq)] pub struct ResponseError { pub message: String, pub line: u32, pub column: u32, } pub struct Response { pub status: StatusCode, pub version: RequestVersion, pub fields: HashMap<String, String>, pub content: Vec<u8>, } impl Default for Response { fn default() -> Self { Response { status: StatusCode::Unknown, version: RequestVersion::HTTP1, fields: HashMap::<String, String>::new(), content: Vec::<u8>::new(), } } } impl Response { pub fn new(h: &request::Header) -> Self { let mut response = Response::default(); if !h.is_valid() { response.status = StatusCode::BadRequest; return response; } let m = h.get_method(); match m { RequestMethod::Get => response.get_request(&h), RequestMethod::Head => response.head_request(&h), RequestMethod::Post => response.post_request(&h), _ => response.unsupported_request(&h), } response } pub fn respond(&mut self) -> Vec<u8> { let mut resp_header; let mut r; if self.status == StatusCode::BadRequest || self.status == StatusCode::Unauthorized || self.status == StatusCode::Forbidden || self.status == StatusCode::NotFound { r = format! { "{} {}\r\n\r\n", version_to_string(&self.version), status_to_string(&self.status) }; resp_header = r.as_bytes().to_vec(); } else { r = format!( "{} {}\r\n", version_to_string(&self.version), status_to_string(&self.status) ); for (key, value) in &self.fields { r.push_str(&format!("{}{}\r\n", key, value)); } r.push_str("\r\n"); resp_header = r.as_bytes().to_vec(); if !self.content.is_empty() { resp_header.append(&mut self.content); } } resp_header } fn get_last_modified(meta: &Metadata) -> Result<String, ResponseError> { let lm = match meta.modified() { Ok(lm) => lm, Err(_) => { return Err(ResponseError { message: "Could not get modifed data on file".to_string(), line: line!(), column: column!(), }) } }; let sec_from_epoch = lm.duration_since(SystemTime::UNIX_EPOCH).unwrap(); let local_dt = Local.timestamp(sec_from_epoch.as_secs() as i64, 0); let utc_dt: DateTime<Utc> = DateTime::from(local_dt); Ok(format!("{}", utc_dt.format("%a, %d %b %Y %H:%M:%S GMT"))) } fn get_resource(&mut self, p: &str) -> Result<(), ResponseError> { let doc_root = &CONFIG.doc_root; let index = match &CONFIG.root_file { Some(x) => &x, None => match &CONFIG.default_root_file { Some(x) => x, _ => { return Err(ResponseError { message: "Could not find a default root file!".to_string(), line: line!(), column: column!(), }) } }, }; if p == "/" { let mut file = match File::open(&format!("{}/{}", doc_root, index)) { Ok(file) => file, Err(x) => { return Err(ResponseError { message: format!("Could not open file! {}", x), line: line!(), column: column!(), }) } }; let meta = match file.metadata() { Ok(meta) => meta, Err(_) => { return Err(ResponseError { message: "Could not get meta data on file".to_string(), line: line!(), column: column!(), }) } }; if let Ok(time) = Response::get_last_modified(&meta) { self.fields .insert(field_to_string(&RequestField::LastModified), time); } match file.read_to_end(&mut self.content) { Ok(size) => { self.fields.insert( field_to_string(&RequestField::ContentLength), size.to_string(), ); } Err(x) => { return Err(ResponseError { message: format!("Could not read file! {}", x), line: line!(), column: column!(), }) } }; } else { let p = format!("{}{}", CONFIG.doc_root, p); let path = Path::new(&p); println!("Path: {:?}", p); if path.exists() { let mut file = match File::open(path) { Ok(file) => file, Err(x) => { return Err(ResponseError { message: format!("Could not open file! {}", x), line: line!(), column: column!(), }) } }; let meta = match file.metadata() { Ok(meta) => meta, Err(_) => { return Err(ResponseError { message: "Could not get meta data on file".to_string(), line: line!(), column: column!(), }) } }; if let Ok(time) = Response::get_last_modified(&meta) { self.fields .insert(field_to_string(&RequestField::LastModified), time); } match file.read_to_end(&mut self.content) { Ok(size) => { self.fields.insert( field_to_string(&RequestField::ContentLength), size.to_string(), ); } Err(x) => { return Err(ResponseError { message: format!("Could not read file! {}", x), line: line!(), column: column!(), }) } } } } Ok(()) } fn get_request(&mut self, req: &request::Header) { match self.get_resource(req.get_path()) { Ok(_) => self.status = StatusCode::OK, Err(_) => { self.status = StatusCode::NotFound; } } } fn head_request(&mut self, req: &request::Header) { match self.get_resource(req.get_path()) { Ok(_) => self.status = StatusCode::OK, Err(_) => { self.status = StatusCode::NotFound; } } self.content.clear(); } fn post_request(&mut self, _req: &request::Header) { todo!() } fn unsupported_request(&mut self, _req: &request::Header) { todo!() } }
use chrono::{DateTime, Local, TimeZone, Utc}; use std::collections::HashMap; use std::fs::{File, Metadata}; use std::io::prelude::*; use std::path::Path; use std::time::SystemTime; use crate::configuration::CONFIG; use crate::protocol::*; use crate::request; #[derive(Debug, Clone, PartialEq)] pub struct ResponseError { pub message: String, pub line: u32, pub column: u32, } pub struct Response { pub status: StatusCode, pub version: RequestVersion, pub fields: HashMap<String, String>, pub content: Vec<u8>, } impl Default for Response { fn default() -> Self { Response { status: StatusCode::Unknown, version: RequestVersion::HTTP1, fields: HashMap::<String, String>::new(), content: Vec::<u8>::new(), } } } impl Response { pub fn new(h: &request::Header) -> Self { let mut response = Response::default(); if !h.is_valid() { response.status = StatusCode::BadRequest; return response; } let m = h.get_method(); match m { RequestMethod::Get => response.get_request(&h), RequestMethod::Head => response.head_request(&h), RequestMethod::Post => response.post_request(&h), _ => response.unsupported_request(&h), } response } pub fn respond(&mut self) -> Vec<u8> { let mut resp_header; let mut r; if self.status == StatusCode::BadRequest || self.status == StatusCode::Unauthorized || self.status == StatusCode::Forbidden || self.status == StatusCode::NotFound { r = format! { "{} {}\r\n\r\n", version_to_string(&self.version), status_to_string(&self.status) }; resp_header = r.as_bytes().to_vec(); } else { r = format!( "{} {}\r\n", version_to_string(&self.version), status_to_string(&self.status) ); for (key, value) in &self.fields { r.push_str(&format!("{}{}\r\n", key, value)); } r.push_str("\r\n"); resp_header = r.as_bytes().to_vec(); if !self.content.is_empty() { resp_header.append(&mut self.content); } } resp_header } fn get_last_modified(meta: &Metadata) -> Result<String, ResponseError> { let lm = match meta.modified() { Ok(lm) => lm, Err(_) => { return Err(ResponseError { message: "Could not get modifed data on file".to_string(), line: line!(), column: column!(), }) } }; let sec_from_epoch = lm.duration_since(SystemTime::UNIX_EPOCH).unwrap(); let local_dt = Local.timestamp(sec_from_epoch.as_secs() as i64, 0); let utc_dt: DateTime<Utc> = DateTime::from(local_dt); Ok(format!("{}", utc_dt.format("%a, %d %b %Y %H:%M:%S GMT"))) } fn get_resource(&mut self, p: &str) -> Result<(), ResponseError> { let doc_root = &CONFIG.doc_root; let index = match &CONFIG.root_file { Some(x) => &x, None => match &CONFIG.default_root_file { Some(x) => x, _ => { return Err(ResponseError { message: "Could not find a default root file!".to_string(), line: line!(), column: column!(), }) } }, }; if p == "/" { let mut file = match File::open(&format!("{}/{}", doc_root, index)) { Ok(file) => file, Err(x) => { return Err(ResponseError { message: format!("Could not open file! {}", x), line: line!(), column: column!(), }) } }; let meta = match file.metadata() { Ok(meta) => meta, Err(_) => { return Err(ResponseError { message: "Could not get meta data on file".to_string(), line: line!(), column: column!(), }) } }; if let Ok(time) = Response::get_last_modified(&meta) { self.fields .insert(field_to_string(&RequestField::LastModified), time); } match file.read_to_end(&mut self.content) { Ok(size) => { self.fields.insert( field_to_string(&RequestField::ContentLength), size.to_string(), ); } Err(x) => { return Err(ResponseError { message: format!("Could not read file! {}", x), line: line!(), column: column!(), }) } }; } else { let p = format!("{}{}", CONFIG.doc_root, p); let path = Path::new(&p); println!("Path: {:?}", p); if path.exists() { let mut file = match File::open(path) { Ok(file) => file, Err(x) => { return Err(ResponseError { message: format!("Could not open file! {}", x), line: line!(), column: column!(), }) } }; let meta = match file.metadata() { Ok(meta) => meta, Err(_) => { return Err(ResponseError { message: "Could not get meta data on file".to_string(), line: line!(), column: column!(), }) } }; if let Ok(time) = Response::get_last_modified(&meta) { self.fields .insert(field_to_string(&RequestField::LastModified), time); } match file.read_to_end(&mut self.content) { Ok(size) => { self.fields.insert( field_to_string(&RequestField::ContentLength), size.to_string(), ); } Err(x) => { return Err(ResponseError { message: format!("Could not read file! {}", x), line: line!(), column: column!(), }) } } } } Ok(()) } fn get_request(&mut self, req: &request::Header) { match self.get_resource(req.get_path()) { Ok(_) => self.status = StatusCode::OK, Err(_) => { self.status = StatusCode::NotFound; } } } fn head_request(&mut self, req: &request::Header) {
fn post_request(&mut self, _req: &request::Header) { todo!() } fn unsupported_request(&mut self, _req: &request::Header) { todo!() } }
match self.get_resource(req.get_path()) { Ok(_) => self.status = StatusCode::OK, Err(_) => { self.status = StatusCode::NotFound; } } self.content.clear(); }
function_block-function_prefix_line
[ { "content": "/// Get the string representation of a HTTP version\n\npub fn version_to_string(r: &RequestVersion) -> String {\n\n match r {\n\n RequestVersion::SimpleRequest => \"Simple Request\".to_string(),\n\n RequestVersion::HTTP1 => \"HTTP/1.0\".to_string(),\n\n RequestVersion::HTTP...
Rust
cocoon-core/src/message/mod.rs
d42ejh/ilnyaplus-dev
c5f2d04b3d1c6a1b2d6089e583b470779c9b4278
use crate::constant; use bytecheck::CheckBytes; use rkyv::{ ser::{serializers::AllocSerializer, Serializer}, Archive, Deserialize, Infallible, Serialize, }; use std::net::SocketAddr; use tracing::{event, Level}; #[derive(Debug, PartialEq, Eq, FromPrimitive)] pub enum MessageType { PingRequest = 1, FindNodeRequest = 2, FindValueRequest = 3, StoreValueRequest = 4, PingResponse = 5, FindNodeResponse = 6, FindValueResponse = 7, } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct MessageHeader { pub message_type: u32, } impl MessageHeader { pub fn new(message_type: MessageType) -> Self { MessageHeader { message_type: message_type as u32, } } pub fn from_bytes(bytes: &[u8]) -> Self { assert!(bytes.len() >= constant::MESSAGE_HEADER_SIZE); let archived = rkyv::check_archived_root::<Self>(&bytes[0..constant::MESSAGE_HEADER_SIZE]).unwrap(); let header: Self = archived.deserialize(&mut Infallible).unwrap(); header } pub fn to_bytes(&self) -> Vec<u8> { let mut serializer = AllocSerializer::<256>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); let av = serializer.into_serializer().into_inner(); assert_eq!(av.len(), constant::MESSAGE_HEADER_SIZE); av.to_vec() } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct PingRequestMessage {} impl PingRequestMessage { pub fn new() -> Self { PingRequestMessage {} } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::PingRequest); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<32>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct FindNodeRequestMessage { pub key: Vec<u8>, } impl FindNodeRequestMessage { pub fn new(key: &[u8]) -> Self { FindNodeRequestMessage { key: key.to_vec() } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::FindNodeRequest); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct FindValueRequestMessage { pub key: Vec<u8>, } impl FindValueRequestMessage { pub fn new(key: &[u8]) -> Self { debug_assert!(key.len() != 0); FindValueRequestMessage { key: key.to_owned(), } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::FindValueRequest); let mut bytes = header.to_bytes(); println!("find val header {} bytes", bytes.len()); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); let body_bytes = serializer.into_serializer().into_inner(); println!("find val body {} bytes", body_bytes.len()); bytes.extend_from_slice(&body_bytes); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct StoreValueRequestMessage { pub key: Vec<u8>, pub data: Vec<u8>, pub replication_level: u32, } impl StoreValueRequestMessage { pub fn new(key: &[u8], data: &[u8], replication_level: u32) -> Self { StoreValueRequestMessage { key: key.to_vec(), data: data.to_vec(), replication_level: replication_level, } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::StoreValueRequest); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct PingResponseMessage {} impl PingResponseMessage { pub fn new() -> Self { PingResponseMessage {} } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::PingResponse); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct FindNodeResponseMessage { pub nodes: Vec<SocketAddr>, } impl FindNodeResponseMessage { pub fn new(addrs: &[SocketAddr]) -> Self { FindNodeResponseMessage { nodes: addrs.to_vec(), } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::FindNodeResponse); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct FindValueResponseMessage { pub key: Vec<u8>, pub node: Option<SocketAddr>, pub data: Option<Vec<u8>>, } impl FindValueResponseMessage { pub fn new(key: &[u8], node: Option<&SocketAddr>, data: Option<&[u8]>) -> Self { assert!(!(node.is_none() && data.is_none())); assert!(!(node.is_some() && data.is_some())); if node.is_some() && data.is_none() { FindValueResponseMessage { key: key.to_vec(), node: Some(*node.unwrap()), data: None, } } else { FindValueResponseMessage { key: key.to_vec(), node: None, data: Some(data.unwrap().to_vec()), } } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::FindValueResponse); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[cfg(test)] mod tests { use super::constant::MESSAGE_HEADER_SIZE; use super::{FindNodeRequestMessage, MessageHeader, MessageType, PingRequestMessage}; use crate::message::{FindValueRequestMessage, PingResponseMessage, StoreValueRequestMessage}; use openssl::rand::rand_bytes; #[test] pub fn header() -> anyhow::Result<()> { let h = MessageHeader::new(MessageType::PingRequest); assert_eq!(h.message_type, MessageType::PingRequest as u32); let bytes = h.to_bytes(); assert_eq!(bytes.len(), MESSAGE_HEADER_SIZE); let hh = MessageHeader::from_bytes(&bytes); assert_eq!(h, hh); Ok(()) } #[test] pub fn ping_request() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::PingRequest); let req = PingRequestMessage::new(); let bytes = req.to_bytes(); let (h, r) = PingRequestMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } #[test] pub fn find_node_request() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::FindNodeRequest); let mut key = vec![0; 64]; rand_bytes(&mut key)?; let req = FindNodeRequestMessage::new(&key); assert_eq!(key, req.key); let bytes = req.to_bytes(); let (h, r) = FindNodeRequestMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } #[test] pub fn find_value_request() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::FindValueRequest); let mut key = vec![0; 64]; rand_bytes(&mut key)?; let req = FindValueRequestMessage::new(&key); assert_eq!(key, req.key); let bytes = req.to_bytes(); let (h, r) = FindValueRequestMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } #[test] pub fn store_value_request() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::StoreValueRequest); let mut key = vec![0; 64]; let mut data = vec![0; 64]; rand_bytes(&mut key)?; rand_bytes(&mut data)?; let rep_level = 99; let req = StoreValueRequestMessage::new(&key, &data, rep_level); assert_eq!(key, req.key); assert_eq!(data, req.data); assert_eq!(rep_level, req.replication_level); let bytes = req.to_bytes(); let (h, r) = StoreValueRequestMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } #[test] pub fn ping_response() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::PingResponse); let req = PingResponseMessage::new(); let bytes = req.to_bytes(); let (h, r) = PingResponseMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } }
use crate::constant; use bytecheck::CheckBytes; use rkyv::{ ser::{serializers::AllocSerializer, Serializer}, Archive, Deserialize, Infallible, Serialize, }; use std::net::SocketAddr; use tracing::{event, Level}; #[derive(Debug, PartialEq, Eq, FromPrimitive)] pub enum MessageType { PingRequest = 1, FindNodeRequest = 2, FindValueRequest = 3, StoreValueRequest = 4, PingResponse = 5, FindNodeResponse = 6, FindValueResponse = 7, } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct MessageHeader { pub message_type: u32, } impl MessageHeader { pub fn new(message_type: MessageType) -> Self { MessageHeader { message_type: message_type as u32, } } pub fn from_bytes(bytes: &[u8]) -> Self { assert!(bytes.len() >= constant::MESSAGE_HEADER_SIZE); let archived = rkyv::check_archived_root::<Self>(&bytes[0..constant::MESSAGE_HEADER_SIZE]).unwrap(); let header: Self = archived.deserialize(&mut Infallible).unwrap(); header } pub fn to_bytes(&self) -> Vec<u8> { let mut serializer = AllocSerializer::<256>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); let av = serializer.into_serializer().into_inner(); assert_eq!(av.len(), constant::MESSAGE_HEADER_SIZE); av.to_vec() } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct PingRequestMessage {} impl PingRequestMessage { pub fn new() -> Self { PingRequestMessage {} } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::PingRequest); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<32>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct FindNodeRequestMessage { pub key: Vec<u8>, } impl FindNodeRequestMessage { pub fn new(key: &[u8]) -> Self { FindNodeRequestMessage { key: key.to_vec() } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::FindNodeRequest); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct FindValueRequestMessage { pub key: Vec<u8>, } impl FindValueRequestMessage { pub fn new(key: &[u8]) -> Self { debug_assert!(key.len() != 0); FindValueRequestMessage { key: key.to_owned(), } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::FindValueRequest); let mut bytes = header.to_bytes(); println!("find val header {} bytes", bytes.len()); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); let body_bytes = serializer.into_serializer().into_inner(); println!("find val body {} bytes", body_bytes.len()); bytes.extend_from_slice(&body_bytes); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct StoreValueRequestMessage { pub key: Vec<u8>, pub data: Vec<u8>, pub replication_level: u32, } impl StoreValueRequestMessage { pub fn new(key: &[u8], data: &[u8], replication_level: u32) -> Self { StoreValueRequestMessage { key: key.to_vec(), data: data.to_vec(), replication_level: replication_level, } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::StoreValueRequest); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct PingResponseMessage {} impl PingResponseMessage { pub fn new() -> Self { PingResponseMessage {} } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::PingResponse); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct FindNodeResponseMessage { pub nodes: Vec<SocketAddr>, } impl FindNodeResponseMessage { pub fn new(addrs: &[SocketAddr]) -> Self { FindNodeResponseMessage { nodes: addrs.to_vec(), } } pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::FindNodeResponse); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[archive_attr(derive(CheckBytes, Debug))] pub struct FindValueResponseMessage { pub key: Vec<u8>, pub node: Option<SocketAddr>, pub data: Option<Vec<u8>>, } impl FindValueResponseMessage { pub fn new(key: &[u8], node: Option<&SocketAddr>, data: Option<&[u8]>) -> Self { assert!(!(node.is_none() && data.is_none())); assert!(!(node.is_some() && data.is_some()));
} pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); (header, msg) } pub fn to_bytes(&self) -> Vec<u8> { let header = MessageHeader::new(MessageType::FindValueResponse); let mut bytes = header.to_bytes(); let mut serializer = AllocSerializer::<512>::default(); serializer .serialize_value(self) .expect("Failed to serialize a message"); bytes.extend_from_slice(&serializer.into_serializer().into_inner()); bytes } } #[cfg(test)] mod tests { use super::constant::MESSAGE_HEADER_SIZE; use super::{FindNodeRequestMessage, MessageHeader, MessageType, PingRequestMessage}; use crate::message::{FindValueRequestMessage, PingResponseMessage, StoreValueRequestMessage}; use openssl::rand::rand_bytes; #[test] pub fn header() -> anyhow::Result<()> { let h = MessageHeader::new(MessageType::PingRequest); assert_eq!(h.message_type, MessageType::PingRequest as u32); let bytes = h.to_bytes(); assert_eq!(bytes.len(), MESSAGE_HEADER_SIZE); let hh = MessageHeader::from_bytes(&bytes); assert_eq!(h, hh); Ok(()) } #[test] pub fn ping_request() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::PingRequest); let req = PingRequestMessage::new(); let bytes = req.to_bytes(); let (h, r) = PingRequestMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } #[test] pub fn find_node_request() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::FindNodeRequest); let mut key = vec![0; 64]; rand_bytes(&mut key)?; let req = FindNodeRequestMessage::new(&key); assert_eq!(key, req.key); let bytes = req.to_bytes(); let (h, r) = FindNodeRequestMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } #[test] pub fn find_value_request() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::FindValueRequest); let mut key = vec![0; 64]; rand_bytes(&mut key)?; let req = FindValueRequestMessage::new(&key); assert_eq!(key, req.key); let bytes = req.to_bytes(); let (h, r) = FindValueRequestMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } #[test] pub fn store_value_request() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::StoreValueRequest); let mut key = vec![0; 64]; let mut data = vec![0; 64]; rand_bytes(&mut key)?; rand_bytes(&mut data)?; let rep_level = 99; let req = StoreValueRequestMessage::new(&key, &data, rep_level); assert_eq!(key, req.key); assert_eq!(data, req.data); assert_eq!(rep_level, req.replication_level); let bytes = req.to_bytes(); let (h, r) = StoreValueRequestMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } #[test] pub fn ping_response() -> anyhow::Result<()> { let header = MessageHeader::new(MessageType::PingResponse); let req = PingResponseMessage::new(); let bytes = req.to_bytes(); let (h, r) = PingResponseMessage::from_bytes(&bytes); assert_eq!(h, header); assert_eq!(r, req); Ok(()) } }
if node.is_some() && data.is_none() { FindValueResponseMessage { key: key.to_vec(), node: Some(*node.unwrap()), data: None, } } else { FindValueResponseMessage { key: key.to_vec(), node: None, data: Some(data.unwrap().to_vec()), } }
if_condition
[]
Rust
src/options.rs
Dentosal/constcodegen
09d61a536d729aeda9639d03a52025b401ab1b53
use std::collections::HashMap; use serde::Deserialize; use crate::constants::Constant; use crate::format_value::*; use crate::template; #[derive(Debug, Deserialize, Default)] #[serde(default, deny_unknown_fields)] pub struct Options { pub codegen: CodegenOptions, lang: HashMap<String, LangOptions>, } impl Options { pub fn languages(&self) -> Vec<(&String, &LangOptions)> { self.lang .iter() .filter(|(ref name, _)| self.codegen.enabled.contains(name)) .collect() } } #[derive(Debug, Deserialize, Default)] #[serde(deny_unknown_fields)] pub struct CodegenOptions { enabled: Vec<String>, #[serde(default)] pub comment_sections: bool, } #[derive(Debug, Deserialize, Default)] #[serde(deny_unknown_fields)] pub struct LangOptions { pub file_ext: String, template: String, #[serde(default)] import: Option<String>, #[serde(default)] comment: Option<String>, #[serde(default)] intro: Option<String>, #[serde(default)] outro: Option<String>, #[serde(default)] format: Format, #[serde(default)] pub formatter: Option<Vec<String>>, #[serde(default, rename = "type")] pub types: HashMap<String, LangTypeOptions>, } impl LangOptions { pub fn format_constant(&self, constant: &Constant) -> Option<String> { let mut t_ctx = HashMap::new(); t_ctx.insert("$name", constant.name.clone()); t_ctx.insert( "$value", constant .type_ .clone() .and_then(|t| self.types.get(&t)) .map(|t_opts| t_opts.format.clone()) .unwrap_or_else(|| self.format.clone()) .format(&constant.value()), ); if template::contains_parameter(&self.template, "$type") { let type_ = constant.type_.clone()?; t_ctx.insert("$type", type_.clone()); if let Some(type_opts) = self.types.get(&type_) { if let Some(type_name) = &type_opts.name { t_ctx.insert("$type", type_name.clone()); } let old_value = t_ctx["$value"].clone(); t_ctx.insert( "$value", format!( "{}{}{}", type_opts.value_prefix, old_value, type_opts.value_suffix ), ); } } Some(template::replace_parameters(&self.template, &t_ctx)) } pub fn format_import(&self, import: &str) -> Option<String> { let mut t_ctx = HashMap::new(); t_ctx.insert("$import", import.to_owned()); let im = self.import.clone()?; Some(template::replace_parameters(&im, &t_ctx)) } pub fn format_comment(&self, comment: &str) -> String { let mut t_ctx = HashMap::new(); t_ctx.insert("$comment", comment.to_owned()); self.comment .clone() .map(|c| format!("{}\n", template::replace_parameters(&c, &t_ctx))) .unwrap_or_else(String::new) } pub fn format_intro(&self) -> String { let t_ctx = HashMap::new(); self.intro .clone() .map(|c| format!("{}\n", template::replace_parameters(&c, &t_ctx))) .unwrap_or_else(String::new) } pub fn format_outro(&self) -> String { let t_ctx = HashMap::new(); self.outro .clone() .map(|c| format!("{}\n", template::replace_parameters(&c, &t_ctx))) .unwrap_or_else(String::new) } pub fn constant_imports(&self, constant: &Constant) -> Vec<String> { if let Some(type_) = constant.type_.clone() { if let Some(type_opts) = self.types.get(&type_) { return type_opts.import.clone(); } } Vec::new() } } #[derive(Debug, Deserialize, Default)] #[serde(default, deny_unknown_fields)] pub struct LangTypeOptions { pub name: Option<String>, pub value_prefix: String, pub value_suffix: String, pub format: Format, pub import: Vec<String>, }
use std::collections::HashMap; use serde::Deserialize; use crate::constants::Constant; use crate::format_value::*; use crate::template; #[derive(Debug, Deserialize, Default)] #[serde(default, deny_unknown_fields)] pub struct Options { pub codegen: CodegenOptions, lang: HashMap<String, LangOptions>, } impl Options { pub fn languages(&self) -> Vec<(&String, &LangOptions)> { self.lang .iter() .filter(|(ref name, _)| self.codegen.enabled.contains(name)) .collect() } } #[derive(Debug, Deserialize, Default)] #[serde(deny_unknown_fields)] pub struct CodegenOptions { enabled: Vec<String>, #[serde(default)] pub comment_sections: bool, } #[derive(Debug, Deserialize, Default)] #[serde(deny_unknown_fields)] pub struct LangOptions { pub file_ext: String, template: String, #[serde(default)] import: Option<String>, #[serde(default)] comment: Option<String>, #[serde(default)] intro: Option<String>, #[serde(default)] outro: Option<String>, #[serde(default)] format: Format, #[serde(default)] pub formatter: Option<Vec<String>>, #[serde(default, rename = "type")] pub types: HashMap<String, LangTypeOptions>, } impl LangOptions { pub fn format_constant(&self, constant: &Constant) -> Option<String> { let mut t_ctx = HashMap::new(); t_ctx.insert("$name", constant.name.clone()); t_ctx.insert( "$value", constant .type_ .clone() .and_then(|t| self.types.get(&t)) .map(|t_opts| t_opts.format.clone()) .unwrap_or_else(|| self.format.clone()) .format(&constant.value()), ); if template::contains_parameter(&self.template, "$type") { let type_ = constant.type_.clone()?; t_ctx.insert("$type", type_.clone()); if let Some(type_opts) = self.types.get(&type_) { if let Some(type_name) = &type_opts.name { t_ctx.insert("$type", type_name.clone()); } let old_value = t_ctx["$value"].clone(); t_ctx.insert( "$value", format!( "{}{}{}", type_opts.value_prefix, old_value, type_opts.value_suffix ), ); } } Some(template::replace_parameters(&self.template, &t_ctx)) } pub fn format_import(&self, import: &str) -> Option<String> { let mut t_ctx = HashMap::new(); t_ctx.insert("$import", import.to_owned()); let im = self.import.clone()?; Some(template::replace_parameters(&im, &t_ctx)) } pub fn format_comment(&self, comment: &str) -> String { let mut t_ctx = HashMap::new(); t_ctx.insert("$comment", comment.to_owned()); self.comment .clone() .map(|c| format!("{}\n", template::replace_parameters(&c, &t_ctx))) .unwrap_or_else(String::new) } pub fn format_intro(&self) -> String { let t_ctx = HashMap::new(); self.intro .clone() .map(|c| format!("{}\n", template::replace_parameters(&c, &t_ctx))) .unwrap_or_else(String::new) } pub fn format_outro(&self) -> Strin
pub fn constant_imports(&self, constant: &Constant) -> Vec<String> { if let Some(type_) = constant.type_.clone() { if let Some(type_opts) = self.types.get(&type_) { return type_opts.import.clone(); } } Vec::new() } } #[derive(Debug, Deserialize, Default)] #[serde(default, deny_unknown_fields)] pub struct LangTypeOptions { pub name: Option<String>, pub value_prefix: String, pub value_suffix: String, pub format: Format, pub import: Vec<String>, }
g { let t_ctx = HashMap::new(); self.outro .clone() .map(|c| format!("{}\n", template::replace_parameters(&c, &t_ctx))) .unwrap_or_else(String::new) }
function_block-function_prefixed
[ { "content": "pub fn contains_parameter(text: &str, parameter: &str) -> bool {\n\n for cap in RE_PARAM.find_iter(text) {\n\n let name = cap.as_str();\n\n if name != \"$$\" && name == parameter {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "src/te...
Rust
websolver/src/ui/view/sudoku.rs
pepijnd/sudoku_web_solver
c3c04da1349d268843772abc5703bec3634a2906
use solver::Cell; use crate::{ ui::controller::{app::AppController, sudoku::SudokuController}, util::InitCell, }; use webelements::{we_builder, Result, WebElement}; #[we_builder( <div class="sdk-sudoku"> <CellBox we_field="cells" we_repeat="81" we_element /> </div> )] #[derive(Debug, Clone)] pub struct Sudoku {} impl WebElement for Sudoku { fn init(&mut self) -> Result<()> { for (index, cell) in self.cells.iter_mut().enumerate() { cell.set_cell(Cell::from_index(index)); } Ok(()) } } impl Sudoku { pub fn controller(&self, app: InitCell<AppController>) -> Result<SudokuController> { SudokuController::build(app, self) } pub fn cells(&self) -> std::slice::Iter<CellBox> { self.cells.iter() } pub fn update(&self, sudoku: &SudokuController) -> Result<()> { for cell in self.cells.iter() { cell.update(sudoku); } Ok(()) } } #[we_builder( <div class="sdk-cell"> <div class="background" /> <Indicator we_field="indicator" we_element /> <Cage we_field="cage" we_element /> <Options we_field="options" we_element /> <div class="sdk-number" we_field="number" /> </div> )] #[derive(Debug, Clone, WebElement)] pub struct CellBox { cell: Cell, } impl CellBox { pub fn cell(&self) -> Cell { self.cell } pub fn set_cell(&mut self, cell: Cell) { self.cell = cell; self.options.cell = cell; self.indicator.cell = cell; } pub fn update(&self, sudoku: &SudokuController) { let info = sudoku.app.info.info.borrow(); let model = sudoku.state.borrow(); let step = info .solve_step() .as_ref() .map(|s| *s.sudoku.cell(self.cell)); let value = model.start().cell(self.cell); debug_assert!(value <= 9, "invalid cell value {}", value); self.number.remove_class("starting state empty"); self.remove_class("target source selected"); if info.solve().is_some() { self.options.remove_class("hidden"); } else { self.options.add_class("hidden"); } if value > 0 { self.number.set_text(&format!("{}", value)); self.number.add_class("starting"); self.options.add_class("hidden"); } else if let Some(value) = step { self.number.add_class("state"); if value > 0 { self.number.set_text(&format!("{}", value)); self.options.add_class("hidden"); } else { self.number.set_text(""); } } else { self.number.add_class("empty"); self.number.set_text(""); } if let Some(step) = info.solve_step().as_ref() { if step.change.is_target(self.cell) { self.add_class("target"); } else if step.change.is_source(self.cell) { self.add_class("source"); } } if let Some(selected) = model.selected() { if selected == self.cell { self.add_class("selected"); } } self.options.update(sudoku); } } #[we_builder( <div class="cell-indicator"> <div class="indicator top" /> <div class="indicator left" /> <div class="indicator right" /> <div class="indicator bottom" /> </div> )] #[derive(Debug, Clone, WebElement)] pub struct Indicator { cell: Cell, } #[we_builder( <div class="cell-cage"> <div class="cage top" /> <div class="cage left" /> <div class="cage right" /> <div class="cage bottom" /> </div> )] #[derive(Debug, Clone, WebElement)] pub struct Cage { cell: Cell, } #[we_builder( <div class="cell-options"> <div class="cell-option" we_field="options" we_repeat="9" /> </div> )] #[derive(Debug, Clone)] pub struct Options { cell: Cell, } impl WebElement for Options { fn init(&mut self) -> Result<()> { dbg!("{:?}", &self.options); for (i, cell) in self.options.iter().enumerate() { cell.set_text(format!("{}", i + 1)); } Ok(()) } } impl Options { fn update(&self, sudoku: &SudokuController) { let info = sudoku.app.info.info.borrow(); for (option, e) in self.options.iter().enumerate() { if let Some(step) = info.solve_step() { let index = option as u8 + 1; let mut cache = step.cache; e.remove_class("target"); e.remove_class("source"); e.remove_class("hidden"); e.remove_class("digit"); if !cache.options(self.cell, &step.sudoku).has(index) { e.add_class("hidden"); } if let Some(step) = info.solve_step() { if step.change.is_target_digit(self.cell, index) { e.add_class("digit") } else if step.change.is_target_option(self.cell, index) { e.add_class("target") } else if step.change.is_source_option(self.cell, index) { e.add_class("source") } } } } } }
use solver::Cell; use crate::{ ui::controller::{app::AppController, sudoku::SudokuController}, util::InitCell, }; use webelements::{we_builder, Result, WebElement}; #[we_builder( <div class="sdk-sudoku"> <CellBox we_field="cells" we_repeat="81" we_element /> </div> )] #[derive(Debug, Clone)] pub struct Sudoku {} impl WebElement for Sudoku { fn init(&mut self) -> Result<()> { for (index, cell) in self.cells.iter_mut().enumerate() { cell.set_cell(Cell::from_index(index)); } Ok(()) } } impl Sudoku { pub fn controller(&self, app: InitCell<AppController>) -> Result<SudokuController> { SudokuController::build(app, self) } pub fn cells(&self) -> std::slice::Iter<CellBox> { self.cells.iter() } pub fn update(&self, sudoku: &SudokuController) -> Result<()> { for cell in self.cells.iter() { cell.update(sudoku); } Ok(()) } } #[we_builder( <div class="sdk-cell"> <div class="background" /> <Indicator we_field="indicator" we_element /> <Cage we_field="cage" we_element /> <Options we_field="options" we_element /> <div class="sdk-number" we_field="number" /> </div> )] #[derive(Debug, Clone, WebElement)] pub struct CellBox { cell:
if selected == self.cell { self.add_class("selected"); } } self.options.update(sudoku); } } #[we_builder( <div class="cell-indicator"> <div class="indicator top" /> <div class="indicator left" /> <div class="indicator right" /> <div class="indicator bottom" /> </div> )] #[derive(Debug, Clone, WebElement)] pub struct Indicator { cell: Cell, } #[we_builder( <div class="cell-cage"> <div class="cage top" /> <div class="cage left" /> <div class="cage right" /> <div class="cage bottom" /> </div> )] #[derive(Debug, Clone, WebElement)] pub struct Cage { cell: Cell, } #[we_builder( <div class="cell-options"> <div class="cell-option" we_field="options" we_repeat="9" /> </div> )] #[derive(Debug, Clone)] pub struct Options { cell: Cell, } impl WebElement for Options { fn init(&mut self) -> Result<()> { dbg!("{:?}", &self.options); for (i, cell) in self.options.iter().enumerate() { cell.set_text(format!("{}", i + 1)); } Ok(()) } } impl Options { fn update(&self, sudoku: &SudokuController) { let info = sudoku.app.info.info.borrow(); for (option, e) in self.options.iter().enumerate() { if let Some(step) = info.solve_step() { let index = option as u8 + 1; let mut cache = step.cache; e.remove_class("target"); e.remove_class("source"); e.remove_class("hidden"); e.remove_class("digit"); if !cache.options(self.cell, &step.sudoku).has(index) { e.add_class("hidden"); } if let Some(step) = info.solve_step() { if step.change.is_target_digit(self.cell, index) { e.add_class("digit") } else if step.change.is_target_option(self.cell, index) { e.add_class("target") } else if step.change.is_source_option(self.cell, index) { e.add_class("source") } } } } } }
Cell, } impl CellBox { pub fn cell(&self) -> Cell { self.cell } pub fn set_cell(&mut self, cell: Cell) { self.cell = cell; self.options.cell = cell; self.indicator.cell = cell; } pub fn update(&self, sudoku: &SudokuController) { let info = sudoku.app.info.info.borrow(); let model = sudoku.state.borrow(); let step = info .solve_step() .as_ref() .map(|s| *s.sudoku.cell(self.cell)); let value = model.start().cell(self.cell); debug_assert!(value <= 9, "invalid cell value {}", value); self.number.remove_class("starting state empty"); self.remove_class("target source selected"); if info.solve().is_some() { self.options.remove_class("hidden"); } else { self.options.add_class("hidden"); } if value > 0 { self.number.set_text(&format!("{}", value)); self.number.add_class("starting"); self.options.add_class("hidden"); } else if let Some(value) = step { self.number.add_class("state"); if value > 0 { self.number.set_text(&format!("{}", value)); self.options.add_class("hidden"); } else { self.number.set_text(""); } } else { self.number.add_class("empty"); self.number.set_text(""); } if let Some(step) = info.solve_step().as_ref() { if step.change.is_target(self.cell) { self.add_class("target"); } else if step.change.is_source(self.cell) { self.add_class("source"); } } if let Some(selected) = model.selected() {
random
[ { "content": "#[cfg(feature = \"worker\")]\n\n#[wasm_bindgen]\n\npub fn solve(sudoku: &JsValue) -> Result<JsValue, JsValue> {\n\n let s: Sudoku = sudoku\n\n .into_serde()\n\n .map_err(|e| JsValue::from_str(&format!(\"{}\", e)))?;\n\n let solve = s.solve_steps();\n\n JsValue::from_serde(&s...
Rust
firm-construction/src/runtime.rs
comprakt/comprakt
2315e85972e63ea327c4d115ffe623253b520440
use libfirm_rs::{types::*, Entity}; use strum_macros::EnumDiscriminants; use crate::type_checking::type_system; #[strum_discriminants(derive(Display))] #[derive(EnumDiscriminants)] pub enum RuntimeFunction { SystemOutPrintln, SystemOutWrite, SystemOutFlush, SystemInRead, New, Dumpstack, NullUsage, ArrayOutOfBounds, DivByZero, } pub trait RTLib { fn ld_name(&self, builtin: RuntimeFunction) -> &'static str; fn mj_main_name(&self) -> &'static str; } impl From<type_system::BuiltinMethodBody> for RuntimeFunction { fn from(mb: type_system::BuiltinMethodBody) -> Self { use self::type_system::BuiltinMethodBody; match mb { BuiltinMethodBody::SystemOutPrintln => RuntimeFunction::SystemOutPrintln, BuiltinMethodBody::SystemOutWrite => RuntimeFunction::SystemOutWrite, BuiltinMethodBody::SystemOutFlush => RuntimeFunction::SystemOutFlush, BuiltinMethodBody::SystemInRead => RuntimeFunction::SystemInRead, } } } pub struct Mjrt; impl RTLib for Mjrt { fn ld_name(&self, rtf: RuntimeFunction) -> &'static str { match rtf { RuntimeFunction::SystemOutPrintln => "mjrt_system_out_println", RuntimeFunction::SystemOutWrite => "mjrt_system_out_write", RuntimeFunction::SystemOutFlush => "mjrt_system_out_flush", RuntimeFunction::SystemInRead => "mjrt_system_in_read", RuntimeFunction::Dumpstack => "mjrt_dumpstack", RuntimeFunction::DivByZero => "mjrt_div_by_zero", RuntimeFunction::NullUsage => "mjrt_null_usage", RuntimeFunction::ArrayOutOfBounds => "mjrt_array_out_of_bounds", RuntimeFunction::New => "mjrt_new", } } fn mj_main_name(&self) -> &'static str { "mj_main" } } pub struct Runtime { pub lib: Box<dyn RTLib>, pub system_out_println: Entity, pub system_out_write: Entity, pub system_out_flush: Entity, pub system_in_read: Entity, pub new: Entity, pub dumpstack: Entity, pub null_usage: Entity, pub array_out_of_bounds: Entity, pub div_by_zero: Entity, } impl Runtime { pub fn new(lib: Box<dyn RTLib>) -> Self { let dumpstack = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::Dumpstack), t.into()) }; let system_out_println = { let it = PrimitiveTy::i32(); let mut t = MethodTyBuilder::new(); t.add_param(it.into()); let t = t.build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::SystemOutPrintln), t.into()) }; let system_out_write = { let it = PrimitiveTy::i32(); let mut t = MethodTyBuilder::new(); t.add_param(it.into()); let t = t.build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::SystemOutWrite), t.into()) }; let system_out_flush = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::SystemOutFlush), t.into()) }; let system_in_read = { let it = PrimitiveTy::i32(); let mut t = MethodTyBuilder::new(); t.set_res(it.into()); let t = t.build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::SystemInRead), t.into()) }; let new = { let loc = PrimitiveTy::ptr(); let size = PrimitiveTy::i64(); let mut t = MethodTyBuilder::new(); t.add_param(size.into()); t.set_res(loc.into()); let t = t.build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::New), t.into()) }; let div_by_zero = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::DivByZero), t.into()) }; let null_usage = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::NullUsage), t.into()) }; let array_out_of_bounds = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::ArrayOutOfBounds), t.into()) }; Self { lib, system_out_println, system_out_write, system_out_flush, system_in_read, new, dumpstack, div_by_zero, null_usage, array_out_of_bounds, } } }
use libfirm_rs::{types::*, Entity}; use strum_macros::EnumDiscriminants; use crate::type_checking::type_system; #[strum_discriminants(derive(Display))] #[derive(EnumDiscriminants)] pub enum RuntimeFunction { SystemOutPrintln, SystemOutWrite, SystemOutFlush, SystemInRead, New, Dumpstack, NullUsage, ArrayOutOfBounds, DivByZero, } pub trait RTLib { fn ld_name(&self, builtin: RuntimeFunction) -> &'static str; fn mj_main_name(&self) -> &'static str; } impl From<type_system::BuiltinMethodBody> for RuntimeFunction { fn from(mb: type_system::BuiltinMethodBody) -> Self { use self::type_system::BuiltinMethodBody; match mb { BuiltinMethodBody::SystemOutPrintln => RuntimeFunction::SystemOutPrintln, BuiltinMethodBody::SystemOutWrite => RuntimeFunction::SystemOutWrite, BuiltinMethodBody::SystemOutFlush => RuntimeFunction::SystemOutFlush, BuiltinMethodBody::SystemInRead => RuntimeFunction::SystemInRead, } } } pub struct Mjrt; impl RTLib for Mjrt {
fn mj_main_name(&self) -> &'static str { "mj_main" } } pub struct Runtime { pub lib: Box<dyn RTLib>, pub system_out_println: Entity, pub system_out_write: Entity, pub system_out_flush: Entity, pub system_in_read: Entity, pub new: Entity, pub dumpstack: Entity, pub null_usage: Entity, pub array_out_of_bounds: Entity, pub div_by_zero: Entity, } impl Runtime { pub fn new(lib: Box<dyn RTLib>) -> Self { let dumpstack = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::Dumpstack), t.into()) }; let system_out_println = { let it = PrimitiveTy::i32(); let mut t = MethodTyBuilder::new(); t.add_param(it.into()); let t = t.build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::SystemOutPrintln), t.into()) }; let system_out_write = { let it = PrimitiveTy::i32(); let mut t = MethodTyBuilder::new(); t.add_param(it.into()); let t = t.build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::SystemOutWrite), t.into()) }; let system_out_flush = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::SystemOutFlush), t.into()) }; let system_in_read = { let it = PrimitiveTy::i32(); let mut t = MethodTyBuilder::new(); t.set_res(it.into()); let t = t.build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::SystemInRead), t.into()) }; let new = { let loc = PrimitiveTy::ptr(); let size = PrimitiveTy::i64(); let mut t = MethodTyBuilder::new(); t.add_param(size.into()); t.set_res(loc.into()); let t = t.build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::New), t.into()) }; let div_by_zero = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::DivByZero), t.into()) }; let null_usage = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::NullUsage), t.into()) }; let array_out_of_bounds = { let t = MethodTyBuilder::new().build_no_this_call(); Entity::new_global(lib.ld_name(RuntimeFunction::ArrayOutOfBounds), t.into()) }; Self { lib, system_out_println, system_out_write, system_out_flush, system_in_read, new, dumpstack, div_by_zero, null_usage, array_out_of_bounds, } } }
fn ld_name(&self, rtf: RuntimeFunction) -> &'static str { match rtf { RuntimeFunction::SystemOutPrintln => "mjrt_system_out_println", RuntimeFunction::SystemOutWrite => "mjrt_system_out_write", RuntimeFunction::SystemOutFlush => "mjrt_system_out_flush", RuntimeFunction::SystemInRead => "mjrt_system_in_read", RuntimeFunction::Dumpstack => "mjrt_dumpstack", RuntimeFunction::DivByZero => "mjrt_div_by_zero", RuntimeFunction::NullUsage => "mjrt_null_usage", RuntimeFunction::ArrayOutOfBounds => "mjrt_array_out_of_bounds", RuntimeFunction::New => "mjrt_new", } }
function_block-full_function
[ { "content": "pub fn dot_string(string: &str) -> String {\n\n format!(\"\\\"{}\\\"\", string.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\n\"))\n\n}\n", "file_path": "debugging/src/dot/mod.rs", "rank": 0, "score": 206150.33104397444 }, { "content": "// dummy_writer returns a Wri...
Rust
src/chirps.rs
vi/desyncmeasure
ed9767c6d2b52e74133c9a8ba8ce6dbf504a48c2
use std::sync::Arc; pub fn get_buckets() -> [[usize; 4]; 7] { let mut ret = [[0; 4]; 7]; let mut freq = 830; for b in &mut ret { for x in b { *x = freq / 10; freq += 87; } } ret } fn encode_bucket(x: usize) -> [f32; 4] { assert!(x < 4); match x { 0 => [1.0, 0.0, 0.0, 0.0], 1 => [0.0, 1.0, 0.0, 0.0], 2 => [0.0, 0.0, 1.0, 0.0], 3 => [0.0, 0.0, 0.0, 1.0], _ => unreachable!(), } } pub fn number_indexes(mut x: usize) -> [usize; 7] { assert!(x < 4096); let mut idxs = [0; 7]; let mut parity = 0; for i in 0..=5 { idxs[i] = x & 0b11; parity ^= x & 0b11; x >>= 2; } idxs[6] = parity; idxs } pub fn encode_number(x: usize) -> [[f32; 4]; 7] { assert!(x < 4096); let idxs = number_indexes(x); let mut cfs = [[0.0f32; 4]; 7]; for i in 0..=6 { cfs[i] = encode_bucket(idxs[i]); } cfs } pub struct ChirpAnalyzer { fft: Arc<dyn rustfft::Fft<f32>>, buckets : [[usize; 4]; 7], saved_num: usize, save_num_ctr: usize, } impl ChirpAnalyzer { pub fn new() -> ChirpAnalyzer { ChirpAnalyzer { fft: rustfft::FftPlanner::new().plan_fft_inverse(800), buckets : get_buckets(), saved_num: usize::MAX, save_num_ctr: 0, } } pub fn analyze_block(&mut self, _ts: f64, mut block: Vec<num_complex::Complex32>) -> Option<usize> { assert_eq!(block.len(), 800); self.fft.process(&mut block); let mut signal_quality = 100.0; let mut indexes = Vec::with_capacity(7); for bucket in self.buckets { let mut magnitutes = Vec::with_capacity(4); for string in bucket { let mut x = 0.0; x += 0.3*block[string].norm(); x += 0.7*block[string].norm(); x += 1.0*block[string].norm(); x += 0.7*block[string].norm(); x += 0.3*block[string].norm(); magnitutes.push(x); } let mut sum : f32 = magnitutes.iter().sum(); let best_idx = magnitutes.iter().enumerate().max_by_key(|(_,v)|ordered_float::OrderedFloat(**v)).unwrap().0; let mut losers_magnitutes = 0.0; for (n,x) in magnitutes.iter().enumerate() { if n == best_idx { continue } losers_magnitutes += *x; } sum += 0.0001; let mut qual = (magnitutes[best_idx] - losers_magnitutes)/sum; if qual < 0.05 { qual = 0.05; } signal_quality *= qual; indexes.push(best_idx); } let mut the_num = 0; let mut multiplier = 1; for i in 0..=5 { the_num += multiplier * indexes[i]; multiplier *= 4; } let canonical_indexes_for_this_number = number_indexes(the_num); if indexes[6] != canonical_indexes_for_this_number[6] { signal_quality = 0.0; } if signal_quality > 0.01 { if the_num == self.saved_num { self.save_num_ctr += 1; if self.save_num_ctr >= 3 { Some(the_num) } else { None } } else { self.saved_num = the_num; self.save_num_ctr = 1; None } } else { self.save_num_ctr = 0; None } } }
use std::sync::Arc; pub fn get_buckets() -> [[usize; 4]; 7] { let mut ret = [[0; 4]; 7]; let mut freq = 830; for b in &mut ret { for x in b { *x = freq / 10; freq += 87; } } ret } fn encode_bucket(x: usize) -> [f
pub fn number_indexes(mut x: usize) -> [usize; 7] { assert!(x < 4096); let mut idxs = [0; 7]; let mut parity = 0; for i in 0..=5 { idxs[i] = x & 0b11; parity ^= x & 0b11; x >>= 2; } idxs[6] = parity; idxs } pub fn encode_number(x: usize) -> [[f32; 4]; 7] { assert!(x < 4096); let idxs = number_indexes(x); let mut cfs = [[0.0f32; 4]; 7]; for i in 0..=6 { cfs[i] = encode_bucket(idxs[i]); } cfs } pub struct ChirpAnalyzer { fft: Arc<dyn rustfft::Fft<f32>>, buckets : [[usize; 4]; 7], saved_num: usize, save_num_ctr: usize, } impl ChirpAnalyzer { pub fn new() -> ChirpAnalyzer { ChirpAnalyzer { fft: rustfft::FftPlanner::new().plan_fft_inverse(800), buckets : get_buckets(), saved_num: usize::MAX, save_num_ctr: 0, } } pub fn analyze_block(&mut self, _ts: f64, mut block: Vec<num_complex::Complex32>) -> Option<usize> { assert_eq!(block.len(), 800); self.fft.process(&mut block); let mut signal_quality = 100.0; let mut indexes = Vec::with_capacity(7); for bucket in self.buckets { let mut magnitutes = Vec::with_capacity(4); for string in bucket { let mut x = 0.0; x += 0.3*block[string].norm(); x += 0.7*block[string].norm(); x += 1.0*block[string].norm(); x += 0.7*block[string].norm(); x += 0.3*block[string].norm(); magnitutes.push(x); } let mut sum : f32 = magnitutes.iter().sum(); let best_idx = magnitutes.iter().enumerate().max_by_key(|(_,v)|ordered_float::OrderedFloat(**v)).unwrap().0; let mut losers_magnitutes = 0.0; for (n,x) in magnitutes.iter().enumerate() { if n == best_idx { continue } losers_magnitutes += *x; } sum += 0.0001; let mut qual = (magnitutes[best_idx] - losers_magnitutes)/sum; if qual < 0.05 { qual = 0.05; } signal_quality *= qual; indexes.push(best_idx); } let mut the_num = 0; let mut multiplier = 1; for i in 0..=5 { the_num += multiplier * indexes[i]; multiplier *= 4; } let canonical_indexes_for_this_number = number_indexes(the_num); if indexes[6] != canonical_indexes_for_this_number[6] { signal_quality = 0.0; } if signal_quality > 0.01 { if the_num == self.saved_num { self.save_num_ctr += 1; if self.save_num_ctr >= 3 { Some(the_num) } else { None } } else { self.saved_num = the_num; self.save_num_ctr = 1; None } } else { self.save_num_ctr = 0; None } } }
32; 4] { assert!(x < 4); match x { 0 => [1.0, 0.0, 0.0, 0.0], 1 => [0.0, 1.0, 0.0, 0.0], 2 => [0.0, 0.0, 1.0, 0.0], 3 => [0.0, 0.0, 0.0, 1.0], _ => unreachable!(), } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let buckets = desyncmeasure::chirps::get_buckets();\n\n\n\n let zeroes = [0.0f32; 800];\n\n\n\n let mut audio_data = Vec::with_capacity(800 * 2 * 8192);\n\n\n\n let fft = rustfft::FftPlanner::<f32>::new().plan_fft_forward(800);\n\n\n\n\n\n for x in 0..4096 {\n\n ...
Rust
mindup_server/src/lib.rs
noogen-projects/mindup
74bcb9288337ea4daba473c55f30fa222c8cb8bc
use borsh::BorshSerialize; pub use dapla_wasm::{alloc, dealloc}; use dapla_wasm::{ database::{execute, query, Value}, WasmSlice, }; use mindup_common::{Response, Task}; use sql_builder::{quote, SqlBuilder, SqlBuilderError}; use thiserror::Error; const TASKS_TABLE_NAME: &str = "Tasks"; #[no_mangle] pub unsafe extern "C" fn init() -> WasmSlice { let result = execute(format!( r"CREATE TABLE IF NOT EXISTS {table}( description TEXT NOT NULL, completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0,1)) );", table = TASKS_TABLE_NAME )); let data = result .map(drop) .try_to_vec() .expect("Init result should be serializable"); WasmSlice::from(data) } #[no_mangle] pub unsafe extern "C" fn get(uri: WasmSlice) -> WasmSlice { WasmSlice::from(do_get(uri.into_string_in_wasm())) } fn do_get(uri: String) -> String { let response = TodoRequest::parse(&uri, None) .map(|request| request.process()) .unwrap_or_else(Response::Error); serde_json::to_string(&response).unwrap_or_else(Response::json_error_from) } #[no_mangle] pub unsafe extern "C" fn post(uri: WasmSlice, body: WasmSlice) -> WasmSlice { WasmSlice::from(do_post(uri.into_string_in_wasm(), body.into_string_in_wasm())) } fn do_post(uri: String, body: String) -> String { let response = TodoRequest::parse(&uri, Some(&body)) .map(|request| request.process()) .unwrap_or_else(Response::Error); serde_json::to_string(&response).unwrap_or_else(Response::json_error_from) } #[derive(Debug, Error)] enum TaskError { #[error("Invalid SQL query: {0}")] Sql(#[from] SqlBuilderError), #[error("Error: {0}")] AnyhowError(#[from] anyhow::Error), #[error("Error message: {0}")] ErrorMessage(String), } impl From<String> for TaskError { fn from(message: String) -> Self { Self::ErrorMessage(message) } } impl From<TaskError> for Response { fn from(err: TaskError) -> Self { Response::Error(format!("{}", err)) } } enum TodoRequest { List, Add(Task), Update(u32, Task), Delete(u32), ClearCompleted, } impl TodoRequest { fn parse(uri: &str, body: Option<&str>) -> Result<Self, String> { let chunks: Vec<_> = uri.split(|c| c == '/').collect(); match &chunks[..] { [.., "list"] => Ok(Self::List), [.., "add"] => { let body = body.ok_or_else(|| "Task not specified".to_string())?; parse_task(body).map(Self::Add) } [.., "update", idx] => { let idx = parse_idx(idx)?; let body = body.ok_or_else(|| "Task not specified".to_string())?; parse_task(body).map(|task| Self::Update(idx, task)) } [.., "delete", idx] => parse_idx(idx).map(Self::Delete), [.., "clear_completed"] => Ok(Self::ClearCompleted), _ => Err(format!("Cannot parse uri {}, {:?}", uri, chunks)), } } fn process(self) -> Response { match self { Self::List => process_list().map(Response::List), Self::Add(task) => process_add(task).map(Response::List), Self::Update(idx, task) => process_update(idx, task).map(|_| Response::Empty), Self::Delete(idx) => process_delete(idx).map(Response::List), Self::ClearCompleted => process_clear_completed().map(Response::List), } .unwrap_or_else(Response::from) } } fn parse_idx(source: &str) -> Result<u32, String> { source .parse() .map_err(|err| format!("Parse task index error: {:?}", err)) } fn parse_task(source: &str) -> Result<Task, String> { serde_json::from_str(source).map_err(|err| format!("Parse task error: {:?}", err)) } fn process_list() -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::select_from(TASKS_TABLE_NAME).sql()?; let rows = query(sql)?; let mut tasks = Vec::with_capacity(rows.len()); for row in rows { tasks.push(task_from(row.into_values())?); } Ok(tasks) } fn process_add(task: Task) -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::insert_into(TASKS_TABLE_NAME) .fields(&["description", "completed"]) .values(&[quote(task.description), if task.completed { 1 } else { 0 }.to_string()]) .sql()?; execute(sql)?; process_list() } fn process_update(idx: u32, update: Task) -> Result<(), TaskError> { let sql = SqlBuilder::update_table(TASKS_TABLE_NAME) .set("description", quote(update.description)) .set("completed", update.completed) .and_where_eq("rowid", idx) .sql()?; execute(sql)?; execute("VACUUM")?; Ok(()) } fn process_delete(idx: u32) -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::delete_from(TASKS_TABLE_NAME) .and_where_eq("rowid", idx) .sql()?; execute(sql)?; execute("VACUUM")?; process_list() } fn process_clear_completed() -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::delete_from(TASKS_TABLE_NAME) .and_where_ne("completed", 0) .sql()?; execute(sql)?; execute("VACUUM")?; process_list() } fn task_from(values: Vec<Value>) -> Result<Task, String> { let mut task = Task::default(); let mut iter = values.into_iter(); match iter.next() { Some(Value::Text(description)) => task.description = description, Some(value) => Err(format!("Incorrect task description value: {:?}", value))?, None => Err("Task description value does not exist".to_string())?, } match iter.next() { Some(Value::Integer(completed)) => task.completed = completed != 0, Some(value) => Err(format!("Incorrect task completed value: {:?}", value))?, None => Err("Task completed value does not exist".to_string())?, } Ok(task) }
use borsh::BorshSerialize; pub use dapla_wasm::{alloc, dealloc}; use dapla_wasm::{ database::{execute, query, Value}, WasmSlice, }; use mindup_common::{Response, Task}; use sql_builder::{quote, SqlBuilder, SqlBuilderError}; use thiserror::Error; const TASKS_TABLE_NAME: &str = "Tasks"; #[no_mangle] pub unsafe extern "C" fn init() -> WasmSlice { let result = execute(format!( r"CREATE TABLE IF NOT EXISTS {table}( description TEXT NOT NULL,
.map_err(|err| format!("Parse task index error: {:?}", err)) } fn parse_task(source: &str) -> Result<Task, String> { serde_json::from_str(source).map_err(|err| format!("Parse task error: {:?}", err)) } fn process_list() -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::select_from(TASKS_TABLE_NAME).sql()?; let rows = query(sql)?; let mut tasks = Vec::with_capacity(rows.len()); for row in rows { tasks.push(task_from(row.into_values())?); } Ok(tasks) } fn process_add(task: Task) -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::insert_into(TASKS_TABLE_NAME) .fields(&["description", "completed"]) .values(&[quote(task.description), if task.completed { 1 } else { 0 }.to_string()]) .sql()?; execute(sql)?; process_list() } fn process_update(idx: u32, update: Task) -> Result<(), TaskError> { let sql = SqlBuilder::update_table(TASKS_TABLE_NAME) .set("description", quote(update.description)) .set("completed", update.completed) .and_where_eq("rowid", idx) .sql()?; execute(sql)?; execute("VACUUM")?; Ok(()) } fn process_delete(idx: u32) -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::delete_from(TASKS_TABLE_NAME) .and_where_eq("rowid", idx) .sql()?; execute(sql)?; execute("VACUUM")?; process_list() } fn process_clear_completed() -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::delete_from(TASKS_TABLE_NAME) .and_where_ne("completed", 0) .sql()?; execute(sql)?; execute("VACUUM")?; process_list() } fn task_from(values: Vec<Value>) -> Result<Task, String> { let mut task = Task::default(); let mut iter = values.into_iter(); match iter.next() { Some(Value::Text(description)) => task.description = description, Some(value) => Err(format!("Incorrect task description value: {:?}", value))?, None => Err("Task description value does not exist".to_string())?, } match iter.next() { Some(Value::Integer(completed)) => task.completed = completed != 0, Some(value) => Err(format!("Incorrect task completed value: {:?}", value))?, None => Err("Task completed value does not exist".to_string())?, } Ok(task) }
completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0,1)) );", table = TASKS_TABLE_NAME )); let data = result .map(drop) .try_to_vec() .expect("Init result should be serializable"); WasmSlice::from(data) } #[no_mangle] pub unsafe extern "C" fn get(uri: WasmSlice) -> WasmSlice { WasmSlice::from(do_get(uri.into_string_in_wasm())) } fn do_get(uri: String) -> String { let response = TodoRequest::parse(&uri, None) .map(|request| request.process()) .unwrap_or_else(Response::Error); serde_json::to_string(&response).unwrap_or_else(Response::json_error_from) } #[no_mangle] pub unsafe extern "C" fn post(uri: WasmSlice, body: WasmSlice) -> WasmSlice { WasmSlice::from(do_post(uri.into_string_in_wasm(), body.into_string_in_wasm())) } fn do_post(uri: String, body: String) -> String { let response = TodoRequest::parse(&uri, Some(&body)) .map(|request| request.process()) .unwrap_or_else(Response::Error); serde_json::to_string(&response).unwrap_or_else(Response::json_error_from) } #[derive(Debug, Error)] enum TaskError { #[error("Invalid SQL query: {0}")] Sql(#[from] SqlBuilderError), #[error("Error: {0}")] AnyhowError(#[from] anyhow::Error), #[error("Error message: {0}")] ErrorMessage(String), } impl From<String> for TaskError { fn from(message: String) -> Self { Self::ErrorMessage(message) } } impl From<TaskError> for Response { fn from(err: TaskError) -> Self { Response::Error(format!("{}", err)) } } enum TodoRequest { List, Add(Task), Update(u32, Task), Delete(u32), ClearCompleted, } impl TodoRequest { fn parse(uri: &str, body: Option<&str>) -> Result<Self, String> { let chunks: Vec<_> = uri.split(|c| c == '/').collect(); match &chunks[..] { [.., "list"] => Ok(Self::List), [.., "add"] => { let body = body.ok_or_else(|| "Task not specified".to_string())?; parse_task(body).map(Self::Add) } [.., "update", idx] => { let idx = parse_idx(idx)?; let body = body.ok_or_else(|| "Task not specified".to_string())?; parse_task(body).map(|task| Self::Update(idx, task)) } [.., "delete", idx] => parse_idx(idx).map(Self::Delete), [.., "clear_completed"] => Ok(Self::ClearCompleted), _ => Err(format!("Cannot parse uri {}, {:?}", uri, chunks)), } } fn process(self) -> Response { match self { Self::List => process_list().map(Response::List), Self::Add(task) => process_add(task).map(Response::List), Self::Update(idx, task) => process_update(idx, task).map(|_| Response::Empty), Self::Delete(idx) => process_delete(idx).map(Response::List), Self::ClearCompleted => process_clear_completed().map(Response::List), } .unwrap_or_else(Response::from) } } fn parse_idx(source: &str) -> Result<u32, String> { source .parse()
random
[ { "content": "fn main() {\n\n yew::start_app::<Root>();\n\n}\n", "file_path": "mindup_client/src/main.rs", "rank": 8, "score": 31229.389855600333 }, { "content": "use std::fmt;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Debug, Default, Clone, Deserialize, Serialize)]\n\np...
Rust
apis/clyde-3g-eps-api/examples/eps.rs
wau/kubos
074b61738a49ef87fbb08814285fa3173f4f32df
/* * Copyright (C) 2018 Kubos Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use clyde_3g_eps_api::*; use rust_i2c::*; use std::thread; use std::time::Duration; macro_rules! print_result { ($p:expr, $r:expr) => { match $r { Ok(v) => println!("{} - {:#?}", $p, v), Err(e) => println!("{} Err - {:#?}", $p, e), } }; } macro_rules! dump_mother_telem { ( $eps:expr, $($type:ident,)+ ) => { $( print_result!( format!("{:?}", MotherboardTelemetry::Type::$type), $eps.get_motherboard_telemetry(MotherboardTelemetry::Type::$type) ); thread::sleep(Duration::from_millis(100)); )+ }; } macro_rules! dump_daughter_telem { ( $eps:expr, $($type:ident,)+ ) => { $( print_result!( format!("{:?}", DaughterboardTelemetry::Type::$type), $eps.get_daughterboard_telemetry(DaughterboardTelemetry::Type::$type) ); thread::sleep(Duration::from_millis(100)); )+ }; } macro_rules! dump_reset_telem { ( $eps:expr, $($type:ident,)+ ) => { $( print_result!( format!("{:?}", ResetTelemetry::Type::$type), $eps.get_reset_telemetry(ResetTelemetry::Type::$type) ); thread::sleep(Duration::from_millis(100)); )+ }; } pub fn main() { let eps = Eps::new(Connection::from_path("/dev/i2c-1", 0x2B)); print_result!("Version Info", eps.get_version_info()); thread::sleep(Duration::from_millis(100)); print_result!("Board Status", eps.get_board_status()); thread::sleep(Duration::from_millis(100)); print_result!("Checksum", eps.get_checksum()); thread::sleep(Duration::from_millis(100)); print_result!("Last Error", eps.get_last_error()); thread::sleep(Duration::from_millis(100)); print_result!("Watchdog Period", eps.get_comms_watchdog_period()); thread::sleep(Duration::from_millis(100)); dump_mother_telem!( eps, VoltageFeedingBcr1, CurrentBcr1Sa1a, CurrentBcr1Sa1b, ArrayTempSa1a, ArrayTempSa1b, SunDetectorSa1a, SunDetectorSa1b, VoltageFeedingBcr2, CurrentBcr2Sa2a, CurrentBcr2Sa2b, ArrayTempSa2a, ArrayTempSa2b, SunDetectorSa2a, SunDetectorSa2b, VoltageFeedingBcr3, CurrentBcr3Sa3a, CurrentBcr3Sa3b, ArrayTempSa3a, ArrayTempSa3b, SunDetectorSa3a, SunDetectorSa3b, BcrOutputCurrent, BcrOutputVoltage, CurrentDraw3V3, CurrentDraw5V, OutputCurrent12V, OutputVoltage12V, OutputCurrentBattery, OutputVoltageBattery, OutputCurrent5v, OutputVoltage5v, OutputCurrent33v, OutputVoltage33v, OutputVoltageSwitch1, OutputCurrentSwitch1, OutputVoltageSwitch2, OutputCurrentSwitch2, OutputVoltageSwitch3, OutputCurrentSwitch3, OutputVoltageSwitch4, OutputCurrentSwitch4, OutputVoltageSwitch5, OutputCurrentSwitch5, OutputVoltageSwitch6, OutputCurrentSwitch6, OutputVoltageSwitch7, OutputCurrentSwitch7, OutputVoltageSwitch8, OutputCurrentSwitch8, OutputVoltageSwitch9, OutputCurrentSwitch9, OutputVoltageSwitch10, OutputCurrentSwitch10, BoardTemperature, ); dump_daughter_telem!( eps, VoltageFeedingBcr4, CurrentBcr4Sa4a, CurrentBcr4Sa4b, ArrayTempSa4a, ArrayTempSa4b, SunDetectorSa4a, SunDetectorSa4b, VoltageFeedingBcr5, CurrentBcr5Sa5a, CurrentBcr5Sa5b, ArrayTempSa5a, ArrayTempSa5b, SunDetectorSa5a, SunDetectorSa5b, VoltageFeedingBcr6, CurrentBcr6Sa6a, CurrentBcr6Sa6b, ArrayTempSa6a, ArrayTempSa6b, SunDetectorSa6a, SunDetectorSa6b, VoltageFeedingBcr7, CurrentBcr7Sa7a, CurrentBcr7Sa7b, ArrayTempSa7a, ArrayTempSa7b, SunDetectorSa7a, SunDetectorSa7b, VoltageFeedingBcr8, CurrentBcr8Sa8a, CurrentBcr8Sa8b, ArrayTempSa8a, ArrayTempSa8b, SunDetectorSa8a, SunDetectorSa8b, VoltageFeedingBcr9, CurrentBcr9Sa9a, CurrentBcr9Sa9b, ArrayTempSa9a, ArrayTempSa9b, SunDetectorSa9a, SunDetectorSa9b, BoardTemperature, ); dump_reset_telem!(eps, BrownOut, AutomaticSoftware, Manual, Watchdog,); }
/* * Copyright (C) 2018 Kubos Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance w
, ArrayTempSa1a, ArrayTempSa1b, SunDetectorSa1a, SunDetectorSa1b, VoltageFeedingBcr2, CurrentBcr2Sa2a, CurrentBcr2Sa2b, ArrayTempSa2a, ArrayTempSa2b, SunDetectorSa2a, SunDetectorSa2b, VoltageFeedingBcr3, CurrentBcr3Sa3a, CurrentBcr3Sa3b, ArrayTempSa3a, ArrayTempSa3b, SunDetectorSa3a, SunDetectorSa3b, BcrOutputCurrent, BcrOutputVoltage, CurrentDraw3V3, CurrentDraw5V, OutputCurrent12V, OutputVoltage12V, OutputCurrentBattery, OutputVoltageBattery, OutputCurrent5v, OutputVoltage5v, OutputCurrent33v, OutputVoltage33v, OutputVoltageSwitch1, OutputCurrentSwitch1, OutputVoltageSwitch2, OutputCurrentSwitch2, OutputVoltageSwitch3, OutputCurrentSwitch3, OutputVoltageSwitch4, OutputCurrentSwitch4, OutputVoltageSwitch5, OutputCurrentSwitch5, OutputVoltageSwitch6, OutputCurrentSwitch6, OutputVoltageSwitch7, OutputCurrentSwitch7, OutputVoltageSwitch8, OutputCurrentSwitch8, OutputVoltageSwitch9, OutputCurrentSwitch9, OutputVoltageSwitch10, OutputCurrentSwitch10, BoardTemperature, ); dump_daughter_telem!( eps, VoltageFeedingBcr4, CurrentBcr4Sa4a, CurrentBcr4Sa4b, ArrayTempSa4a, ArrayTempSa4b, SunDetectorSa4a, SunDetectorSa4b, VoltageFeedingBcr5, CurrentBcr5Sa5a, CurrentBcr5Sa5b, ArrayTempSa5a, ArrayTempSa5b, SunDetectorSa5a, SunDetectorSa5b, VoltageFeedingBcr6, CurrentBcr6Sa6a, CurrentBcr6Sa6b, ArrayTempSa6a, ArrayTempSa6b, SunDetectorSa6a, SunDetectorSa6b, VoltageFeedingBcr7, CurrentBcr7Sa7a, CurrentBcr7Sa7b, ArrayTempSa7a, ArrayTempSa7b, SunDetectorSa7a, SunDetectorSa7b, VoltageFeedingBcr8, CurrentBcr8Sa8a, CurrentBcr8Sa8b, ArrayTempSa8a, ArrayTempSa8b, SunDetectorSa8a, SunDetectorSa8b, VoltageFeedingBcr9, CurrentBcr9Sa9a, CurrentBcr9Sa9b, ArrayTempSa9a, ArrayTempSa9b, SunDetectorSa9a, SunDetectorSa9b, BoardTemperature, ); dump_reset_telem!(eps, BrownOut, AutomaticSoftware, Manual, Watchdog,); }
ith the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use clyde_3g_eps_api::*; use rust_i2c::*; use std::thread; use std::time::Duration; macro_rules! print_result { ($p:expr, $r:expr) => { match $r { Ok(v) => println!("{} - {:#?}", $p, v), Err(e) => println!("{} Err - {:#?}", $p, e), } }; } macro_rules! dump_mother_telem { ( $eps:expr, $($type:ident,)+ ) => { $( print_result!( format!("{:?}", MotherboardTelemetry::Type::$type), $eps.get_motherboard_telemetry(MotherboardTelemetry::Type::$type) ); thread::sleep(Duration::from_millis(100)); )+ }; } macro_rules! dump_daughter_telem { ( $eps:expr, $($type:ident,)+ ) => { $( print_result!( format!("{:?}", DaughterboardTelemetry::Type::$type), $eps.get_daughterboard_telemetry(DaughterboardTelemetry::Type::$type) ); thread::sleep(Duration::from_millis(100)); )+ }; } macro_rules! dump_reset_telem { ( $eps:expr, $($type:ident,)+ ) => { $( print_result!( format!("{:?}", ResetTelemetry::Type::$type), $eps.get_reset_telemetry(ResetTelemetry::Type::$type) ); thread::sleep(Duration::from_millis(100)); )+ }; } pub fn main() { let eps = Eps::new(Connection::from_path("/dev/i2c-1", 0x2B)); print_result!("Version Info", eps.get_version_info()); thread::sleep(Duration::from_millis(100)); print_result!("Board Status", eps.get_board_status()); thread::sleep(Duration::from_millis(100)); print_result!("Checksum", eps.get_checksum()); thread::sleep(Duration::from_millis(100)); print_result!("Last Error", eps.get_last_error()); thread::sleep(Duration::from_millis(100)); print_result!("Watchdog Period", eps.get_comms_watchdog_period()); thread::sleep(Duration::from_millis(100)); dump_mother_telem!( eps, VoltageFeedingBcr1, CurrentBcr1Sa1a, CurrentBcr1Sa1b
random
[ { "content": " const char* file;\n", "file_path": "cmocka/cmocka-1.1.0/include/cmocka.h", "rank": 0, "score": 132737.9092915765 }, { "content": "/// Fetch information about the version(s) of KubOS installed in the system\n\n///\n\n/// Returns the current and previous version(s) of KubOS.\...
Rust
examples/todomvc/src/store.rs
tlively/wasm-bindgen
64e53a5502d92143ff312d461c286cc22522c8ae
use js_sys::JSON; use wasm_bindgen::prelude::*; pub struct Store { local_storage: web_sys::Storage, data: ItemList, name: String, } impl Store { pub fn new(name: &str) -> Option<Store> { let window = web_sys::window()?; if let Ok(Some(local_storage)) = window.local_storage() { let mut store = Store { local_storage, data: ItemList::new(), name: String::from(name), }; store.fetch_local_storage(); Some(store) } else { None } } fn fetch_local_storage(&mut self) -> Option<()> { let mut item_list = ItemList::new(); if let Ok(Some(value)) = self.local_storage.get_item(&self.name) { let data = JSON::parse(&value).ok()?; let iter = js_sys::try_iter(&data).ok()??; for item in iter { let item = item.ok()?; let item_array: &js_sys::Array = wasm_bindgen::JsCast::dyn_ref(&item)?; let title = item_array.shift().as_string()?; let completed = item_array.shift().as_bool()?; let id = item_array.shift().as_string()?; let temp_item = Item { title, completed, id, }; item_list.push(temp_item); } } self.data = item_list; Some(()) } fn sync_local_storage(&mut self) { let array = js_sys::Array::new(); for item in self.data.iter() { let child = js_sys::Array::new(); child.push(&JsValue::from(&item.title)); child.push(&JsValue::from(item.completed)); child.push(&JsValue::from(&item.id)); array.push(&JsValue::from(child)); } if let Ok(storage_string) = JSON::stringify(&JsValue::from(array)) { let storage_string: String = storage_string.into(); self.local_storage .set_item(&self.name, &storage_string) .unwrap(); } } pub fn find(&mut self, query: ItemQuery) -> Option<ItemListSlice<'_>> { Some( self.data .iter() .filter(|todo| query.matches(todo)) .collect(), ) } pub fn update(&mut self, update: ItemUpdate) { let id = update.id(); self.data.iter_mut().for_each(|todo| { if id == todo.id { todo.update(&update); } }); self.sync_local_storage(); } pub fn insert(&mut self, item: Item) { self.data.push(item); self.sync_local_storage(); } pub fn remove(&mut self, query: ItemQuery) { self.data.retain(|todo| !query.matches(todo)); self.sync_local_storage(); } pub fn count(&mut self) -> Option<(usize, usize, usize)> { self.find(ItemQuery::EmptyItemQuery).map(|data| { let total = data.length(); let mut completed = 0; for item in data.iter() { if item.completed { completed += 1; } } (total, total - completed, completed) }) } } pub struct Item { pub id: String, pub title: String, pub completed: bool, } impl Item { pub fn update(&mut self, update: &ItemUpdate) { match update { ItemUpdate::Title { title, .. } => { self.title = title.to_string(); } ItemUpdate::Completed { completed, .. } => { self.completed = *completed; } } } } pub trait ItemListTrait<T> { fn new() -> Self; fn get(&self, i: usize) -> Option<&T>; fn length(&self) -> usize; fn push(&mut self, item: T); fn iter(&self) -> std::slice::Iter<'_, T>; } pub struct ItemList { list: Vec<Item>, } impl ItemList { fn retain<F>(&mut self, f: F) where F: FnMut(&Item) -> bool, { self.list.retain(f); } fn iter_mut(&mut self) -> std::slice::IterMut<'_, Item> { self.list.iter_mut() } } impl ItemListTrait<Item> for ItemList { fn new() -> ItemList { ItemList { list: Vec::new() } } fn get(&self, i: usize) -> Option<&Item> { self.list.get(i) } fn length(&self) -> usize { self.list.len() } fn push(&mut self, item: Item) { self.list.push(item) } fn iter(&self) -> std::slice::Iter<'_, Item> { self.list.iter() } } use std::iter::FromIterator; impl<'a> FromIterator<Item> for ItemList { fn from_iter<I: IntoIterator<Item = Item>>(iter: I) -> Self { let mut c = ItemList::new(); for i in iter { c.push(i); } c } } pub struct ItemListSlice<'a> { list: Vec<&'a Item>, } impl<'a> ItemListTrait<&'a Item> for ItemListSlice<'a> { fn new() -> ItemListSlice<'a> { ItemListSlice { list: Vec::new() } } fn get(&self, i: usize) -> Option<&&'a Item> { self.list.get(i) } fn length(&self) -> usize { self.list.len() } fn push(&mut self, item: &'a Item) { self.list.push(item) } fn iter(&self) -> std::slice::Iter<'_, &'a Item> { self.list.iter() } } impl<'a> FromIterator<&'a Item> for ItemListSlice<'a> { fn from_iter<I: IntoIterator<Item = &'a Item>>(iter: I) -> Self { let mut c = ItemListSlice::new(); for i in iter { c.push(i); } c } } impl<'a> Into<ItemList> for ItemListSlice<'a> { fn into(self) -> ItemList { let mut i = ItemList::new(); let items = self.list.into_iter(); for j in items { let item = Item { id: j.id.clone(), completed: j.completed, title: j.title.clone(), }; i.push(item); } i } } pub enum ItemQuery { Id { id: String }, Completed { completed: bool }, EmptyItemQuery, } impl ItemQuery { fn matches(&self, item: &Item) -> bool { match *self { ItemQuery::EmptyItemQuery => true, ItemQuery::Id { ref id } => &item.id == id, ItemQuery::Completed { completed } => item.completed == completed, } } } pub enum ItemUpdate { Title { id: String, title: String }, Completed { id: String, completed: bool }, } impl ItemUpdate { fn id(&self) -> String { match self { ItemUpdate::Title { id, .. } => id.clone(), ItemUpdate::Completed { id, .. } => id.clone(), } } }
use js_sys::JSON; use wasm_bindgen::prelude::*; pub struct Store { local_storage: web_sys::Storage, data: ItemList, name: String, } impl Store { pub fn new(name: &str) -> Option<Store> { let window = web_sys::window()?; if let Ok(Some(local_storage)) = window.local_storage() { let mut store = Store { local_storage, data: ItemList::new(), name: String::from(name), }; store.fetch_local_storage(); Some(store) } else { None } } fn fetch_local_storage(&mut self) -> Option<()> { let mut item_list = ItemList::new();
self.data = item_list; Some(()) } fn sync_local_storage(&mut self) { let array = js_sys::Array::new(); for item in self.data.iter() { let child = js_sys::Array::new(); child.push(&JsValue::from(&item.title)); child.push(&JsValue::from(item.completed)); child.push(&JsValue::from(&item.id)); array.push(&JsValue::from(child)); } if let Ok(storage_string) = JSON::stringify(&JsValue::from(array)) { let storage_string: String = storage_string.into(); self.local_storage .set_item(&self.name, &storage_string) .unwrap(); } } pub fn find(&mut self, query: ItemQuery) -> Option<ItemListSlice<'_>> { Some( self.data .iter() .filter(|todo| query.matches(todo)) .collect(), ) } pub fn update(&mut self, update: ItemUpdate) { let id = update.id(); self.data.iter_mut().for_each(|todo| { if id == todo.id { todo.update(&update); } }); self.sync_local_storage(); } pub fn insert(&mut self, item: Item) { self.data.push(item); self.sync_local_storage(); } pub fn remove(&mut self, query: ItemQuery) { self.data.retain(|todo| !query.matches(todo)); self.sync_local_storage(); } pub fn count(&mut self) -> Option<(usize, usize, usize)> { self.find(ItemQuery::EmptyItemQuery).map(|data| { let total = data.length(); let mut completed = 0; for item in data.iter() { if item.completed { completed += 1; } } (total, total - completed, completed) }) } } pub struct Item { pub id: String, pub title: String, pub completed: bool, } impl Item { pub fn update(&mut self, update: &ItemUpdate) { match update { ItemUpdate::Title { title, .. } => { self.title = title.to_string(); } ItemUpdate::Completed { completed, .. } => { self.completed = *completed; } } } } pub trait ItemListTrait<T> { fn new() -> Self; fn get(&self, i: usize) -> Option<&T>; fn length(&self) -> usize; fn push(&mut self, item: T); fn iter(&self) -> std::slice::Iter<'_, T>; } pub struct ItemList { list: Vec<Item>, } impl ItemList { fn retain<F>(&mut self, f: F) where F: FnMut(&Item) -> bool, { self.list.retain(f); } fn iter_mut(&mut self) -> std::slice::IterMut<'_, Item> { self.list.iter_mut() } } impl ItemListTrait<Item> for ItemList { fn new() -> ItemList { ItemList { list: Vec::new() } } fn get(&self, i: usize) -> Option<&Item> { self.list.get(i) } fn length(&self) -> usize { self.list.len() } fn push(&mut self, item: Item) { self.list.push(item) } fn iter(&self) -> std::slice::Iter<'_, Item> { self.list.iter() } } use std::iter::FromIterator; impl<'a> FromIterator<Item> for ItemList { fn from_iter<I: IntoIterator<Item = Item>>(iter: I) -> Self { let mut c = ItemList::new(); for i in iter { c.push(i); } c } } pub struct ItemListSlice<'a> { list: Vec<&'a Item>, } impl<'a> ItemListTrait<&'a Item> for ItemListSlice<'a> { fn new() -> ItemListSlice<'a> { ItemListSlice { list: Vec::new() } } fn get(&self, i: usize) -> Option<&&'a Item> { self.list.get(i) } fn length(&self) -> usize { self.list.len() } fn push(&mut self, item: &'a Item) { self.list.push(item) } fn iter(&self) -> std::slice::Iter<'_, &'a Item> { self.list.iter() } } impl<'a> FromIterator<&'a Item> for ItemListSlice<'a> { fn from_iter<I: IntoIterator<Item = &'a Item>>(iter: I) -> Self { let mut c = ItemListSlice::new(); for i in iter { c.push(i); } c } } impl<'a> Into<ItemList> for ItemListSlice<'a> { fn into(self) -> ItemList { let mut i = ItemList::new(); let items = self.list.into_iter(); for j in items { let item = Item { id: j.id.clone(), completed: j.completed, title: j.title.clone(), }; i.push(item); } i } } pub enum ItemQuery { Id { id: String }, Completed { completed: bool }, EmptyItemQuery, } impl ItemQuery { fn matches(&self, item: &Item) -> bool { match *self { ItemQuery::EmptyItemQuery => true, ItemQuery::Id { ref id } => &item.id == id, ItemQuery::Completed { completed } => item.completed == completed, } } } pub enum ItemUpdate { Title { id: String, title: String }, Completed { id: String, completed: bool }, } impl ItemUpdate { fn id(&self) -> String { match self { ItemUpdate::Title { id, .. } => id.clone(), ItemUpdate::Completed { id, .. } => id.clone(), } } }
if let Ok(Some(value)) = self.local_storage.get_item(&self.name) { let data = JSON::parse(&value).ok()?; let iter = js_sys::try_iter(&data).ok()??; for item in iter { let item = item.ok()?; let item_array: &js_sys::Array = wasm_bindgen::JsCast::dyn_ref(&item)?; let title = item_array.shift().as_string()?; let completed = item_array.shift().as_bool()?; let id = item_array.shift().as_string()?; let temp_item = Item { title, completed, id, }; item_list.push(temp_item); } }
if_condition
[ { "content": "#[wasm_bindgen]\n\npub fn return_optional_str_none() -> Option<String> {\n\n None\n\n}\n\n\n", "file_path": "tests/wasm/simple.rs", "rank": 0, "score": 469336.6002525708 }, { "content": "#[wasm_bindgen]\n\npub fn take_optional_str_none(x: Option<String>) {\n\n assert!(x.i...
Rust
circlemud_ffi_client/src/slack_descriptor.rs
medwards/CircleMUD
f24154b52cceec7df93d750816c4aea7e332cc29
use std::collections::{HashMap, HashSet}; use std::sync::mpsc; use std::sync::Mutex; use std::thread; use slack_morphism::prelude::*; use slack_morphism_hyper::*; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response}; use log::*; use tokio::runtime::Runtime; use std::sync::Arc; use crate::descriptor; use crate::descriptor::Descriptor; pub struct SlackDescriptorManager { server: thread::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>, bot_token: SlackApiTokenValue, descriptors: HashMap<String, Box<dyn descriptor::Descriptor>>, new_descriptors: mpsc::Receiver<SlackDescriptor>, } impl SlackDescriptorManager { pub fn new(signing_secret: &str, bot_token: SlackApiTokenValue) -> Self { let (new_descriptors_send, new_descriptors) = mpsc::channel(); SlackDescriptorManager { server: SlackDescriptorManager::launch_server( signing_secret.to_owned(), SlackApiToken::new(bot_token.clone()), new_descriptors_send, ), bot_token: bot_token, descriptors: HashMap::new(), new_descriptors: new_descriptors, } } fn launch_server( signing_secret: String, bot_token: SlackApiToken, new_descriptors_sender: mpsc::Sender<SlackDescriptor>, ) -> thread::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>> { thread::spawn(|| { let runtime = Runtime::new().expect("Unable to create Runtime"); info!("Launching Slack Event API callback server"); runtime.block_on(async { init_log()?; let hyper_connector = SlackClientHyperConnector::new(); let client: Arc<SlackHyperClient> = Arc::new(SlackClient::new(hyper_connector)); create_server(client, signing_secret, bot_token, new_descriptors_sender).await }) }) } } impl descriptor::DescriptorManager for SlackDescriptorManager { fn get_new_descriptor(&mut self) -> Option<descriptor::DescriptorId> { match self.new_descriptors.try_recv() { Ok(descriptor) => { let ret = descriptor.identifier().clone(); self.descriptors .insert(ret.identifier.clone(), Box::new(descriptor)); Some(ret) } Err(mpsc::TryRecvError::Empty) => None, Err(_) => panic!("Channel for receiving new SlackDescriptors unexpectedly closed"), } } fn get_descriptor( &mut self, descriptor: &descriptor::DescriptorId, ) -> Option<&mut Box<dyn descriptor::Descriptor>> { self.descriptors.get_mut(&descriptor.identifier) } fn close_descriptor(&mut self, descriptor: &descriptor::DescriptorId) { info!("closing {:#?}", descriptor); self.descriptors.remove(&descriptor.identifier); } } async fn push_events_handler( event: SlackPushEvent, _client: Arc<SlackHyperClient>, bot_token: &SlackApiToken, new_descriptors_sender: Arc<Mutex<mpsc::Sender<SlackDescriptor>>>, message_senders: Arc<Mutex<HashMap<String, mpsc::Sender<SlackMessageContent>>>>, ) { info!("{}", display_push_event(&event)); debug!("{:#?}", event); if let SlackPushEvent::EventCallback(callback) = event { if let SlackEventCallbackBody::Message(message) = callback.event { if let Some(channel_type) = message.origin.channel_type { if channel_type == SlackChannelType("im".to_owned()) && message.sender.bot_id.is_none() { let mut message_senders = message_senders .lock() .expect("Unable to get lock for senders hashmap"); if let Some(channel) = message.origin.channel { let key = channel.to_string(); if !message_senders.contains_key(&key) { insert_new_session_for_channel( channel.clone(), bot_token.clone(), new_descriptors_sender, &mut message_senders, ); info!("New Events connection from {:?}", channel); } else if let Some(content) = message.content { match message_senders .get(&key) .expect("Sender went missing") .send(content.clone()) { Ok(()) => info!("Sent event from {:?} to descriptor", channel), Err(e) => { insert_new_session_for_channel( channel.clone(), bot_token.clone(), new_descriptors_sender, &mut message_senders, ); info!( "Old events connection failed for {:?}, creating a new one", channel ) } } } } } } } } } fn insert_new_session_for_channel( channel: SlackChannelId, bot_token: SlackApiToken, new_descriptors_sender: Arc<Mutex<mpsc::Sender<SlackDescriptor>>>, message_senders: &mut HashMap<String, mpsc::Sender<SlackMessageContent>>, ) { let (sender, receiver) = mpsc::channel(); message_senders.insert(channel.to_string(), sender); new_descriptors_sender .lock() .expect("Unable to lock SlackDescriptor sender") .send(SlackDescriptor::new(channel.clone(), receiver, bot_token)) .expect(&format!( "Unable to send new SlackDescriptor {:?} to SlackDescriptorManager", channel )); } fn display_push_event(event: &SlackPushEvent) -> String { match event { SlackPushEvent::EventCallback(cb) => match &cb.event { SlackEventCallbackBody::Message(message) => format!( "{:?} {:?} {:?} - had text content {:?}", message.origin.channel, message.origin.channel_type, message.subtype, message .content .as_ref() .and_then(|c| c.text.as_ref()) .is_some() ), _ => format!("unexpected event"), }, SlackPushEvent::AppRateLimited(event) => { format!("AppRateLimited event {:?}", event.minute_rate_limited) } _ => "unexpected push event".to_owned(), } } fn test_error_handler( err: Box<dyn std::error::Error + Send + Sync>, _client: Arc<SlackHyperClient>, ) { println!("{:#?}", err); } async fn create_server( client: Arc<SlackHyperClient>, signing_secret: String, bot_token: SlackApiToken, new_descriptors_sender: mpsc::Sender<SlackDescriptor>, ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let addr = std::env::var("SLACK_SOCKET_ADDR") .unwrap_or("127.0.0.1:8000".to_owned()) .parse() .expect("Invalid SLACK_SOCKET_ADDR provided"); info!("Loading server: {}", addr); async fn your_others_routes( _req: Request<Body>, ) -> Result<Response<Body>, Box<dyn std::error::Error + Send + Sync>> { Response::builder() .body("Hey, this is a default users route handler".into()) .map_err(|e| e.into()) } let push_events_config = Arc::new(SlackPushEventsListenerConfig::new(signing_secret)); let message_senders = Arc::new(Mutex::new(HashMap::new())); let new_descriptors_sender = Arc::new(Mutex::new(new_descriptors_sender)); let wrapped_push_events_handler = move |event, client| { let message_senders_clone = message_senders.clone(); let new_descriptors_sender_clone = new_descriptors_sender.clone(); let bot_token_clone = bot_token.clone(); async move { push_events_handler( event, client, &bot_token_clone, new_descriptors_sender_clone, message_senders_clone, ) .await } }; let make_svc = make_service_fn(move |_| { let thread_push_events_config = push_events_config.clone(); let wrapped_p_clone = wrapped_push_events_handler.clone(); let listener_environment = SlackClientEventsListenerEnvironment::new(client.clone()) .with_error_handler(test_error_handler); let listener = SlackClientEventsHyperListener::new(listener_environment); async move { let routes = chain_service_routes_fn( listener.push_events_service_fn(thread_push_events_config, wrapped_p_clone), your_others_routes, ); Ok::<_, Box<dyn std::error::Error + Send + Sync>>(service_fn(routes)) } }); let server = hyper::server::Server::bind(&addr).serve(make_svc); server.await.map_err(|e| { error!("Server error: {}", e); e.into() }) } fn init_log() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { use fern::colors::{Color, ColoredLevelConfig}; let colors_level = ColoredLevelConfig::new() .info(Color::Green) .warn(Color::Magenta); fern::Dispatch::new() .format(move |out, message, record| { out.finish(format_args!( "{}[{}][{}] {}{}\x1B[0m", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), colors_level.color(record.level()), format_args!( "\x1B[{}m", colors_level.get_color(&record.level()).to_fg_str() ), message )) }) .level(log::LevelFilter::Info) .level_for("hyper", log::LevelFilter::Info) .chain(std::io::stdout()) .apply()?; Ok(()) } pub struct SlackDescriptor { slack_bot_token: SlackApiToken, input_channel: Arc<Mutex<mpsc::Receiver<SlackMessageContent>>>, channel_id: SlackChannelId, identifier: descriptor::DescriptorId, user_id: u32, } impl SlackDescriptor { pub fn new( channel_id: SlackChannelId, input_channel: mpsc::Receiver<SlackMessageContent>, token: SlackApiToken, ) -> Self { let identifier = descriptor::DescriptorId { identifier: channel_id.to_string(), descriptor_type: "SLACK".to_owned(), }; SlackDescriptor { slack_bot_token: token, input_channel: Arc::new(Mutex::new(input_channel)), channel_id: channel_id, identifier: identifier, user_id: 0, } } async fn send_message( &self, content: SlackMessageContent, ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { info!( "chat_post_message response: {:?} to {:?}", content.clone().text.map(|mut s| s.truncate(10)), self.channel_id ); let request = SlackApiChatPostMessageRequest::new(self.channel_id.clone(), content); let hyper_connector = SlackClientHyperConnector::new(); let client = SlackClient::new(hyper_connector); let session = client.open_session(&self.slack_bot_token); session .chat_post_message(&request) .await .map(|_response| ()) } } impl descriptor::Descriptor for SlackDescriptor { fn identifier(&self) -> &descriptor::DescriptorId { &self.identifier } fn read(&mut self, buf: &mut [u8]) -> Result<usize, descriptor::ErrorCode> { let temp = self .input_channel .lock() .expect("Unable to get lock on input channel") .try_recv(); match temp { Ok(content) => { let text_raw = format!("{}\n", content.text.expect("text content was empty")); let text = text_raw.as_bytes(); if text.len() > buf.len() { println!( "ERROR got slack message bigger than buffer CircleMUD allocated ({} > {}", text.len(), buf.len() ); return Err(1); } let common_length = std::cmp::min(text.len(), buf.len()); buf[0..common_length].copy_from_slice(&text[0..common_length]); Ok(common_length) } Err(mpsc::TryRecvError::Empty) => Ok(0), Err(_) => Err(2), } } fn write(&mut self, content: String) -> Result<usize, descriptor::ErrorCode> { let runtime = tokio::runtime::Builder::new_current_thread() .enable_io() .enable_time() .build() .expect("Failed to create local runtime"); match runtime .block_on(self.send_message(SlackMessageContent::new().with_text(content.clone()))) { Ok(()) => Ok(content.as_bytes().len()), Err(_) => Err(1), } } }
use std::collections::{HashMap, HashSet}; use std::sync::mpsc; use std::sync::Mutex; use std::thread; use slack_morphism::prelude::*; use slack_morphism_hyper::*; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response}; use log::*; use tokio::runtime::Runtime; use std::sync::Arc; use crate::descriptor; use crate::descriptor::Descriptor; pub struct SlackDescriptorManager { server: thread::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>, bot_token: SlackApiTokenValue, descriptors: HashMap<String, Box<dyn descriptor::Descriptor>>, new_descriptors: mpsc::Receiver<SlackDescriptor>, } impl SlackDescriptorManager { pub fn new(signing_secret: &str, bot_token: SlackApiTokenValue) -> Self { let (new_descriptors_send, new_descriptors) = mpsc::channel(); SlackDescriptorManager { server: SlackDescriptorManager::launch_server( signing_secret.to_owned(), SlackApiToken::new(bot_token.clone()), new_descriptors_send, ), bot_token: bot_token, descriptors: HashMap::new(), new_descriptors: new_descriptors, } } fn launch_server( signing_secret: String, bot_token: SlackApiToken, new_descriptors_sender: mpsc::Sender<SlackDescriptor>, ) -> thread::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>> { thread::spawn(|| { let runtime = Runtime::new().expect("Unable to create Runtime"); info!("Launching Slack Event API callback server"); runtime.block_on(async { init_log()?; let hyper_connector = SlackClientHyperConnector::new(); let client: Arc<SlackHyperClient> = Arc::new(SlackClient::new(hyper_connector)); create_server(client, signing_secret, bot_token, new_descriptors_sender).await }) }) } } impl descriptor::DescriptorManager for SlackDescriptorManager { fn get_new_descriptor(&mut self) -> Option<descriptor::DescriptorId> { match self.new_descriptors.try_recv() { Ok(descriptor) => { let ret = descriptor.identifier().clone(); self.descriptors .insert(ret.identifier.clone(), Box::new(descriptor)); Some(ret) } Err(mpsc::TryRecvError::Empty) => None, Err(_) => panic!("Channel for receiving new SlackDescriptors unexpectedly closed"), } } fn get_descriptor( &mut self, descriptor: &descriptor::DescriptorId, ) -> Option<&mut Box<dyn descriptor::Descriptor>> { self.descriptors.get_mut(&descriptor.identifier) } fn close_descriptor(&mut self, descriptor: &descriptor::DescriptorId) { info!("closing {:#?}", descriptor); self.descriptors.remove(&descriptor.identifier); } } async fn push_events_handler( event: SlackPushEvent, _client: Arc<SlackHyperClient>, bot_token: &SlackApiToken, new_descriptors_sender: Arc<Mutex<mpsc::Sender<SlackDescriptor>>>, message_senders: Arc<Mutex<HashMap<String, mpsc::Sender<SlackMessageContent>>>>, ) { info!("{}", display_push_event(&event)); debug!("{:#?}", event); if let SlackPushEvent::EventCallback(callback) = event { if let SlackEventCallbackBody::Message(message) = callback.event { if let Some(channel_type) = message.origin.channel_type { if channel_type == SlackChannelType("im".to_owned()) && message.sender.bot_id.is_none() { let mut message_senders = message_senders .lock() .expect("Unable to get lock for senders hashmap"); if let Some(channel) = message.origin.channel { let key = channel.to_string(); if !message_senders.contains_key(&key) { insert_new_session_for_channel( channel.clone(), bot_token.clone(), new_descriptors_sender, &mut message_senders, ); info!("New Events connection from {:?}", channel); } else if let Some(content) = message.content { match message_senders .get(&key) .expect("Sender went missing") .send(content.clone()) { Ok(()) => info!("Sent event from {:?} to descriptor", channel), Err(e) => { insert_new_session_for_channel( channel.clone(), bot_token.clone(), new_descriptors_sender, &mut message_senders, ); info!( "Old events connection failed for {:?}, creating a new one", channel ) } } } } } } } } } fn insert_new_session_for_channel( channel: SlackChannelId, bot_token: SlackApiToken, new_descriptors_sender: Arc<Mutex<mpsc::Sender<SlackDescriptor>>>, message_senders: &mut HashMap<String, mpsc::Sender<SlackMessageContent>>, ) { let (sender, receiver) = mpsc::channel(); message_senders.insert(channel.to_string(), sender); new_descriptors_sender .lock() .expect("Unable to lock SlackDescriptor sender") .send(SlackDescriptor::new(channel.clone(), receiver, bot_token)) .expect(&format!( "Unable to send new SlackDescriptor {:?} to SlackDescriptorManager", channel )); } fn display_push_event(event: &SlackPushEvent) -> String { match event { SlackPushEvent::EventCallback(cb) => match &cb.event { SlackEventCallbackBody::Message(message) => format!( "{:?} {:?} {:?} - had text content {:?}", message.origin.channel, message.origin.channel_type, message.subtype, message .content .as_ref() .and_then(|c| c.text.as_ref()) .is_some() ), _ => format!("unexpected event"), }, SlackPushEvent::AppRateLimited(event) => { format!("AppRateLimited event {:?}", event.minute_rate_limited) } _ => "unexpected push event".to_owned(), } } fn test_error_handler( err: Box<dyn std::error::Error + Send + Sync>, _client: Arc<SlackHyperClient>, ) { println!("{:#?}", err); } async fn create_server( client: Arc<SlackHyperClient>, signing_secret: String, bot_token: SlackApiToken, new_descriptors_sender: mpsc::Sender<SlackDescriptor>, ) -> Result<(), Box<dyn std::er
channel: Arc::new(Mutex::new(input_channel)), channel_id: channel_id, identifier: identifier, user_id: 0, } } async fn send_message( &self, content: SlackMessageContent, ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { info!( "chat_post_message response: {:?} to {:?}", content.clone().text.map(|mut s| s.truncate(10)), self.channel_id ); let request = SlackApiChatPostMessageRequest::new(self.channel_id.clone(), content); let hyper_connector = SlackClientHyperConnector::new(); let client = SlackClient::new(hyper_connector); let session = client.open_session(&self.slack_bot_token); session .chat_post_message(&request) .await .map(|_response| ()) } } impl descriptor::Descriptor for SlackDescriptor { fn identifier(&self) -> &descriptor::DescriptorId { &self.identifier } fn read(&mut self, buf: &mut [u8]) -> Result<usize, descriptor::ErrorCode> { let temp = self .input_channel .lock() .expect("Unable to get lock on input channel") .try_recv(); match temp { Ok(content) => { let text_raw = format!("{}\n", content.text.expect("text content was empty")); let text = text_raw.as_bytes(); if text.len() > buf.len() { println!( "ERROR got slack message bigger than buffer CircleMUD allocated ({} > {}", text.len(), buf.len() ); return Err(1); } let common_length = std::cmp::min(text.len(), buf.len()); buf[0..common_length].copy_from_slice(&text[0..common_length]); Ok(common_length) } Err(mpsc::TryRecvError::Empty) => Ok(0), Err(_) => Err(2), } } fn write(&mut self, content: String) -> Result<usize, descriptor::ErrorCode> { let runtime = tokio::runtime::Builder::new_current_thread() .enable_io() .enable_time() .build() .expect("Failed to create local runtime"); match runtime .block_on(self.send_message(SlackMessageContent::new().with_text(content.clone()))) { Ok(()) => Ok(content.as_bytes().len()), Err(_) => Err(1), } } }
ror::Error + Send + Sync>> { let addr = std::env::var("SLACK_SOCKET_ADDR") .unwrap_or("127.0.0.1:8000".to_owned()) .parse() .expect("Invalid SLACK_SOCKET_ADDR provided"); info!("Loading server: {}", addr); async fn your_others_routes( _req: Request<Body>, ) -> Result<Response<Body>, Box<dyn std::error::Error + Send + Sync>> { Response::builder() .body("Hey, this is a default users route handler".into()) .map_err(|e| e.into()) } let push_events_config = Arc::new(SlackPushEventsListenerConfig::new(signing_secret)); let message_senders = Arc::new(Mutex::new(HashMap::new())); let new_descriptors_sender = Arc::new(Mutex::new(new_descriptors_sender)); let wrapped_push_events_handler = move |event, client| { let message_senders_clone = message_senders.clone(); let new_descriptors_sender_clone = new_descriptors_sender.clone(); let bot_token_clone = bot_token.clone(); async move { push_events_handler( event, client, &bot_token_clone, new_descriptors_sender_clone, message_senders_clone, ) .await } }; let make_svc = make_service_fn(move |_| { let thread_push_events_config = push_events_config.clone(); let wrapped_p_clone = wrapped_push_events_handler.clone(); let listener_environment = SlackClientEventsListenerEnvironment::new(client.clone()) .with_error_handler(test_error_handler); let listener = SlackClientEventsHyperListener::new(listener_environment); async move { let routes = chain_service_routes_fn( listener.push_events_service_fn(thread_push_events_config, wrapped_p_clone), your_others_routes, ); Ok::<_, Box<dyn std::error::Error + Send + Sync>>(service_fn(routes)) } }); let server = hyper::server::Server::bind(&addr).serve(make_svc); server.await.map_err(|e| { error!("Server error: {}", e); e.into() }) } fn init_log() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { use fern::colors::{Color, ColoredLevelConfig}; let colors_level = ColoredLevelConfig::new() .info(Color::Green) .warn(Color::Magenta); fern::Dispatch::new() .format(move |out, message, record| { out.finish(format_args!( "{}[{}][{}] {}{}\x1B[0m", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), colors_level.color(record.level()), format_args!( "\x1B[{}m", colors_level.get_color(&record.level()).to_fg_str() ), message )) }) .level(log::LevelFilter::Info) .level_for("hyper", log::LevelFilter::Info) .chain(std::io::stdout()) .apply()?; Ok(()) } pub struct SlackDescriptor { slack_bot_token: SlackApiToken, input_channel: Arc<Mutex<mpsc::Receiver<SlackMessageContent>>>, channel_id: SlackChannelId, identifier: descriptor::DescriptorId, user_id: u32, } impl SlackDescriptor { pub fn new( channel_id: SlackChannelId, input_channel: mpsc::Receiver<SlackMessageContent>, token: SlackApiToken, ) -> Self { let identifier = descriptor::DescriptorId { identifier: channel_id.to_string(), descriptor_type: "SLACK".to_owned(), }; SlackDescriptor { slack_bot_token: token, input_
random
[ { "content": "// TODO: this should probably just require the Read trait\n\npub trait Descriptor: Send + Sync {\n\n fn identifier(&self) -> &DescriptorId;\n\n fn read(&mut self, read_point: &mut [u8]) -> Result<usize, ErrorCode>;\n\n fn write(&mut self, content: String) -> Result<usize, ErrorCode>;\n\n}...
Rust
src/io/sequences_reader.rs
Guilucand/biloki
7c1d710bd03e797584e7f4db151d7b4c7b4433d7
use crate::io::lines_reader::LinesReader; use bstr::ByteSlice; use nix::sys::signal::{self, Signal}; use nix::unistd::Pid; use rand::Rng; use serde::Serialize; use std::fs::File; use std::hint::unreachable_unchecked; use std::intrinsics::unlikely; use std::io::{BufRead, BufReader, Read}; use std::num::Wrapping; use std::path::{Path, PathBuf}; use std::process::Command; use std::process::Stdio; use std::ptr::null_mut; use std::slice::from_raw_parts; const IDENT_STATE: usize = 0; const SEQ_STATE: usize = 1; const QUAL_STATE: usize = 2; enum FileType { Fasta, Fastq, } #[derive(Copy, Clone)] pub struct FastaSequence<'a> { pub ident: &'a [u8], pub seq: &'a [u8], pub qual: Option<&'a [u8]>, } const SEQ_LETTERS_MAPPING: [u8; 256] = { let mut lookup = [b'N'; 256]; lookup[b'A' as usize] = b'A'; lookup[b'C' as usize] = b'C'; lookup[b'G' as usize] = b'G'; lookup[b'T' as usize] = b'T'; lookup[b'a' as usize] = b'A'; lookup[b'c' as usize] = b'C'; lookup[b'g' as usize] = b'G'; lookup[b't' as usize] = b'T'; lookup }; pub struct SequencesReader; impl SequencesReader { fn normalize_sequence(seq: &mut [u8]) { for el in seq.iter_mut() { *el = SEQ_LETTERS_MAPPING[*el as usize]; } } pub fn process_file_extended<F: FnMut(FastaSequence)>( source: impl AsRef<Path>, mut func: F, remove_file: bool, ) { const FASTQ_EXTS: &[&str] = &["fq", "fastq"]; const FASTA_EXTS: &[&str] = &["fa", "fasta", "fna", "ffn"]; let mut file_type = None; let mut tmp = source.as_ref().file_name().unwrap().to_str().unwrap(); let mut path: &Path = tmp.as_ref(); while let Some(ext) = path.extension() { if FASTQ_EXTS.contains(&ext.to_str().unwrap()) { file_type = Some(FileType::Fastq); break; } if FASTA_EXTS.contains(&ext.to_str().unwrap()) { file_type = Some(FileType::Fasta); break; } tmp = &tmp[0..tmp.len() - ext.len() - 1]; path = tmp.as_ref() } match file_type { None => panic!( "Cannot recognize file type of '{}'", source.as_ref().display() ), Some(ftype) => match ftype { FileType::Fasta => { Self::process_fasta(source, func, remove_file); } FileType::Fastq => { Self::process_fastq(source, func, remove_file); } }, } } fn process_fasta( source: impl AsRef<Path>, mut func: impl FnMut(FastaSequence), remove_file: bool, ) { let mut intermediate = [Vec::new(), Vec::new()]; LinesReader::process_lines( source, |line: &[u8], finished| { if finished || (line.len() > 0 && line[0] == b'>') { if intermediate[SEQ_STATE].len() > 0 { Self::normalize_sequence(&mut intermediate[SEQ_STATE]); func(FastaSequence { ident: &intermediate[IDENT_STATE], seq: &intermediate[SEQ_STATE], qual: None, }); intermediate[SEQ_STATE].clear(); } intermediate[IDENT_STATE].clear(); intermediate[IDENT_STATE].extend_from_slice(line); } else if line.len() > 0 && line[0] == b';' { return; } else { intermediate[SEQ_STATE].extend_from_slice(line); } }, remove_file, ); } fn process_fastq( source: impl AsRef<Path>, mut func: impl FnMut(FastaSequence), remove_file: bool, ) { let mut state = IDENT_STATE; let mut skipped_plus = false; let mut intermediate = [Vec::new(), Vec::new()]; LinesReader::process_lines( source, |line: &[u8], finished| { match state { QUAL_STATE => { if !skipped_plus { skipped_plus = true; return; } Self::normalize_sequence(&mut intermediate[SEQ_STATE]); func(FastaSequence { ident: &intermediate[IDENT_STATE], seq: &intermediate[SEQ_STATE], qual: Some(line), }); skipped_plus = false; } state => { intermediate[state].clear(); intermediate[state].extend_from_slice(line); } } state = (state + 1) % 3; }, remove_file, ); } }
use crate::io::lines_reader::LinesReader; use bstr::ByteSlice; use nix::sys::signal::{self, Signal}; use nix::unistd::Pid; use rand::Rng; use serde::Serialize; use std::fs::File; use std::hint::unreachable_unchecked; use std::intrinsics::unlikely; use std::io::{BufRead, BufReader, Read}; use std::num::Wrapping; use std::path::{Path, PathBuf}; use std::process::Command; use std::process::Stdio; use std::ptr::null_mut; use std::slice::from_raw_parts; const IDENT_STATE: usize = 0; const SEQ_STATE: usize = 1; const QUAL_STATE: usize = 2; enum FileType { Fasta, Fastq, } #[derive(Copy, Clone)] pub struct FastaSequence<'a> { pub ident: &'a [u8], pub seq: &'a [u8], pub qual: Option<&'a [u8]>, } const SEQ_LETTERS_MAPPING: [u8; 256] = { let mut lookup = [b'N'; 256]; lookup[b'A' as usize] = b'A'; lookup[b'C' as usize] = b'C'; lookup[b'G' as usize] = b'G'; lookup[b'T' as usize] = b'T'; lookup[b'a' as usize] = b'A'; lookup[b'c' as usize] = b'C'; lookup[b'g' as usize] = b'G'; lookup[b't' as usize] = b'T'; lookup }; pub struct SequencesReader; impl SequencesReader { fn normalize_sequence(seq: &mut [u8]) { for el in seq.iter_mut() { *el = SEQ_LETTERS_MAPPING[*el as usize]; } } pub fn process_file_extended<F: FnMut(FastaSequence)>( source: impl AsRef<Path>, mut func: F, remove_file: bool, ) { const FASTQ_EXTS: &[&str] = &["fq", "fastq"]; const FASTA_EXTS: &[&str] = &["fa", "fasta", "fna", "ffn"]; let mut file_type = None; let mut tmp = source.as_ref().file_name().unwrap().to_str().unwrap(); let mut path: &Path = tmp.as_ref(); while let Some(ext) = path.extension() { if FASTQ_EXTS.contains(&ext.to_str().unwrap()) { file_type = Some(FileType::Fastq); break; } if FASTA_EXTS.contains(&ext.to_str().unwrap()) { file_type = Some(FileType::Fasta); break; } tmp = &tmp[0..tmp.len() - ext.len() - 1]; path = tmp.as_ref() } match file_type { None => panic!( "Cannot recognize file type of '{}'", source.as_ref().display() ), Some(ftype) => match ftype { FileType::Fasta => { Self::process_fasta(source, func, remove_file); } FileType::Fastq => { Self::process_fastq(source, func, remove_file); } }, } } fn process_fasta( source: impl AsRef<Path>, mut func: impl FnMut(FastaSequence), remove_file: bool, ) { let mut intermediate = [Vec::new(), Vec::new()]; LinesReader::process_lines(
e[IDENT_STATE], seq: &intermediate[SEQ_STATE], qual: None, }); intermediate[SEQ_STATE].clear(); } intermediate[IDENT_STATE].clear(); intermediate[IDENT_STATE].extend_from_slice(line); } else if line.len() > 0 && line[0] == b';' { return; } else { intermediate[SEQ_STATE].extend_from_slice(line); } }, remove_file, ); } fn process_fastq( source: impl AsRef<Path>, mut func: impl FnMut(FastaSequence), remove_file: bool, ) { let mut state = IDENT_STATE; let mut skipped_plus = false; let mut intermediate = [Vec::new(), Vec::new()]; LinesReader::process_lines( source, |line: &[u8], finished| { match state { QUAL_STATE => { if !skipped_plus { skipped_plus = true; return; } Self::normalize_sequence(&mut intermediate[SEQ_STATE]); func(FastaSequence { ident: &intermediate[IDENT_STATE], seq: &intermediate[SEQ_STATE], qual: Some(line), }); skipped_plus = false; } state => { intermediate[state].clear(); intermediate[state].extend_from_slice(line); } } state = (state + 1) % 3; }, remove_file, ); } }
source, |line: &[u8], finished| { if finished || (line.len() > 0 && line[0] == b'>') { if intermediate[SEQ_STATE].len() > 0 { Self::normalize_sequence(&mut intermediate[SEQ_STATE]); func(FastaSequence { ident: &intermediat
random
[ { "content": "pub fn decompress_file_buffered(file: impl AsRef<Path>, func: impl FnMut(&[u8]) -> Result<(), ()>, buf_size: usize) -> Result<(), LibdeflateError> {\n\n let mut read_file = File::open(file).unwrap();\n\n\n\n let mut input_stream = DeflateChunkedBufferInput::new(|buf| {\n\n read_file.r...
Rust
riddle-image/src/image.rs
LaudateCorpus1/riddle-2
eec60152f2c934a0ebdb627a50286ce05fb6914d
use crate::*; use riddle_common::{Color, ColorElementConversion}; use riddle_math::*; use futures::{AsyncRead, AsyncReadExt}; use std::io::{BufReader, Cursor, Read, Write}; const ERR_PNG_ENCODE_FAILURE: &str = "Failed to encode Png"; const ERR_BMP_ENCODE_FAILURE: &str = "Failed to encode Bmp"; const ERR_JPEG_ENCODE_FAILURE: &str = "Failed to encode Jpeg"; const ERR_PNG_DECODE_FAILURE: &str = "Failed to decode Png"; const ERR_BMP_DECODE_FAILURE: &str = "Failed to decode Bmp"; const ERR_JPEG_DECODE_FAILURE: &str = "Failed to decode Jpeg"; #[derive(Clone, Debug)] pub struct Image { img: ::image::RgbaImage, } impl Image { pub fn load<R: Read>(mut r: R, format: ImageFormat) -> Result<Self> { let mut buf = vec![]; r.read_to_end(&mut buf)?; Self::from_bytes(&buf, format) } pub async fn load_async<R>(mut data: R, format: ImageFormat) -> Result<Self> where R: AsyncRead + Unpin, { let mut buf = vec![]; data.read_to_end(&mut buf).await?; Self::from_bytes(&buf, format) } pub fn save<W: Write>(&self, mut w: W, format: ImageFormat) -> Result<()> { match format { ImageFormat::Png => { ::image::png::PngEncoder::new(w) .encode( self.as_rgba8(), self.width(), self.height(), ::image::ColorType::Rgba8, ) .map_err(|_| ImageError::Save(ERR_PNG_ENCODE_FAILURE))?; } ImageFormat::Bmp => { ::image::bmp::BmpEncoder::new(&mut w) .encode( self.as_rgba8(), self.width(), self.height(), ::image::ColorType::Rgba8, ) .map_err(|_| ImageError::Save(ERR_BMP_ENCODE_FAILURE))?; } ImageFormat::Jpeg => { ::image::jpeg::JpegEncoder::new(&mut w) .encode( self.as_rgba8(), self.width(), self.height(), ::image::ColorType::Rgba8, ) .map_err(|_| ImageError::Save(ERR_JPEG_ENCODE_FAILURE))?; } } Ok(()) } pub fn from_bytes(bytes: &[u8], format: ImageFormat) -> Result<Self> { let buf_reader = BufReader::new(Cursor::new(bytes)); let img = match format { ImageFormat::Png => ::image::png::PngDecoder::new(buf_reader) .and_then(::image::DynamicImage::from_decoder) .map_err(|_| ImageError::Load(ERR_PNG_DECODE_FAILURE))?, ImageFormat::Bmp => ::image::bmp::BmpDecoder::new(buf_reader) .and_then(::image::DynamicImage::from_decoder) .map_err(|_| ImageError::Load(ERR_BMP_DECODE_FAILURE))?, ImageFormat::Jpeg => ::image::jpeg::JpegDecoder::new(buf_reader) .and_then(::image::DynamicImage::from_decoder) .map_err(|_| ImageError::Load(ERR_JPEG_DECODE_FAILURE))?, }; Ok(Image { img: img.into_rgba8(), }) } pub fn new(width: u32, height: u32) -> Self { let img = ::image::RgbaImage::from_raw(width, height, vec![0u8; (width * height * 4) as usize]) .unwrap(); Image { img } } pub fn get_pixel<L: Into<Vector2<u32>>>(&self, location: L) -> Color<u8> { let location = location.into(); let c: ::image::Rgba<u8> = *self.img.get_pixel(location.x, location.y); Color::rgba(c[0], c[1], c[2], c[3]) } pub fn set_pixel<L: Into<Vector2<u32>>, C: ColorElementConversion<Color<u8>>>( &mut self, location: L, color: C, ) { let color: Color<u8> = color.convert(); let color: [u8; 4] = color.into(); let location = location.into(); self.img.put_pixel(location.x, location.y, color.into()); } pub fn as_rgba8(&self) -> &[u8] { self.img.as_ref() } pub fn as_rgba8_mut(&mut self) -> &mut [u8] { self.img.as_mut() } pub fn byte_count(&self) -> usize { self.img.as_ref().len() } pub fn width(&self) -> u32 { self.img.width() } pub fn height(&self) -> u32 { self.img.height() } pub fn dimensions(&self) -> Vector2<u32> { let (w, h) = self.img.dimensions(); Vector2 { x: w, y: h } } pub fn rect(&self) -> Rect<u32> { Rect { location: Vector2 { x: 0, y: 0 }, dimensions: self.dimensions(), } } pub fn copy_rect(&self, source: &Rect<u32>) -> Image { let source_rect = self.rect().intersect(&source).unwrap_or_default(); let mut dest_img = Image::new(source_rect.dimensions.x, source_rect.dimensions.y); dest_img.blit_rect(self, &source_rect, Vector2::default()); dest_img } pub fn blit(&mut self, source: &Image, location: Vector2<i32>) { self.blit_rect(source, &source.rect(), location) } pub fn blit_rect(&mut self, source: &Image, source_rect: &Rect<u32>, location: Vector2<i32>) { let source_rect = if let Some(rect) = source.rect().intersect(source_rect) { rect } else { return; }; if let Some((rel_dest_rect, rel_src_rect)) = Rect::intersect_relative_to_both(self.dimensions(), source_rect.dimensions, location) { let abs_src_rec = Rect::new( rel_src_rect.location + source_rect.location.convert(), rel_src_rect.dimensions, ); let mut dest_view = self.create_view_mut(rel_dest_rect.clone().convert()); let src_view = source.create_view(abs_src_rec.convert()); for row in 0..(rel_dest_rect.dimensions.y as u32) { let dest = dest_view.get_row_rgba8_mut(row); let src = src_view.get_row_rgba8(row); dest.clone_from_slice(src); } } } pub fn fill_rect<C: ColorElementConversion<Color<u8>>>(&mut self, rect: Rect<u32>, color: C) { if let Some(dest_rect) = self.rect().intersect(&rect) { let color_bytes: [u8; 4] = color.convert().into(); let mut row_vec = Vec::with_capacity(dest_rect.dimensions.x as usize * 4); for _ in 0..dest_rect.dimensions.x { row_vec.extend_from_slice(&color_bytes[..]); } let mut dest_view = self.create_view_mut(dest_rect.clone().convert()); for row_idx in 0..(dest_rect.dimensions.y as u32) { let dest = dest_view.get_row_rgba8_mut(row_idx); dest.clone_from_slice(bytemuck::cast_slice(&row_vec[..])); } } } pub fn fill<C: ColorElementConversion<Color<u8>>>(&mut self, color: C) { self.fill_rect(self.rect(), color) } pub(crate) fn create_view(&self, rect: Rect<u32>) -> ImageView { ImageView::new(self, rect) } pub(crate) fn create_view_mut(&mut self, rect: Rect<u32>) -> ImageViewMut { ImageViewMut::new(self, rect) } } impl image_ext::ImageImageExt for Image { fn image_rgbaimage(&self) -> &::image::RgbaImage { &self.img } fn image_from_dynimage(img: ::image::DynamicImage) -> Self { Self { img: img.into_rgba8(), } } } #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub enum ImageFormat { Png, Bmp, Jpeg, } impl ImageFormat { pub fn derive_from_path(path: &str) -> Option<Self> { let p = std::path::Path::new(path); let extension_str = p.extension()?.to_str()?; let extension = String::from(extension_str).to_lowercase(); match extension.as_str() { "png" => Some(ImageFormat::Png), "bmp" => Some(ImageFormat::Bmp), "jpeg" | "jpg" => Some(ImageFormat::Jpeg), _ => None, } } }
use crate::*; use riddle_common::{Color, ColorElementConversion}; use riddle_math::*; use futures::{AsyncRead, AsyncReadExt}; use std::io::{BufReader, Cursor, Read, Write}; const ERR_PNG_ENCODE_FAILURE: &str = "Failed to encode Png"; const ERR_BMP_ENCODE_FAILURE: &str = "Failed to encode Bmp"; const ERR_JPEG_ENCODE_FAILURE: &str = "Failed to encode Jpeg"; const ERR_PNG_DECODE_FAILURE: &str = "Failed to decode Png"; const ERR_BMP_DECODE_FAILURE: &str = "Failed to decode Bmp"; const ERR_JPEG_DECODE_FAILURE: &str = "Failed to decode Jpeg"; #[derive(Clone, Debug)] pub struct Image { img: ::image::RgbaImage, } impl Image { pub fn load<R: Read>(mut r: R, format: ImageFormat) -> Result<Self> { let mut buf = vec![]; r.read_to_end(&mut buf)?; Self::from_bytes(&buf, format) } pub async fn load_async<R>(mut data: R, format: ImageFormat) -> Result<Self> where R: AsyncRead + Unpin, { let mut buf = vec![]; data.read_to_end(&mut buf).await?; Self::from_bytes(&buf, format) } pub fn save<W: Write>(&self, mut w: W, format: ImageFormat) -> Result<()> { match format { ImageFormat::Png => { ::image::png::PngEncoder::new(w) .encode( self.as_rgba8(), self.width(), self.height(), ::image::ColorType::Rgba8, ) .map_err(|_| ImageError::Save(ERR_PNG_ENCODE_FAILURE))?; } ImageFormat::Bmp => { ::image::bmp::BmpEncoder::new(&mut w) .encode( self.as_rgba8(), self.width(), self.height(), ::image::ColorType::Rgba8, ) .map_err(|_| ImageError::Save(ERR_BMP_ENCODE_FAILURE))?; } ImageFormat::Jpeg => { ::image::jpeg::JpegEncoder::new(&mut w) .encode( self.as_rgba8(), self.width(), self.height(), ::image::ColorType::Rgba8, ) .map_err(|_| ImageError::Save(ERR_JPEG_ENCODE_FAILURE))?; } } Ok(()) } pub fn from_bytes(bytes: &[u8], format: ImageFormat) -> Result<Self> { let buf_reader = BufReader::new(Cursor::new(bytes)); let img = match format { ImageFormat::Png => ::image::png::PngDecoder::new(buf_reader) .and_then(::image::DynamicImage::from_decoder) .map_err(|_| ImageError::Load(ERR_PNG_DECODE_FAILURE))?, ImageFormat::Bmp => ::image::bmp::BmpDecoder::new(buf_reader) .and_then(::image::DynamicImage::from_decoder) .map_err(|_| ImageError::Load(ERR_BMP_DECODE_FAILURE))?, ImageFormat::Jpeg => ::image::jpeg::JpegDecoder::new(buf_reader) .and_then(::image::DynamicImage::from_decoder) .map_err(|_| ImageError::Load(ERR_JPEG_DECODE_FAILURE))?, }; Ok(Image { img: img.into_rgba8(), }) } pub fn new(width: u32, height: u32) -> Self { let img = ::image::RgbaImage::from_raw(width, height, vec![0u8; (width * height * 4) as usize]) .unwrap(); Image { img } } pub fn get_pixel<L: Into<Vector2<u32>>>(&self, location: L) -> Color<u8> { let location = location.into(); let c: ::image::Rgba<u8> = *self.img.get_pixel(location.x, location.y); Color::rgba(c[0], c[1], c[2], c[3]) } pub fn set_pixel<L: Into<Vector2<u32>>, C: ColorElementConversion<Color<u8>>>( &mut self, location: L, color: C, ) { let color: Color<u8> = color
rel_src_rect.dimensions, ); let mut dest_view = self.create_view_mut(rel_dest_rect.clone().convert()); let src_view = source.create_view(abs_src_rec.convert()); for row in 0..(rel_dest_rect.dimensions.y as u32) { let dest = dest_view.get_row_rgba8_mut(row); let src = src_view.get_row_rgba8(row); dest.clone_from_slice(src); } } } pub fn fill_rect<C: ColorElementConversion<Color<u8>>>(&mut self, rect: Rect<u32>, color: C) { if let Some(dest_rect) = self.rect().intersect(&rect) { let color_bytes: [u8; 4] = color.convert().into(); let mut row_vec = Vec::with_capacity(dest_rect.dimensions.x as usize * 4); for _ in 0..dest_rect.dimensions.x { row_vec.extend_from_slice(&color_bytes[..]); } let mut dest_view = self.create_view_mut(dest_rect.clone().convert()); for row_idx in 0..(dest_rect.dimensions.y as u32) { let dest = dest_view.get_row_rgba8_mut(row_idx); dest.clone_from_slice(bytemuck::cast_slice(&row_vec[..])); } } } pub fn fill<C: ColorElementConversion<Color<u8>>>(&mut self, color: C) { self.fill_rect(self.rect(), color) } pub(crate) fn create_view(&self, rect: Rect<u32>) -> ImageView { ImageView::new(self, rect) } pub(crate) fn create_view_mut(&mut self, rect: Rect<u32>) -> ImageViewMut { ImageViewMut::new(self, rect) } } impl image_ext::ImageImageExt for Image { fn image_rgbaimage(&self) -> &::image::RgbaImage { &self.img } fn image_from_dynimage(img: ::image::DynamicImage) -> Self { Self { img: img.into_rgba8(), } } } #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub enum ImageFormat { Png, Bmp, Jpeg, } impl ImageFormat { pub fn derive_from_path(path: &str) -> Option<Self> { let p = std::path::Path::new(path); let extension_str = p.extension()?.to_str()?; let extension = String::from(extension_str).to_lowercase(); match extension.as_str() { "png" => Some(ImageFormat::Png), "bmp" => Some(ImageFormat::Bmp), "jpeg" | "jpg" => Some(ImageFormat::Jpeg), _ => None, } } }
.convert(); let color: [u8; 4] = color.into(); let location = location.into(); self.img.put_pixel(location.x, location.y, color.into()); } pub fn as_rgba8(&self) -> &[u8] { self.img.as_ref() } pub fn as_rgba8_mut(&mut self) -> &mut [u8] { self.img.as_mut() } pub fn byte_count(&self) -> usize { self.img.as_ref().len() } pub fn width(&self) -> u32 { self.img.width() } pub fn height(&self) -> u32 { self.img.height() } pub fn dimensions(&self) -> Vector2<u32> { let (w, h) = self.img.dimensions(); Vector2 { x: w, y: h } } pub fn rect(&self) -> Rect<u32> { Rect { location: Vector2 { x: 0, y: 0 }, dimensions: self.dimensions(), } } pub fn copy_rect(&self, source: &Rect<u32>) -> Image { let source_rect = self.rect().intersect(&source).unwrap_or_default(); let mut dest_img = Image::new(source_rect.dimensions.x, source_rect.dimensions.y); dest_img.blit_rect(self, &source_rect, Vector2::default()); dest_img } pub fn blit(&mut self, source: &Image, location: Vector2<i32>) { self.blit_rect(source, &source.rect(), location) } pub fn blit_rect(&mut self, source: &Image, source_rect: &Rect<u32>, location: Vector2<i32>) { let source_rect = if let Some(rect) = source.rect().intersect(source_rect) { rect } else { return; }; if let Some((rel_dest_rect, rel_src_rect)) = Rect::intersect_relative_to_both(self.dimensions(), source_rect.dimensions, location) { let abs_src_rec = Rect::new( rel_src_rect.location + source_rect.location.convert(),
random
[ { "content": "pub fn simple<R, F: FnOnce(&AudioSystem) -> Result<R>>(f: F) {\n\n\tlet (audio_system, _main_thread_state) = AudioSystem::new_system_pair().unwrap();\n\n\tlet _r = f(&audio_system).unwrap();\n\n\tlet start_time = Instant::now();\n\n\twhile Instant::now() - start_time < Duration::from_secs(2) {\n\n...
Rust
src/lang.rs
alamminsalo/ram
22ecebf41d1919e8f996779dc8fccb6a80740c88
use super::assets::Assets; use super::util; use super::Model; use failure::Fallible; use handlebars::Handlebars; use handlebars::*; use itertools::Itertools; use maplit::hashmap; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Lang { #[serde(skip)] pub path: PathBuf, #[serde(default)] pub types: HashMap<String, Type>, #[serde(default)] pub helpers: HashMap<String, String>, #[serde(default)] pub files: Vec<AddFile>, #[serde(default)] pub paths: HashMap<String, String>, #[serde(default)] pub reserved: Vec<String>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct AddFile { pub filename: Option<String>, pub template: String, #[serde(rename = "in")] pub file_in: Option<String>, pub path: Option<String>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Type { #[serde(default)] pub alias: Vec<String>, pub format: HashMap<String, Format>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Format { #[serde(rename = "type")] pub schema_type: String, } impl Lang { pub fn load_file(path: &Path) -> Fallible<Self> { let mut pathbuf = path.to_owned(); let data = { if path.extension().is_none() { pathbuf = PathBuf::from(&format!( "{lang}/{lang}.yaml", lang = &path.to_str().unwrap() )); } Assets::read_file(&PathBuf::from(&pathbuf))? }; let ext = path .extension() .and_then(std::ffi::OsStr::to_str) .unwrap_or("yaml"); let mut lang: Self = match ext { "yaml" | "yml" => serde_yaml::from_str(&data)?, "json" | _ => serde_json::from_str(&data)?, }; lang.path = pathbuf .parent() .expect("failed to get lang parent dir") .to_owned(); if lang.paths.get("root") == None { lang.paths.insert("root".into(), "".into()); } Ok(lang) } pub fn default_path(&self, path: &str) -> PathBuf { PathBuf::from( &self .paths .get(path) .expect(&format!("failed to find default path: {}", path)), ) } pub fn files_relative(&self) -> Vec<AddFile> { self.files .iter() .map(|af| AddFile { template: util::join_relative(&self.path, &PathBuf::from(&af.template)) .to_str() .unwrap() .into(), ..af.clone() }) .collect() } /* * Formatter functions */ pub fn format(&self, template_key: &str, value: &String) -> Fallible<String> { match template_key { "r" if !self.reserved.contains(&value) => Ok(value.clone()), _ => { let mut map = HashMap::new(); map.insert("value", value.as_str()); Ok(self.format_map(template_key, &map)) } } } pub fn format_map(&self, template_key: &str, map: &HashMap<&str, &str>) -> String { let mut hb = Handlebars::new(); util::init_handlebars(&mut hb); self.add_helpers(&mut hb); self.helpers .get(template_key) .and_then(|template| hb.render_template(template, map).ok()) .unwrap_or_else(|| map.get("value").unwrap().to_string()) } pub fn translate_modelname(&self, name: &String) -> String { let modelname = self.format("classname", &name).unwrap_or(name.clone()); self.format("object_property", &modelname) .unwrap_or(modelname) } pub fn translate_array(&self, m: &Model) -> String { let child = m .items .as_ref() .expect("array child type is None") .clone() .translate(self); self.format_map( "array", &hashmap!["value" => m.name.as_str(), "type" => child.schema_type.as_str(), "name" => m.name.as_str()], ) } pub fn translate_primitive(&self, schema_type: &String, format: &String) -> String { self.types .iter() .find(|(name, t)| *name == schema_type || t.alias.contains(schema_type)) .and_then(|(_, t)| t.format.get(format).or_else(|| t.format.get("default"))) .map(|f| f.schema_type.clone()) .expect(&format!( "Error while processing {}: failed to find primitive type {}", schema_type, format )) } pub fn add_helpers(&self, hb: &mut Handlebars) { for k in self.helpers.keys() { let lang = self.clone(); let key = k.clone(); let closure = move |h: &Helper, _: &Handlebars, _: &Context, _: &mut RenderContext, out: &mut dyn Output| -> HelperResult { let param = h .param(0) .and_then(|v| v.value().as_str()) .expect("parameter is missing") .to_string(); out.write(&lang.format(&key, &param).unwrap_or(param))?; Ok(()) }; hb.register_helper(k, Box::new(closure)); } } pub fn format_path(&self, p: String) -> String { let re = Regex::new(r"^\{(\w+)\}$").unwrap(); self.helpers .get("pathparam") .map(|_| { format!( "/{}", &Path::new(&p) .iter() .skip(1) .map(|part| part.to_str().unwrap()) .map(|part| { if let Some(cap) = re.captures_iter(part).next() { self.format("pathparam", &cap[1].to_owned()) .unwrap_or(part.to_string()) } else { part.to_string() } }) .join("/") ) }) .unwrap_or(p) } }
use super::assets::Assets; use super::util; use super::Model; use failure::Fallible; use handlebars::Handlebars; use handlebars::*; use itertools::Itertools; use maplit::hashmap; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Lang { #[serde(skip)] pub path: PathBuf, #[serde(default)] pub types: HashMap<String, Type>, #[serde(default)] pub helpers: HashMap<String, String>, #[serde(default)] pub files: Vec<AddFile>, #[serde(default)] pub paths: HashMap<String, String>, #[serde(default)] pub reserved: Vec<String>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct AddFile { pub filename: Option<String>, pub template: String, #[serde(rename = "in")] pub file_in: Option<String>, pub path: Option<String>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Type { #[serde(default)] pub alias: Vec<String>, pub format: HashMap<String, Format>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Format { #[serde(rename = "type")] pub schema_type: String, } impl Lang { pub fn load_file(path: &Path) -> Fallible<Self> { let mut pathbuf = path.to_owned(); let data = { if path.extension().is_none() { pathbuf = PathBuf::from(&format!( "{lang}/{lang}.yaml", lang = &path.to_str().unwrap() )); } Assets::read_file(&PathBuf::from(&pathbuf))? }; let ext = path .extension() .and_then(std::ffi::OsStr::to_str) .unwrap_or("yaml"); let mut lang: Self = match ext { "yaml" | "yml" => serde_yaml::from_str(&data)?, "
pub fn default_path(&self, path: &str) -> PathBuf { PathBuf::from( &self .paths .get(path) .expect(&format!("failed to find default path: {}", path)), ) } pub fn files_relative(&self) -> Vec<AddFile> { self.files .iter() .map(|af| AddFile { template: util::join_relative(&self.path, &PathBuf::from(&af.template)) .to_str() .unwrap() .into(), ..af.clone() }) .collect() } /* * Formatter functions */ pub fn format(&self, template_key: &str, value: &String) -> Fallible<String> { match template_key { "r" if !self.reserved.contains(&value) => Ok(value.clone()), _ => { let mut map = HashMap::new(); map.insert("value", value.as_str()); Ok(self.format_map(template_key, &map)) } } } pub fn format_map(&self, template_key: &str, map: &HashMap<&str, &str>) -> String { let mut hb = Handlebars::new(); util::init_handlebars(&mut hb); self.add_helpers(&mut hb); self.helpers .get(template_key) .and_then(|template| hb.render_template(template, map).ok()) .unwrap_or_else(|| map.get("value").unwrap().to_string()) } pub fn translate_modelname(&self, name: &String) -> String { let modelname = self.format("classname", &name).unwrap_or(name.clone()); self.format("object_property", &modelname) .unwrap_or(modelname) } pub fn translate_array(&self, m: &Model) -> String { let child = m .items .as_ref() .expect("array child type is None") .clone() .translate(self); self.format_map( "array", &hashmap!["value" => m.name.as_str(), "type" => child.schema_type.as_str(), "name" => m.name.as_str()], ) } pub fn translate_primitive(&self, schema_type: &String, format: &String) -> String { self.types .iter() .find(|(name, t)| *name == schema_type || t.alias.contains(schema_type)) .and_then(|(_, t)| t.format.get(format).or_else(|| t.format.get("default"))) .map(|f| f.schema_type.clone()) .expect(&format!( "Error while processing {}: failed to find primitive type {}", schema_type, format )) } pub fn add_helpers(&self, hb: &mut Handlebars) { for k in self.helpers.keys() { let lang = self.clone(); let key = k.clone(); let closure = move |h: &Helper, _: &Handlebars, _: &Context, _: &mut RenderContext, out: &mut dyn Output| -> HelperResult { let param = h .param(0) .and_then(|v| v.value().as_str()) .expect("parameter is missing") .to_string(); out.write(&lang.format(&key, &param).unwrap_or(param))?; Ok(()) }; hb.register_helper(k, Box::new(closure)); } } pub fn format_path(&self, p: String) -> String { let re = Regex::new(r"^\{(\w+)\}$").unwrap(); self.helpers .get("pathparam") .map(|_| { format!( "/{}", &Path::new(&p) .iter() .skip(1) .map(|part| part.to_str().unwrap()) .map(|part| { if let Some(cap) = re.captures_iter(part).next() { self.format("pathparam", &cap[1].to_owned()) .unwrap_or(part.to_string()) } else { part.to_string() } }) .join("/") ) }) .unwrap_or(p) } }
json" | _ => serde_json::from_str(&data)?, }; lang.path = pathbuf .parent() .expect("failed to get lang parent dir") .to_owned(); if lang.paths.get("root") == None { lang.paths.insert("root".into(), "".into()); } Ok(lang) }
function_block-function_prefix_line
[ { "content": "pub fn register_helpers(hb: &mut Handlebars) {\n\n hb.register_helper(\"lowercase\", Box::new(lowercase));\n\n hb.register_helper(\"uppercase\", Box::new(uppercase));\n\n hb.register_helper(\"pascalcase\", Box::new(pascalcase));\n\n hb.register_helper(\"snakecase\", Box::new(snakecase)...
Rust
src/curve25519/point.rs
cronokirby/eddo
015b8ce77249605f2f760ea5d907a0e6e1ea79bd
use std::{ convert::{TryFrom, TryInto}, ops::{Add, Mul}, }; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq}; use super::{arithmetic::U256, error::SignatureError, field::Z25519, scalar::Scalar}; const D: Z25519 = Z25519 { value: U256 { limbs: [ 0x75eb4dca135978a3, 0x00700a4d4141d8ab, 0x8cc740797779e898, 0x52036cee2b6ffe73, ], }, }; pub const B: Point = Point { x: Z25519 { value: U256 { limbs: [ 0xc9562d608f25d51a, 0x692cc7609525a7b2, 0xc0a4e231fdd6dc5c, 0x216936d3cd6e53fe, ], }, }, y: Z25519 { value: U256 { limbs: [ 0x6666666666666658, 0x6666666666666666, 0x6666666666666666, 0x6666666666666666, ], }, }, z: Z25519 { value: U256 { limbs: [1, 0, 0, 0], }, }, t: Z25519 { value: U256 { limbs: [ 0x6dde8ab3a5b7dda3, 0x20f09f80775152f5, 0x66ea4e8e64abe37d, 0x67875f0fd78b7665, ], }, }, }; #[derive(Clone, Copy, Debug)] pub struct Point { x: Z25519, y: Z25519, z: Z25519, t: Z25519, } impl Point { fn identity() -> Point { Point { x: Z25519::from(0), y: Z25519::from(1), z: Z25519::from(1), t: Z25519::from(0), } } fn from_affine_unchecked(x: Z25519, y: Z25519) -> Point { Point { x, y, z: Z25519::from(1), t: x * y, } } #[must_use] fn doubled(&self) -> Point { let a = self.x.squared(); let b = self.y.squared(); let c = self.z.squared() * 2; let h = a + b; let e = h - (self.x + self.y).squared(); let g = a - b; let f = c + g; Point { x: e * f, y: g * h, t: e * h, z: f * g, } } } impl ConditionallySelectable for Point { fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self { Point { x: Z25519::conditional_select(&a.x, &b.x, choice), y: Z25519::conditional_select(&a.y, &b.y, choice), z: Z25519::conditional_select(&a.z, &b.z, choice), t: Z25519::conditional_select(&a.t, &b.t, choice), } } } impl Into<[u8; 32]> for Point { fn into(self) -> [u8; 32] { let zinv = self.z.inverse(); let x = self.x * zinv; let y = self.y * zinv; let mut out: [u8; 32] = y.into(); out[31] |= ((x.value.limbs[0] & 1) as u8) << 7; out } } impl<'a> TryFrom<&'a [u8]> for Point { type Error = SignatureError; fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> { if value.len() < 32 { return Err(SignatureError::InvalidPoint); } let mut value_bytes: [u8; 32] = value[..32].try_into().unwrap(); let x_0 = u64::from(value_bytes[31] >> 7); value_bytes[31] &= 0x7F; let y = Z25519::try_from(&value_bytes[..])?; let y_2 = y.squared(); let u = y_2 - Z25519::from(1); let v = D * y_2 + Z25519::from(1); let mut x = Z25519::fraction_root(u, v).ok_or(SignatureError::InvalidPoint)?; if x_0 == 1 && x.value.eq(U256::from(0)) { return Err(SignatureError::InvalidPoint); } if x_0 != x.value.limbs[0] % 2 { x = -x; } Ok(Point::from_affine_unchecked(x, y)) } } impl Add for Point { type Output = Point; fn add(self, other: Point) -> Self::Output { let a = (self.y - self.x) * (other.y - other.x); let b = (self.y + self.x) * (other.y + other.x); let c = self.t * D * other.t * 2; let d = self.z * other.z * 2; let e = b - a; let f = d - c; let g = d + c; let h = b + a; Point { x: e * f, y: g * h, t: e * h, z: f * g, } } } impl Mul<Scalar> for Point { type Output = Point; fn mul(self, other: Scalar) -> Self::Output { let mut out = Point::identity(); const WINDOW_SIZE: usize = 4; let mut window = [Point::identity(); (1 << WINDOW_SIZE) - 1]; window[0] = self; for i in 1..window.len() { window[i] = self + window[i - 1]; } for x in other.value.limbs.iter().rev() { for i in (0..64).step_by(WINDOW_SIZE).rev() { out = out.doubled(); out = out.doubled(); out = out.doubled(); out = out.doubled(); let w = ((x >> i) & ((1 << WINDOW_SIZE) - 1)) as usize; let mut selected = Point::identity(); for i in 0..window.len() { selected.conditional_assign(&window[i], w.ct_eq(&(i + 1))); } out = out + selected; } } out } }
use std::{ convert::{TryFrom, TryInto}, ops::{Add, Mul}, }; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq}; use super::{arithmetic::U256, error::SignatureError, field::Z25519, scalar::Scalar}; const D: Z25519 = Z25519 { value: U256 { limbs: [ 0x75eb4dca135978a3, 0x00700a4d4141d8ab, 0x8cc740797779e898, 0x52036cee2b6ffe73, ], }, }; pub const B: Point = Point { x: Z25519 { value: U256 { limbs: [ 0xc9562d608f25d51a, 0x692cc7609525a7b2, 0xc0a4e231fdd6dc5c, 0x216936d3cd6e53fe, ], }, }, y: Z25519 { value: U256 { limbs: [ 0x6666666666666658, 0x6666666666666666, 0x6666666666666666, 0x6666666666666666, ], }, }, z: Z25519 { value: U256 { limbs: [1, 0, 0, 0], }, }, t: Z25519 { value: U256 { limbs: [ 0x6dde8ab3a5b7dda3, 0x20f09f80775152f5, 0x66ea4e8e64abe37d, 0x67875f0fd78b7665, ], }, }, }; #[derive(Clone, Copy, Debug)] pub struct Point { x: Z25519, y: Z25519, z: Z25519, t: Z25519, } impl Point { fn identity() -> Point { Point { x: Z25519::from(0), y: Z25519::from(1), z: Z25519::from(1), t: Z25519::from(0), } } fn from_affine_unchecked(x: Z25519, y: Z2551
#[must_use] fn doubled(&self) -> Point { let a = self.x.squared(); let b = self.y.squared(); let c = self.z.squared() * 2; let h = a + b; let e = h - (self.x + self.y).squared(); let g = a - b; let f = c + g; Point { x: e * f, y: g * h, t: e * h, z: f * g, } } } impl ConditionallySelectable for Point { fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self { Point { x: Z25519::conditional_select(&a.x, &b.x, choice), y: Z25519::conditional_select(&a.y, &b.y, choice), z: Z25519::conditional_select(&a.z, &b.z, choice), t: Z25519::conditional_select(&a.t, &b.t, choice), } } } impl Into<[u8; 32]> for Point { fn into(self) -> [u8; 32] { let zinv = self.z.inverse(); let x = self.x * zinv; let y = self.y * zinv; let mut out: [u8; 32] = y.into(); out[31] |= ((x.value.limbs[0] & 1) as u8) << 7; out } } impl<'a> TryFrom<&'a [u8]> for Point { type Error = SignatureError; fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> { if value.len() < 32 { return Err(SignatureError::InvalidPoint); } let mut value_bytes: [u8; 32] = value[..32].try_into().unwrap(); let x_0 = u64::from(value_bytes[31] >> 7); value_bytes[31] &= 0x7F; let y = Z25519::try_from(&value_bytes[..])?; let y_2 = y.squared(); let u = y_2 - Z25519::from(1); let v = D * y_2 + Z25519::from(1); let mut x = Z25519::fraction_root(u, v).ok_or(SignatureError::InvalidPoint)?; if x_0 == 1 && x.value.eq(U256::from(0)) { return Err(SignatureError::InvalidPoint); } if x_0 != x.value.limbs[0] % 2 { x = -x; } Ok(Point::from_affine_unchecked(x, y)) } } impl Add for Point { type Output = Point; fn add(self, other: Point) -> Self::Output { let a = (self.y - self.x) * (other.y - other.x); let b = (self.y + self.x) * (other.y + other.x); let c = self.t * D * other.t * 2; let d = self.z * other.z * 2; let e = b - a; let f = d - c; let g = d + c; let h = b + a; Point { x: e * f, y: g * h, t: e * h, z: f * g, } } } impl Mul<Scalar> for Point { type Output = Point; fn mul(self, other: Scalar) -> Self::Output { let mut out = Point::identity(); const WINDOW_SIZE: usize = 4; let mut window = [Point::identity(); (1 << WINDOW_SIZE) - 1]; window[0] = self; for i in 1..window.len() { window[i] = self + window[i - 1]; } for x in other.value.limbs.iter().rev() { for i in (0..64).step_by(WINDOW_SIZE).rev() { out = out.doubled(); out = out.doubled(); out = out.doubled(); out = out.doubled(); let w = ((x >> i) & ((1 << WINDOW_SIZE) - 1)) as usize; let mut selected = Point::identity(); for i in 0..window.len() { selected.conditional_assign(&window[i], w.ct_eq(&(i + 1))); } out = out + selected; } } out } }
9) -> Point { Point { x, y, z: Z25519::from(1), t: x * y, } }
function_block-function_prefixed
[ { "content": "/// Represents a \"hash value\", as described in Section 6:\n\n/// https://datatracker.ietf.org/doc/html/rfc6234#section-6\n\n///\n\n/// This can be thought of as the ongoing state of our hash function,\n\n/// which gets modified using our message blocks.\n\nstruct HashValue {\n\n data: [u64; 8...
Rust
src/pointer/raw.rs
oliver-giersch/reclaim
ab55cb7eb9078376597dcdbaa298daeb9bf22d0b
use core::cmp::{self, PartialEq, PartialOrd}; use core::fmt; use core::marker::PhantomData; use core::ptr::{self, NonNull}; use typenum::{IsGreaterOrEqual, True, Unsigned}; use crate::pointer::{self, MarkedNonNull, MarkedPtr}; /********** impl Clone ****************************************************************************/ impl<T, N> Clone for MarkedPtr<T, N> { #[inline] fn clone(&self) -> Self { Self::new(self.inner) } } /********** impl Copy *****************************************************************************/ impl<T, N> Copy for MarkedPtr<T, N> {} /********** impl inherent (const) *****************************************************************/ impl<T, N> MarkedPtr<T, N> { #[inline] pub const fn new(ptr: *mut T) -> Self { Self { inner: ptr, _marker: PhantomData } } #[inline] pub const fn null() -> Self { Self::new(ptr::null_mut()) } #[inline] pub const fn cast<U>(self) -> MarkedPtr<U, N> { MarkedPtr::new(self.inner as *mut U) } #[inline] pub const fn from_usize(val: usize) -> Self { Self::new(val as *mut _) } } /********** impl inherent *************************************************************************/ impl<T, N: Unsigned> MarkedPtr<T, N> { pub const MARK_BITS: usize = N::USIZE; pub const MARK_MASK: usize = pointer::mark_mask::<T>(Self::MARK_BITS); pub const POINTER_MASK: usize = !Self::MARK_MASK; #[inline] pub fn into_usize(self) -> usize { self.inner as usize } #[inline] pub fn into_ptr(self) -> *mut T { self.inner } #[inline] pub fn compose(ptr: *mut T, tag: usize) -> Self { debug_assert_eq!(0, ptr as usize & Self::MARK_MASK, "pointer must be properly aligned"); Self::new(pointer::compose::<_, N>(ptr, tag)) } #[inline] pub fn convert<M: Unsigned>(other: MarkedPtr<T, M>) -> Self where N: IsGreaterOrEqual<M, Output = True>, { Self::new(other.inner) } #[inline] pub fn clear_tag(self) -> Self { Self::new(self.decompose_ptr()) } #[inline] pub fn with_tag(self, tag: usize) -> Self { Self::compose(self.decompose_ptr(), tag) } #[inline] pub fn decompose(self) -> (*mut T, usize) { pointer::decompose(self.into_usize(), Self::MARK_BITS) } #[inline] pub fn decompose_ptr(self) -> *mut T { pointer::decompose_ptr(self.into_usize(), Self::MARK_BITS) } #[inline] pub fn decompose_tag(self) -> usize { pointer::decompose_tag::<T>(self.into_usize(), Self::MARK_BITS) } #[inline] pub unsafe fn decompose_ref<'a>(self) -> (Option<&'a T>, usize) { let (ptr, tag) = self.decompose(); (ptr.as_ref(), tag) } #[inline] pub unsafe fn decompose_mut<'a>(self) -> (Option<&'a mut T>, usize) { let (ptr, tag) = self.decompose(); (ptr.as_mut(), tag) } #[inline] pub unsafe fn as_ref<'a>(self) -> Option<&'a T> { self.decompose_ptr().as_ref() } #[inline] pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> { self.decompose_ptr().as_mut() } #[inline] pub fn is_null(self) -> bool { self.decompose_ptr().is_null() } } /********** impl Default **************************************************************************/ impl<T, N: Unsigned> Default for MarkedPtr<T, N> { #[inline] fn default() -> Self { Self::null() } } /********** impl Debug ****************************************************************************/ impl<T, N: Unsigned> fmt::Debug for MarkedPtr<T, N> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (ptr, tag) = self.decompose(); f.debug_struct("MarkedPtr").field("ptr", &ptr).field("tag", &tag).finish() } } /********** impl Pointer **************************************************************************/ impl<T, N: Unsigned> fmt::Pointer for MarkedPtr<T, N> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Pointer::fmt(&self.decompose_ptr(), f) } } /********** impl From *****************************************************************************/ impl<T, N: Unsigned> From<*const T> for MarkedPtr<T, N> { #[inline] fn from(ptr: *const T) -> Self { Self::new(ptr as *mut _) } } impl<T, N: Unsigned> From<*mut T> for MarkedPtr<T, N> { fn from(ptr: *mut T) -> Self { Self::new(ptr) } } impl<'a, T, N: Unsigned> From<&'a T> for MarkedPtr<T, N> { #[inline] fn from(reference: &'a T) -> Self { Self::new(reference as *const _ as *mut _) } } impl<'a, T, N: Unsigned> From<&'a mut T> for MarkedPtr<T, N> { #[inline] fn from(reference: &'a mut T) -> Self { Self::new(reference) } } impl<T, N: Unsigned> From<NonNull<T>> for MarkedPtr<T, N> { #[inline] fn from(ptr: NonNull<T>) -> Self { Self::new(ptr.as_ptr()) } } impl<T, N: Unsigned> From<(*mut T, usize)> for MarkedPtr<T, N> { #[inline] fn from(pair: (*mut T, usize)) -> Self { let (ptr, tag) = pair; Self::compose(ptr, tag) } } impl<T, N: Unsigned> From<(*const T, usize)> for MarkedPtr<T, N> { #[inline] fn from(pair: (*const T, usize)) -> Self { let (ptr, tag) = pair; Self::compose(ptr as *mut _, tag) } } /********** impl PartialEq ************************************************************************/ impl<T, N> PartialEq for MarkedPtr<T, N> { #[inline] fn eq(&self, other: &Self) -> bool { self.inner == other.inner } } impl<T, N> PartialEq<MarkedNonNull<T, N>> for MarkedPtr<T, N> { #[inline] fn eq(&self, other: &MarkedNonNull<T, N>) -> bool { self.inner.eq(&other.inner.as_ptr()) } } /********** impl PartialOrd ***********************************************************************/ impl<T, N> PartialOrd for MarkedPtr<T, N> { #[inline] fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.inner.partial_cmp(&other.inner) } } impl<T, N> PartialOrd<MarkedNonNull<T, N>> for MarkedPtr<T, N> { #[inline] fn partial_cmp(&self, other: &MarkedNonNull<T, N>) -> Option<cmp::Ordering> { self.inner.partial_cmp(&other.inner.as_ptr()) } } #[cfg(test)] mod test { use core::ptr; use matches::assert_matches; use typenum::{U0, U1, U3}; use crate::align::Aligned8; type UnmarkedMarkedPtr = super::MarkedPtr<Aligned8<i32>, U0>; type MarkedPtr1N = super::MarkedPtr<Aligned8<i32>, U1>; type MarkedPtr3N = super::MarkedPtr<Aligned8<i32>, U3>; #[test] fn decompose_ref() { let null = MarkedPtr3N::null(); assert_eq!((None, 0), unsafe { null.decompose_ref() }); let marked_null = MarkedPtr3N::compose(ptr::null_mut(), 0b111); assert_eq!((None, 0b111), unsafe { marked_null.decompose_ref() }); let value = Aligned8(1); let marked = MarkedPtr3N::compose(&value as *const Aligned8<i32> as *mut _, 0b11); assert_eq!((Some(&value), 0b11), unsafe { marked.decompose_ref() }); } #[test] fn decompose_mut() { let null = MarkedPtr3N::null(); assert_eq!((None, 0), unsafe { null.decompose_mut() }); let marked_null = MarkedPtr3N::compose(ptr::null_mut(), 0b111); assert_eq!((None, 0b111), unsafe { marked_null.decompose_mut() }); let mut value = Aligned8(1); let marked = MarkedPtr3N::compose(&mut value, 0b11); assert_eq!((Some(&mut value), 0b11), unsafe { marked.decompose_mut() }); } #[test] fn from_usize() { unsafe { let unmarked = UnmarkedMarkedPtr::from_usize(&Aligned8(1) as *const _ as usize); assert_matches!(unmarked.as_ref(), Some(&Aligned8(1))); let tagged = (&Aligned8(1i32) as *const _ as usize) | 0b1; assert_eq!( (Some(&Aligned8(1i32)), 0b1), MarkedPtr1N::from_usize(tagged).decompose_ref() ); } } #[test] fn from() { let mut x = Aligned8(1); let from_ref = MarkedPtr1N::from(&x); let from_mut = MarkedPtr1N::from(&mut x); let from_const_ptr = MarkedPtr1N::from(&x as *const _); let from_mut_ptr = MarkedPtr1N::from(&mut x as *mut _); assert!(from_ref == from_mut && from_const_ptr == from_mut_ptr); } #[test] fn eq_ord() { let null = MarkedPtr3N::null(); assert!(null.is_null()); assert_eq!(null, null); let mut aligned = Aligned8(1); let marked1 = MarkedPtr3N::compose(&mut aligned, 0b01); let marked2 = MarkedPtr3N::compose(&mut aligned, 0b11); assert_ne!(marked1, marked2); assert!(marked1 < marked2); } #[test] fn convert() { let mut aligned = Aligned8(1); let marked = MarkedPtr1N::compose(&mut aligned, 0b1); let convert = MarkedPtr3N::convert(marked); assert_eq!((Some(&aligned), 0b1), unsafe { convert.decompose_ref() }); } }
use core::cmp::{self, PartialEq, PartialOrd}; use core::fmt; use core::marker::PhantomData; use core::ptr::{self, NonNull}; use typenum::{IsGreaterOrEqual, True, Unsigned}; use crate::pointer::{self, MarkedNonNull, MarkedPtr}; /********** impl Clone ****************************************************************************/ impl<T, N> Clone for MarkedPtr<T, N> { #[inline] fn clone(&self) -> Self { Self::new(self.inner) } } /********** impl Copy *****************************************************************************/ impl<T, N> Copy for MarkedPtr<T, N> {} /********** impl inherent (const) *****************************************************************/ impl<T, N> MarkedPtr<T, N> { #[inline] pub const fn new(ptr: *mut T) -> Self { Self { inner: ptr, _marker: PhantomData } } #[inline] pub const fn null() -> Self { Self::new(ptr::null_mut()) } #[inline] pub const fn cast<U>(self) -> MarkedPtr<U, N> { MarkedPtr::new(self.inner as *mut U) } #[inline] pub const fn from_usize(val: usize) -> Self { Self::new(val as *mut _) } } /********** impl inherent *************************************************************************/ impl<T, N: Unsigned> MarkedPtr<T, N> { pub const MARK_BITS: usize = N::USIZE; pub const MARK_MASK: usize = pointer::mark_mask::<T>(Self::MARK_BITS); pub const POINTER_MASK: usize = !Self::MARK_MASK; #[inline] pub fn into_usize(self) -> usize { self.inner as usize } #[inline] pub fn into_ptr(self) -> *mut T { self.inner } #[inline] pub fn compose(ptr: *mut T, tag: usize) -> Self { debug_assert_eq!(0, ptr as usize & Self::MARK_MASK, "pointer must be properly aligned"); Self::new(pointer::compose::<_, N>(ptr, tag)) } #[inline] pub fn convert<M: Unsigned>(other: MarkedPtr<T, M>) -> Self where N: IsGreaterOrEqual<M, Output = True>, { Self::new(other.inner) } #[inline] pub fn clear_tag(self) -> Self { Self::new(self.decompose_ptr()) } #[inline] pub fn with_tag(self, tag: usize) -> Self { Self::compose(self.decompose_ptr(), tag) } #[inline] pub fn decompose(self) -> (*mut T, usize) { pointer::decompose(self.into_usize(), Self::MARK_BITS) } #[inline] pub fn decompose_ptr(self) -> *mut T { pointer::decompose_ptr(self.into_usize(), Self::MARK_BITS) } #[inline] pub fn decompose_tag(self) -> usize { pointer::decompose_tag::<T>(self.into_usize(), Self::MARK_BITS) } #[inline] pub unsafe fn decompose_ref<'a>(self) -> (Option<&'a T>, usize) { let (ptr, tag) = self.decompose(); (ptr.as_ref(), tag) } #[inline] pub unsafe fn decompose_mut<'a>(self) -> (Option<&'a mut T>, usize) { let (ptr, tag) = self.decompose(); (ptr.as_mut(), tag) } #[inline] pub unsafe fn as_ref<'a>(self) -> Option<&'a T> { self.decompose_ptr().as_ref() } #[inline] pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> { self.decompose_ptr().as_mut() } #[inline] pub fn is_null(self) -> bool { self.decompose_ptr().is_null() } } /********** impl Default **************************************************************************/ impl<T, N: Unsigned> Default for MarkedPtr<T, N> { #[inline] fn default() -> Self { Self::null() } } /********** impl Debug ****************************************************************************/ impl<T, N: Unsigned> fmt::Debug for MarkedPtr<T, N> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (ptr, tag) = self.decompose(); f.debug_struct("MarkedPtr").field("ptr", &ptr).field("tag", &tag).finish() } } /********** impl Pointer **************************************************************************/ impl<T, N: Unsigned> fmt::Pointer for MarkedPtr<T, N> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Pointer::fmt(&self.decompose_ptr(), f) } } /********** impl From *****************************************************************************/ impl<T, N: Unsigned> From<*const T> for MarkedPtr<T, N> { #[inline] fn from(ptr: *const T) -> Self { Self::new(ptr as *mut _) } } impl<T, N: Unsigned> From<*mut T> for MarkedPtr<T, N> { fn from(ptr: *mut T) -> Self { Self::new(ptr) } } impl<'a, T, N: Unsigned> From<&'a T> for MarkedPtr<T, N> { #[inline] fn from(reference: &'a T) -> Self { Self::new(reference as *const _ as *mut _) } } impl<'a, T, N: Unsigned> From<&'a mut T> for MarkedPtr<T, N> { #[inline] fn from(reference: &'a mut T) -> Self { Self::new(reference) } } impl<T, N: Unsigned> From<NonNull<T>> for MarkedPtr<T, N> { #[inline] fn from(ptr: NonNull<T>) -> Self { Self::new(ptr.as_ptr()) } } impl<T, N: Unsigned> From<(*mut T, usize)> for MarkedPtr<T, N> { #[inline] fn from(pair: (*mut T, usize)) ->
r: &Self) -> Option<cmp::Ordering> { self.inner.partial_cmp(&other.inner) } } impl<T, N> PartialOrd<MarkedNonNull<T, N>> for MarkedPtr<T, N> { #[inline] fn partial_cmp(&self, other: &MarkedNonNull<T, N>) -> Option<cmp::Ordering> { self.inner.partial_cmp(&other.inner.as_ptr()) } } #[cfg(test)] mod test { use core::ptr; use matches::assert_matches; use typenum::{U0, U1, U3}; use crate::align::Aligned8; type UnmarkedMarkedPtr = super::MarkedPtr<Aligned8<i32>, U0>; type MarkedPtr1N = super::MarkedPtr<Aligned8<i32>, U1>; type MarkedPtr3N = super::MarkedPtr<Aligned8<i32>, U3>; #[test] fn decompose_ref() { let null = MarkedPtr3N::null(); assert_eq!((None, 0), unsafe { null.decompose_ref() }); let marked_null = MarkedPtr3N::compose(ptr::null_mut(), 0b111); assert_eq!((None, 0b111), unsafe { marked_null.decompose_ref() }); let value = Aligned8(1); let marked = MarkedPtr3N::compose(&value as *const Aligned8<i32> as *mut _, 0b11); assert_eq!((Some(&value), 0b11), unsafe { marked.decompose_ref() }); } #[test] fn decompose_mut() { let null = MarkedPtr3N::null(); assert_eq!((None, 0), unsafe { null.decompose_mut() }); let marked_null = MarkedPtr3N::compose(ptr::null_mut(), 0b111); assert_eq!((None, 0b111), unsafe { marked_null.decompose_mut() }); let mut value = Aligned8(1); let marked = MarkedPtr3N::compose(&mut value, 0b11); assert_eq!((Some(&mut value), 0b11), unsafe { marked.decompose_mut() }); } #[test] fn from_usize() { unsafe { let unmarked = UnmarkedMarkedPtr::from_usize(&Aligned8(1) as *const _ as usize); assert_matches!(unmarked.as_ref(), Some(&Aligned8(1))); let tagged = (&Aligned8(1i32) as *const _ as usize) | 0b1; assert_eq!( (Some(&Aligned8(1i32)), 0b1), MarkedPtr1N::from_usize(tagged).decompose_ref() ); } } #[test] fn from() { let mut x = Aligned8(1); let from_ref = MarkedPtr1N::from(&x); let from_mut = MarkedPtr1N::from(&mut x); let from_const_ptr = MarkedPtr1N::from(&x as *const _); let from_mut_ptr = MarkedPtr1N::from(&mut x as *mut _); assert!(from_ref == from_mut && from_const_ptr == from_mut_ptr); } #[test] fn eq_ord() { let null = MarkedPtr3N::null(); assert!(null.is_null()); assert_eq!(null, null); let mut aligned = Aligned8(1); let marked1 = MarkedPtr3N::compose(&mut aligned, 0b01); let marked2 = MarkedPtr3N::compose(&mut aligned, 0b11); assert_ne!(marked1, marked2); assert!(marked1 < marked2); } #[test] fn convert() { let mut aligned = Aligned8(1); let marked = MarkedPtr1N::compose(&mut aligned, 0b1); let convert = MarkedPtr3N::convert(marked); assert_eq!((Some(&aligned), 0b1), unsafe { convert.decompose_ref() }); } }
Self { let (ptr, tag) = pair; Self::compose(ptr, tag) } } impl<T, N: Unsigned> From<(*const T, usize)> for MarkedPtr<T, N> { #[inline] fn from(pair: (*const T, usize)) -> Self { let (ptr, tag) = pair; Self::compose(ptr as *mut _, tag) } } /********** impl PartialEq ************************************************************************/ impl<T, N> PartialEq for MarkedPtr<T, N> { #[inline] fn eq(&self, other: &Self) -> bool { self.inner == other.inner } } impl<T, N> PartialEq<MarkedNonNull<T, N>> for MarkedPtr<T, N> { #[inline] fn eq(&self, other: &MarkedNonNull<T, N>) -> bool { self.inner.eq(&other.inner.as_ptr()) } } /********** impl PartialOrd ***********************************************************************/ impl<T, N> PartialOrd for MarkedPtr<T, N> { #[inline] fn partial_cmp(&self, othe
random
[ { "content": "#[inline]\n\nfn compose<T, N: Unsigned>(ptr: *mut T, tag: usize) -> *mut T {\n\n debug_assert_eq!(ptr as usize & mark_mask::<T>(N::USIZE), 0);\n\n ((ptr as usize) | (mark_mask::<T>(N::USIZE) & tag)) as *mut _\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use core::ptr;\n\n\n\n use typenum...
Rust
lib/grammers-client/src/types/chat/mod.rs
the-blank-x/grammers
ad3fd4b7facafccc1eeacbf1df11a67b58d52e60
mod channel; mod group; mod user; use grammers_tl_types as tl; use std::fmt; pub use channel::Channel; pub use group::Group; pub use user::{Platform, RestrictionReason, User}; #[derive(Clone, Debug)] pub enum Chat { User(User), Group(Group), Channel(Channel), } #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) enum PackedType { User = 0b0000_0010, Bot = 0b0000_0011, Chat = 0b0000_0100, Megagroup = 0b0010_1000, Broadcast = 0b0011_0000, Gigagroup = 0b0011_1000, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PackedChat { pub(crate) ty: PackedType, pub(crate) id: i32, pub(crate) access_hash: Option<i64>, } impl PackedChat { pub fn to_bytes(&self) -> Vec<u8> { let mut res = if let Some(access_hash) = self.access_hash { let mut res = vec![0; 14]; res[6..14].copy_from_slice(&access_hash.to_le_bytes()); res } else { vec![0; 6] }; res[0] = self.ty as u8; res[1] = res.len() as u8; res[2..6].copy_from_slice(&self.id.to_le_bytes()); res } pub fn from_bytes(buf: &[u8]) -> Result<Self, ()> { if buf.len() != 6 && buf.len() != 14 { return Err(()); } if buf[1] as usize != buf.len() { return Err(()); } let ty = match buf[0] { 0b0000_0010 => PackedType::User, 0b0000_0011 => PackedType::Bot, 0b0000_0100 => PackedType::Chat, 0b0010_1000 => PackedType::Megagroup, 0b0011_0000 => PackedType::Broadcast, 0b0011_1000 => PackedType::Gigagroup, _ => return Err(()), }; let id = i32::from_le_bytes([buf[2], buf[3], buf[4], buf[5]]); let access_hash = if buf[1] == 14 { Some(i64::from_le_bytes([ buf[6], buf[7], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], ])) } else { None }; Ok(Self { ty, id, access_hash, }) } pub fn unpack(&self) -> Chat { match self.ty { PackedType::User | PackedType::Bot => { let mut user = User::from_raw(tl::types::UserEmpty { id: self.id }.into()); user.0.access_hash = self.access_hash; Chat::User(user) } PackedType::Chat => { Chat::Group(Group::from_raw(tl::types::ChatEmpty { id: self.id }.into())) } PackedType::Megagroup => Chat::Group(Group::from_raw( tl::types::ChannelForbidden { id: self.id, broadcast: false, megagroup: true, access_hash: self.access_hash.unwrap_or(0), title: String::new(), until_date: None, } .into(), )), PackedType::Broadcast | PackedType::Gigagroup => Chat::Channel(Channel::from_raw( tl::types::ChannelForbidden { id: self.id, broadcast: false, megagroup: true, access_hash: self.access_hash.unwrap_or(0), title: String::new(), until_date: None, } .into(), )), } } } impl fmt::Display for PackedType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::User => "User", Self::Bot => "Bot", Self::Chat => "Group", Self::Megagroup => "Supergroup", Self::Broadcast => "Channel", Self::Gigagroup => "BroadcastGroup", }) } } impl fmt::Display for PackedChat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "PackedChat::{}({})", self.ty, self.id) } } impl Chat { pub(crate) fn from_user(user: tl::enums::User) -> Self { Self::User(User::from_raw(user)) } pub(crate) fn from_chat(chat: tl::enums::Chat) -> Self { use tl::enums::Chat as C; match chat { C::Empty(_) | C::Chat(_) | C::Forbidden(_) => Self::Group(Group::from_raw(chat)), C::Channel(ref channel) => { if channel.broadcast { Self::Channel(Channel::from_raw(chat)) } else { Self::Group(Group::from_raw(chat)) } } C::ChannelForbidden(ref channel) => { if channel.broadcast { Self::Channel(Channel::from_raw(chat)) } else { Self::Group(Group::from_raw(chat)) } } } } pub(crate) fn to_peer(&self) -> tl::enums::Peer { match self { Self::User(user) => user.to_peer(), Self::Group(group) => group.to_peer(), Self::Channel(channel) => channel.to_peer(), } } pub(crate) fn to_input_peer(&self) -> tl::enums::InputPeer { match self { Self::User(user) => user.to_input_peer(), Self::Group(group) => group.to_input_peer(), Self::Channel(channel) => channel.to_input_peer(), } } pub(crate) fn to_input_user(&self) -> Option<tl::enums::InputUser> { match self { Self::User(user) => Some(user.to_input()), Self::Group(_) => None, Self::Channel(_) => None, } } pub(crate) fn to_input_channel(&self) -> Option<tl::enums::InputChannel> { match self { Self::User(_) => None, Self::Group(group) => group.to_input_channel(), Self::Channel(channel) => Some(channel.to_input()), } } pub(crate) fn to_chat_id(&self) -> Option<i32> { match self { Self::User(_) => None, Self::Group(group) => group.to_chat_id(), Self::Channel(_) => None, } } pub fn id(&self) -> i32 { match self { Self::User(user) => user.id(), Self::Group(group) => group.id(), Self::Channel(channel) => channel.id(), } } fn access_hash(&self) -> Option<i64> { match self { Self::User(user) => user.access_hash(), Self::Group(group) => group.access_hash(), Self::Channel(channel) => channel.access_hash(), } } pub fn name(&self) -> &str { match self { Self::User(user) => user.first_name(), Self::Group(group) => group.title(), Self::Channel(channel) => channel.title(), } } pub fn pack(&self) -> PackedChat { let ty = match self { Self::User(user) => { if user.is_bot() { PackedType::Bot } else { PackedType::User } } Self::Group(chat) => { if chat.is_megagroup() { PackedType::Megagroup } else { PackedType::Chat } } Self::Channel(channel) => { if channel.0.gigagroup { PackedType::Gigagroup } else { PackedType::Broadcast } } }; PackedChat { ty, id: self.id(), access_hash: self.access_hash(), } } }
mod channel; mod group; mod user; use grammers_tl_types as tl; use std::fmt; pub use channel::Channel; pub use group::Group; pub use user::{Platform, RestrictionReason, User}; #[derive(Clone, Debug)] pub enum Chat { User(User), Group(Group), Channel(Channel), } #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) enum PackedType { User = 0b0000_0010, Bot = 0b0000_0011, Chat = 0b0000_0100, Megagroup = 0b0010_1000, Broadcast = 0b0011_0000, Gigagroup = 0b0011_1000, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PackedChat { pub(crate) ty: PackedType, pub(crate) id: i32, pub(crate) access_hash: Option<i64>, } impl PackedChat { pub fn to_bytes(&self) -> Vec<u8> { let mut res = if let Some(access_hash) = self.access_hash { let mut res = vec![0; 14]; res[6..14].copy_from_slice(&access_hash.to_le_bytes()); res } else { vec![0; 6] }; res[0] = self.ty as u8; res[1] = res.len() as u8; res[2..6].copy_from_slice(&self.id.to_le_bytes()); res } pub fn from_bytes(buf: &[u8]) -> Result<Self, ()> { if buf.len() != 6 && buf.len() != 14 { return Err(()); } if buf[1] as usize != buf.len() { return Err(()); } let ty = match buf[0] { 0b0000_0010 => PackedType::User, 0b0000_0011 => PackedType::Bot, 0b0000_0100 => PackedType::Chat, 0b0010_1000 => PackedType::Megagroup, 0b0011_0000 => PackedType::Broadcast, 0b0011_1000 => PackedType::Gigagroup, _ => return Err(()), }; let id = i32::from_le_bytes([buf[2], buf[3], buf[4], buf[5]]); let access_hash = if buf[1] == 14 { Some(i64::from_le_bytes([ buf[6], buf[7], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], ])) } else { None }; Ok(Self { ty, id, access_hash, }) } pub fn unpack(&self) -> Chat { match self.ty { PackedType::User | PackedType::Bot => { let mut user = User::from_raw(tl::types::UserEmpty { id: self.id }.into()); user.0.access_hash = self.access_hash; Chat::User(user) } PackedType::Chat => { Chat::Group(Group::from_raw(tl::types::ChatEmpty { id: self.id }.into())) } PackedType::Megagroup => Chat::Group(Group::from_raw( tl::types::ChannelForbidden { id: self.id, broadcast: false, megagroup: true, access_hash: self.access_hash.unwrap_or(0), title: String::new(), until_date: None, } .into(), )), PackedType::Broadcast | PackedType::Gigagroup => Chat::Channel(Channel::from_raw( tl::types::ChannelForbidden { id: self.id, broadcast: false, megagroup: true, access_hash: self.access_hash.unwrap_or(0), title: String::new(), until_date: None, } .into(), )), } } } impl fmt::Display for PackedType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::User => "User", Self::Bot => "Bot", Self::Chat => "Group", Self::Megagroup => "Supergroup", Self::Broadcast => "Channel", Self::Gigagroup => "BroadcastGroup", }) } } impl fmt::Display for PackedChat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "PackedChat::{}({})", self.ty, self.id) } } impl Chat { pub(crate) fn from_user(user: tl::enums::User) -> Self { Self::User(User::from_raw(user)) } pub(crate) fn from_chat(chat: tl::enums::Chat) -> Self { use tl::enums::Chat as C; match chat { C::Empty(_) | C::Chat(_) | C::Forbidden(_) => Self::Group(Group::from_raw(chat)), C::Channel(ref channel) => { if channel.broadcast { Self::Channel(Channel::from_raw(chat)) } else { Self::Group(Group::from_raw(chat)) } } C::ChannelForbidden(ref channel) => { if channel.broadcast { Self::Channel(Channel::from_raw(chat)) } else { Self::Group(Group::from_raw(chat)) } } } } pub(crate) fn to_peer(&self) -> tl::enums::Peer { match self { Self::User(user) => user.to_peer(), Self::Group(group) => group.to_peer(), Self::Channel(channel) => channel.to_peer(), } } pub(crate) fn to_input_peer(&self) -> tl::enums::InputPeer { match self { Self::User(user) => user.to_input_peer(), Self::Group(group) => group.to_input_peer(), Self::Channel(channel) => channel.to_input_peer(), } } pub(crate) fn to_input_user(&self) -> Option<tl::enums::InputUser> { match self { Self::User(user) => Some(user.to_input()), Self::Group(_) => None, Self::Channel(_) => None, } } pub(crate) fn to_input_channel(&self) -> Option<tl::enums::InputChannel> { match self { Self::User(_) => None, Self::Group(group) => group.to_input_channel(),
lf::User(user) => user.access_hash(), Self::Group(group) => group.access_hash(), Self::Channel(channel) => channel.access_hash(), } } pub fn name(&self) -> &str { match self { Self::User(user) => user.first_name(), Self::Group(group) => group.title(), Self::Channel(channel) => channel.title(), } } pub fn pack(&self) -> PackedChat { let ty = match self { Self::User(user) => { if user.is_bot() { PackedType::Bot } else { PackedType::User } } Self::Group(chat) => { if chat.is_megagroup() { PackedType::Megagroup } else { PackedType::Chat } } Self::Channel(channel) => { if channel.0.gigagroup { PackedType::Gigagroup } else { PackedType::Broadcast } } }; PackedChat { ty, id: self.id(), access_hash: self.access_hash(), } } }
Self::Channel(channel) => Some(channel.to_input()), } } pub(crate) fn to_chat_id(&self) -> Option<i32> { match self { Self::User(_) => None, Self::Group(group) => group.to_chat_id(), Self::Channel(_) => None, } } pub fn id(&self) -> i32 { match self { Self::User(user) => user.id(), Self::Group(group) => group.id(), Self::Channel(channel) => channel.id(), } } fn access_hash(&self) -> Option<i64> { match self { Se
random
[ { "content": "fn message_channel_id(message: &tl::enums::Message) -> Option<i32> {\n\n match message {\n\n tl::enums::Message::Empty(_) => None,\n\n tl::enums::Message::Message(m) => match &m.peer_id {\n\n tl::enums::Peer::Channel(c) => Some(c.channel_id),\n\n _ => None,\n...
Rust
edgelet/edgelet-http-workload/src/edge_ca.rs
brotherneeru/iotedge
830259ad2f748db58f7271101ed58fdf5fc7bf3f
#[cfg(not(test))] use aziot_cert_client_async::Client as CertClient; #[cfg(not(test))] use aziot_key_client_async::Client as KeyClient; #[cfg(not(test))] use aziot_key_openssl_engine as KeyEngine; #[cfg(test)] use test_common::client::CertClient; #[cfg(test)] use test_common::client::KeyClient; #[cfg(test)] use test_common::client::KeyEngine; pub(crate) struct EdgeCaRenewal { rotate_key: bool, temp_cert: String, cert_client: std::sync::Arc<futures_util::lock::Mutex<CertClient>>, key_client: std::sync::Arc<futures_util::lock::Mutex<KeyClient>>, key_connector: http_common::Connector, renewal_tx: tokio::sync::mpsc::UnboundedSender<edgelet_core::WatchdogAction>, } impl EdgeCaRenewal { pub fn new( rotate_key: bool, config: &crate::WorkloadConfig, cert_client: std::sync::Arc<futures_util::lock::Mutex<CertClient>>, key_client: std::sync::Arc<futures_util::lock::Mutex<KeyClient>>, key_connector: http_common::Connector, renewal_tx: tokio::sync::mpsc::UnboundedSender<edgelet_core::WatchdogAction>, ) -> Self { let temp_cert = format!("{}-temp", config.edge_ca_cert); EdgeCaRenewal { rotate_key, temp_cert, cert_client, key_client, key_connector, renewal_tx, } } } #[async_trait::async_trait] impl cert_renewal::CertInterface for EdgeCaRenewal { type NewKey = String; async fn get_cert( &mut self, cert_id: &str, ) -> Result<Vec<openssl::x509::X509>, cert_renewal::Error> { let cert_client = self.cert_client.lock().await; let cert = cert_client .get_cert(cert_id) .await .map_err(|_| cert_renewal::Error::retryable_error("failed to retrieve edge CA cert"))?; let cert_chain = openssl::x509::X509::stack_from_pem(&cert) .map_err(|_| cert_renewal::Error::fatal_error("failed to parse edge CA cert"))?; if cert_chain.is_empty() { Err(cert_renewal::Error::fatal_error("no certs in chain")) } else { Ok(cert_chain) } } async fn get_key( &mut self, key_id: &str, ) -> Result<openssl::pkey::PKey<openssl::pkey::Private>, cert_renewal::Error> { let key_client = self.key_client.lock().await; let key_handle = key_client .load_key_pair(key_id) .await .map_err(|_| cert_renewal::Error::retryable_error("failed to get identity cert key"))?; let (private_key, _) = keys(self.key_connector.clone(), &key_handle) .map_err(cert_renewal::Error::retryable_error)?; Ok(private_key) } async fn renew_cert( &mut self, old_cert_chain: &[openssl::x509::X509], key_id: &str, ) -> Result<(Vec<openssl::x509::X509>, Self::NewKey), cert_renewal::Error> { let (key_id, key_handle) = { let key_client = self.key_client.lock().await; if self.rotate_key { let key_id = format!("{}-temp", key_id); if let Ok(key_handle) = key_client.load_key_pair(&key_id).await { key_client.delete_key_pair(&key_handle).await.map_err(|_| { cert_renewal::Error::retryable_error("failed to clear temp key") })?; } let key_handle = key_client .create_key_pair_if_not_exists(&key_id, Some("rsa-2048:*")) .await .map_err(|_| { cert_renewal::Error::retryable_error("failed to generate temp key") })?; (key_id, key_handle) } else { let key_handle = key_client.load_key_pair(key_id).await.map_err(|_| { cert_renewal::Error::retryable_error("failed to get identity cert key") })?; (key_id.to_string(), key_handle) } }; let keys = keys(self.key_connector.clone(), &key_handle) .map_err(cert_renewal::Error::retryable_error)?; let extensions = extensions().map_err(|_| { cert_renewal::Error::fatal_error("failed to generate edge CA extensions") })?; let csr = crate::module::cert::new_csr( old_cert_chain[0].subject_name(), keys, Vec::new(), extensions, ) .map_err(|_| cert_renewal::Error::retryable_error("failed to create csr"))?; let new_cert = { let cert_client = self.cert_client.lock().await; let new_cert = cert_client .create_cert(&self.temp_cert, &csr, None) .await .map_err(|_| cert_renewal::Error::retryable_error("failed to create new cert"))?; if let Err(err) = cert_client.delete_cert(&self.temp_cert).await { log::warn!( "Failed to delete temporary certificate created by cert renewal: {}", err ); } new_cert }; let new_cert_chain = openssl::x509::X509::stack_from_pem(&new_cert) .map_err(|_| cert_renewal::Error::retryable_error("failed to parse new cert"))?; if new_cert_chain.is_empty() { Err(cert_renewal::Error::retryable_error("no certs in chain")) } else { Ok((new_cert_chain, key_id)) } } async fn write_credentials( &mut self, old_cert_chain: &[openssl::x509::X509], new_cert_chain: (&str, &[openssl::x509::X509]), key: (&str, Self::NewKey), ) -> Result<(), cert_renewal::Error> { let (cert_id, new_cert_chain) = (new_cert_chain.0, new_cert_chain.1); let (old_key, new_key) = (key.0, key.1); if old_cert_chain.is_empty() || new_cert_chain.is_empty() { return Err(cert_renewal::Error::retryable_error("no certs in chain")); } let mut new_cert_chain_pem = Vec::new(); for cert in new_cert_chain { let mut cert = cert .to_pem() .map_err(|_| cert_renewal::Error::retryable_error("bad cert"))?; new_cert_chain_pem.append(&mut cert); } let mut old_cert_chain_pem = Vec::new(); for cert in old_cert_chain { let mut cert = cert .to_pem() .map_err(|_| cert_renewal::Error::retryable_error("bad cert"))?; old_cert_chain_pem.append(&mut cert); } { let cert_client = self.cert_client.lock().await; cert_client .import_cert(cert_id, &new_cert_chain_pem) .await .map_err(|_| cert_renewal::Error::retryable_error("failed to import new cert"))?; } if old_key != new_key { let res = { let key_client = self.key_client.lock().await; key_client.move_key_pair(&new_key, old_key).await }; if res.is_err() { let cert_client = self.cert_client.lock().await; cert_client .import_cert(cert_id, &old_cert_chain_pem) .await .map_err(|_| { cert_renewal::Error::retryable_error("failed to restore old cert") })?; } } log::info!("Edge CA was renewed"); if let Err(err) = self .renewal_tx .send(edgelet_core::WatchdogAction::EdgeCaRenewal) { log::warn!("Failed to request module restart: {}", err); } Ok(()) } } pub(crate) fn keys( key_connector: http_common::Connector, key_handle: &aziot_key_common::KeyHandle, ) -> Result< ( openssl::pkey::PKey<openssl::pkey::Private>, openssl::pkey::PKey<openssl::pkey::Public>, ), String, > { let key_client = aziot_key_client::Client::new( aziot_key_common_http::ApiVersion::V2021_05_01, key_connector, ); let key_client = std::sync::Arc::new(key_client); let key_handle = std::ffi::CString::new(key_handle.0.clone()).expect("key handle contained null"); let mut engine = KeyEngine::load(key_client).map_err(|_| "failed to load openssl key engine".to_string())?; let private_key = engine .load_private_key(&key_handle) .map_err(|_| "failed to load edge ca private key".to_string())?; let public_key = engine .load_public_key(&key_handle) .map_err(|_| "failed to load edge ca public key".to_string())?; Ok((private_key, public_key)) } pub(crate) fn extensions( ) -> Result<openssl::stack::Stack<openssl::x509::X509Extension>, openssl::error::ErrorStack> { let mut csr_extensions = openssl::stack::Stack::new()?; let mut key_usage = openssl::x509::extension::KeyUsage::new(); key_usage.critical().digital_signature().key_cert_sign(); let mut basic_constraints = openssl::x509::extension::BasicConstraints::new(); basic_constraints.ca().critical().pathlen(0); let key_usage = key_usage.build()?; let basic_constraints = basic_constraints.build()?; csr_extensions.push(key_usage)?; csr_extensions.push(basic_constraints)?; Ok(csr_extensions) } #[cfg(test)] mod tests { use super::EdgeCaRenewal; use super::{CertClient, KeyClient}; use cert_renewal::CertInterface; fn new_renewal(rotate_key: bool) -> EdgeCaRenewal { let settings = edgelet_test_utils::Settings::default(); let device_info = aziot_identity_common::AzureIoTSpec { hub_name: "test-hub.test.net".to_string(), gateway_host: "gateway-host.test.net".to_string(), device_id: aziot_identity_common::DeviceId("test-device".to_string()), module_id: None, gen_id: None, auth: None, }; let config = crate::WorkloadConfig::new(&settings, &device_info); let cert_client = CertClient::default(); let cert_client = std::sync::Arc::new(futures_util::lock::Mutex::new(cert_client)); let key_client = KeyClient::default(); let key_client = std::sync::Arc::new(futures_util::lock::Mutex::new(key_client)); let key_connector = url::Url::parse("unix:///tmp/test.sock").unwrap(); let key_connector = http_common::Connector::new(&key_connector).unwrap(); let (renewal_tx, _) = tokio::sync::mpsc::unbounded_channel::<edgelet_core::WatchdogAction>(); EdgeCaRenewal::new( rotate_key, &config, cert_client, key_client, key_connector, renewal_tx, ) } #[tokio::test] async fn get_cert() { let mut renewal = new_renewal(true); let (cert_1, _) = test_common::credential::test_certificate("test-cert-1"); let (cert_2, _) = test_common::credential::test_certificate("test-cert-2"); let mut cert_1_pem = cert_1.to_pem().unwrap(); let mut cert_2_pem = cert_2.to_pem().unwrap(); cert_1_pem.append(&mut cert_2_pem); let test_cert_chain = vec![cert_1, cert_2]; { let cert_client = renewal.cert_client.lock().await; cert_client.import_cert("empty-cert", &[]).await.unwrap(); cert_client .import_cert("test-cert", &cert_1_pem) .await .unwrap(); } renewal.get_cert("empty-cert").await.unwrap_err(); renewal.get_cert("does-not-exist").await.unwrap_err(); let cert_chain = renewal.get_cert("test-cert").await.unwrap(); assert_eq!(2, cert_chain.len()); assert_eq!( test_cert_chain[0].to_pem().unwrap(), cert_chain[0].to_pem().unwrap() ); assert_eq!( test_cert_chain[1].to_pem().unwrap(), cert_chain[1].to_pem().unwrap() ); } #[tokio::test] async fn get_key() { let mut renewal = new_renewal(true); renewal.get_key("test-key").await.unwrap(); { let mut key_client = renewal.key_client.lock().await; key_client.load_key_pair_ok = false; } renewal.get_key("test-key").await.unwrap_err(); } }
#[cfg(not(test))] use aziot_cert_client_async::Client as CertClient; #[cfg(not(test))] use aziot_key_client_async::Client as KeyClient; #[cfg(not(test))] use aziot_key_openssl_engine as KeyEngine; #[cfg(test)] use test_common::client::CertClient; #[cfg(test)] use test_common::client::KeyClient; #[cfg(test)] use test_common::client::KeyEngine; pub(crate) struct EdgeCaRenewal { rotate_key: bool, temp_cert: String, cert_client: std::sync::Arc<futures_util::lock::Mutex<CertClient>>, key_client: std::sync::Arc<futures_util::lock::Mutex<KeyClient>>, key_connector: http_common::Connector, renewal_tx: tokio::sync::mpsc::UnboundedSender<edgelet_core::WatchdogAction>, } impl EdgeCaRenewal { pub fn new( rotate_key: bool, config: &crate::WorkloadConfig, cert_client: std::sync::Arc<futures_util::lock::Mutex<CertClient>>, key_client: std::sync::Arc<futures_util::lock::Mutex<KeyClient>>, key_connector: http_common::Connector, renewal_tx: tokio::sync::mpsc::UnboundedSender<edgelet_core::WatchdogAction>, ) -> Self { let temp_cert = format!("{}-temp", config.edge_ca_cert); EdgeCaRenewal { rotate_key, temp_cert, cert_client, key_client, key_connector, renewal_tx, } } } #[async_trait::async_trait] impl cert_renewal::CertInterface for EdgeCaRenewal { type NewKey = String; async fn get_cert( &mut self, cert_id: &str, ) -> Result<Vec<openssl::x509::X509>, cert_renewal::Error> { let cert_client = self.cert_client.lock().await; let cert = cert_client .get_cert(cert_id) .await .map_err(|_| cert_renewal::Error::retryable_error("failed to retrieve edge CA cert"))?; let cert_chain = openssl::x509::X509::stack_from_pem(&cert) .map_err(|_| cert_renewal::Error::fatal_error("failed to parse edge CA cert"))?; if cert_chain.is_empty() { Err(cert_renewal::Error::fatal_error("no certs in chain")) } else { Ok(cert_chain) } }
async fn renew_cert( &mut self, old_cert_chain: &[openssl::x509::X509], key_id: &str, ) -> Result<(Vec<openssl::x509::X509>, Self::NewKey), cert_renewal::Error> { let (key_id, key_handle) = { let key_client = self.key_client.lock().await; if self.rotate_key { let key_id = format!("{}-temp", key_id); if let Ok(key_handle) = key_client.load_key_pair(&key_id).await { key_client.delete_key_pair(&key_handle).await.map_err(|_| { cert_renewal::Error::retryable_error("failed to clear temp key") })?; } let key_handle = key_client .create_key_pair_if_not_exists(&key_id, Some("rsa-2048:*")) .await .map_err(|_| { cert_renewal::Error::retryable_error("failed to generate temp key") })?; (key_id, key_handle) } else { let key_handle = key_client.load_key_pair(key_id).await.map_err(|_| { cert_renewal::Error::retryable_error("failed to get identity cert key") })?; (key_id.to_string(), key_handle) } }; let keys = keys(self.key_connector.clone(), &key_handle) .map_err(cert_renewal::Error::retryable_error)?; let extensions = extensions().map_err(|_| { cert_renewal::Error::fatal_error("failed to generate edge CA extensions") })?; let csr = crate::module::cert::new_csr( old_cert_chain[0].subject_name(), keys, Vec::new(), extensions, ) .map_err(|_| cert_renewal::Error::retryable_error("failed to create csr"))?; let new_cert = { let cert_client = self.cert_client.lock().await; let new_cert = cert_client .create_cert(&self.temp_cert, &csr, None) .await .map_err(|_| cert_renewal::Error::retryable_error("failed to create new cert"))?; if let Err(err) = cert_client.delete_cert(&self.temp_cert).await { log::warn!( "Failed to delete temporary certificate created by cert renewal: {}", err ); } new_cert }; let new_cert_chain = openssl::x509::X509::stack_from_pem(&new_cert) .map_err(|_| cert_renewal::Error::retryable_error("failed to parse new cert"))?; if new_cert_chain.is_empty() { Err(cert_renewal::Error::retryable_error("no certs in chain")) } else { Ok((new_cert_chain, key_id)) } } async fn write_credentials( &mut self, old_cert_chain: &[openssl::x509::X509], new_cert_chain: (&str, &[openssl::x509::X509]), key: (&str, Self::NewKey), ) -> Result<(), cert_renewal::Error> { let (cert_id, new_cert_chain) = (new_cert_chain.0, new_cert_chain.1); let (old_key, new_key) = (key.0, key.1); if old_cert_chain.is_empty() || new_cert_chain.is_empty() { return Err(cert_renewal::Error::retryable_error("no certs in chain")); } let mut new_cert_chain_pem = Vec::new(); for cert in new_cert_chain { let mut cert = cert .to_pem() .map_err(|_| cert_renewal::Error::retryable_error("bad cert"))?; new_cert_chain_pem.append(&mut cert); } let mut old_cert_chain_pem = Vec::new(); for cert in old_cert_chain { let mut cert = cert .to_pem() .map_err(|_| cert_renewal::Error::retryable_error("bad cert"))?; old_cert_chain_pem.append(&mut cert); } { let cert_client = self.cert_client.lock().await; cert_client .import_cert(cert_id, &new_cert_chain_pem) .await .map_err(|_| cert_renewal::Error::retryable_error("failed to import new cert"))?; } if old_key != new_key { let res = { let key_client = self.key_client.lock().await; key_client.move_key_pair(&new_key, old_key).await }; if res.is_err() { let cert_client = self.cert_client.lock().await; cert_client .import_cert(cert_id, &old_cert_chain_pem) .await .map_err(|_| { cert_renewal::Error::retryable_error("failed to restore old cert") })?; } } log::info!("Edge CA was renewed"); if let Err(err) = self .renewal_tx .send(edgelet_core::WatchdogAction::EdgeCaRenewal) { log::warn!("Failed to request module restart: {}", err); } Ok(()) } } pub(crate) fn keys( key_connector: http_common::Connector, key_handle: &aziot_key_common::KeyHandle, ) -> Result< ( openssl::pkey::PKey<openssl::pkey::Private>, openssl::pkey::PKey<openssl::pkey::Public>, ), String, > { let key_client = aziot_key_client::Client::new( aziot_key_common_http::ApiVersion::V2021_05_01, key_connector, ); let key_client = std::sync::Arc::new(key_client); let key_handle = std::ffi::CString::new(key_handle.0.clone()).expect("key handle contained null"); let mut engine = KeyEngine::load(key_client).map_err(|_| "failed to load openssl key engine".to_string())?; let private_key = engine .load_private_key(&key_handle) .map_err(|_| "failed to load edge ca private key".to_string())?; let public_key = engine .load_public_key(&key_handle) .map_err(|_| "failed to load edge ca public key".to_string())?; Ok((private_key, public_key)) } pub(crate) fn extensions( ) -> Result<openssl::stack::Stack<openssl::x509::X509Extension>, openssl::error::ErrorStack> { let mut csr_extensions = openssl::stack::Stack::new()?; let mut key_usage = openssl::x509::extension::KeyUsage::new(); key_usage.critical().digital_signature().key_cert_sign(); let mut basic_constraints = openssl::x509::extension::BasicConstraints::new(); basic_constraints.ca().critical().pathlen(0); let key_usage = key_usage.build()?; let basic_constraints = basic_constraints.build()?; csr_extensions.push(key_usage)?; csr_extensions.push(basic_constraints)?; Ok(csr_extensions) } #[cfg(test)] mod tests { use super::EdgeCaRenewal; use super::{CertClient, KeyClient}; use cert_renewal::CertInterface; fn new_renewal(rotate_key: bool) -> EdgeCaRenewal { let settings = edgelet_test_utils::Settings::default(); let device_info = aziot_identity_common::AzureIoTSpec { hub_name: "test-hub.test.net".to_string(), gateway_host: "gateway-host.test.net".to_string(), device_id: aziot_identity_common::DeviceId("test-device".to_string()), module_id: None, gen_id: None, auth: None, }; let config = crate::WorkloadConfig::new(&settings, &device_info); let cert_client = CertClient::default(); let cert_client = std::sync::Arc::new(futures_util::lock::Mutex::new(cert_client)); let key_client = KeyClient::default(); let key_client = std::sync::Arc::new(futures_util::lock::Mutex::new(key_client)); let key_connector = url::Url::parse("unix:///tmp/test.sock").unwrap(); let key_connector = http_common::Connector::new(&key_connector).unwrap(); let (renewal_tx, _) = tokio::sync::mpsc::unbounded_channel::<edgelet_core::WatchdogAction>(); EdgeCaRenewal::new( rotate_key, &config, cert_client, key_client, key_connector, renewal_tx, ) } #[tokio::test] async fn get_cert() { let mut renewal = new_renewal(true); let (cert_1, _) = test_common::credential::test_certificate("test-cert-1"); let (cert_2, _) = test_common::credential::test_certificate("test-cert-2"); let mut cert_1_pem = cert_1.to_pem().unwrap(); let mut cert_2_pem = cert_2.to_pem().unwrap(); cert_1_pem.append(&mut cert_2_pem); let test_cert_chain = vec![cert_1, cert_2]; { let cert_client = renewal.cert_client.lock().await; cert_client.import_cert("empty-cert", &[]).await.unwrap(); cert_client .import_cert("test-cert", &cert_1_pem) .await .unwrap(); } renewal.get_cert("empty-cert").await.unwrap_err(); renewal.get_cert("does-not-exist").await.unwrap_err(); let cert_chain = renewal.get_cert("test-cert").await.unwrap(); assert_eq!(2, cert_chain.len()); assert_eq!( test_cert_chain[0].to_pem().unwrap(), cert_chain[0].to_pem().unwrap() ); assert_eq!( test_cert_chain[1].to_pem().unwrap(), cert_chain[1].to_pem().unwrap() ); } #[tokio::test] async fn get_key() { let mut renewal = new_renewal(true); renewal.get_key("test-key").await.unwrap(); { let mut key_client = renewal.key_client.lock().await; key_client.load_key_pair_ok = false; } renewal.get_key("test-key").await.unwrap_err(); } }
async fn get_key( &mut self, key_id: &str, ) -> Result<openssl::pkey::PKey<openssl::pkey::Private>, cert_renewal::Error> { let key_client = self.key_client.lock().await; let key_handle = key_client .load_key_pair(key_id) .await .map_err(|_| cert_renewal::Error::retryable_error("failed to get identity cert key"))?; let (private_key, _) = keys(self.key_connector.clone(), &key_handle) .map_err(cert_renewal::Error::retryable_error)?; Ok(private_key) }
function_block-full_function
[ { "content": "pub fn prepare_cert_uri_module(hub_name: &str, device_id: &str, module_id: &str) -> String {\n\n format!(\"URI: azureiot://{hub_name}/devices/{device_id}/modules/{module_id}\")\n\n}\n", "file_path": "edgelet/edgelet-utils/src/lib.rs", "rank": 0, "score": 326233.4091490721 }, { ...
Rust
httpfs/tests/httpfs.rs
obonobo/ecurl
715d407f287728933cadc35eaad927d02e10ec73
#![allow(clippy::type_complexity)] #[cfg(test)] pub mod test_utils; use crate::test_utils::*; use core::panic; use httpfs::bullshit_scanner::BullshitScanner; use std::{ io::Write, net::TcpStream, sync::{mpsc, Arc, Mutex}, thread, }; use test_utils::better_ureq::*; lazy_static::lazy_static! { static ref SERVERS: Mutex<AddressCountingServerFactory> = Mutex::new( AddressCountingServerFactory::default(), ); } fn server() -> ServerDropper { SERVERS.lock().unwrap().next_server() } #[test] fn test_simple_get() { let handle = server(); let contents = "Hello world!\n"; let file = TempFile::new_or_panic("hello!.txt", contents); let got = ureq::get(&handle.file_addr(&file.name)) .call() .unwrap() .into_string() .unwrap(); assert_eq!(contents, &got); } #[test] fn test_simple_post() { let handle = server(); let contents = "Hello world!\n"; let file = TempFile::new_or_panic("hello.txt", ""); let posted = ureq::post(&handle.file_addr(&file.name)) .send_string(contents) .unwrap(); assert_eq!(posted.status(), 201); let got = ureq::get(&handle.file_addr(&file.name)) .call() .unwrap() .into_string() .unwrap(); assert_eq!(contents, &got); } #[test] fn test_not_found() { let handle = server(); assertions::assert_request_returns_error( ureq::get(&handle.file_addr("hello.txt")), 404, Some("File '/hello.txt' could not be found on the server (directory being served is ./)\n"), ); } #[test] fn test_forbidden() { let handle = server(); let request = "GET /../../hello.txt HTTP/1.1\r\n\r\n"; let mut sock = TcpStream::connect(handle.addr().trim_start_matches("http://")).unwrap(); sock.write_all(request.as_bytes()).unwrap(); let mut scnr = BullshitScanner::new(&mut sock); let status = scnr .next_line() .unwrap() .0 .split_once(' ') .map(|pair| String::from(pair.1)) .unwrap(); assert_eq!("403 Forbidden", status); let body = scnr .lines() .map(|l| l.0) .skip_while(|line| !line.is_empty()) .collect::<Vec<_>>() .join("\n"); assert!(body.contains("hello.txt' is located outside the directory that is being served")) } #[test] fn test_multiple_clients_get_same_file() { let server = server(); let contents = "Hello world\n"; let file = TempFile::new("hello.txt", contents).unwrap(); let n = 25; let mut threads = Vec::with_capacity(n); let (taskout, taskin) = mpsc::channel::<Result<(u16, String), ureq::Error>>(); let addr = server.file_addr(&file.name); for _ in 0..n { let (out, addr) = (taskout.clone(), addr.clone()); threads.push(thread::spawn(move || { out.send(ureq_get_errors_are_ok(&addr)).unwrap() })); } threads.into_iter().for_each(|t| t.join().unwrap()); for (i, res) in taskin.iter().take(n).enumerate() { match res { Ok((code, body)) => { assert_eq!(200, code); assert_eq!(contents, body); } Err(e) => panic!("Got an error on request {}: {}", i, e), } } } #[test] fn test_multiple_clients_reading_and_writing_same_file() { let handle = server(); let contents = "Hello world\n"; let file = TempFile::new("hello.txt", contents).unwrap(); let n = 25; let mut threads = Vec::with_capacity(n); let (taskout, taskin) = mpsc::channel::<Result<(u16, String), ureq::Error>>(); let addr = handle.file_addr(&file.name); let mut read = 0; let mut task = || -> Arc<dyn Fn(&str, &str) -> Result<(u16, String), ureq::Error> + Send + Sync> { read += 1; Arc::new(if read % 2 == 0 { |path, _| ureq_get_errors_are_ok(path) } else { ureq_post_errors_are_ok }) }; for i in 0..n { let (out, path, task) = (taskout.clone(), addr.clone(), task()); let body = format!("From thread {}", i); threads.push(thread::spawn(move || out.send(task(&path, &body)).unwrap())); } threads.into_iter().for_each(|t| t.join().unwrap()); let results = taskin.iter().take(n).collect::<Vec<_>>(); for (i, res) in results.iter().enumerate() { match res { Ok((code, body)) => match code { 200 => assert!( body.contains("From thread") || body.contains(contents), "Body: {}", body ), 201 => assert_eq!("", body), code => panic!("Expected status 200 or 201 but got {}", code), }, Err(e) => panic!("Got an error on request {}: {}", i, e), } } }
#![allow(clippy::type_complexity)] #[cfg(test)] pub mod test_utils; use crate::test_utils::*; use core::panic; use httpfs::bullshit_scanner::BullshitScanner; use std::{ io::Write, net::TcpStream, sync::{mpsc, Arc, Mutex}, thread, }; use test_utils::better_ureq::*; lazy_static::lazy_static! { static ref SERVERS: Mutex<AddressCountingServerFactory> = Mutex::new( AddressCountingServerFactory::default(), ); } fn server() -> ServerDropper { SERVERS.lock().unwrap().next_server() } #[test] fn test_simple_get() { let handle = server(); let contents = "Hello world!\n"; let file = TempFile::new_or_panic("hello!.txt", contents); let got = ureq::get(&handle.file_addr(&file.name)) .call() .unwrap() .into_string() .unwrap(); assert_eq!(contents, &got); } #[test] fn test_simple_post() { let handle = server(); let contents = "Hello world!\n"; let file = TempFile::new_or_panic("hello.txt", ""); let posted = ureq::post(&handle.file_addr(&file.name)) .send_string(contents) .unwrap(); assert_eq!(posted.status(), 201); let got = ureq::get(&handle.file_addr(&file.name)) .call() .unwrap() .into_string() .unwrap(); assert_eq!(contents, &got); } #[test] fn test_not_found() { let handle = server(); assertions::assert_request_returns_error( ureq::get(&handle.file_addr("hello.txt")), 404, Some("File '/hello.txt' could not be found on the server (directory being served is ./)\n"), ); } #[test] fn test_forbidden() { let handle = server(); let request = "GET /../../hello.txt HTTP/1.1\r\n\r\n"; let mut sock = TcpStream::connect(handle.addr().trim_start_matches("http://")).unwrap(); sock.write_all(request.as_bytes()).unwrap(); let mut scnr = BullshitScanner::new(&mut sock); let status = scnr .next_line() .unwrap() .0 .split_once(' ') .map(|pair| String::from(pair.1)) .unwrap(); assert_eq!("403 Forbidden", status); let body = scnr .lines() .map(|l| l.0) .skip_while(|line| !line.is_empty()) .colle
#[test] fn test_multiple_clients_get_same_file() { let server = server(); let contents = "Hello world\n"; let file = TempFile::new("hello.txt", contents).unwrap(); let n = 25; let mut threads = Vec::with_capacity(n); let (taskout, taskin) = mpsc::channel::<Result<(u16, String), ureq::Error>>(); let addr = server.file_addr(&file.name); for _ in 0..n { let (out, addr) = (taskout.clone(), addr.clone()); threads.push(thread::spawn(move || { out.send(ureq_get_errors_are_ok(&addr)).unwrap() })); } threads.into_iter().for_each(|t| t.join().unwrap()); for (i, res) in taskin.iter().take(n).enumerate() { match res { Ok((code, body)) => { assert_eq!(200, code); assert_eq!(contents, body); } Err(e) => panic!("Got an error on request {}: {}", i, e), } } } #[test] fn test_multiple_clients_reading_and_writing_same_file() { let handle = server(); let contents = "Hello world\n"; let file = TempFile::new("hello.txt", contents).unwrap(); let n = 25; let mut threads = Vec::with_capacity(n); let (taskout, taskin) = mpsc::channel::<Result<(u16, String), ureq::Error>>(); let addr = handle.file_addr(&file.name); let mut read = 0; let mut task = || -> Arc<dyn Fn(&str, &str) -> Result<(u16, String), ureq::Error> + Send + Sync> { read += 1; Arc::new(if read % 2 == 0 { |path, _| ureq_get_errors_are_ok(path) } else { ureq_post_errors_are_ok }) }; for i in 0..n { let (out, path, task) = (taskout.clone(), addr.clone(), task()); let body = format!("From thread {}", i); threads.push(thread::spawn(move || out.send(task(&path, &body)).unwrap())); } threads.into_iter().for_each(|t| t.join().unwrap()); let results = taskin.iter().take(n).collect::<Vec<_>>(); for (i, res) in results.iter().enumerate() { match res { Ok((code, body)) => match code { 200 => assert!( body.contains("From thread") || body.contains(contents), "Body: {}", body ), 201 => assert_eq!("", body), code => panic!("Expected status 200 or 201 but got {}", code), }, Err(e) => panic!("Got an error on request {}: {}", i, e), } } }
ct::<Vec<_>>() .join("\n"); assert!(body.contains("hello.txt' is located outside the directory that is being served")) }
function_block-function_prefixed
[ { "content": "fn parse_request_line(scnr: &mut BullshitScanner) -> Result<(Proto, Method, String), ServerError> {\n\n let words = scnr\n\n .next_line()\n\n .map(|l| l.0)\n\n .map_err(|e| ServerError::new().msg(&format!(\"{}\", e)))?\n\n .split_whitespace()\n\n .map(String::...