text
stringlengths
8
4.13M
extern crate sigar_rs; use sigar_rs::{net, strip_bytes}; use std::str; fn main() { let ifaces = net::interface_list().unwrap(); println!("{:?} interfaces:", ifaces.len()); for cs in ifaces { println!("\t{:?}", cs.into_string().unwrap()); } let interface = net::interface_config_primary().unwrap(); println!("primary interface:"); let name = str::from_utf8(strip_bytes(&interface.name[..])).unwrap(); println!("\tname: {:?}", name); println!( "\ttype_: {:?}", str::from_utf8(strip_bytes(&interface.type_[..])).unwrap() ); println!( "\tdescription: {:?}", str::from_utf8(strip_bytes(&interface.description[..])).unwrap() ); println!("\thwaddr: {:?}", interface.hwaddr); println!("\taddress: {:?}", interface.address); println!("\tdestination: {:?}", interface.destination); println!("\tbroadcast: {:?}", interface.broadcast); println!("\tnetmask: {:?}", interface.netmask); println!("\taddress6: {:?}", interface.address6); println!("\tprefix6_length: {:?}", interface.prefix6_length); println!("\tscope6: {:?}", interface.scope6); println!("\tflags: {:?}", interface.flags); println!("\tmtu: {:?}", interface.mtu); let stat = net::interface_stat(name).unwrap(); println!("interface stat for {:?}: {:?}", name, stat); }
use matcher::MatchScope; use serde::{Deserialize, Serialize}; use std::borrow::Cow; use types::{ClapItem, FuzzyText}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct ProjectTag { name: String, path: String, pattern: String, line: usize, kind: String, } impl ProjectTag { /// Builds the line for displaying the tag info. pub fn format_proj_tag(&self) -> String { let name_lnum = format!("{}:{}", self.name, self.line); let kind = format!("[{}@{}]", self.kind, self.path); let pattern = super::trim_pattern(&self.pattern); format!( "{text:<text_width$} {kind:<kind_width$} {pattern}", text = name_lnum, text_width = 30, kind = kind, kind_width = 30, ) } pub fn into_project_tag_item(self) -> ProjectTagItem { let output_text = self.format_proj_tag(); ProjectTagItem { name: self.name, kind: self.kind, output_text, } } } #[derive(Debug)] pub struct ProjectTagItem { pub name: String, pub kind: String, pub output_text: String, } impl ClapItem for ProjectTagItem { fn raw_text(&self) -> &str { &self.output_text } fn fuzzy_text(&self, _match_scope: MatchScope) -> Option<FuzzyText> { Some(FuzzyText::new(&self.name, 0)) } fn output_text(&self) -> Cow<'_, str> { Cow::Borrowed(&self.output_text) } fn icon(&self, _icon: icon::Icon) -> Option<icon::IconType> { Some(icon::tags_kind_icon(&self.kind)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_deserialize_project_tag() { let data = r#"{"_type": "tag", "name": "Exec", "path": "crates/maple_cli/src/cmd/exec.rs", "pattern": "/^pub struct Exec {$/", "line": 10, "kind": "struct"}"#; let tag: ProjectTag = serde_json::from_str(data).unwrap(); assert_eq!( tag, ProjectTag { name: "Exec".into(), path: "crates/maple_cli/src/cmd/exec.rs".into(), pattern: "/^pub struct Exec {$/".into(), line: 10, kind: "struct".into() } ); } }
//! A driver concretely executes a Falcon IL programs. use crate::architecture::Architecture; use crate::executor::successor::*; use crate::executor::State; use crate::il; use crate::Error; use crate::RC; /// A driver for a concrete executor over Falcon IL. #[derive(Debug, Clone)] pub struct Driver { program: RC<il::Program>, location: il::ProgramLocation, state: State, architecture: RC<dyn Architecture>, } impl Driver { /// Create a new driver for concrete execution over Falcon IL. pub fn new( program: RC<il::Program>, location: il::ProgramLocation, state: State, architecture: RC<dyn Architecture>, ) -> Driver { Driver { program, location, state, architecture, } } /// Step forward over Falcon IL. pub fn step(self) -> Result<Driver, Error> { let location = self.location.apply(&self.program)?; match *location.function_location() { il::RefFunctionLocation::Instruction(_, instruction) => { let successor = self.state.execute(instruction.operation())?; match successor.type_().clone() { SuccessorType::FallThrough => { let locations = location.forward()?; if locations.len() == 1 { Ok(Driver::new( self.program.clone(), locations[0].clone().into(), successor.into(), self.architecture, )) } else { // every location should be an edge, and only one // edge should be satisfiable for location in locations { if let il::RefFunctionLocation::Edge(edge) = *location.function_location() { if successor .state() .symbolize_and_eval( edge.condition() .ok_or("Failed to get edge condition")?, )? .is_one() { return Ok(Driver::new( self.program.clone(), location.clone().into(), successor.into(), self.architecture, )); } } } Err(Error::ExecutorNoValidLocation) } } SuccessorType::Branch(address) => { match il::RefProgramLocation::from_address(&self.program, address) { Some(location) => Ok(Driver::new( self.program.clone(), location.into(), successor.into(), self.architecture, )), None => { let state: State = successor.into(); let function = self .architecture .translator() .translate_function(state.memory(), address) .map_err(|e| Error::ExecutorLiftFail(address, Box::new(e)))?; let mut program = self.program.clone(); RC::make_mut(&mut program).add_function(function); let location: il::ProgramLocation = il::RefProgramLocation::from_address(&program, address) .ok_or("Failed to get location for newly lifted function")? .into(); Ok(Driver::new(program, location, state, self.architecture)) } } } SuccessorType::Intrinsic(ref intrinsic) => Err(Error::UnhandledIntrinsic( intrinsic.instruction_str().to_string(), )), } } il::RefFunctionLocation::Edge(_) => { let locations = location.forward()?; Ok(Driver::new( self.program.clone(), locations[0].clone().into(), self.state, self.architecture, )) } il::RefFunctionLocation::EmptyBlock(_) => { let locations = location.forward()?; if locations.len() == 1 { return Ok(Driver::new( self.program.clone(), locations[0].clone().into(), self.state, self.architecture, )); } else { for location in locations { if let il::RefFunctionLocation::Edge(edge) = *location.function_location() { if self .state .symbolize_and_eval( edge.condition().ok_or(Error::ExecutorNoEdgeCondition)?, )? .is_one() { return Ok(Driver::new( self.program.clone(), location.clone().into(), self.state, self.architecture, )); } } } } Err(Error::ExecutorNoValidLocation) } } } /// Retrieve the Falcon IL program associated with this driver. pub fn program(&self) -> &il::Program { &self.program } /// If this driver is sitting on an instruction with an address, return /// that address. pub fn address(&self) -> Option<u64> { self.location .apply(&self.program) .expect("Failed to apply program location") .address() } /// Retrieve the `il::ProgramLocation` associated with this driver. pub fn location(&self) -> &il::ProgramLocation { &self.location } /// Retrieve the concrete `State` associated with this driver. pub fn state(&self) -> &State { &self.state } /// Retrieve a mutable reference to the `State` associated with this driver. pub fn state_mut(&mut self) -> &mut State { &mut self.state } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtGui/qmatrix.h // dst-file: /src/gui/qmatrix.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use std::ops::Deref; use super::super::core::qpoint::*; // 771 use super::qpolygon::*; // 773 use super::qregion::*; // 773 use super::super::core::qline::*; // 771 use super::qpainterpath::*; // 773 use super::super::core::qrect::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QMatrix_Class_Size() -> c_int; // proto: qreal QMatrix::dx(); fn C_ZNK7QMatrix2dxEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: qreal QMatrix::dy(); fn C_ZNK7QMatrix2dyEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: QMatrix & QMatrix::scale(qreal sx, qreal sy); fn C_ZN7QMatrix5scaleEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double) -> *mut c_void; // proto: QMatrix & QMatrix::translate(qreal dx, qreal dy); fn C_ZN7QMatrix9translateEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double) -> *mut c_void; // proto: qreal QMatrix::determinant(); fn C_ZNK7QMatrix11determinantEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: QMatrix & QMatrix::shear(qreal sh, qreal sv); fn C_ZN7QMatrix5shearEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double) -> *mut c_void; // proto: void QMatrix::QMatrix(); fn C_ZN7QMatrixC2Ev() -> u64; // proto: qreal QMatrix::m21(); fn C_ZNK7QMatrix3m21Ev(qthis: u64 /* *mut c_void*/) -> c_double; // proto: QPointF QMatrix::map(const QPointF & p); fn C_ZNK7QMatrix3mapERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QPolygonF QMatrix::map(const QPolygonF & a); fn C_ZNK7QMatrix3mapERK9QPolygonF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix::map(qreal x, qreal y, qreal * tx, qreal * ty); fn C_ZNK7QMatrix3mapEddPdS0_(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: *mut c_double, arg3: *mut c_double); // proto: QMatrix & QMatrix::rotate(qreal a); fn C_ZN7QMatrix6rotateEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> *mut c_void; // proto: QRegion QMatrix::map(const QRegion & r); fn C_ZNK7QMatrix3mapERK7QRegion(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix::setMatrix(qreal m11, qreal m12, qreal m21, qreal m22, qreal dx, qreal dy); fn C_ZN7QMatrix9setMatrixEdddddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: c_double, arg5: c_double); // proto: void QMatrix::QMatrix(const QMatrix & matrix); fn C_ZN7QMatrixC2ERKS_(arg0: *mut c_void) -> u64; // proto: void QMatrix::reset(); fn C_ZN7QMatrix5resetEv(qthis: u64 /* *mut c_void*/); // proto: QLineF QMatrix::map(const QLineF & l); fn C_ZNK7QMatrix3mapERK6QLineF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QPainterPath QMatrix::map(const QPainterPath & p); fn C_ZNK7QMatrix3mapERK12QPainterPath(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: qreal QMatrix::m11(); fn C_ZNK7QMatrix3m11Ev(qthis: u64 /* *mut c_void*/) -> c_double; // proto: QPolygon QMatrix::mapToPolygon(const QRect & r); fn C_ZNK7QMatrix12mapToPolygonERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QMatrix QMatrix::inverted(bool * invertible); fn C_ZNK7QMatrix8invertedEPb(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> *mut c_void; // proto: QPoint QMatrix::map(const QPoint & p); fn C_ZNK7QMatrix3mapERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix::map(int x, int y, int * tx, int * ty); fn C_ZNK7QMatrix3mapEiiPiS0_(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_int, arg3: *mut c_int); // proto: QLine QMatrix::map(const QLine & l); fn C_ZNK7QMatrix3mapERK5QLine(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QRectF QMatrix::mapRect(const QRectF & ); fn C_ZNK7QMatrix7mapRectERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: bool QMatrix::isIdentity(); fn C_ZNK7QMatrix10isIdentityEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: qreal QMatrix::m12(); fn C_ZNK7QMatrix3m12Ev(qthis: u64 /* *mut c_void*/) -> c_double; // proto: bool QMatrix::isInvertible(); fn C_ZNK7QMatrix12isInvertibleEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QRect QMatrix::mapRect(const QRect & ); fn C_ZNK7QMatrix7mapRectERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix::QMatrix(qreal m11, qreal m12, qreal m21, qreal m22, qreal dx, qreal dy); fn C_ZN7QMatrixC2Edddddd(arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: c_double, arg5: c_double) -> u64; // proto: qreal QMatrix::m22(); fn C_ZNK7QMatrix3m22Ev(qthis: u64 /* *mut c_void*/) -> c_double; // proto: QPolygon QMatrix::map(const QPolygon & a); fn C_ZNK7QMatrix3mapERK8QPolygon(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; } // <= ext block end // body block begin => // class sizeof(QMatrix)=48 #[derive(Default)] pub struct QMatrix { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QMatrix { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMatrix { return QMatrix{qclsinst: qthis, ..Default::default()}; } } // proto: qreal QMatrix::dx(); impl /*struct*/ QMatrix { pub fn dx<RetType, T: QMatrix_dx<RetType>>(& self, overload_args: T) -> RetType { return overload_args.dx(self); // return 1; } } pub trait QMatrix_dx<RetType> { fn dx(self , rsthis: & QMatrix) -> RetType; } // proto: qreal QMatrix::dx(); impl<'a> /*trait*/ QMatrix_dx<f64> for () { fn dx(self , rsthis: & QMatrix) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix2dxEv()}; let mut ret = unsafe {C_ZNK7QMatrix2dxEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: qreal QMatrix::dy(); impl /*struct*/ QMatrix { pub fn dy<RetType, T: QMatrix_dy<RetType>>(& self, overload_args: T) -> RetType { return overload_args.dy(self); // return 1; } } pub trait QMatrix_dy<RetType> { fn dy(self , rsthis: & QMatrix) -> RetType; } // proto: qreal QMatrix::dy(); impl<'a> /*trait*/ QMatrix_dy<f64> for () { fn dy(self , rsthis: & QMatrix) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix2dyEv()}; let mut ret = unsafe {C_ZNK7QMatrix2dyEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: QMatrix & QMatrix::scale(qreal sx, qreal sy); impl /*struct*/ QMatrix { pub fn scale<RetType, T: QMatrix_scale<RetType>>(& self, overload_args: T) -> RetType { return overload_args.scale(self); // return 1; } } pub trait QMatrix_scale<RetType> { fn scale(self , rsthis: & QMatrix) -> RetType; } // proto: QMatrix & QMatrix::scale(qreal sx, qreal sy); impl<'a> /*trait*/ QMatrix_scale<QMatrix> for (f64, f64) { fn scale(self , rsthis: & QMatrix) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrix5scaleEdd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let mut ret = unsafe {C_ZN7QMatrix5scaleEdd(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QMatrix::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QMatrix & QMatrix::translate(qreal dx, qreal dy); impl /*struct*/ QMatrix { pub fn translate<RetType, T: QMatrix_translate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.translate(self); // return 1; } } pub trait QMatrix_translate<RetType> { fn translate(self , rsthis: & QMatrix) -> RetType; } // proto: QMatrix & QMatrix::translate(qreal dx, qreal dy); impl<'a> /*trait*/ QMatrix_translate<QMatrix> for (f64, f64) { fn translate(self , rsthis: & QMatrix) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrix9translateEdd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let mut ret = unsafe {C_ZN7QMatrix9translateEdd(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QMatrix::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: qreal QMatrix::determinant(); impl /*struct*/ QMatrix { pub fn determinant<RetType, T: QMatrix_determinant<RetType>>(& self, overload_args: T) -> RetType { return overload_args.determinant(self); // return 1; } } pub trait QMatrix_determinant<RetType> { fn determinant(self , rsthis: & QMatrix) -> RetType; } // proto: qreal QMatrix::determinant(); impl<'a> /*trait*/ QMatrix_determinant<f64> for () { fn determinant(self , rsthis: & QMatrix) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix11determinantEv()}; let mut ret = unsafe {C_ZNK7QMatrix11determinantEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: QMatrix & QMatrix::shear(qreal sh, qreal sv); impl /*struct*/ QMatrix { pub fn shear<RetType, T: QMatrix_shear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.shear(self); // return 1; } } pub trait QMatrix_shear<RetType> { fn shear(self , rsthis: & QMatrix) -> RetType; } // proto: QMatrix & QMatrix::shear(qreal sh, qreal sv); impl<'a> /*trait*/ QMatrix_shear<QMatrix> for (f64, f64) { fn shear(self , rsthis: & QMatrix) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrix5shearEdd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let mut ret = unsafe {C_ZN7QMatrix5shearEdd(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QMatrix::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix::QMatrix(); impl /*struct*/ QMatrix { pub fn new<T: QMatrix_new>(value: T) -> QMatrix { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QMatrix_new { fn new(self) -> QMatrix; } // proto: void QMatrix::QMatrix(); impl<'a> /*trait*/ QMatrix_new for () { fn new(self) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrixC2Ev()}; let ctysz: c_int = unsafe{QMatrix_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN7QMatrixC2Ev()}; let rsthis = QMatrix{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: qreal QMatrix::m21(); impl /*struct*/ QMatrix { pub fn m21<RetType, T: QMatrix_m21<RetType>>(& self, overload_args: T) -> RetType { return overload_args.m21(self); // return 1; } } pub trait QMatrix_m21<RetType> { fn m21(self , rsthis: & QMatrix) -> RetType; } // proto: qreal QMatrix::m21(); impl<'a> /*trait*/ QMatrix_m21<f64> for () { fn m21(self , rsthis: & QMatrix) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3m21Ev()}; let mut ret = unsafe {C_ZNK7QMatrix3m21Ev(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: QPointF QMatrix::map(const QPointF & p); impl /*struct*/ QMatrix { pub fn map<RetType, T: QMatrix_map<RetType>>(& self, overload_args: T) -> RetType { return overload_args.map(self); // return 1; } } pub trait QMatrix_map<RetType> { fn map(self , rsthis: & QMatrix) -> RetType; } // proto: QPointF QMatrix::map(const QPointF & p); impl<'a> /*trait*/ QMatrix_map<QPointF> for (&'a QPointF) { fn map(self , rsthis: & QMatrix) -> QPointF { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapERK7QPointF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix3mapERK7QPointF(rsthis.qclsinst, arg0)}; let mut ret1 = QPointF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QPolygonF QMatrix::map(const QPolygonF & a); impl<'a> /*trait*/ QMatrix_map<QPolygonF> for (&'a QPolygonF) { fn map(self , rsthis: & QMatrix) -> QPolygonF { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapERK9QPolygonF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix3mapERK9QPolygonF(rsthis.qclsinst, arg0)}; let mut ret1 = QPolygonF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix::map(qreal x, qreal y, qreal * tx, qreal * ty); impl<'a> /*trait*/ QMatrix_map<()> for (f64, f64, &'a mut Vec<f64>, &'a mut Vec<f64>) { fn map(self , rsthis: & QMatrix) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapEddPdS0_()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2.as_ptr() as *mut c_double; let arg3 = self.3.as_ptr() as *mut c_double; unsafe {C_ZNK7QMatrix3mapEddPdS0_(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: QMatrix & QMatrix::rotate(qreal a); impl /*struct*/ QMatrix { pub fn rotate<RetType, T: QMatrix_rotate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rotate(self); // return 1; } } pub trait QMatrix_rotate<RetType> { fn rotate(self , rsthis: & QMatrix) -> RetType; } // proto: QMatrix & QMatrix::rotate(qreal a); impl<'a> /*trait*/ QMatrix_rotate<QMatrix> for (f64) { fn rotate(self , rsthis: & QMatrix) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrix6rotateEd()}; let arg0 = self as c_double; let mut ret = unsafe {C_ZN7QMatrix6rotateEd(rsthis.qclsinst, arg0)}; let mut ret1 = QMatrix::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QRegion QMatrix::map(const QRegion & r); impl<'a> /*trait*/ QMatrix_map<QRegion> for (&'a QRegion) { fn map(self , rsthis: & QMatrix) -> QRegion { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapERK7QRegion()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix3mapERK7QRegion(rsthis.qclsinst, arg0)}; let mut ret1 = QRegion::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix::setMatrix(qreal m11, qreal m12, qreal m21, qreal m22, qreal dx, qreal dy); impl /*struct*/ QMatrix { pub fn setMatrix<RetType, T: QMatrix_setMatrix<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setMatrix(self); // return 1; } } pub trait QMatrix_setMatrix<RetType> { fn setMatrix(self , rsthis: & QMatrix) -> RetType; } // proto: void QMatrix::setMatrix(qreal m11, qreal m12, qreal m21, qreal m22, qreal dx, qreal dy); impl<'a> /*trait*/ QMatrix_setMatrix<()> for (f64, f64, f64, f64, f64, f64) { fn setMatrix(self , rsthis: & QMatrix) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrix9setMatrixEdddddd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; let arg4 = self.4 as c_double; let arg5 = self.5 as c_double; unsafe {C_ZN7QMatrix9setMatrixEdddddd(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)}; // return 1; } } // proto: void QMatrix::QMatrix(const QMatrix & matrix); impl<'a> /*trait*/ QMatrix_new for (&'a QMatrix) { fn new(self) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrixC2ERKS_()}; let ctysz: c_int = unsafe{QMatrix_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN7QMatrixC2ERKS_(arg0)}; let rsthis = QMatrix{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QMatrix::reset(); impl /*struct*/ QMatrix { pub fn reset<RetType, T: QMatrix_reset<RetType>>(& self, overload_args: T) -> RetType { return overload_args.reset(self); // return 1; } } pub trait QMatrix_reset<RetType> { fn reset(self , rsthis: & QMatrix) -> RetType; } // proto: void QMatrix::reset(); impl<'a> /*trait*/ QMatrix_reset<()> for () { fn reset(self , rsthis: & QMatrix) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrix5resetEv()}; unsafe {C_ZN7QMatrix5resetEv(rsthis.qclsinst)}; // return 1; } } // proto: QLineF QMatrix::map(const QLineF & l); impl<'a> /*trait*/ QMatrix_map<QLineF> for (&'a QLineF) { fn map(self , rsthis: & QMatrix) -> QLineF { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapERK6QLineF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix3mapERK6QLineF(rsthis.qclsinst, arg0)}; let mut ret1 = QLineF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QPainterPath QMatrix::map(const QPainterPath & p); impl<'a> /*trait*/ QMatrix_map<QPainterPath> for (&'a QPainterPath) { fn map(self , rsthis: & QMatrix) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapERK12QPainterPath()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix3mapERK12QPainterPath(rsthis.qclsinst, arg0)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: qreal QMatrix::m11(); impl /*struct*/ QMatrix { pub fn m11<RetType, T: QMatrix_m11<RetType>>(& self, overload_args: T) -> RetType { return overload_args.m11(self); // return 1; } } pub trait QMatrix_m11<RetType> { fn m11(self , rsthis: & QMatrix) -> RetType; } // proto: qreal QMatrix::m11(); impl<'a> /*trait*/ QMatrix_m11<f64> for () { fn m11(self , rsthis: & QMatrix) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3m11Ev()}; let mut ret = unsafe {C_ZNK7QMatrix3m11Ev(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: QPolygon QMatrix::mapToPolygon(const QRect & r); impl /*struct*/ QMatrix { pub fn mapToPolygon<RetType, T: QMatrix_mapToPolygon<RetType>>(& self, overload_args: T) -> RetType { return overload_args.mapToPolygon(self); // return 1; } } pub trait QMatrix_mapToPolygon<RetType> { fn mapToPolygon(self , rsthis: & QMatrix) -> RetType; } // proto: QPolygon QMatrix::mapToPolygon(const QRect & r); impl<'a> /*trait*/ QMatrix_mapToPolygon<QPolygon> for (&'a QRect) { fn mapToPolygon(self , rsthis: & QMatrix) -> QPolygon { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix12mapToPolygonERK5QRect()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix12mapToPolygonERK5QRect(rsthis.qclsinst, arg0)}; let mut ret1 = QPolygon::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QMatrix QMatrix::inverted(bool * invertible); impl /*struct*/ QMatrix { pub fn inverted<RetType, T: QMatrix_inverted<RetType>>(& self, overload_args: T) -> RetType { return overload_args.inverted(self); // return 1; } } pub trait QMatrix_inverted<RetType> { fn inverted(self , rsthis: & QMatrix) -> RetType; } // proto: QMatrix QMatrix::inverted(bool * invertible); impl<'a> /*trait*/ QMatrix_inverted<QMatrix> for (Option<&'a mut Vec<i8>>) { fn inverted(self , rsthis: & QMatrix) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix8invertedEPb()}; let arg0 = (if self.is_none() {0 as *const i8} else {self.unwrap().as_ptr()}) as *mut c_char; let mut ret = unsafe {C_ZNK7QMatrix8invertedEPb(rsthis.qclsinst, arg0)}; let mut ret1 = QMatrix::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QPoint QMatrix::map(const QPoint & p); impl<'a> /*trait*/ QMatrix_map<QPoint> for (&'a QPoint) { fn map(self , rsthis: & QMatrix) -> QPoint { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapERK6QPoint()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix3mapERK6QPoint(rsthis.qclsinst, arg0)}; let mut ret1 = QPoint::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix::map(int x, int y, int * tx, int * ty); impl<'a> /*trait*/ QMatrix_map<()> for (i32, i32, &'a mut Vec<i32>, &'a mut Vec<i32>) { fn map(self , rsthis: & QMatrix) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapEiiPiS0_()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; let arg2 = self.2.as_ptr() as *mut c_int; let arg3 = self.3.as_ptr() as *mut c_int; unsafe {C_ZNK7QMatrix3mapEiiPiS0_(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: QLine QMatrix::map(const QLine & l); impl<'a> /*trait*/ QMatrix_map<QLine> for (&'a QLine) { fn map(self , rsthis: & QMatrix) -> QLine { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapERK5QLine()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix3mapERK5QLine(rsthis.qclsinst, arg0)}; let mut ret1 = QLine::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QRectF QMatrix::mapRect(const QRectF & ); impl /*struct*/ QMatrix { pub fn mapRect<RetType, T: QMatrix_mapRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.mapRect(self); // return 1; } } pub trait QMatrix_mapRect<RetType> { fn mapRect(self , rsthis: & QMatrix) -> RetType; } // proto: QRectF QMatrix::mapRect(const QRectF & ); impl<'a> /*trait*/ QMatrix_mapRect<QRectF> for (&'a QRectF) { fn mapRect(self , rsthis: & QMatrix) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix7mapRectERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix7mapRectERK6QRectF(rsthis.qclsinst, arg0)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QMatrix::isIdentity(); impl /*struct*/ QMatrix { pub fn isIdentity<RetType, T: QMatrix_isIdentity<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isIdentity(self); // return 1; } } pub trait QMatrix_isIdentity<RetType> { fn isIdentity(self , rsthis: & QMatrix) -> RetType; } // proto: bool QMatrix::isIdentity(); impl<'a> /*trait*/ QMatrix_isIdentity<i8> for () { fn isIdentity(self , rsthis: & QMatrix) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix10isIdentityEv()}; let mut ret = unsafe {C_ZNK7QMatrix10isIdentityEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: qreal QMatrix::m12(); impl /*struct*/ QMatrix { pub fn m12<RetType, T: QMatrix_m12<RetType>>(& self, overload_args: T) -> RetType { return overload_args.m12(self); // return 1; } } pub trait QMatrix_m12<RetType> { fn m12(self , rsthis: & QMatrix) -> RetType; } // proto: qreal QMatrix::m12(); impl<'a> /*trait*/ QMatrix_m12<f64> for () { fn m12(self , rsthis: & QMatrix) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3m12Ev()}; let mut ret = unsafe {C_ZNK7QMatrix3m12Ev(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: bool QMatrix::isInvertible(); impl /*struct*/ QMatrix { pub fn isInvertible<RetType, T: QMatrix_isInvertible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isInvertible(self); // return 1; } } pub trait QMatrix_isInvertible<RetType> { fn isInvertible(self , rsthis: & QMatrix) -> RetType; } // proto: bool QMatrix::isInvertible(); impl<'a> /*trait*/ QMatrix_isInvertible<i8> for () { fn isInvertible(self , rsthis: & QMatrix) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix12isInvertibleEv()}; let mut ret = unsafe {C_ZNK7QMatrix12isInvertibleEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QRect QMatrix::mapRect(const QRect & ); impl<'a> /*trait*/ QMatrix_mapRect<QRect> for (&'a QRect) { fn mapRect(self , rsthis: & QMatrix) -> QRect { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix7mapRectERK5QRect()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix7mapRectERK5QRect(rsthis.qclsinst, arg0)}; let mut ret1 = QRect::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix::QMatrix(qreal m11, qreal m12, qreal m21, qreal m22, qreal dx, qreal dy); impl<'a> /*trait*/ QMatrix_new for (f64, f64, f64, f64, f64, f64) { fn new(self) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZN7QMatrixC2Edddddd()}; let ctysz: c_int = unsafe{QMatrix_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; let arg4 = self.4 as c_double; let arg5 = self.5 as c_double; let qthis: u64 = unsafe {C_ZN7QMatrixC2Edddddd(arg0, arg1, arg2, arg3, arg4, arg5)}; let rsthis = QMatrix{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: qreal QMatrix::m22(); impl /*struct*/ QMatrix { pub fn m22<RetType, T: QMatrix_m22<RetType>>(& self, overload_args: T) -> RetType { return overload_args.m22(self); // return 1; } } pub trait QMatrix_m22<RetType> { fn m22(self , rsthis: & QMatrix) -> RetType; } // proto: qreal QMatrix::m22(); impl<'a> /*trait*/ QMatrix_m22<f64> for () { fn m22(self , rsthis: & QMatrix) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3m22Ev()}; let mut ret = unsafe {C_ZNK7QMatrix3m22Ev(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: QPolygon QMatrix::map(const QPolygon & a); impl<'a> /*trait*/ QMatrix_map<QPolygon> for (&'a QPolygon) { fn map(self , rsthis: & QMatrix) -> QPolygon { // let qthis: *mut c_void = unsafe{calloc(1, 48)}; // unsafe{_ZNK7QMatrix3mapERK8QPolygon()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK7QMatrix3mapERK8QPolygon(rsthis.qclsinst, arg0)}; let mut ret1 = QPolygon::inheritFrom(ret as u64); return ret1; // return 1; } } // <= body block end
#[cfg(feature = "Win32_Web_InternetExplorer")] pub mod InternetExplorer;
use super::*; #[derive(Clone)] pub struct InterfaceImpl(pub Row); impl InterfaceImpl { pub fn interface(&self) -> TypeDefOrRef { self.0.decode(1) } fn attributes(&self) -> impl Iterator<Item = Attribute> { self.0.file.attributes(HasAttribute::InterfaceImpl(self.clone())) } fn has_attribute(&self, name: &str) -> bool { self.attributes().any(|attribute| attribute.name() == name) } pub fn is_default(&self) -> bool { self.has_attribute("DefaultAttribute") } pub fn is_overridable(&self) -> bool { self.has_attribute("OverridableAttribute") } pub fn generic_interface(&self, generics: &[ElementType]) -> ElementType { TypeReader::get().type_from_code(&self.interface(), None, generics) } }
//! This module holds the definitions of //! JYInfo related wrappers. use data_structs::JYInfo; use jalali_bindings::*; impl JYInfo { /// This function initializes the struct. /// /// # Examples /// /// ``` /// extern crate jalali; /// /// jalali::JYInfo::new(); /// /// ``` pub fn new() -> Self { JYInfo { lf: 0, y: 0, r: 0, p: 0, rl: 0, pl: 0, apl: 0, } } /// This function initializes the struct based on the provided year. /// /// # Arguments /// /// * `year` - A 32 bit integer representing jalali year. /// /// # Examples /// /// ``` /// extern crate jalali; /// /// jalali::JYInfo::get_jalali_year_info(1371); /// /// ``` pub fn get_jalali_year_info(year: i32) -> Self { let mut result = Self::new(); result.y = year; unsafe { jalali_get_jyear_info(&mut result); } result } }
use super::{input::Input, status::Status}; use crate::cpu::CPU; use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers}; use std::io::Stdout; use tui::{ backend::CrosstermBackend, layout::{Constraint, Direction, Layout, Rect}, style::{Color, Style}, Frame, }; pub enum KeyAction { Nothing, Run, Step, Pause, Quit, } /// Represents an interactable element of the terminal UI, presenting data and possibly ways to /// interact with them. pub trait Widget { /// Refreshes the content of the widget, readying it to be displayed with up-to-date information. fn refresh(&mut self, cpu: &CPU); /// Draws the widget on the screen, in the area specified by `chunk`. fn draw(&mut self, f: &mut Frame<CrosstermBackend<Stdout>>, chunk: Rect, cpu: &CPU); /// Selects the widget, in order to toggle visual elements that shows that the widget /// is selected (title color, borders, ...) fn select(&mut self); /// Deselects the widget. fn deselect(&mut self); /// Returns whether or not the widget is currently selected fn is_selected(&self) -> bool; /// Handles a `KeyEvent` input from the user, processing it. The widget can either /// handle the input internally (for example, shifting a cursor upwards or downwards in a list), /// in which case it returns `None`; or it can signal that the input leads to a text input, /// in which case it returns `Some` tuple containing the `WidgetKind` to call back after /// the text input, and a `String` which represents the prompt. /// /// For example, if the widget returns `Some(Assembly, "Go to address:")`, this means /// that the widget requires a text input, that will be then processed by the widget /// with the kind `Assembly`, with a prompt reading `"Go to address:"`. Usually, the /// `WidgetKind` returned is the same as the one from the widget called. /// /// The text input is usually then processed by using the `process_input` function. fn handle_key(&mut self, _: KeyEvent, _: &mut CPU) -> Option<(WidgetKind, String)> { None } /// Processes a text input from the input widget. This is generally used after a call /// of `handle_key` that returned `Some`. The text input is usually processed according to /// the last command that was requested before the text input; this requires some kind of /// memorisation on the implementation side. /// /// The input can be malformed and not suitable for the widget, in which case the function /// returns `Err(Option<String>)`. The `Option` here is used to possibly send to the input /// widget a custom error message. /// /// If the input was processed successfully, the function returns `Ok(())`. fn process_input(&mut self, _: String, _: &mut CPU) -> Result<(), Option<String>> { Ok(()) } /// Returns the `Style` used for the title, depending on if the widget is currently selected /// or not. fn title_style(&self) -> Style { if self.is_selected() { Style::default().fg(Color::Yellow) } else { Style::default() } } } /// The different kind of widgets present in this application. #[derive(PartialEq, Copy, Clone)] pub enum WidgetKind { /// The disassembly window, implemented by the `Assembly` widget. Assembly, /// The breakpoint visualisation window, implemented by the `BreakpointView` widget. Breakpoints, /// The memory map visualisation window, implemented by the `MemoryView` widget. Memory, /// The register visualisation window, implemented by the `RegisterView` widget. Registers, } impl WidgetKind { /// Returns the widget on the left of this widget. pub fn left(&self) -> Option<WidgetKind> { match self { WidgetKind::Assembly => Some(WidgetKind::Registers), WidgetKind::Breakpoints => Some(WidgetKind::Memory), WidgetKind::Memory => None, WidgetKind::Registers => None, } } /// Returns the widget on the right of this widget. pub fn right(&self) -> Option<WidgetKind> { match self { WidgetKind::Assembly => None, WidgetKind::Breakpoints => None, WidgetKind::Memory => Some(WidgetKind::Breakpoints), WidgetKind::Registers => Some(WidgetKind::Assembly), } } /// Returns the widget on top of this widget. pub fn up(&self) -> Option<WidgetKind> { match self { WidgetKind::Assembly => None, WidgetKind::Breakpoints => Some(WidgetKind::Assembly), WidgetKind::Memory => Some(WidgetKind::Registers), WidgetKind::Registers => None, } } /// Returns the widget underneath this widget. pub fn down(&self) -> Option<WidgetKind> { match self { WidgetKind::Assembly => Some(WidgetKind::Breakpoints), WidgetKind::Breakpoints => None, WidgetKind::Memory => None, WidgetKind::Registers => Some(WidgetKind::Memory), } } } type WidgetWithKind = (WidgetKind, Box<dyn Widget>); /// Represents the list of widgets in the application, responsible /// of refreshing, drawing, and dispatching the inputs to the /// correct widget. pub struct WidgetList { widgets: Vec<WidgetWithKind>, input: Input, status: Status, widget_callback: Option<WidgetKind>, } impl WidgetList { /// Creates a new, empty `WidgetList`. pub fn new() -> WidgetList { WidgetList { widgets: vec![], input: Input::new(), status: Status::new(), widget_callback: None, } } /// Adds a new widget to the list pub fn add(&mut self, widget: Box<dyn Widget>, kind: WidgetKind) { self.widgets.push((kind, widget)); } /// Refreshes all the widgets in the list. pub fn refresh(&mut self, cpu: &CPU) { self.widgets.iter_mut().for_each(|(_, w)| { w.refresh(cpu); }) } /// Selects a widget based on the specified kind, and deselects all the others. /// If `None` is passed, then everything is deselected. pub fn select(&mut self, kind: Option<WidgetKind>) { self.widgets.iter_mut().for_each(|(k, w)| match (&kind, k) { (Some(a), b) if *a == *b => w.select(), _ => w.deselect(), }); } /// Returns the index of the widget that is currently selected. pub fn selected(&mut self) -> Option<usize> { self.widgets.iter().position(|(_, w)| w.is_selected()) } /// Returns the index of the widget corresponding to the specified kind. pub fn find(&self, kind: &WidgetKind) -> Option<usize> { self.widgets.iter().position(|(k, _)| *k == *kind) } /// Sets the status line text pub fn set_status(&mut self, status: &'static str) { self.status.set_status(status) } pub fn display_error<S: Into<String>>(&mut self, message: S) { self.input.set_error(true); self.input.set_error_title(Some(message.into())); } fn event_to_key(&self, event: Event) -> KeyEvent { match event { Event::Key(ke) => ke, _ => panic!("Not a key event"), } } fn handle_input(&mut self, event: Event, cpu: &mut CPU) -> Option<()> { if self.input.is_selected() { let key = self.event_to_key(event); if let Some(s) = self.input.handle_input_key(key) { match s { Ok(s) => { if let Some(k) = self.widget_callback { match self .find(&k) .map(|i| self.widgets[i].1.process_input(s, cpu)) .unwrap_or_else(|| Err(Some(r#"Widget not found"#.to_string()))) { Ok(_) => { self.select(Some(k)); self.input.deselect(); self.input.set_title(String::new()); if let Some(i) = self.find(&k) { self.widgets[i].1.refresh(cpu) } } Err(e) => { self.input.set_error(true); self.input.set_error_title(e); } } } } Err(_) => { if let Some(k) = self.widget_callback { self.select(Some(k)); self.input.deselect(); self.input.set_title(String::new()); if let Some(i) = self.find(&k) { self.widgets[i].1.refresh(cpu) } } } } } Some(()) } else { None } } fn global_keys(&mut self, event: Event, ret: &mut KeyAction) -> Option<()> { let key = self.event_to_key(event); match key.code { KeyCode::Char('q') => { *ret = KeyAction::Quit; Some(()) } KeyCode::Char('n') => { *ret = KeyAction::Step; Some(()) } KeyCode::Char('r') => { *ret = KeyAction::Run; Some(()) } KeyCode::Char(' ') => { *ret = KeyAction::Pause; Some(()) } KeyCode::Esc => { self.select(None); Some(()) } _ => None, } } fn arrow_keys(&mut self, event: Event, _: &mut CPU) -> Option<()> { if let Some(kind) = self.selected().map(|i| self.widgets[i].0) { match event { Event::Key(KeyEvent { code: KeyCode::Left, modifiers: KeyModifiers::SHIFT, }) => { self.select(Some(kind.left().unwrap_or(kind))); Some(()) } Event::Key(KeyEvent { code: KeyCode::Right, modifiers: KeyModifiers::SHIFT, }) => { self.select(Some(kind.right().unwrap_or(kind))); Some(()) } Event::Key(KeyEvent { code: KeyCode::Up, modifiers: KeyModifiers::SHIFT, }) => { self.select(Some(kind.up().unwrap_or(kind))); Some(()) } Event::Key(KeyEvent { code: KeyCode::Down, modifiers: KeyModifiers::SHIFT, }) => { self.select(Some(kind.down().unwrap_or(kind))); Some(()) } _ => None, } } else { None } } fn direct_widget_keys(&mut self, event: Event, _: &mut CPU) -> Option<()> { let key = self.event_to_key(event); match key.code { KeyCode::Char('D') => { self.select(Some(WidgetKind::Assembly)); Some(()) } KeyCode::Char('R') => { self.select(Some(WidgetKind::Registers)); Some(()) } KeyCode::Char('M') => { self.select(Some(WidgetKind::Memory)); Some(()) } KeyCode::Char('B') => { self.select(Some(WidgetKind::Breakpoints)); Some(()) } _ => None, } } /// Handles a keyboard input from the terminal, and dispatches it to the correct widget, if any. /// This function returns `true` if the program should quit. pub fn handle_key(&mut self, key: Event, cpu: &mut CPU) -> KeyAction { let mut ret = KeyAction::Nothing; self.handle_input(key, cpu) .or_else(|| self.global_keys(key, &mut ret)) .or_else(|| self.arrow_keys(key, cpu)) .or_else(|| self.direct_widget_keys(key, cpu)) .or_else(|| { let key = self.event_to_key(key); if let Some((kind, string)) = { self.selected() .map(|i| self.widgets[i].1.handle_key(key, cpu)) .unwrap_or(None) } { self.widget_callback = Some(kind); self.input.set_title(string); self.input.select(); } else { self.widget_callback = None; } Some(()) }); ret } // This might be beneficial for the user to be able to configure this, but it might // just be too much trouble... /// Draws all the widgets contained in the list, according to a hard-coded layout. pub fn draw(&mut self, f: &mut Frame<CrosstermBackend<Stdout>>, cpu: &CPU) { let top_bottom = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Length(f.size().height.saturating_sub(3)), Constraint::Min(3), ] .as_ref(), ) .split(f.size()); // The Constraint::Max(58) is the maximum size needed for the memory viewer; // this way, we don't use too much space for it. let chunks = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Max(58), Constraint::Percentage(50)].as_ref()) .split(top_bottom[0]); let right_chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Percentage(70), Constraint::Percentage(30)].as_ref()) .split(chunks[1]); let left_chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Min(5), Constraint::Percentage(100)]) .split(chunks[0]); let bottom = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Percentage(70), Constraint::Percentage(30)].as_ref()) .split(top_bottom[1]); vec![ (&WidgetKind::Registers, left_chunks[0]), (&WidgetKind::Memory, left_chunks[1]), (&WidgetKind::Assembly, right_chunks[0]), (&WidgetKind::Breakpoints, right_chunks[1]), ] .into_iter() .for_each(|(k, r)| { self.find(k) .map(|i| self.widgets[i].1.as_mut()) .unwrap() .draw(f, r, cpu); }); self.input.draw(f, bottom[0], cpu); self.status.draw(f, bottom[1], cpu); } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. //! Defines a `BufferBuilder` capable of creating a `Buffer` which can be used as an internal //! buffer in an `ArrayData` object. use std::io::Write; use std::marker::PhantomData; use std::mem; use buffer::{Buffer, MutableBuffer}; use datatypes::{ArrowPrimitiveType, ToByteSlice}; use error::{ArrowError, Result}; use util::bit_util; /// Buffer builder with zero-copy build method pub struct BufferBuilder<T> where T: ArrowPrimitiveType, { buffer: MutableBuffer, len: i64, _marker: PhantomData<T>, } macro_rules! impl_buffer_builder { ($native_ty:ident) => { impl BufferBuilder<$native_ty> { /// Creates a builder with a fixed initial capacity pub fn new(capacity: i64) -> Self { let buffer = MutableBuffer::new(capacity as usize * mem::size_of::<$native_ty>()); Self { buffer, len: 0, _marker: PhantomData, } } /// Returns the number of array elements (slots) in the builder pub fn len(&self) -> i64 { self.len } /// Returns the current capacity of the builder (number of elements) pub fn capacity(&self) -> i64 { let byte_capacity = self.buffer.capacity(); (byte_capacity / mem::size_of::<$native_ty>()) as i64 } /// Push a value into the builder, growing the internal buffer as needed pub fn push(&mut self, v: $native_ty) -> Result<()> { self.reserve(1)?; self.write_bytes(v.to_byte_slice(), 1) } /// Push a slice of type T, growing the internal buffer as needed pub fn push_slice(&mut self, slice: &[$native_ty]) -> Result<()> { let array_slots = slice.len() as i64; self.reserve(array_slots)?; self.write_bytes(slice.to_byte_slice(), array_slots) } /// Reserve memory for n elements of type T pub fn reserve(&mut self, n: i64) -> Result<()> { let new_capacity = self.len + n; if new_capacity > self.capacity() { return self.grow(new_capacity); } Ok(()) } /// Grow the internal buffer to `new_capacity`, where `new_capacity` is the capacity in /// elements of type T fn grow(&mut self, new_capacity: i64) -> Result<()> { let byte_capacity = mem::size_of::<$native_ty>() * new_capacity as usize; self.buffer.resize(byte_capacity)?; Ok(()) } /// Build an immutable `Buffer` from the existing internal `MutableBuffer`'s memory pub fn finish(self) -> Buffer { self.buffer.freeze() } /// Writes a byte slice to the underlying buffer and updates the `len`, i.e. the number array /// elements in the builder. Also, converts the `io::Result` required by the `Write` trait /// to the Arrow `Result` type. fn write_bytes(&mut self, bytes: &[u8], len_added: i64) -> Result<()> { let write_result = self.buffer.write(bytes); // `io::Result` has many options one of which we use, so pattern matching is overkill here if write_result.is_err() { Err(ArrowError::MemoryError( "Could not write to Buffer, not big enough".to_string(), )) } else { self.len += len_added; Ok(()) } } } }; } impl_buffer_builder!(u8); impl_buffer_builder!(u16); impl_buffer_builder!(u32); impl_buffer_builder!(u64); impl_buffer_builder!(i8); impl_buffer_builder!(i16); impl_buffer_builder!(i32); impl_buffer_builder!(i64); impl_buffer_builder!(f32); impl_buffer_builder!(f64); impl BufferBuilder<bool> { /// Creates a builder with a fixed initial capacity pub fn new(capacity: i64) -> Self { let byte_capacity = bit_util::ceil(capacity, 8); let actual_capacity = bit_util::round_upto_multiple_of_64(byte_capacity) as usize; let mut buffer = MutableBuffer::new(actual_capacity); buffer.set_null_bits(0, actual_capacity); Self { buffer, len: 0, _marker: PhantomData, } } /// Returns the number of array elements (slots) in the builder pub fn len(&self) -> i64 { self.len } /// Returns the current capacity of the builder (number of elements) pub fn capacity(&self) -> i64 { let byte_capacity = self.buffer.capacity() as i64; byte_capacity * 8 } /// Push a value into the builder, growing the internal buffer as needed pub fn push(&mut self, v: bool) -> Result<()> { self.reserve(1)?; if v { // For performance the `len` of the buffer is not updated on each push but // is updated in the `freeze` method instead unsafe { bit_util::set_bit_raw(self.buffer.raw_data() as *mut u8, (self.len) as usize); } } self.len += 1; Ok(()) } /// Push a slice of type T, growing the internal buffer as needed pub fn push_slice(&mut self, slice: &[bool]) -> Result<()> { let array_slots = slice.len(); for i in 0..array_slots { self.push(slice[i])?; } Ok(()) } /// Reserve memory for n elements of type T pub fn reserve(&mut self, n: i64) -> Result<()> { let new_capacity = self.len + n; if new_capacity > self.capacity() { return self.grow(new_capacity); } Ok(()) } /// Grow the internal buffer to `new_capacity`, where `new_capacity` is the capacity in /// elements of type T fn grow(&mut self, new_capacity: i64) -> Result<()> { let new_byte_capacity = bit_util::ceil(new_capacity, 8) as usize; let existing_capacity = self.buffer.capacity(); let capacity_added = self.buffer.resize(new_byte_capacity)?; self.buffer.set_null_bits(existing_capacity, capacity_added); Ok(()) } /// Build an immutable `Buffer` from the existing internal `MutableBuffer`'s memory pub fn finish(mut self) -> Buffer { // `push` does not update the buffer's `len` to it is done before `freeze` is called let new_buffer_len = bit_util::ceil(self.len, 8); self.buffer.set_len(new_buffer_len as usize); self.buffer.freeze() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_builder_i32_empty() { let b = BufferBuilder::<i32>::new(5); assert_eq!(0, b.len()); assert_eq!(16, b.capacity()); let a = b.finish(); assert_eq!(0, a.len()); } #[test] fn test_builder_i32_alloc_zero_bytes() { let mut b = BufferBuilder::<i32>::new(0); b.push(123).unwrap(); let a = b.finish(); assert_eq!(4, a.len()); } #[test] fn test_builder_i32() { let mut b = BufferBuilder::<i32>::new(5); for i in 0..5 { b.push(i).unwrap(); } assert_eq!(16, b.capacity()); let a = b.finish(); assert_eq!(20, a.len()); } #[test] fn test_builder_i32_grow_buffer() { let mut b = BufferBuilder::<i32>::new(2); assert_eq!(16, b.capacity()); for i in 0..20 { b.push(i).unwrap(); } assert_eq!(32, b.capacity()); let a = b.finish(); assert_eq!(80, a.len()); } #[test] fn test_reserve() { let mut b = BufferBuilder::<u8>::new(2); assert_eq!(64, b.capacity()); b.reserve(64).unwrap(); assert_eq!(64, b.capacity()); b.reserve(65).unwrap(); assert_eq!(128, b.capacity()); let mut b = BufferBuilder::<i32>::new(2); assert_eq!(16, b.capacity()); b.reserve(16).unwrap(); assert_eq!(16, b.capacity()); b.reserve(17).unwrap(); assert_eq!(32, b.capacity()); } #[test] fn test_push_slice() { let mut b = BufferBuilder::<u8>::new(0); b.push_slice("Hello, ".as_bytes()).unwrap(); b.push_slice("World!".as_bytes()).unwrap(); let buffer = b.finish(); assert_eq!(13, buffer.len()); let mut b = BufferBuilder::<i32>::new(0); b.push_slice(&[32, 54]).unwrap(); let buffer = b.finish(); assert_eq!(8, buffer.len()); } #[test] fn test_write_bytes() { let mut b = BufferBuilder::<bool>::new(4); b.push(false).unwrap(); b.push(true).unwrap(); b.push(false).unwrap(); b.push(true).unwrap(); assert_eq!(4, b.len()); assert_eq!(512, b.capacity()); let buffer = b.finish(); assert_eq!(1, buffer.len()); let mut b = BufferBuilder::<bool>::new(4); b.push_slice(&[false, true, false, true]).unwrap(); assert_eq!(4, b.len()); assert_eq!(512, b.capacity()); let buffer = b.finish(); assert_eq!(1, buffer.len()); } #[test] fn test_write_bytes_i32() { let mut b = BufferBuilder::<i32>::new(4); let bytes = [8, 16, 32, 64].to_byte_slice(); b.write_bytes(bytes, 4).unwrap(); assert_eq!(4, b.len()); assert_eq!(16, b.capacity()); let buffer = b.finish(); assert_eq!(16, buffer.len()); } #[test] #[should_panic(expected = "Could not write to Buffer, not big enough")] fn test_write_too_many_bytes() { let mut b = BufferBuilder::<i32>::new(0); let bytes = [8, 16, 32, 64].to_byte_slice(); b.write_bytes(bytes, 4).unwrap(); } #[test] fn test_boolean_builder_increases_buffer_len() { // 00000010 01001000 let buf = Buffer::from([72_u8, 2_u8]); let mut builder = BufferBuilder::<bool>::new(8); for i in 0..10 { if i == 3 || i == 6 || i == 9 { builder.push(true).unwrap(); } else { builder.push(false).unwrap(); } } let buf2 = builder.finish(); assert_eq!(buf.len(), buf2.len()); assert_eq!(buf.data(), buf2.data()); } }
extern crate engine; use std::collections::linked_list::LinkedList; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion}; use rand::Rng; use engine::algos::book::*; use engine::algos::*; fn fill_order_book(mut book: &mut dyn Book, n_orders: u64) { // Set up a book with significant volume for _ in 0..n_orders { let order = Order { client_id: 0, seq_number: 0, price: 1100, //rand::thread_rng().gen_range(1000..=1100) / 10 * 10, size: rand::thread_rng().gen_range(1..=20), side: Side::Buy, }; book.apply(order); let order = Order { client_id: 0, seq_number: 0, price: 1000, //rand::thread_rng().gen_range(1000..=1100) / 10 * 10, size: rand::thread_rng().gen_range(1..=20), side: Side::Sell, }; book.apply(order); } // Clear trades out of the book book.check_for_trades(); // Add a new tradeable order let order = Order { client_id: 0, seq_number: 0, price: 1000, size: 1000, side: Side::Sell, }; book.apply(order); } fn criterion_benchmark(c: &mut Criterion) { for n_orders in vec![100, 1_000, 10_000, 100_000, 1_000_000].into_iter() { let mut book = art_book::FIFOBook::new(); fill_order_book(&mut book, n_orders); c.bench_function(&*format!("check_for_trades_{:}", n_orders), move |b| { // iter_batched_ref avoids timing the construction and destruction of the book b.iter_batched_ref( || book.clone(), |data| { let mut data = black_box(data); data.check_for_trades() }, BatchSize::SmallInput, ) }); } } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
use rocket::Route; mod up; pub fn routes() -> Vec<Route> { routes![up::site_po] }
extern crate glob; extern crate serde; extern crate chrono; #[macro_use] extern crate serde_derive; use glob::glob; use pulldown_cmark::{html, Parser}; use std::fs; use std::fs::File; use std::io::prelude::*; use std::io::{BufReader, Result, SeekFrom}; use std::path::Path; use tera::{Context, Tera}; use chrono::prelude::*; #[derive(Serialize, Eq, Ord, PartialEq, PartialOrd)] struct Item { url: String, title: String, created_at: String, updated_at: String, } fn main() -> Result<()> { let tera = setup_template_engine(); let input_dir_str = "docs"; let output_dir_str = "dist"; let output_dir = Path::new(output_dir_str); if output_dir.exists() { fs::remove_dir_all(output_dir)?; } fs::create_dir(output_dir)?; let mut item_list = vec![]; // Generate pages for entry in glob(&format!("{}/**/*.md", input_dir_str)).expect("Failed to read glob pattern") { match entry { Ok(path) => { let mut file = File::open(&path)?; let buf_reader = BufReader::new(&file); let title = extract_title_string(buf_reader); // Go back to the beginning of the file for the second reading file.seek(SeekFrom::Start(0))?; let html_buf = convert_markdown_to_html(file); let metadata = fs::metadata(&path)?; let created_at = metadata.created()?; let updated_at = metadata.modified()?; let created_at = DateTime::<Utc>::from(created_at) .format("%Y-%m-%d %H:%M") .to_string(); let updated_at = DateTime::<Utc>::from(updated_at) .format("%Y-%m-%d %H:%M") .to_string(); let mut context = Context::new(); context.insert("content", &html_buf); context.insert("created_at", &created_at); context.insert("updated_at", &updated_at); let rendered_html = tera.render("page.html", &context).unwrap(); let output_path_str = path .to_str() .unwrap() .replace(input_dir_str, output_dir_str) .replace(".md", ".html"); let output_path = Path::new(&output_path_str); let parent_dir = output_path.parent().unwrap(); if parent_dir.exists() == false { fs::create_dir_all(parent_dir)?; } let mut write_buf = File::create(&output_path)?; write_buf.write(rendered_html.as_bytes())?; let url = output_path_str.replace(output_dir_str, ""); let item = Item { title: title, url: url, created_at: created_at, updated_at: updated_at, }; item_list.push(item); } Err(e) => println!("{:?}", e), } } item_list.sort_by(|a, b| b.created_at.cmp(&a.created_at)); // Generate home page let mut context = Context::new(); context.insert("item_list", &item_list); let rendered_html = tera.render("index.html", &context).unwrap(); let mut write_buf = File::create(format!("{}/index.html", output_dir_str))?; write_buf.write(rendered_html.as_bytes())?; // Copy assets let css = include_str!("theme/assets/css/style.css"); fs::create_dir_all("dist/assets/css")?; fs::write("dist/assets/css/style.css", css)?; Ok(()) } fn setup_template_engine() -> Tera { let mut tera = Tera::default(); tera.add_raw_template("base.html", include_str!("theme/base.html")) .unwrap(); tera.add_raw_template("page.html", include_str!("theme/page.html")) .unwrap(); tera.add_raw_template("index.html", include_str!("theme/index.html")) .unwrap(); tera.autoescape_on(vec![]); tera } fn convert_markdown_to_html(mut file: File) -> String { let mut md_buf = String::new(); file.read_to_string(&mut md_buf).unwrap(); let parser = Parser::new(&md_buf); let mut html_buf = String::new(); html::push_html(&mut html_buf, parser); html_buf } fn extract_title_string<R: BufRead>(mut rdr: R) -> String { let mut first_line = String::new(); rdr.read_line(&mut first_line).unwrap(); let last_hash = first_line .char_indices() .skip_while(|&(_, c)| c == '#') .next() .map_or(0, |(idx, _)| idx); first_line[last_hash..].trim().into() }
#![cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use crate::detail::sse::{rcp_nr1}; pub type Element = __m128; /// A point is represented as the multivector /// $x\mathbf{e}_{032} + y\mathbf{e}_{013} + z\mathbf{e}_{021} + /// \mathbf{e}_{123}$. The point has a trivector representation because it is /// the fixed point of 3 planar reflections (each of which is a grade-1 /// multivector). In practice, the coordinate mapping can be thought of as an /// implementation detail. #[derive(Copy, Clone, Debug)] pub struct Point { pub p3_: __m128, } // impl From<__m128> for Point { // fn from(xmm: __m128) -> Self { // unsafe { // Motor { // p3_: xmm, // } // } // } // } pub fn origin() -> Point { Point::new(0., 0., 0.) } // // trait AsRef<T: ?Sized> { // // fn as_ref(&self) -> &T; // // } // impl AsRef<Point> for Point { // fn as_ref(&self) -> &Point { // &(&self) // } // } use std::fmt; impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "\nPlane\te032\te013\te21\te123\n\t{:.3}\t{:.3}\t{:.3}\t{:.3}\n", self.x(), self.y(), self.z(), self.w() ) } } // impl Default for [f32; 4] { // #[inline] // fn default() -> [f32; 4] { // [0.0,0.0,0.0,0.0] // } // } impl Point { pub fn scale(&mut self, scale: f32) { unsafe { self.p3_ = _mm_mul_ss( _mm_mul_ps(self.p3_, _mm_set1_ps(scale)), _mm_set_ss(1. / scale), ); } } pub fn scaled(self, scale: f32) -> Point { let mut out = Point::from(self.p3_); out.scale(scale); out } /// Create a normalized direction pub fn direction(x: f32, y: f32, z: f32) -> Point { unsafe { let mut p = Point { p3_: _mm_set_ps(z, y, x, 0.), }; p.normalize(); p } } /// Component-wise constructor (homogeneous coordinate is automatically /// initialized to 1) pub fn new(x: f32, y: f32, z: f32) -> Point { Point { p3_: unsafe { _mm_set_ps(z, y, x, 1.0) }, } } /// Normalize this point (division is done via rcpps with an additional /// Newton-Raphson refinement). pub fn normalize(&mut self) { unsafe { // if self.w() == 0. { // // it's a direction, a point at infinity // let tmp = rsqrt_nr1(hi_dp_bc(self.p3_, self.p3_)); // self.p3_ = _mm_mul_ps(self.p3_, tmp); // } else { // // it's a regular point let tmp = rcp_nr1(_mm_shuffle_ps(self.p3_, self.p3_, 0)); self.p3_ = _mm_mul_ps(self.p3_, tmp); // } } } pub fn invert(&mut self) { unsafe { let inv_norm = rcp_nr1(_mm_shuffle_ps(self.p3_, self.p3_, 0)); self.p3_ = _mm_mul_ps(inv_norm, self.p3_); self.p3_ = _mm_mul_ps(inv_norm, self.p3_); } } pub fn inverse(self) -> Point { let mut out = Point::clone(&self); out.invert(); out } get_basis_blade_fn!(e032, e023, p3_, 1); get_basis_blade_fn!(e013, e031, p3_, 2); get_basis_blade_fn!(e021, e012, p3_, 3); pub fn x(self) -> f32 { self.e032() } pub fn y(self) -> f32 { self.e013() } pub fn z(self) -> f32 { self.e021() } /// The homogeneous coordinate `w` is exactly $1$ when normalized. pub fn w(self) -> f32 { let mut out: f32 = 0.0; unsafe { _mm_store_ss(&mut out, self.p3_); } out } pub fn e123(self) -> f32 { self.w() } } common_operations!(Point, p3_); /// Point uniform scale macro_rules! mul_scalar_by_point { ($s:ty) => { impl Mul<Point> for $s { type Output = Point; #[inline] fn mul(self, l: Point) -> Point { l * (self as f32) } } }; } mul_scalar_by_point!(f32); mul_scalar_by_point!(f64); mul_scalar_by_point!(i32); /// Point uniform inverse scale impl<T: Into<f32>> Div<T> for Point { type Output = Point; #[inline] fn div(self, s: T) -> Self { unsafe { Point::from(_mm_mul_ps(self.p3_, rcp_nr1(_mm_set1_ps(s.into())))) } } } use std::ops::Neg; impl Neg for Point { type Output = Point; /// Unary minus (leaves homogeneous coordinate untouched) #[inline] fn neg(self) -> Self::Output { Point::from(unsafe { _mm_xor_ps(self.p3_, _mm_set_ps(-0.0, -0.0, -0.0, 0.0)) }) } } #[cfg(test)] mod tests { #![cfg(target_arch = "x86_64")] fn approx_eq(a: f32, b: f32) { assert!((a - b).abs() < 1e-6) } use super::Point; #[test] fn multivector_sum() { let p1 = Point::new(1.0, 2.0, 3.0); let p2 = Point::new(2.0, 3.0, -1.0); let p3 = p1 + p2; approx_eq(p3.x(), 1.0 + 2.0); approx_eq(p3.y(), 2.0 + 3.0); approx_eq(p3.z(), 3.0 + -1.0); let p4 = p1 - p2; approx_eq(p4.x(), 1.0 - 2.0); approx_eq(p4.y(), 2.0 - 3.0); approx_eq(p4.z(), 3.0 - -1.0); // // Adding rvalue to lvalue let p5 = Point::new(1.0, 2.0, 3.0) + p2; assert_eq!(p5.x(), 1.0 + 2.0); assert_eq!(p5.y(), 2.0 + 3.0); assert_eq!(p5.z(), 3.0 + -1.0); // // Adding rvalue to rvalue let p6 = Point::new(1.0, 2.0, 3.0) + Point::new(2.0, 3.0, -1.0); assert_eq!(p6.x(), 1.0 + 2.0); assert_eq!(p6.y(), 2.0 + 3.0); assert_eq!(p6.z(), 3.0 + -1.0); } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::SHAMD5_DMARIS { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct SHAMD5_DMARIS_CINR { bits: bool, } impl SHAMD5_DMARIS_CINR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SHAMD5_DMARIS_CINW<'a> { w: &'a mut W, } impl<'a> _SHAMD5_DMARIS_CINW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct SHAMD5_DMARIS_COUTR { bits: bool, } impl SHAMD5_DMARIS_COUTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SHAMD5_DMARIS_COUTW<'a> { w: &'a mut W, } impl<'a> _SHAMD5_DMARIS_COUTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct SHAMD5_DMARIS_DINR { bits: bool, } impl SHAMD5_DMARIS_DINR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SHAMD5_DMARIS_DINW<'a> { w: &'a mut W, } impl<'a> _SHAMD5_DMARIS_DINW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct SHAMD5_DMARIS_DOUTR { bits: bool, } impl SHAMD5_DMARIS_DOUTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _SHAMD5_DMARIS_DOUTW<'a> { w: &'a mut W, } impl<'a> _SHAMD5_DMARIS_DOUTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Context In DMA Done Raw Interrupt Status"] #[inline(always)] pub fn shamd5_dmaris_cin(&self) -> SHAMD5_DMARIS_CINR { let bits = ((self.bits >> 0) & 1) != 0; SHAMD5_DMARIS_CINR { bits } } #[doc = "Bit 1 - Context Out DMA Done Raw Interrupt Status"] #[inline(always)] pub fn shamd5_dmaris_cout(&self) -> SHAMD5_DMARIS_COUTR { let bits = ((self.bits >> 1) & 1) != 0; SHAMD5_DMARIS_COUTR { bits } } #[doc = "Bit 2 - Data In DMA Done Raw Interrupt Status"] #[inline(always)] pub fn shamd5_dmaris_din(&self) -> SHAMD5_DMARIS_DINR { let bits = ((self.bits >> 2) & 1) != 0; SHAMD5_DMARIS_DINR { bits } } #[doc = "Bit 3 - Data Out DMA Done Raw Interrupt Status"] #[inline(always)] pub fn shamd5_dmaris_dout(&self) -> SHAMD5_DMARIS_DOUTR { let bits = ((self.bits >> 3) & 1) != 0; SHAMD5_DMARIS_DOUTR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Context In DMA Done Raw Interrupt Status"] #[inline(always)] pub fn shamd5_dmaris_cin(&mut self) -> _SHAMD5_DMARIS_CINW { _SHAMD5_DMARIS_CINW { w: self } } #[doc = "Bit 1 - Context Out DMA Done Raw Interrupt Status"] #[inline(always)] pub fn shamd5_dmaris_cout(&mut self) -> _SHAMD5_DMARIS_COUTW { _SHAMD5_DMARIS_COUTW { w: self } } #[doc = "Bit 2 - Data In DMA Done Raw Interrupt Status"] #[inline(always)] pub fn shamd5_dmaris_din(&mut self) -> _SHAMD5_DMARIS_DINW { _SHAMD5_DMARIS_DINW { w: self } } #[doc = "Bit 3 - Data Out DMA Done Raw Interrupt Status"] #[inline(always)] pub fn shamd5_dmaris_dout(&mut self) -> _SHAMD5_DMARIS_DOUTW { _SHAMD5_DMARIS_DOUTW { w: self } } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #[cfg(test)] use { crate::create_fidl_service, crate::registry::device_storage::testing::*, crate::registry::service_context::ServiceContext, crate::switchboard::base::SettingType, failure::format_err, fidl::endpoints::{ServerEnd, ServiceMarker}, fidl_fuchsia_settings::*, fuchsia_async as fasync, fuchsia_component::server::ServiceFs, fuchsia_zircon as zx, futures::prelude::*, parking_lot::RwLock, std::sync::Arc, }; const ENV_NAME: &str = "settings_service_intl_test_environment"; #[fuchsia_async::run_singlethreaded(test)] async fn test_intl() { const INITIAL_TIME_ZONE: &'static str = "PDT"; let service_gen = |service_name: &str, channel: zx::Channel| { if service_name != fidl_fuchsia_timezone::TimezoneMarker::NAME { return Err(format_err!("unsupported!")); } let mut timezone_stream = ServerEnd::<fidl_fuchsia_timezone::TimezoneMarker>::new(channel).into_stream()?; fasync::spawn(async move { let mut stored_timezone = INITIAL_TIME_ZONE.to_string(); while let Some(req) = timezone_stream.try_next().await.unwrap() { #[allow(unreachable_patterns)] match req { fidl_fuchsia_timezone::TimezoneRequest::GetTimezoneId { responder } => { responder.send(&stored_timezone).unwrap(); } fidl_fuchsia_timezone::TimezoneRequest::SetTimezone { timezone_id, responder, } => { stored_timezone = timezone_id; responder.send(true).unwrap(); } _ => {} } } }); Ok(()) }; let mut fs = ServiceFs::new(); create_fidl_service( fs.root_dir(), [SettingType::Intl].iter().cloned().collect(), Arc::new(RwLock::new(ServiceContext::new(Some(Box::new(service_gen))))), Box::new(InMemoryStorageFactory::create()), ); let env = fs.create_salted_nested_environment(ENV_NAME).unwrap(); fasync::spawn(fs.collect()); let intl_service = env.connect_to_service::<IntlMarker>().unwrap(); let settings = intl_service.watch().await.expect("watch completed").expect("watch successful"); if let Some(time_zone_id) = settings.time_zone_id { assert_eq!(time_zone_id.id, INITIAL_TIME_ZONE); } let mut intl_settings = fidl_fuchsia_settings::IntlSettings::empty(); let updated_timezone = "PDT"; intl_settings.time_zone_id = Some(fidl_fuchsia_intl::TimeZoneId { id: updated_timezone.to_string() }); intl_service.set(intl_settings).await.expect("set completed").expect("set successful"); let settings = intl_service.watch().await.expect("watch completed").expect("watch successful"); assert_eq!( settings.time_zone_id, Some(fidl_fuchsia_intl::TimeZoneId { id: updated_timezone.to_string() }) ); }
table! { entries (id) { id -> Int4, opt -> Nullable<Text>, num -> Timestamp, hash -> Text, } }
// Copyright 2021 Datafuse Labs. // // 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 std::collections::HashMap; use std::sync::Arc; use common_catalog::table::Table; use common_catalog::table_context::TableContext; use common_exception::ErrorCode; use common_exception::Result; use storages_common_table_meta::meta::TableSnapshot; use storages_common_table_meta::meta::TableSnapshotStatistics; use tracing::warn; use crate::io::SegmentsIO; use crate::FuseTable; impl FuseTable { pub async fn do_analyze(&self, ctx: &Arc<dyn TableContext>) -> Result<()> { // 1. Read table snapshot. let r = self.read_table_snapshot().await; let snapshot_opt = match r { Err(e) if e.code() == ErrorCode::STORAGE_NOT_FOUND => { warn!( "concurrent statistic: snapshot {:?} already collected. table: {}, ident {}", self.snapshot_loc().await?, self.table_info.desc, self.table_info.ident, ); return Ok(()); } Err(e) => return Err(e), Ok(v) => v, }; if let Some(snapshot) = snapshot_opt { // 2. Iterator segments and blocks to estimate statistics. let mut sum_map = HashMap::new(); let mut row_count_sum = 0; let mut block_count_sum: u64 = 0; let segments_io = SegmentsIO::create(ctx.clone(), self.operator.clone(), self.schema()); let segments = segments_io.read_segments(&snapshot.segments).await?; for segment in segments { let segment = segment?; segment.blocks.iter().for_each(|block| { let block = block.as_ref(); let row_count = block.row_count; if row_count != 0 { block_count_sum += 1; row_count_sum += row_count; for (i, col_stat) in block.col_stats.iter() { let density = match col_stat.distinct_of_values { Some(ndv) => ndv as f64 / row_count as f64, None => 0.0, }; match sum_map.get_mut(i) { Some(sum) => { *sum += density; } None => { let _ = sum_map.insert(*i, density); } } } } }); } let mut ndv_map = HashMap::new(); for (i, sum) in sum_map.iter() { let density_avg = *sum / block_count_sum as f64; ndv_map.insert(*i, (density_avg * row_count_sum as f64) as u64); } // 3. Generate new table statistics let table_statistics = TableSnapshotStatistics::new(ndv_map); let table_statistics_location = self .meta_location_generator .snapshot_statistics_location_from_uuid( &table_statistics.snapshot_id, table_statistics.format_version(), )?; // 4. Save table statistics let mut new_snapshot = TableSnapshot::from_previous(&snapshot); new_snapshot.table_statistics_location = Some(table_statistics_location); FuseTable::commit_to_meta_server( ctx.as_ref(), &self.table_info, &self.meta_location_generator, new_snapshot, Some(table_statistics), &None, &self.operator, ) .await?; } Ok(()) } }
mod handler; mod input; mod job; mod plugin; mod provider; mod service; mod vim; pub use self::input::InputHistory; use self::input::{ActionEvent, Event, ProviderEvent}; use self::plugin::{ ActionType, ClapPlugin, CtagsPlugin, CursorWordHighlighter, GitPlugin, MarkdownPlugin, PluginId, SystemPlugin, }; use self::provider::{create_provider, Context}; use self::service::ServiceManager; use self::vim::initialize_syntax_map; pub use self::vim::{Vim, VimProgressor}; use anyhow::{anyhow, Result}; use parking_lot::Mutex; use rpc::{RpcClient, RpcNotification, RpcRequest, VimMessage}; use serde_json::{json, Value}; use std::collections::HashMap; use std::io::{BufReader, BufWriter}; use std::sync::Arc; use std::time::Duration; use tokio::sync::mpsc::UnboundedReceiver; use tokio::time::Instant; // Do the initialization on startup. async fn initialize( vim: Vim, actions: Vec<&str>, config_err: Option<toml::de::Error>, ) -> Result<()> { if let Some(err) = config_err { vim.echo_warn(format!( "Using default Config due to the error in {}: {err}", crate::config::config_file().display() ))?; } // The output of `autocmd filetypedetect` could be incomplete as the // filetype won't be instantly initialized, thus the current workaround // is to introduce some delay. // // TODO: parse filetype.vim tokio::time::sleep(Duration::from_millis(1000)).await; let output: String = vim .call("execute", json!(["autocmd filetypedetect"])) .await?; let ext_map = initialize_syntax_map(&output); vim.exec("clap#ext#set", json![ext_map])?; vim.set_var("g:clap_actions", json![actions])?; tracing::debug!("Client initialized successfully"); Ok(()) } /// Starts and keep running the server on top of stdio. pub async fn start(config_err: Option<toml::de::Error>) { // TODO: setup test framework using vim_message_sender. let (vim_message_sender, vim_message_receiver) = tokio::sync::mpsc::unbounded_channel(); let rpc_client = Arc::new(RpcClient::new( BufReader::new(std::io::stdin()), BufWriter::new(std::io::stdout()), vim_message_sender.clone(), )); let vim = Vim::new(rpc_client); let mut callable_action_methods = Vec::new(); let mut all_actions = HashMap::new(); let mut service_manager = ServiceManager::default(); let mut register_plugin = |plugin: Box<dyn ClapPlugin>| { callable_action_methods.extend( plugin .actions(ActionType::Callable) .iter() .map(|a| a.method), ); let (plugin_id, actions) = service_manager.register_plugin(plugin); all_actions.insert(plugin_id, actions); }; register_plugin(Box::new(SystemPlugin::new(vim.clone()))); register_plugin(Box::new(GitPlugin::new(vim.clone()))); let plugin_config = &crate::config::config().plugin; if plugin_config.ctags.enable { register_plugin(Box::new(CtagsPlugin::new(vim.clone()))); } if plugin_config.markdown.enable { register_plugin(Box::new(MarkdownPlugin::new(vim.clone()))); } if plugin_config.cursor_word_highlighter.enable { register_plugin(Box::new(CursorWordHighlighter::new(vim.clone()))); } tokio::spawn({ let vim = vim.clone(); async move { if let Err(e) = initialize(vim, callable_action_methods, config_err).await { tracing::error!(error = ?e, "Failed to initialize Client") } } }); Client::new(vim, service_manager, all_actions) .run(vim_message_receiver) .await; } #[derive(Clone)] struct Client { vim: Vim, plugin_actions: Arc<Mutex<HashMap<PluginId, Vec<String>>>>, service_manager: Arc<Mutex<ServiceManager>>, } impl Client { /// Creates a new instnace of [`Client`]. fn new( vim: Vim, service_manager: ServiceManager, plugin_actions: HashMap<PluginId, Vec<String>>, ) -> Self { Self { vim, plugin_actions: Arc::new(Mutex::new(plugin_actions)), service_manager: Arc::new(Mutex::new(service_manager)), } } /// Entry of the bridge between Vim and Rust. /// /// Handle the messages actively initiated from Vim. async fn run(self, mut rx: UnboundedReceiver<VimMessage>) { // If the debounce timer isn't active, it will be set to expire "never", // which is actually just 1 year in the future. const NEVER: Duration = Duration::from_secs(365 * 24 * 60 * 60); let mut pending_notification = None; let mut notification_dirty = false; let notification_delay = Duration::from_millis(50); let notification_timer = tokio::time::sleep(NEVER); tokio::pin!(notification_timer); loop { tokio::select! { maybe_call = rx.recv() => { match maybe_call { Some(call) => { match call { VimMessage::Request(rpc_request) => self.process_request(rpc_request), VimMessage::Notification(notification) => { // Avoid spawn too frequently if user opens and // closes the provider frequently in a very short time. if notification.method == "new_provider" { pending_notification.replace(notification); notification_dirty = true; notification_timer .as_mut() .reset(Instant::now() + notification_delay); } else { self.process_notification(notification); } } } } None => break, // channel has closed. } } _ = notification_timer.as_mut(), if notification_dirty => { notification_dirty = false; notification_timer.as_mut().reset(Instant::now() + NEVER); if let Some(notification) = pending_notification.take() { let last_session_id = notification .session_id() .unwrap_or_default() .saturating_sub(1); self.service_manager.lock().try_exit(last_session_id); let session_id = notification.session_id(); if let Err(err) = self.do_process_notification(notification).await { tracing::error!(?session_id, ?err, "Error at processing Vim Notification"); } } } } } } fn process_notification(&self, notification: RpcNotification) { if let Some(session_id) = notification.session_id() { if self.service_manager.lock().exists(session_id) { let client = self.clone(); tokio::spawn(async move { if let Err(err) = client.do_process_notification(notification).await { tracing::error!(?session_id, ?err, "Error at processing Vim Notification"); } }); } } else { let client = self.clone(); tokio::spawn(async move { if let Err(err) = client.do_process_notification(notification).await { tracing::error!(?err, "Error at processing Vim Notification"); } }); } } /// Actually process a Vim notification message. async fn do_process_notification(&self, notification: RpcNotification) -> Result<()> { let maybe_session_id = notification.session_id(); let action_parser = |notification: RpcNotification| -> Result<ActionEvent> { for (plugin_id, actions) in self.plugin_actions.lock().iter() { if actions.contains(&notification.method) { return Ok((*plugin_id, notification.into())); } } Err(anyhow!("Failed to parse {notification:?}")) }; match Event::parse_notification(notification, action_parser)? { Event::NewProvider(params) => { let session_id = maybe_session_id.ok_or_else(|| anyhow!("`session_id` not found in Params"))?; let ctx = Context::new(params, self.vim.clone()).await?; let provider = create_provider(&ctx).await?; self.service_manager .lock() .new_provider(session_id, provider, ctx); } Event::ProviderWorker(provider_event) => match provider_event { ProviderEvent::Exit => { let session_id = maybe_session_id .ok_or_else(|| anyhow!("`session_id` not found in Params"))?; self.service_manager.lock().notify_provider_exit(session_id); } to_send => { let session_id = maybe_session_id .ok_or_else(|| anyhow!("`session_id` not found in Params"))?; self.service_manager .lock() .notify_provider(session_id, to_send); } }, Event::Key(key_event) => { let session_id = maybe_session_id.ok_or_else(|| anyhow!("`session_id` not found in Params"))?; self.service_manager .lock() .notify_provider(session_id, ProviderEvent::Key(key_event)); } Event::Autocmd(autocmd_event) => { self.service_manager.lock().notify_plugins(autocmd_event); } Event::Action((plugin_id, plugin_action)) => { if plugin_id == PluginId::System && plugin_action.method == "list-plugins" { let lines = self .service_manager .lock() .plugins .keys() .map(|p| p.to_string()) .collect::<Vec<_>>(); self.vim.echo_info(lines.join(","))?; return Ok(()); } self.service_manager .lock() .notify_plugin_action(plugin_id, plugin_action); } } Ok(()) } /// Process [`RpcRequest`] initiated from Vim. fn process_request(&self, rpc_request: RpcRequest) { let client = self.clone(); tokio::spawn(async move { let id = rpc_request.id; match client.do_process_request(rpc_request).await { Ok(Some(result)) => { // Send back the result of method call. if let Err(err) = client.vim.send_response(id, Ok(result)) { tracing::debug!(id, ?err, "Failed to send the output result"); } } Ok(None) => {} Err(err) => { tracing::error!(id, ?err, "Error at processing Vim RpcRequest"); } } }); } async fn do_process_request(&self, rpc_request: RpcRequest) -> Result<Option<Value>> { let msg = rpc_request; let value = match msg.method.as_str() { "preview/file" => Some(handler::messages::preview_file(msg).await?), "quickfix" => Some(handler::messages::preview_quickfix(msg).await?), _ => Some(json!({ "error": format!("Unknown request: {}", msg.method) })), }; Ok(value) } }
use crate::librb::size_t; use libc; use libc::close; use libc::free; #[repr(C)] #[derive(Copy, Clone)] pub struct volume_id { pub fd: libc::c_int, pub error: libc::c_int, pub sbbuf_len: size_t, pub seekbuf_len: size_t, pub sbbuf: *mut u8, pub seekbuf: *mut u8, pub seekbuf_off: u64, pub label: [libc::c_char; 65], pub uuid: [libc::c_char; 37], pub type_0: *const libc::c_char, } pub type probe_fptr = Option<unsafe fn(_: *mut volume_id) -> libc::c_int>; /*, u64 off*/ /* * volume_id - reads filesystem label and uuid * * Copyright (C) 2005 Kay Sievers <kay.sievers@vrfy.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ //kbuild:lib-$(CONFIG_VOLUMEID) += volume_id.o util.o /* Some detection routines do not set label or uuid anyway, * so they are disabled. */ /* Looks for partitions, we don't use it: */ /* #define ENABLE_FEATURE_VOLUMEID_MSDOS 0 - NB: this one * was not properly added to probe table anyway - ??! */ /* None of RAIDs have label or uuid, except LinuxRAID: */ /* These filesystems also have no label or uuid: */ pub type raid_probe_fptr = Option<unsafe fn(_: *mut volume_id, _: u64) -> libc::c_int>; static mut raid1: [raid_probe_fptr; 1] = { [Some( crate::util_linux::volume_id::linux_raid::volume_id_probe_linux_raid, )] }; static mut raid2: [probe_fptr; 1] = { [Some( crate::util_linux::volume_id::luks::volume_id_probe_luks, )] }; /*u64 off,*/ /* signature in the first block, only small buffer needed */ static mut fs1: [probe_fptr; 6] = { [ Some(crate::util_linux::volume_id::fat::volume_id_probe_vfat), Some(crate::util_linux::volume_id::exfat::volume_id_probe_exfat), Some(crate::util_linux::volume_id::lfs::volume_id_probe_lfs), Some(crate::util_linux::volume_id::squashfs::volume_id_probe_squashfs), Some(crate::util_linux::volume_id::xfs::volume_id_probe_xfs), Some(crate::util_linux::volume_id::bcache::volume_id_probe_bcache), ] }; /* fill buffer with maximum */ static mut fs2: [probe_fptr; 17] = { [ Some(crate::util_linux::volume_id::linux_swap::volume_id_probe_linux_swap), Some(crate::util_linux::volume_id::ext::volume_id_probe_ext), Some(crate::util_linux::volume_id::btrfs::volume_id_probe_btrfs), Some(crate::util_linux::volume_id::reiserfs::volume_id_probe_reiserfs), Some(crate::util_linux::volume_id::jfs::volume_id_probe_jfs), Some(crate::util_linux::volume_id::udf::volume_id_probe_udf), Some(crate::util_linux::volume_id::iso9660::volume_id_probe_iso9660), Some(crate::util_linux::volume_id::hfs::volume_id_probe_hfs_hfsplus), Some(crate::util_linux::volume_id::f2fs::volume_id_probe_f2fs), Some(crate::util_linux::volume_id::nilfs::volume_id_probe_nilfs), Some(crate::util_linux::volume_id::ntfs::volume_id_probe_ntfs), Some(crate::util_linux::volume_id::cramfs::volume_id_probe_cramfs), Some(crate::util_linux::volume_id::romfs::volume_id_probe_romfs), Some(crate::util_linux::volume_id::sysv::volume_id_probe_sysv), Some(crate::util_linux::volume_id::minix::volume_id_probe_minix), Some(crate::util_linux::volume_id::ocfs2::volume_id_probe_ocfs2), Some(crate::util_linux::volume_id::ubifs::volume_id_probe_ubifs), ] }; pub unsafe fn volume_id_probe_all(mut id: *mut volume_id, mut size: u64) -> libc::c_int { let mut current_block: u64; let mut i: libc::c_uint = 0; /* probe for raid first, cause fs probes may be successful on raid members */ if size != 0 { i = 0 as libc::c_uint; loop { if !(i < (::std::mem::size_of::<[raid_probe_fptr; 1]>() as libc::c_ulong) .wrapping_div(::std::mem::size_of::<raid_probe_fptr>() as libc::c_ulong) as libc::c_uint) { current_block = 7815301370352969686; break; } if raid1[i as usize].expect("non-null function pointer")(id, size) == 0 { current_block = 13835600803501426168; break; } if (*id).error != 0 { current_block = 13835600803501426168; break; } i = i.wrapping_add(1) } } else { current_block = 7815301370352969686; } match current_block { 7815301370352969686 => { i = 0 as libc::c_uint; loop { if !(i < (::std::mem::size_of::<[probe_fptr; 1]>() as libc::c_ulong) .wrapping_div(::std::mem::size_of::<probe_fptr>() as libc::c_ulong) as libc::c_uint) { current_block = 2979737022853876585; break; } if raid2[i as usize].expect("non-null function pointer")(id) == 0 { current_block = 13835600803501426168; break; } if (*id).error != 0 { current_block = 13835600803501426168; break; } i = i.wrapping_add(1) } match current_block { 13835600803501426168 => {} _ => /* signature in the first block, only small buffer needed */ { i = 0 as libc::c_uint; loop { if !(i < (::std::mem::size_of::<[probe_fptr; 6]>() as libc::c_ulong) .wrapping_div(::std::mem::size_of::<probe_fptr>() as libc::c_ulong) as libc::c_uint) { current_block = 17833034027772472439; break; } if fs1[i as usize].expect("non-null function pointer")(id) == 0 { current_block = 13835600803501426168; break; } if (*id).error != 0 { current_block = 13835600803501426168; break; } i = i.wrapping_add(1) } match current_block { 13835600803501426168 => {} _ => { /* fill buffer with maximum */ crate::util_linux::volume_id::util::volume_id_get_buffer( id, 0 as u64, 0x11000i32 as size_t, ); i = 0 as libc::c_uint; while i < (::std::mem::size_of::<[probe_fptr; 17]>() as libc::c_ulong) .wrapping_div(::std::mem::size_of::<probe_fptr>() as libc::c_ulong) as libc::c_uint { if fs2[i as usize].expect("non-null function pointer")(id) == 0 { break; } if (*id).error != 0 { break; } i = i.wrapping_add(1) } } } } } } _ => {} } crate::util_linux::volume_id::util::volume_id_free_buffer(id); return -(*id).error; /* 0 or -1 */ } /* open volume by device node */ pub unsafe fn volume_id_open_node(mut fd: libc::c_int) -> *mut volume_id { let mut id: *mut volume_id = std::ptr::null_mut(); id = crate::libbb::xfuncs_printf::xzalloc(::std::mem::size_of::<volume_id>() as libc::c_ulong) as *mut volume_id; (*id).fd = fd; // /* close fd on device close */ //id->fd_close = 1; return id; } /* * volume_id - reads filesystem label and uuid * * Copyright (C) 2005 Kay Sievers <kay.sievers@vrfy.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* #define dbg(...) bb_error_msg(__VA_ARGS__) */ /* volume_id.h */ // int fd_close:1; // u8 label_raw[VOLUME_ID_LABEL_SIZE]; // size_t label_raw_len; // u8 uuid_raw[VOLUME_ID_UUID_SIZE]; // size_t uuid_raw_len; /* uuid is stored in ASCII (not binary) form here: */ // char type_version[VOLUME_ID_FORMAT_SIZE]; // smallint usage_id; // const char *usage; /*u64 off,*/ pub unsafe fn free_volume_id(mut id: *mut volume_id) { if id.is_null() { return; } //if (id->fd_close != 0) - always true close((*id).fd); crate::util_linux::volume_id::util::volume_id_free_buffer(id); free(id as *mut libc::c_void); }
use crate::smb2::requests::close::Close; /// Serializes the create request body. pub fn serialize_close_request_body(request: &Close) -> Vec<u8> { let mut serialized_request: Vec<u8> = Vec::new(); serialized_request.append(&mut request.structure_size.clone()); serialized_request.append(&mut request.flags.clone()); serialized_request.append(&mut request.reserved.clone()); serialized_request.append(&mut request.file_id.clone()); serialized_request }
pub struct BitField{ inner: Vec<u8>, size: usize, } impl BitField { pub fn new(size) -> BitField { BitField { inner: vec![0; (size + 7) / 8], size } } pub get_first_unset_from(idx: usize) -> usize { let start = idx / 8; let offset = idx % 8; let byte = self.inner[start..]; if self.inner[start] != 0xff { for x in 0..(8 - offset) { if self.get(idx + x) { return Some(idx + x); } } } for byte in start..self.inner.len() { if let Some(x) = self.get_unset_in_byte(byte) { return Some(8 * byte + x) } } // Special handling for final partial byte for byte in 0..start { self.get_unset_in_byte(byte) if let Some(x) = self.get_unset_in_byte(byte) { return Some(8 * byte + x) } } } pub get(&self, idx: usize) -> bool { let byte = idx / 8; self.inner[byte] & self.get_mask(idx) > 0 } pub set(&mut self, idx: usize, value: bool) { let byte = idx / 8; self.inner[byte] |= self.get_mask(idx) } fn get_unset_in_byte(&self, byte: usize) -> Option<usize> { if byte == 0xff { None } else { for offset in 0..8 { if byte & (1 << offset) { return Some(offset); } } unreachable!() } } fn get_mask(&self, idx: usize) -> u8 { 1 << (idx % 8) } }
/* * Copyright 2020 Draphar * * 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. */ /*! Download support for the individual sites. */ use std::path::{Path, PathBuf}; use http::Uri; use tokio::{fs::File, io::AsyncWriteExt}; use gfycat::GfycatType; use crate::prelude::*; use crate::sites::pushshift::{Gallery, SecureMedia}; pub mod gfycat; pub mod imgur; pub mod pinterest; pub mod postimages; pub mod pushshift; pub mod reddit; /// A fetching job. /// Used for describing every download job. #[derive(Debug)] pub struct FetchJob<'a> { /// The HTTP client to use. pub client: &'a Client, /// The parameters passed to the program. pub parameters: &'a Parameters, /// The domain of the post. pub domain: String, /// Whether the post is a self post. pub is_selfpost: bool, /// The URL the post links to. /// This is not necessarily a reddit URL. pub url: Uri, /// The output file. pub output: PathBuf, /// The directory for temporary files. /// Used only while processing with `ffmpeg`. pub temp_dir: &'a Path, /// The text of the post if it is a self post. pub text: Option<String>, /// The gallery data if the post is an image gallery. pub gallery: Option<Gallery>, /// The `secure_media` property if the item is a `v.redd.it` video. pub media: Option<SecureMedia>, } /// Runs the fetch job. pub async fn fetch(config: FetchJob<'_>) -> (FetchJob<'_>, Result<()>) { trace!("fetch({:?})", config.url); let result = if config.is_selfpost { debug!("Detected self post {:?}", config.url); if let Some(text) = config.text.as_ref() { fetch_selfpost(&config.output, text).await } else { // Seriously reddit? return ( config, Err(Error::new("Malformed self post: field 'selftext' missing")), ); } } else { debug!("Fetching {:?}", config.url); match config.domain.as_ref() { "i.redd.it" => reddit::fetch_image(config.client, &config.url, &config.output).await, "v.redd.it" => { reddit::fetch_video( config.client, &config.url, &config.output, &config.temp_dir, &config.parameters.vreddit_mode, &config.media, ) .await } "reddit.com" => { if let Some(ref gallery) = config.gallery { reddit::fetch_gallery(config.client, &config.url, &config.output, gallery).await } else { // This normally indicates a selfpost Ok(()) } } "i.imgur.com" => imgur::fetch(config.client, &config.url, &config.output).await, "imgur.com" => imgur::fetch_album(config.client, &config.url, &config.output).await, "gfycat.com" => { gfycat::fetch_gfycat( config.client, &config.url, &config.output, config.parameters.gfycat_type, ) .await } "redgifs.com" => { gfycat::fetch_redgifs( config.client, &config.url, &config.output, config.parameters.gfycat_type, ) .await } "giant.gfycat.com" => { gfycat::fetch_giant(config.client, &config.url, &config.output).await } "thumbs.gfycat.com" | "thumbs1.redgifs.com" => { gfycat::fetch_thumbs(config.client, &config.url, &config.output).await } "i.pinimg.com" => pinterest::fetch(config.client, &config.url, &config.output).await, "i.postimg.cc" => postimages::fetch(config.client, &config.url, &config.output).await, domain => { if config.parameters.force { download(config.client, &config.url, &config.output).await } else { Err(Error::new(format!("Unsupported domain '{}'", domain))) } } } }; (config, result) } /// Fetches a self post. pub async fn fetch_selfpost(output: &PathBuf, text: &str) -> Result<()> { trace!("fetch_selfpost({:?}, {:?})", output, text); let mut file = File::create(&output).await?; file.write_all(text.as_bytes()).await?; Ok(()) } /// Gets the file extension of an URL. pub fn file_extension(url: &Uri, gfycat_type: GfycatType, is_selfpost: bool) -> Option<&str> { if is_selfpost { return Some(".txt"); }; if url.host() == Some("reddit.com") { return Some(""); } if url.host() == Some("v.redd.it") { return Some(".mp4"); }; if url.host() == Some("gfycat.com") { return match gfycat_type { GfycatType::Mp4 => Some(".mp4"), GfycatType::Webm => Some(".webm"), }; }; let mut chars = url.path().char_indices(); while let Some((index, c)) = chars.next_back() { if c == '.' { return Some(&url.path()[index..]); } else if c == '/' { // Abort at the first slash return None; }; } None } /// Returns the currently supported domains. pub fn supported_domains() -> &'static str { "\ i.redd.it v.redd.it reddit.com i.imgur.com imgur.com gfycat.com thumbs.gfycat.com giant.gfycat.com redgifs.com thumbs1.redgifs.com i.pinimg.com i.postimg.cc\ " } #[test] fn test_url_extension() { let data = "http://example.com/"; assert_eq!( Some(".txt"), file_extension(&Uri::from_static(data), GfycatType::Mp4, true) ); let data = "http://example.com/a/b.c"; assert_eq!( Some(".c"), file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); let data = "http://example.com/a.bc"; assert_eq!( Some(".bc"), file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); let data = "http://example.com/"; assert_eq!( None, file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); let data = "http://example.com/none"; assert_eq!( None, file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); let data = "https://gfycat.com/"; assert_eq!( Some(".mp4"), file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); let data = "https://gfycat.com/"; assert_eq!( Some(".webm"), file_extension(&Uri::from_static(data), GfycatType::Webm, false) ); let data = "http://gfycat.com/.webm"; assert_eq!( Some(".mp4"), file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); let data = "http://gfycat.com/.mp4"; assert_eq!( Some(".webm"), file_extension(&Uri::from_static(data), GfycatType::Webm, false) ); let data = "http://imgur.com/image.jpg"; assert_eq!( Some(".jpg"), file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); let data = "http://imgur.com/a/id"; assert_eq!( None, file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); let data = "http://imgur.com/a/id/"; assert_eq!( None, file_extension(&Uri::from_static(data), GfycatType::Mp4, false) ); }
use crate::vec3::*; pub struct Ray { pub origin: Vec3, pub direction: Vec3, } impl Ray { pub fn new() -> Self { Ray { origin: Vec3::new(), direction: Vec3::new() } } pub fn point_at_parameter(&self, t: f32) -> Vec3 { // LERP from origin self.origin + t * self.direction } } // Construct a Ray from 2 Vec3s impl From<(Vec3, Vec3)> for Ray { fn from(tuple: (Vec3, Vec3)) -> Self { Ray{ origin: tuple.0, direction: tuple.1 } } }
use std::{ thread, time::{Duration, Instant}, }; pub struct Time { start: Instant, frame_count: u32, fps: u32, } impl Time { pub fn new(fps: u32) -> Self { Self { start: Instant::now(), frame_count: 0, fps, } } /// restarts this timer, useful after loading /// a new scene pub fn restart(&mut self) { self.frame_count = 0; self.start = Instant::now(); } pub fn fixed_seconds(&self) -> f32 { 1.0 / self.fps as f32 } pub fn frame(&mut self) { self.frame_count += 1; let finish = Duration::from_micros(1_000_000 / u64::from(self.fps)) * self.frame_count; if self.start.elapsed() < finish { while self.start.elapsed() < finish { thread::yield_now(); } } else { warn!("Lag at frame {}", self.frame_count) } } }
use std::{ path::{Path, PathBuf}, sync::Arc, }; use async_recursion::async_recursion; use futures::TryStreamExt; use log::{error, info, trace, LevelFilter}; use structopt::StructOpt; use tokio::{ fs::{read_dir, DirEntry}, spawn, sync::{ mpsc::{self, Sender}, Mutex, Semaphore, }, time::Instant, }; use tokio_stream::wrappers::ReceiverStream; /// The scenario runner. #[derive(Debug, StructOpt)] struct Cli { /// The path to the directory to be processed. src_dir: PathBuf, /// The number of threads to use for processing. threads: Option<usize>, } #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::builder().filter_level(LevelFilter::Info).init(); let cli = Cli::from_args(); let mut join_handles = Vec::new(); let threads = cli.threads.unwrap_or_else(num_cpus::get); info!("Using {} threads", threads); let semaphore = Arc::new(Semaphore::new(threads)); let (tx, rx): (Sender<std::io::Result<DirEntry>>, _) = mpsc::channel(1); let mut rx = ReceiverStream::new(rx); let cli_src_dir = cli.src_dir.as_path(); spawn(walk_dir(cli_src_dir.to_path_buf(), tx)); let count = Arc::new(Mutex::new(0usize)); let client = reqwest::Client::new(); let start_time = Instant::now(); while let Some(dir) = rx.try_next().await? { let permit = semaphore.clone().acquire_owned().await?; let path = dir.path(); let cnt = count.clone(); if let Ok(path) = path.strip_prefix(cli_src_dir).map(Path::to_string_lossy) { let url = "http://localhost:8080/static/".to_string() + &path; let client_copy = client.clone(); join_handles.push(spawn(async move { *cnt.lock().await += 1; match client_copy.get(&url).send().await { Ok(response) => { let status = response.status(); match response.text().await { Ok(body) => { trace!("{}: {} : {:?}", url, status, body.get(0..10)); } Err(err) => { error!("Error: {:?}", err); } } } Err(err) => { error!("Error: {:?}", err); } } drop(permit); })); } } for handle in join_handles { handle.await?; } let elapsed = Instant::now().duration_since(start_time).as_millis(); let count = *count.lock().await; info!( "Done. Requests count: {}. Elapsed (ms): {}. Requests per ms: {}", count, elapsed, count as f64 / elapsed as f64, ); Ok(()) } #[async_recursion] async fn walk_dir( dir: PathBuf, tx: Sender<std::io::Result<DirEntry>>, ) -> Result<(), anyhow::Error> { let mut dir_info = read_dir(dir).await?; while let Some(dir) = dir_info.next_entry().await? { let path = dir.path(); if path.is_dir() { walk_dir(path, tx.clone()).await?; } else { tx.send(Ok(dir)).await?; } } Ok(()) }
use crate::context::{Context, Output, Printer}; use crate::descriptor::{EnumDescriptor, FileDescriptor, MessageDescriptor}; use crate::pecan_descriptor::google::protobuf::descriptor_pb::*; use id_arena::Id; use pecan::Message; use pecan::Result; use pecan_utils::naming; use std::env; use std::fmt::Write; use std::collections::HashMap; struct FieldDecl<'a> { field_name: String, type_name: String, tag1: u32, tag2: u32, copy: bool, default_val: &'static str, method_symbol: &'static str, map_fields: Vec<FieldDecl<'a>>, proto: &'a FieldDescriptorProto, } impl FieldDecl<'_> { fn strip_field_name(&self) -> &str { if !self.field_name.starts_with("r#") { &self.field_name } else { &self.field_name[2..] } } } struct OneOfDecl<'a> { field_name: String, type_name: String, copy: bool, items: Vec<FieldType<'a>>, } enum FieldType<'a> { Optional(FieldDecl<'a>), Singlular(FieldDecl<'a>), Repeated(FieldDecl<'a>), Oneof(OneOfDecl<'a>), } impl<'a> FieldType<'a> { fn singlular(&self) -> &FieldDecl<'_> { match self { FieldType::Optional(fd) | FieldType::Singlular(fd) => fd, _ => unreachable!(), } } fn unwrap_singlular(self) -> FieldDecl<'a> { match self { FieldType::Optional(fd) | FieldType::Singlular(fd) => fd, _ => unreachable!(), } } } pub struct Generator<'a> { printer: Printer<'a>, file: Id<FileDescriptor>, proto3: bool, file_name: String, } impl Generator<'_> { pub fn new<'a>( ctx: &Context, output: &'a mut Output, file: Id<FileDescriptor>, ) -> Generator<'a> { let file_descriptor = &ctx.db.files.get(file).unwrap(); let input_file_name = file_descriptor.proto.name().to_owned(); let module_name = naming::module_name(&input_file_name); let output_file_name = naming::file_name(&module_name); let printer = output.open(&output_file_name); Generator { printer, file, proto3: file_descriptor.proto3, file_name: input_file_name, } } fn print_top_boilerplate(&mut self) { w!( self.printer, "// This file is generated by pecan {version}, DO NOT EDIT! // @generated // source: {file_name} ", version = env!("CARGO_PKG_VERSION"), file_name = self.file_name ); w!(self.printer, "\n"); w!( self.printer, "#![allow(non_upper_case_globals)]\n#![allow(unused_imports)]\n" ); } fn print_imports(&mut self, ctx: &Context) { w!(self.printer, "\n"); w!( self.printer, "use pecan::{{ codec, EnumType, Message, Result, Buf, BufMut, CodedInputStream, CodedOutputStream, encoded, }}; use std::collections::HashMap;\n" ); let f = ctx.db.files.get(self.file).unwrap(); if f.proto.dependency().is_empty() { return; } w!(self.printer, "\n"); for dependency in f.proto.dependency() { let id = *ctx.files.get(dependency).unwrap(); let dep = &ctx.db.files.get(id).unwrap(); let module_name = naming::module_name(dep.proto.name()); let module_alias = naming::alias_name(dep.proto.name()); w!( self.printer, "use crate::{module_name} as {module_alias};\n", module_name = module_name, module_alias = module_alias ); } } fn print_file_descriptor(&mut self, ctx: &Context) -> Result<()> { let mut proto = ctx.db.files.get(self.file).unwrap().proto.clone(); proto.clear_source_code_info(); let bytes = proto.write_as_bytes()?; w!(self.printer, "\npub static DESCRIPTOR: &[u8] = &[\n"); self.printer.indent(); for chunk in bytes.chunks(16) { for b in &chunk[..chunk.len() - 1] { w!(self.printer, "{}, ", b); } w!(self.printer, "{},\n", chunk[chunk.len() - 1]); } self.printer.outdent(); w!(self.printer, "];\n"); Ok(()) } fn print_enum(&mut self, ctx: &Context, id: Id<EnumDescriptor>) { w!( self.printer, "\n#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]\n" ); let e = ctx.db.enums.get(id).unwrap(); let name = naming::type_name(&e.type_name); w!(self.printer, "pub struct {}(i32);\n\n", name); w_scope!(self.printer, "impl {} {{\n", name); let mut zero_value = format!("{}(0)", name); let mut visited_enums = HashMap::new(); for v in e.proto.value() { let enum_name = naming::camel_case(v.name()); if v.number() == 0 { zero_value = format!("{}::{}", name, enum_name); } if let Some(value) = visited_enums.get(&enum_name) { if v.number() != *value { panic!("there is already enum named {} with value {} != {}", enum_name, value, v.number()); } continue; } w!( self.printer, "pub const {}: {} = {}({});\n", enum_name, name, name, v.number() ); visited_enums.insert(enum_name, v.number()); } w_scope!(self.printer, "\npub const fn new() -> {} {{\n", name); w!(self.printer, "{}\n", zero_value); w_end_scope!(self.printer, "}}\n"); w_end_scope!(self.printer, "}}\n\n"); w!(self.printer, "impl From<i32> for {} {{\n", name); self.printer.indent(); w!(self.printer, "#[inline]\nfn from(u: i32) -> {} {{\n", name); self.printer.indent(); w!(self.printer, "{}(u)\n", name); self.printer.outdent(); w!(self.printer, "}}\n"); self.printer.outdent(); w!(self.printer, "}}\n\n"); w!(self.printer, "impl EnumType for {} {{\n", name); self.printer.indent(); w!( self.printer, "#[inline]\nfn values() -> &'static [{}] {{\n", name ); self.printer.indent(); w!(self.printer, "&[\n"); self.printer.indent(); for v in e.proto.value() { let enum_name = naming::camel_case(v.name()); w!(self.printer, "{}::{},\n", name, enum_name); } self.printer.outdent(); w!(self.printer, "]\n"); self.printer.outdent(); w!( self.printer, "}}\n\n#[inline]\nfn value(&self) -> i32 {{ self.0 }}\n" ); self.printer.outdent(); w!(self.printer, "}}\n"); } fn print_enums(&mut self, ctx: &Context) { let enums = &ctx.db.files.get(self.file).unwrap().enums; for e in enums { self.print_enum(ctx, *e); } } fn build_field<'a>( &mut self, ctx: &'a Context, f: &'a FieldDescriptorProto, ) -> (Option<i32>, FieldType<'a>) { let mut desc = FieldDecl { field_name: naming::field_name(f.name()), type_name: String::new(), tag1: (f.number() as u32) << 3, tag2: 0, copy: true, default_val: "0", method_symbol: "", map_fields: vec![], proto: f, }; let mut wire_type = 0; match f.r#type() { FieldDescriptorProtoNestedType::TypeBool => { desc.method_symbol = "bool"; desc.type_name = "bool".to_owned(); desc.default_val = ""; } FieldDescriptorProtoNestedType::TypeInt32 => { desc.method_symbol = "var_i32"; desc.type_name = "i32".to_owned(); } FieldDescriptorProtoNestedType::TypeInt64 => { desc.method_symbol = "var_i64"; desc.type_name = "i64".to_owned(); } FieldDescriptorProtoNestedType::TypeUint32 => { desc.method_symbol = "var_u32"; desc.type_name = "u32".to_owned(); } FieldDescriptorProtoNestedType::TypeUint64 => { desc.method_symbol = "var_u64"; desc.type_name = "u64".to_owned(); } FieldDescriptorProtoNestedType::TypeSint32 => { desc.method_symbol = "var_s32"; desc.type_name = "i32".to_owned(); } FieldDescriptorProtoNestedType::TypeSint64 => { desc.method_symbol = "var_s64"; desc.type_name = "i64".to_owned(); } FieldDescriptorProtoNestedType::TypeEnum => { desc.method_symbol = "enum"; let id = ctx.enum_address.get(f.type_name()).unwrap(); let e = ctx.db.enums.get(*id).unwrap(); desc.type_name = naming::type_name(&e.type_name); if e.file != self.file { let f = ctx.db.files.get(e.file).unwrap(); desc.type_name = format!( "{}::{}", naming::alias_name(f.proto.name()), &desc.type_name ); } desc.default_val = ""; } FieldDescriptorProtoNestedType::TypeFixed64 => { wire_type = 1; desc.method_symbol = "fixed64"; desc.type_name = "u64".to_owned(); } FieldDescriptorProtoNestedType::TypeSfixed64 => { wire_type = 1; desc.method_symbol = "sfixed64"; desc.type_name = "i64".to_owned(); } FieldDescriptorProtoNestedType::TypeDouble => { wire_type = 1; desc.method_symbol = "f64"; desc.type_name = "f64".to_owned(); desc.default_val = "0f64"; } FieldDescriptorProtoNestedType::TypeString => { wire_type = 2; desc.method_symbol = "string"; desc.type_name = "String".to_owned(); desc.default_val = ""; desc.copy = false; } FieldDescriptorProtoNestedType::TypeBytes => { wire_type = 2; desc.method_symbol = "bytes"; desc.type_name = "Vec<u8>".to_owned(); desc.default_val = ""; desc.copy = false; } FieldDescriptorProtoNestedType::TypeMessage => { wire_type = 2; desc.method_symbol = "message"; let id = ctx.message_address.get(f.type_name()).unwrap(); let e = ctx.db.messages.get(*id).unwrap(); if !e.proto.options().map_entry() { desc.type_name = naming::type_name(&e.type_name); if e.file != self.file { let f = ctx.db.files.get(e.file).unwrap(); desc.type_name = format!( "{}::{}", naming::alias_name(f.proto.name()), &desc.type_name ); } } else { let key_fd = self .build_field(ctx, &e.proto.field()[0]) .1 .unwrap_singlular(); let val_fd = self .build_field(ctx, &e.proto.field()[1]) .1 .unwrap_singlular(); desc.type_name = format!("HashMap<{}, {}>", key_fd.type_name, val_fd.type_name); desc.map_fields.push(key_fd); desc.map_fields.push(val_fd); } desc.default_val = ""; desc.copy = false; } FieldDescriptorProtoNestedType::TypeGroup => unimplemented!(), FieldDescriptorProtoNestedType::TypeFixed32 => { wire_type = 5; desc.method_symbol = "fixed32"; desc.type_name = "u32".to_owned(); } FieldDescriptorProtoNestedType::TypeSfixed32 => { wire_type = 5; desc.method_symbol = "sfixed32"; desc.type_name = "i32".to_owned(); } FieldDescriptorProtoNestedType::TypeFloat => { wire_type = 5; desc.method_symbol = "f32"; desc.type_name = "f32".to_owned(); desc.default_val = "0f32"; } _ => unimplemented!(), } desc.tag1 |= wire_type; let oneof_index = if desc.proto.has_oneof_index() { Some(desc.proto.oneof_index()) } else { None }; let ft = match desc.proto.label() { FieldDescriptorProtoNestedLabel::LabelOptional => { if !self.proto3 || f.r#type() == FieldDescriptorProtoNestedType::TypeMessage { FieldType::Optional(desc) } else { FieldType::Singlular(desc) } } FieldDescriptorProtoNestedLabel::LabelRequired => FieldType::Singlular(desc), FieldDescriptorProtoNestedLabel::LabelRepeated => { if wire_type == 0 || wire_type == 1 || wire_type == 5 { desc.tag2 = (desc.proto.number() as u32) << 3 | 2; } FieldType::Repeated(desc) } _ => unimplemented!(), }; (oneof_index, ft) } fn build_field_set<'a>( &mut self, ctx: &'a Context, m: &'a MessageDescriptor, ) -> Vec<FieldType<'a>> { let mut oneof_decls = vec![]; for oneof in m.proto.oneof_decl() { let mut oneof_names = m.type_name.clone(); oneof_names.push(naming::camel_case(oneof.name())); oneof_decls.push(OneOfDecl { field_name: naming::field_name(oneof.name()), type_name: naming::type_name(&oneof_names), copy: true, items: vec![], }); } let mut fields = vec![]; for f in m.proto.field() { let (oneof_index, ft) = self.build_field(ctx, f); if let Some(index) = oneof_index { oneof_decls[index as usize].copy &= ft.singlular().copy; oneof_decls[index as usize].items.push(ft); } else { fields.push(ft); } } fields.extend(oneof_decls.into_iter().map(FieldType::Oneof)); fields } fn print_field_decl(&mut self, field_sets: &[FieldType]) { for ft in field_sets { match ft { FieldType::Optional(desc) => { // A dirty hack to pass conformance, should use extension instead. if desc.field_name.contains("recursive") { w!( self.printer, "{}: Option<Box<{}>>,\n", desc.field_name, desc.type_name ); } else { w!( self.printer, "{}: Option<{}>,\n", desc.field_name, desc.type_name ); } } FieldType::Singlular(desc) => { w!( self.printer, "pub {}: {},\n", desc.field_name, desc.type_name ); } FieldType::Repeated(desc) => { if desc.map_fields.is_empty() { w!( self.printer, "{}: Vec<{}>,\n", desc.field_name, desc.type_name ); } else { w!(self.printer, "{}: Option<{}>,\n", desc.field_name, desc.type_name) } } FieldType::Oneof(desc) => { w!( self.printer, "pub {}: Option<{}>,\n", desc.field_name, desc.type_name ); } } } } fn print_oneof_decl(&mut self, field_sets: &[FieldType]) { for ft in field_sets { let desc = match ft { FieldType::Oneof(desc) => desc, _ => continue, }; if desc.copy { w!( self.printer, "\n#[derive(Clone, Debug, Coppy, PartialEq)]\n" ); } else { w!(self.printer, "\n#[derive(Clone, Debug, PartialEq)]\n"); } w!(self.printer, "pub enum {} {{\n", desc.type_name); self.printer.indent(); for item in &desc.items { let (ty_name, internal_ty) = match item { FieldType::Oneof(d) => (naming::camel_case(&d.field_name), &d.type_name), FieldType::Optional(d) => (naming::camel_case(&d.field_name), &d.type_name), FieldType::Repeated(d) => (naming::camel_case(&d.field_name), &d.type_name), FieldType::Singlular(d) => (naming::camel_case(&d.field_name), &d.type_name), }; w!(self.printer, "{}({}),\n", ty_name, internal_ty); } self.printer.outdent(); w!(self.printer, "}}\n"); } } fn print_merge_from_optional(&mut self, d: &FieldDecl) { if d.method_symbol != "message" { w!( self.printer, "{} => self.{} = Some(s.read_{}()?),\n", d.tag1, d.field_name, d.method_symbol ); return; } w_scope!(self.printer, "{} => {{\n", d.tag1); w!( self.printer, "let msg = self.{}.get_or_insert_with(Default::default);\n", d.field_name ); w!(self.printer, "s.read_message(msg)?;\n"); w_end_scope!(self.printer, "}}\n"); } fn print_merge_from_singlular(&mut self, d: &FieldDecl) { w!( self.printer, "{} => self.{} = s.read_{}()?,\n", d.tag1, d.field_name, d.method_symbol ); } fn print_merge_from_repeated(&mut self, d: &FieldDecl) { w!(self.printer, "{} => ", d.tag1); if d.map_fields.is_empty() { if d.method_symbol != "message" { w!( self.printer, "self.{}.push(s.read_{}()?),\n", d.field_name, d.method_symbol ); } else { w!( self.printer, "s.read_message_to(&mut self.{})?,\n", d.field_name ); } if d.tag1 != d.tag2 && d.tag2 != 0 { w!( self.printer, "{} => s.read_{}_array(&mut self.{})?,\n", d.tag2, d.method_symbol, d.field_name ); } return; } let (k_fd, v_fd) = (&d.map_fields[0], &d.map_fields[1]); w_scope!(self.printer, "s.read_message_like(|s| {{\n"); w!( self.printer, "let (mut key, mut value) = Default::default();\n" ); w_scope!(self.printer, "loop {{\n"); w!(self.printer, "let tag = s.read_tag()?;\n"); w_scope!(self.printer, "match tag {{\n"); w!( self.printer, "{} => key = s.read_{}()?,\n", k_fd.tag1, k_fd.method_symbol ); if v_fd.method_symbol != "message" { w!( self.printer, "{} => value = s.read_{}()?,\n", v_fd.tag1, v_fd.method_symbol ); } else { w!( self.printer, "{} => s.read_message(&mut value)?,\n", v_fd.tag1 ); } w!(self.printer, "0 => break,\ntag => s.discard_field(tag)?,\n"); w_end_scope!(self.printer, "}}\n"); w_end_scope!(self.printer, "}}\n"); w!(self.printer, "self.{}.get_or_insert_with(Default::default).insert(key, value);\n", d.field_name); w!(self.printer, "Ok(())\n"); w_end_scope!(self.printer, "}})?,\n"); } fn print_merge_from_oneof(&mut self, o: &OneOfDecl) { for item in &o.items { match item { FieldType::Optional(d) => { if d.method_symbol != "message" { w!( self.printer, "{} => self.{} = Some({}::{}(s.read_{}()?)),\n", d.tag1, o.field_name, o.type_name, naming::camel_case(&d.field_name), d.method_symbol ); continue; } w!(self.printer, "{} => {{\n", d.tag1); self.printer.indent(); w!( self.printer, "let msg = self.{}_mut();\n", d.field_name ); w!(self.printer, "s.read_message(msg)?;\n"); self.printer.outdent(); w!(self.printer, "}}\n"); } FieldType::Singlular(d) => { w!( self.printer, "{} => self.{} = Some({}::{}(s.read_{}()?)),\n", d.tag1, o.field_name, o.type_name, naming::camel_case(&d.field_name), d.method_symbol ); } FieldType::Repeated(_) | FieldType::Oneof(_) => unreachable!(), } } } fn print_merge_from(&mut self, field_sets: &[FieldType]) { w!( self.printer, "fn merge_from(&mut self, s: &mut CodedInputStream<impl Buf>) -> Result<()> {{\n" ); self.printer.indent(); w_scope!(self.printer, "loop {{\n"); w_scope!(self.printer, "let tag = s.read_tag()?;\nmatch tag {{\n"); for ft in field_sets { match ft { FieldType::Optional(d) => self.print_merge_from_optional(d), FieldType::Singlular(d) => self.print_merge_from_singlular(d), FieldType::Repeated(d) => self.print_merge_from_repeated(d), FieldType::Oneof(d) => self.print_merge_from_oneof(d), } } w!( self.printer, "0 => return Ok(()),\n_ => s.skip_field(&mut self.unknown, tag)?,\n" ); for _ in 0..3 { w_end_scope!(self.printer, "}}\n"); } } fn print_write_to_tag(&mut self, tag: u32) { let mut buffer = [0u8; 5]; let count = unsafe { pecan_utils::codec::encode_varint_u32_to_array(buffer.as_mut_ptr(), tag) }; w!( self.printer, "s.write_raw_{}_byte({:?})?;\n", count, &buffer[..count] ); } fn print_write_to_raw(&mut self, d: &FieldDecl, method_symbol: &str, field: &str) { let tag = if d.tag2 == 0 { d.tag1 } else { d.tag2 }; self.print_write_to_tag(tag); if method_symbol != "message" { w!(self.printer, "s.write_{}({})?;\n", method_symbol, field); } else { w!(self.printer, "s.write_message({})?;\n", field); } } fn print_write_to_repeated(&mut self, d: &FieldDecl) { if d.map_fields.is_empty() { w!(self.printer, "if !self.{}.is_empty() {{\n", d.field_name); } else { w!(self.printer, "if let Some(m) = &self.{} {{\n", d.field_name); } self.printer.indent(); if d.copy { let method_symbol = format!("{}_array", d.method_symbol); let field = format!("&self.{}", d.field_name); self.print_write_to_raw(d, &method_symbol, &field); } else if d.map_fields.is_empty() { w!(self.printer, "for v in &self.{} {{\n", d.field_name); self.printer.indent(); self.print_write_to_raw(d, d.method_symbol, "v"); self.printer.outdent(); w!(self.printer, "}}\n"); } else { let (key_fd, val_fd) = (&d.map_fields[0], &d.map_fields[1]); let key_mat = if key_fd.copy { "&k" } else { "k" }; let val_mat = if val_fd.copy { "&v" } else { "v" }; w_scope!(self.printer, "for ({}, {}) in m {{\n", key_mat, val_mat); self.print_write_to_tag(d.tag1); w!(self.printer, "let mut n = 0;\n"); self.check_print_singlular(key_fd, "k", Self::print_len_raw); self.check_print_singlular(val_fd, "v", Self::print_len_raw); w!(self.printer, "s.write_var_u32(n as u32)?;\n"); self.check_print_singlular(key_fd, "k", Self::print_write_to_raw); self.check_print_singlular(val_fd, "v", Self::print_write_to_raw); w_end_scope!(self.printer, "}}\n"); } self.printer.outdent(); w!(self.printer, "}}\n"); } fn print_write_to(&mut self, field_sets: &[FieldType]) { w!( self.printer, "\nfn write_to(&self, s: &mut CodedOutputStream<impl BufMut>) -> Result<()> {{\n" ); self.printer.indent(); for ft in field_sets { match ft { FieldType::Optional(d) => self.print_write_to_optional(d), FieldType::Singlular(d) => { let field = if d.copy { format!("self.{}", d.field_name) } else { format!("&self.{}", d.field_name) }; self.check_print_singlular( d, &field, Self::print_write_to_raw, ) }, FieldType::Repeated(d) => self.print_write_to_repeated(d), FieldType::Oneof(d) => self.check_print_oneof(d, Self::print_write_to_raw, false), } } w!(self.printer, "if !self.unknown.is_empty() {{\n"); self.printer.indent(); w!(self.printer, "s.write_unknown(&self.unknown)?;\n"); self.printer.outdent(); w!(self.printer, "}}\nOk(())\n"); self.printer.outdent(); w!(self.printer, "}}\n"); } fn print_len_raw(&mut self, d: &FieldDecl, symbol: &str, field: &str) { let tag = if d.tag2 == 0 { d.tag1 } else { d.tag2 }; let tag_len = pecan::encoded::var_u32_len(tag); w!(self.printer, "n += "); if symbol == "bool" { w!(self.printer, "{}", tag_len + 1); } else if symbol.starts_with("arr_") { if !d.copy { w_scope!(self.printer, "{}.iter().fold(0, |n, m| {{\n", field); w!(self.printer, "let l = m.len();\n"); w!(self.printer, "n + {} + codec::varint_u32_bytes_len(l as u32) as usize + l\n", tag_len); w_end_scope!(self.printer, "}})"); } else { w_scope!(self.printer, "{{\n"); if symbol == "arr_bool" { w!(self.printer, "let l = {}.len();\n", field); } else if symbol.ends_with("fixed64") || symbol.ends_with("f64") { w!(self.printer, "let l = {}.len() * 8;\n", field); } else if symbol.ends_with("fixed32") || symbol.ends_with("f32") { w!(self.printer, "let l = {}.len() * 4;\n", field); } else { w!(self.printer, "let l = {}.iter().map(|v| ", field); if symbol == "arr_enum" { w!(self.printer, "codec::varint_i64_bytes_len(v.value() as i64) as usize"); } else if symbol == "arr_var_i32" { w!(self.printer, "codec::varint_i64_bytes_len(*v as i64) as usize"); } else { w!(self.printer, "codec::varint_{}_bytes_len(*v) as usize", &symbol[symbol.len() - 3..]) } w!(self.printer, ").sum::<usize>();\n"); } w!(self.printer, "{} + codec::varint_u32_bytes_len(l as u32) as usize + l\n", tag_len); w_end_scope!(self.printer, "}}"); } } else { if !d.copy { w_scope!(self.printer, "{{\n"); w!(self.printer, "let l = {}.len();\n", field); w!(self.printer, "{} + codec::varint_u32_bytes_len(l as u32) as usize + l\n", tag_len); w_end_scope!(self.printer, "}}"); } else { if symbol.ends_with("fixed64") || symbol.ends_with("f64") { w!(self.printer, "{}", tag_len + 8); } else if symbol.ends_with("fixed32") || symbol.ends_with("f32") { w!(self.printer, "{}", tag_len + 4); } else { if symbol == "enum" { if field.starts_with('*') { w!(self.printer, "{} + codec::varint_i64_bytes_len(({}).value() as i64) as usize", tag_len, field); } else { w!(self.printer, "{} + codec::varint_i64_bytes_len({}.value() as i64) as usize", tag_len, field); } } else if symbol == "var_i32" { w!(self.printer, "{} + codec::varint_i64_bytes_len({} as i64) as usize", tag_len, field); } else { w!(self.printer, "{} + codec::varint_{}_bytes_len({}) as usize", tag_len, &symbol[symbol.len() - 3..], field) } } } } w!(self.printer, ";\n"); } fn print_write_to_optional(&mut self, d: &FieldDecl) { if d.copy { w_scope!(self.printer, "if let Some(v) = self.{} {{\n", d.field_name); } else { w_scope!(self.printer, "if let Some(v) = &self.{} {{\n", d.field_name); } self.print_write_to_raw(d, d.method_symbol, "v"); w_end_scope!(self.printer, "}}\n"); } fn print_len_optional(&mut self, d: &FieldDecl) { if d.copy { if d.method_symbol.contains("fixed") || d.method_symbol.starts_with('f') || d.method_symbol == "bool" { w_scope!(self.printer, "if self.{}.is_some() {{\n", d.field_name); } else { w_scope!(self.printer, "if let Some(v) = self.{} {{\n", d.field_name); } } else { w_scope!(self.printer, "if let Some(v) = &self.{} {{\n", d.field_name); } self.print_len_raw(d, d.method_symbol, "v"); w_end_scope!(self.printer, "}}\n"); } fn check_print_singlular( &mut self, d: &FieldDecl, field: &str, f: impl FnOnce(&mut Self, &FieldDecl, &str, &str), ) { if !d.default_val.is_empty() { w_scope!(self.printer, "if {} != {} {{\n", d.default_val, field); } else if d.method_symbol == "bool" { w_scope!(self.printer, "if {} {{\n", field); } else if d.method_symbol == "enum" { w_scope!(self.printer, "if {}.value() != 0 {{\n", field); } else if d.method_symbol != "message" { w_scope!(self.printer, "if !{}.is_empty() {{\n", field); } f(self, d, d.method_symbol, &field); if d.method_symbol != "message" { w_end_scope!(self.printer, "}}\n"); } } fn print_len_repeated(&mut self, d: &FieldDecl) { if d.map_fields.is_empty() { w_scope!(self.printer, "if !self.{}.is_empty() {{\n", d.field_name); let method_symbol = format!("arr_{}", d.method_symbol); let field = format!("self.{}", d.field_name); self.print_len_raw(d, &method_symbol, &field); } else { w_scope!(self.printer, "if let Some(m) = &self.{} {{\n", d.field_name); let (key_fd, val_fd) = (&d.map_fields[0], &d.map_fields[1]); if val_fd.copy && key_fd.copy { w_scope!(self.printer, "for (&k, &v) in m {{\n"); } else if key_fd.copy { w_scope!(self.printer, "for (&k, v) in m {{\n"); } else if val_fd.copy { w_scope!(self.printer, "for (k, &v) in m {{\n"); } else { w_scope!(self.printer, "for (k, v) in m {{\n"); } let tag_len = pecan::encoded::var_u32_len(d.tag1); w!(self.printer, "n += {};\n", tag_len); self.check_print_singlular(key_fd, "k", Self::print_len_raw); self.check_print_singlular(val_fd, "v", Self::print_len_raw); w_end_scope!(self.printer, "}}\n"); } w_end_scope!(self.printer, "}}\n"); } fn check_print_oneof(&mut self, o: &OneOfDecl, f: impl Fn(&mut Self, &FieldDecl, &str, &str), is_len: bool) { if o.copy { w!(self.printer, "if let Some(v) = self.{} {{\n", o.field_name); } else { w!(self.printer, "if let Some(v) = &self.{} {{\n", o.field_name); } self.printer.indent(); w!(self.printer, "match v {{\n"); self.printer.indent(); for item in &o.items { let d = item.singlular(); if d.tag1 & 0x7 != 1 && d.tag1 & 0x7 != 5 && d.method_symbol != "bool" || !is_len { w!( self.printer, "{}::{}(v) => {{\n", o.type_name, naming::camel_case(&d.field_name) ); } else { w!( self.printer, "{}::{}(_) => {{\n", o.type_name, naming::camel_case(&d.field_name) ); } self.printer.indent(); let field = if d.copy { "*v" } else { "v" }; f(self, d, d.method_symbol, field); self.printer.outdent(); w!(self.printer, "}}\n"); } for _ in 0..2 { self.printer.outdent(); w!(self.printer, "}}\n"); } } fn print_len(&mut self, field_sets: &[FieldType]) { w!(self.printer, "\nfn len(&self) -> usize {{\n"); self.printer.indent(); w!(self.printer, "let mut n = self.unknown.len();\n"); for ft in field_sets { match ft { FieldType::Optional(d) => self.print_len_optional(d), FieldType::Singlular(d) => self.check_print_singlular( d, &format!("self.{}", d.field_name), Self::print_len_raw, ), FieldType::Repeated(d) => self.print_len_repeated(d), FieldType::Oneof(o) => self.check_print_oneof(o, Self::print_len_raw, true), } } w!(self.printer, "n\n"); w_end_scope!(self.printer, "}}\n"); } fn print_default_instance(&mut self, type_name: &str, field_sets: &[FieldType]) { w_scope!(self.printer, "pub const fn new() -> {} {{\n", type_name); w_scope!(self.printer, "{} {{\n", type_name); for ft in field_sets { match ft { FieldType::Optional(d) => { w!(self.printer, "{}: None,\n", d.field_name); } FieldType::Singlular(d) => { if !d.default_val.is_empty() { w!(self.printer, "{}: {},\n", d.field_name, d.default_val); } else if d.method_symbol == "bool" { w!(self.printer, "{}: false,\n", d.field_name); } else if d.method_symbol == "string" { w!(self.printer, "{}: String::new(),\n", d.field_name); } else if d.method_symbol == "bytes" { w!(self.printer, "{}: Vec::new(),\n", d.field_name); } else { w!(self.printer, "{}: {}::new(),\n", d.field_name, d.type_name); } } FieldType::Repeated(d) => { if d.map_fields.is_empty() { w!(self.printer, "{}: Vec::new(),\n", d.field_name); } else { w!(self.printer, "{}: None,\n", d.field_name); } } FieldType::Oneof(o) => { w!(self.printer, "{}: None,\n", o.field_name); } } } w!(self.printer, "cache_size: 0,\nunknown: Vec::new(),\n"); w_end_scope!(self.printer, "}}\n"); w_end_scope!(self.printer, "}}\n"); w_scope!( self.printer, "\npub fn default_instance() -> &'static {} {{\n", type_name ); w!( self.printer, "static DEFAULT: {} = {}::new();\n", type_name, type_name ); w!(self.printer, "&DEFAULT\n"); w_end_scope!(self.printer, "}}\n"); } fn print_field_accessors_optional(&mut self, d: &FieldDecl) { if d.copy { w_scope!( self.printer, "\npub fn {}(&self) -> {} {{\n", d.field_name, d.type_name ); } else if d.method_symbol == "bytes" { w_scope!( self.printer, "\npub fn {}(&self) -> &[u8] {{\n", d.field_name ); } else if d.method_symbol == "string" { w_scope!( self.printer, "\npub fn {}(&self) -> &str {{\n", d.field_name ); } else { w_scope!( self.printer, "\npub fn {}(&self) -> &{} {{\n", d.field_name, d.type_name ); } if d.copy { w!(self.printer, "self.{}.unwrap_or_default()\n", d.field_name); } else if d.method_symbol == "bytes" { w!( self.printer, "self.{}.as_ref().map_or(&[], |s| s.as_slice())\n", d.field_name ); } else if d.method_symbol == "string" { w!( self.printer, "self.{}.as_ref().map_or(\"\", |s| s.as_str())\n", d.field_name ); } else if !d.field_name.contains("recursive") { w!( self.printer, "self.{}.as_ref().unwrap_or_else(|| {}::default_instance())\n", d.field_name, d.type_name ); } else { w!( self.printer, "self.{}.as_ref().map_or_else(|| {}::default_instance(), |d| d.as_ref())\n", d.field_name, d.type_name ); } w_end_scope!(self.printer, "}}\n"); w!( self.printer, "\npub fn clear_{}(&mut self) {{ self.{} = None; }}\n", d.strip_field_name(), d.field_name ); w!( self.printer, "\npub fn has_{}(&self) -> bool {{ self.{}.is_some() }}\n", d.strip_field_name(), d.field_name ); if !d.field_name.contains("recursive") { w!( self.printer, "\npub fn set_{}(&mut self, v: {}) {{ self.{} = Some(v); }}\n", d.strip_field_name(), d.type_name, d.field_name ); } else { w!( self.printer, "\npub fn set_{}(&mut self, v: {}) {{ self.{} = Some(Box::new(v)); }}\n", d.strip_field_name(), d.type_name, d.field_name ); } if d.copy { return; } w_scope!( self.printer, "\npub fn {}_mut(&mut self) -> &mut {} {{\n", d.strip_field_name(), d.type_name ); w!( self.printer, "self.{}.get_or_insert_with(Default::default)\n", d.field_name ); w_end_scope!(self.printer, "}}\n"); } fn print_field_accessors_singlular(&mut self, d: &FieldDecl) { if d.copy { w!( self.printer, "\npub fn {}(&self) -> {} {{ self.{} }}\n", d.field_name, d.type_name, d.field_name ); } else if d.method_symbol == "bytes" { w!( self.printer, "\npub fn {}(&self) -> &[u8] {{ &self.{} }}\n", d.field_name, d.field_name ); } else if d.method_symbol == "string" { w!( self.printer, "\npub fn {}(&self) -> &str {{ &self.{} }}\n", d.field_name, d.field_name ); } if !d.default_val.is_empty() { w!( self.printer, "\npub fn clear_{}(&mut self) {{ self.{} = {}; }}\n", d.strip_field_name(), d.field_name, d.default_val ); } else if d.method_symbol == "bool" { w!( self.printer, "\npub fn clear_{}(&mut self) {{ self.{} = false; }}\n", d.strip_field_name(), d.field_name ); } else { w!( self.printer, "\npub fn clear_{}(&mut self) {{ self.{} = Default::default(); }}\n", d.strip_field_name(), d.field_name ); } w!( self.printer, "\npub fn set_{}(&mut self, v: {}) {{ self.{} = v; }}\n", d.strip_field_name(), d.type_name, d.field_name ); if d.copy { return; } w!( self.printer, "\npub fn {}_mut(&mut self) -> &mut {} {{ &mut self.{} }}\n", d.strip_field_name(), d.type_name, d.field_name ); } fn print_field_accessors_repeated(&mut self, d: &FieldDecl) { let (ref_ty, owned_ty) = if d.map_fields.is_empty() { ( format!("&[{}]", d.type_name), format!("Vec<{}>", d.type_name), ) } else { (format!("&Option<{}>", d.type_name), format!("Option<{}>", d.type_name)) }; w!( self.printer, "\npub fn {}(&self) -> {} {{ &self.{} }}\n", d.field_name, ref_ty, d.field_name ); if d.map_fields.is_empty() { w!( self.printer, "\npub fn clear_{}(&mut self) {{ self.{}.clear(); }}\n", d.strip_field_name(), d.field_name ); } else { w!( self.printer, "\npub fn clear_{}(&mut self) {{ self.{} = None; }}\n", d.strip_field_name(), d.field_name ); } w!( self.printer, "\npub fn set_{}(&mut self, v: impl Into<{}>) {{ self.{} = v.into(); }}\n", d.strip_field_name(), owned_ty, d.field_name ); w!( self.printer, "\npub fn {}_mut(&mut self) -> &mut {} {{ &mut self.{} }}\n", d.strip_field_name(), owned_ty, d.field_name ); } fn print_field_accessors_oneof(&mut self, o: &OneOfDecl) { for ft in &o.items { let d = ft.singlular(); if d.copy { w_scope!( self.printer, "\npub fn {}(&self) -> {} {{\n", d.field_name, d.type_name ); } else if d.method_symbol == "bytes" { w_scope!( self.printer, "\npub fn {}(&self) -> &[u8] {{\n", d.field_name ); } else if d.method_symbol == "string" { w_scope!( self.printer, "\npub fn {}(&self) -> &str {{\n", d.field_name ); } else { w_scope!( self.printer, "\npub fn {}(&self) -> &{} {{\n", d.field_name, d.type_name ); } if d.copy { w_scope!(self.printer, "match self.{} {{\n", o.field_name); } else { w_scope!(self.printer, "match &self.{} {{\n", o.field_name); } w!( self.printer, "Some({}::{}(v)) => v,\n", o.type_name, naming::camel_case(&d.field_name) ); if d.copy { w!(self.printer, "_ => Default::default(),\n"); } else if d.method_symbol == "bytes" { w!(self.printer, "_ => &[],\n"); } else if d.method_symbol == "string" { w!(self.printer, "_ => \"\",\n"); } else { w!(self.printer, "_ => {}::default_instance(),\n", d.type_name); } w_end_scope!(self.printer, "}}\n"); w_end_scope!(self.printer, "}}\n"); w_scope!( self.printer, "\npub fn clear_{}(&mut self) {{\n", d.strip_field_name() ); w_scope!( self.printer, "if let Some({}::{}(_)) = self.{} {{\n", o.type_name, naming::camel_case(&d.field_name), o.field_name ); w!(self.printer, "self.{} = None;\n", o.field_name); w_end_scope!(self.printer, "}}\n"); w_end_scope!(self.printer, "}}\n"); w_scope!( self.printer, "\npub fn set_{}(&mut self, v: {}) {{\n", d.strip_field_name(), d.type_name ); w!( self.printer, "self.{} = Some({}::{}(v));\n", o.field_name, o.type_name, naming::camel_case(&d.field_name) ); w_end_scope!(self.printer, "}}\n"); if d.copy { continue; } w_scope!( self.printer, "\npub fn {}_mut(&mut self) -> &mut {} {{\n", d.strip_field_name(), d.type_name ); w_scope!( self.printer, "if let Some({}::{}(ref mut v)) = self.{} {{\n", o.type_name, naming::camel_case(&d.field_name), o.field_name ); w!(self.printer, "return v;\n"); w_end_scope!(self.printer, "}}\n"); w!( self.printer, "self.{} = Some({}::{}(Default::default()));\n", o.field_name, o.type_name, naming::camel_case(&d.field_name) ); w_scope!( self.printer, "if let Some({}::{}(ref mut v)) = self.{} {{\n", o.type_name, naming::camel_case(&d.field_name), o.field_name ); w!(self.printer, "return v;\n"); w_end_scope!(self.printer, "}}\nunreachable!()\n"); w_end_scope!(self.printer, "}}\n"); } } fn print_field_accessors(&mut self, field_sets: &[FieldType]) { for ft in field_sets { match ft { FieldType::Optional(d) => self.print_field_accessors_optional(d), FieldType::Singlular(d) => self.print_field_accessors_singlular(d), FieldType::Repeated(d) => self.print_field_accessors_repeated(d), FieldType::Oneof(d) => self.print_field_accessors_oneof(d), } } } /// If m is nested message, it will be named as `Prefix1NestedPrefix2Nested...Name`. fn print_message(&mut self, ctx: &Context, id: Id<MessageDescriptor>) { w!( self.printer, "\n#[derive(Clone, Debug, Default, PartialEq)]\n" ); let m = ctx.db.messages.get(id).unwrap(); let name = naming::type_name(&m.type_name); w!(self.printer, "pub struct {} {{\n", name); self.printer.indent(); let field_sets = self.build_field_set(ctx, &m); self.print_field_decl(&field_sets); w!(self.printer, "cache_size: u32,\nunknown: Vec<u8>,\n"); self.printer.outdent(); w!(self.printer, "}}\n"); self.print_oneof_decl(&field_sets); w!(self.printer, "\nimpl Message for {} {{\n", name); self.printer.indent(); self.print_merge_from(&field_sets); self.print_write_to(&field_sets); self.print_len(&field_sets); self.printer.outdent(); w!(self.printer, "}}\n"); w!(self.printer, "\nimpl {} {{\n", name); self.printer.indent(); self.print_default_instance(&name, &field_sets); self.print_field_accessors(&field_sets); self.printer.outdent(); w!(self.printer, "}}\n"); } fn print_messages(&mut self, ctx: &Context) { let messages = &ctx.db.files.get(self.file).unwrap().messages; for m in messages { self.print_message(ctx, *m); } } pub fn generate(&mut self, ctx: &Context) -> Result<()> { self.print_top_boilerplate(); self.print_imports(ctx); self.print_file_descriptor(ctx)?; self.print_enums(ctx); self.print_messages(ctx); Ok(()) } }
// Copyright 2022 Datafuse Labs. // // 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 std::sync::Arc; use common_base::base::GlobalInstance; use common_expression::types::DataType; use common_expression::types::NumberScalar; use common_expression::Scalar; use common_expression::TableDataType; use common_expression::TableSchemaRefExt; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use common_sql::plans::Join; use common_sql::plans::Scan; use common_sql::plans::Statistics; use databend_query::sql::optimizer::SExpr; use databend_query::sql::planner::plans::JoinType; use databend_query::sql::planner::Metadata; use databend_query::sql::plans::BoundColumnRef; use databend_query::sql::plans::ConstantExpr; use databend_query::sql::plans::Filter; use databend_query::sql::plans::FunctionCall; use databend_query::sql::ColumnBinding; use databend_query::sql::Visibility; use databend_query::storages::Table; use parking_lot::RwLock; struct DummyTable { table_info: TableInfo, } impl DummyTable { pub fn new(table_name: String) -> Self { Self { table_info: TableInfo { ident: TableIdent::new(0, 0), desc: "".to_string(), name: table_name, meta: TableMeta { schema: TableSchemaRefExt::create(vec![]), ..Default::default() }, ..Default::default() }, } } } impl Table for DummyTable { fn as_any(&self) -> &dyn std::any::Any { self } fn get_table_info(&self) -> &TableInfo { &self.table_info } } #[test] fn test_format() { let thread_name = match std::thread::current().name() { None => panic!("thread name is none"), Some(thread_name) => thread_name.to_string(), }; GlobalInstance::init_testing(&thread_name); let mut metadata = Metadata::default(); let tab1 = metadata.add_table( "catalog".to_string(), "database".to_string(), Arc::new(DummyTable::new("table".to_string())), None, false, ); let col1 = metadata.add_base_table_column( "col1".to_string(), TableDataType::Boolean, tab1, None, None, ); let col2 = metadata.add_base_table_column( "col2".to_string(), TableDataType::Boolean, tab1, None, None, ); let s_expr = SExpr::create_binary( Join { right_conditions: vec![ FunctionCall { span: None, func_name: "plus".to_string(), params: vec![], arguments: vec![ BoundColumnRef { span: None, column: ColumnBinding { database_name: None, table_name: None, column_name: "col1".to_string(), index: col1, data_type: Box::new(DataType::Boolean), visibility: Visibility::Visible, }, } .into(), ConstantExpr { span: None, value: Scalar::Number(NumberScalar::UInt64(123u64)), } .into(), ], } .into(), ], left_conditions: vec![ BoundColumnRef { span: None, column: ColumnBinding { database_name: None, table_name: None, column_name: "col2".to_string(), index: col2, data_type: Box::new(DataType::Boolean), visibility: Visibility::Visible, }, } .into(), ], non_equi_conditions: vec![], join_type: JoinType::Inner, marker_index: None, from_correlated_subquery: false, contain_runtime_filter: false, } .into(), SExpr::create_unary( Filter { predicates: vec![ ConstantExpr { span: None, value: Scalar::Boolean(true), } .into(), ], is_having: false, } .into(), SExpr::create_leaf( Scan { table_index: tab1, columns: Default::default(), push_down_predicates: None, limit: None, order_by: None, prewhere: None, statistics: Statistics { statistics: None, col_stats: Default::default(), is_accurate: false, }, } .into(), ), ), SExpr::create_leaf( Scan { table_index: tab1, columns: Default::default(), push_down_predicates: None, limit: None, order_by: None, prewhere: None, statistics: Statistics { statistics: None, col_stats: Default::default(), is_accurate: false, }, } .into(), ), ); let metadata_ref = Arc::new(RwLock::new(metadata)); let tree = s_expr.to_format_tree(&metadata_ref); let result = tree.format_indent().unwrap(); let expect = "HashJoin: INNER\n equi conditions: [col2 (#1) eq plus(col1 (#0), 123)]\n non-equi conditions: []\n Filter\n filters: [true]\n LogicalGet\n table: catalog.database.table\n filters: []\n order by: []\n limit: NONE\n LogicalGet\n table: catalog.database.table\n filters: []\n order by: []\n limit: NONE\n"; assert_eq!(result.as_str(), expect); let pretty_result = tree.format_pretty().unwrap(); let pretty_expect = "HashJoin: INNER\n├── equi conditions: [col2 (#1) eq plus(col1 (#0), 123)]\n├── non-equi conditions: []\n├── Filter\n│ ├── filters: [true]\n│ └── LogicalGet\n│ ├── table: catalog.database.table\n│ ├── filters: []\n│ ├── order by: []\n│ └── limit: NONE\n└── LogicalGet\n ├── table: catalog.database.table\n ├── filters: []\n ├── order by: []\n └── limit: NONE\n"; assert_eq!(pretty_result.as_str(), pretty_expect); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { failure::Fail, fuchsia_syslog::{fx_log_err, fx_log_info}, serde_derive::Deserialize, std::{ fs::File, io::{BufReader, Read}, }, }; /// Static service configuration options. #[derive(Debug, Default, PartialEq, Eq)] pub struct Config { disable_dynamic_configuration: bool, } impl Config { pub fn disable_dynamic_configuration(&self) -> bool { self.disable_dynamic_configuration } pub fn load_from_config_data_or_default() -> Config { let f = match File::open("/config/data/config.json") { Ok(f) => f, Err(e) => { fx_log_info!("no config found, using defaults: {:?}", e.kind()); return Config::default(); } }; Self::load(BufReader::new(f)).unwrap_or_else(|e| { fx_log_err!("unable to load config, using defaults: {:?}", e); Config::default() }) } fn load(r: impl Read) -> Result<Config, ConfigLoadError> { #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] struct ParseConfig { disable_dynamic_configuration: bool, } let parse_config = serde_json::from_reader::<_, ParseConfig>(r)?; Ok(Config { disable_dynamic_configuration: parse_config.disable_dynamic_configuration }) } } #[derive(Debug, Fail)] enum ConfigLoadError { #[fail(display = "parse error: {}", _0)] Parse(#[cause] serde_json::Error), } impl From<serde_json::Error> for ConfigLoadError { fn from(e: serde_json::Error) -> Self { Self::Parse(e) } } #[cfg(test)] mod tests { use {super::*, matches::assert_matches, serde_json::json}; fn verify_load(input: serde_json::Value, expected: Config) { assert_eq!( Config::load(input.to_string().as_bytes()).expect("json value to be valid"), expected ); } #[test] fn test_load_valid_configs() { for val in [true, false].iter() { verify_load( json!({ "disable_dynamic_configuration": *val, }), Config { disable_dynamic_configuration: *val }, ); } } #[test] fn test_load_errors_on_unknown_field() { assert_matches!( Config::load( json!({ "disable_dynamic_configuration": false, "unknown_field": 3 }) .to_string() .as_bytes() ), Err(ConfigLoadError::Parse(_)) ); } #[test] fn test_no_config_data_is_default() { assert_eq!(Config::load_from_config_data_or_default(), Config::default()); } #[test] fn test_default_does_not_disable_dynamic_configuraiton() { assert_eq!(Config::default().disable_dynamic_configuration, false); } }
use super::*; use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use std::ffi::{CString, OsStr}; use std::fmt; use std::mem::ManuallyDrop; use widestring::U16CString; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct fmx_Text { _address: u8, } #[cfg_attr(target_os = "macos", link(kind = "framework", name = "FMWrapper"))] #[cfg_attr(target_os = "windows", link(kind = "static", name = "FMWrapper"))] #[cfg_attr(target_os = "linux", link(kind = "dylib", name = "FMWrapper"))] extern "C" { fn FM_Text_AssignUnicodeWithLength( _self: *mut fmx_Text, s: *const u16, strlength: u32, _x: *mut fmx__fmxcpt, ); fn FM_Text_InsertText( _self: *mut fmx_Text, other: *const fmx_Text, position: u32, _x: *mut fmx__fmxcpt, ); fn FM_Text_AppendText( _self: *mut fmx_Text, other: *const fmx_Text, position: u32, size: u32, _x: *mut fmx__fmxcpt, ); fn FM_Text_SetText( _self: *mut fmx_Text, other: *const fmx_Text, position: u32, size: u32, _x: *mut fmx__fmxcpt, ); fn FM_Text_AssignWide(_self: *mut fmx_Text, s: *const u16, _x: *mut fmx__fmxcpt); fn FM_Text_Assign(_self: *mut fmx_Text, s: *const i8, encoding: i32, _x: *mut fmx__fmxcpt); fn FM_Text_Constructor1(_x: *mut fmx__fmxcpt) -> *mut fmx_Text; fn FM_Text_GetSize(_self: *const fmx_Text, _x: *mut fmx__fmxcpt) -> u32; fn FM_Text_GetUnicode( _self: *const fmx_Text, s: *mut u16, position: u32, size: u32, _x: *mut fmx__fmxcpt, ); fn FM_Text_Delete(_self: *mut fmx_Text, _x: *mut fmx__fmxcpt); fn FM_Text_DeleteText( _self: *mut fmx_Text, positionToDelete: u32, sizeToDelete: u32, _x: *mut fmx__fmxcpt, ); fn FM_Text_Find( _self: *const fmx_Text, other: *const fmx_Text, position: u32, _x: *mut fmx__fmxcpt, ) -> u32; fn FM_Text_FindPrev( _self: *const fmx_Text, other: *const fmx_Text, position: u32, _x: *mut fmx__fmxcpt, ) -> u32; fn FM_Text_FindIgnoringCase( _self: *const fmx_Text, other: *const fmx_Text, position: u32, _x: *mut fmx__fmxcpt, ) -> u32; fn FM_Text_FindPrevIgnoringCase( _self: *const fmx_Text, other: *const fmx_Text, position: u32, _x: *mut fmx__fmxcpt, ) -> u32; fn FM_Text_Uppercase(_self: *const fmx_Text, _x: *mut fmx__fmxcpt); fn FM_Text_Lowercase(_self: *const fmx_Text, _x: *mut fmx__fmxcpt); fn FM_Text_GetStyle( _self: *const fmx_Text, style: *mut fmx_CharacterStyle, position: u32, _x: *mut fmx__fmxcpt, ); fn FM_Text_GetDefaultStyle( _self: *const fmx_Text, style: *mut fmx_CharacterStyle, _x: *mut fmx__fmxcpt, ); fn FM_Text_SetStyle( _self: *mut fmx_Text, style: *const fmx_CharacterStyle, position: u32, size: u32, _x: *mut fmx__fmxcpt, ); fn FM_Text_RemoveStyle( _self: *mut fmx_Text, style: *const fmx_CharacterStyle, _x: *mut fmx__fmxcpt, ); fn FM_Text_ResetAllStyleBuffers(_self: *mut fmx_Text, _x: *mut fmx__fmxcpt); fn FM_Text_operatorEQ( _self: *const fmx_Text, that: *const fmx_Text, _x: *mut fmx__fmxcpt, ) -> bool; fn FM_Text_operatorNE( _self: *const fmx_Text, that: *const fmx_Text, _x: *mut fmx__fmxcpt, ) -> bool; fn FM_Text_operatorLT( _self: *const fmx_Text, that: *const fmx_Text, _x: *mut fmx__fmxcpt, ) -> bool; fn FM_Text_operatorLE( _self: *const fmx_Text, that: *const fmx_Text, _x: *mut fmx__fmxcpt, ) -> bool; fn FM_Text_operatorGT( _self: *const fmx_Text, that: *const fmx_Text, _x: *mut fmx__fmxcpt, ) -> bool; fn FM_Text_operatorGE( _self: *const fmx_Text, that: *const fmx_Text, _x: *mut fmx__fmxcpt, ) -> bool; fn FM_Text_GetBytesEx( _self: *const fmx_Text, buffer: *mut i8, buffersize: u32, position: u32, size: u32, encoding: i32, _x: *mut fmx__fmxcpt, ) -> u32; } #[derive(Eq)] pub struct Text { pub(crate) ptr: *mut fmx_Text, drop: bool, } impl Text { pub fn new() -> Self { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_Text_Constructor1(&mut _x) }; _x.check(); Self { ptr, drop: true } } pub fn from_ptr(ptr: *const fmx_Text) -> Self { Self { ptr: ptr as *mut fmx_Text, drop: false, } } pub fn size(&self) -> u32 { let mut _x = fmx__fmxcpt::new(); let size = unsafe { FM_Text_GetSize(self.ptr, &mut _x) }; _x.check(); size } pub fn set_text<T: ToText>(&mut self, other: T, position: u32, size: u32) { let mut _x = fmx__fmxcpt::new(); let text = other.to_text(); unsafe { FM_Text_SetText(self.ptr, text.ptr, position, size, &mut _x) }; _x.check(); } pub fn delete_text(&mut self, position: u32, size: u32) { let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_DeleteText(self.ptr, position, size, &mut _x) }; _x.check(); } pub fn find<T: ToText>(&self, other: T, position: u32) { let mut _x = fmx__fmxcpt::new(); let text = other.to_text(); unsafe { FM_Text_Find(self.ptr, text.ptr, position, &mut _x) }; _x.check(); } pub fn find_previous<T: ToText>(&self, other: T, position: u32) { let mut _x = fmx__fmxcpt::new(); let text = other.to_text(); unsafe { FM_Text_FindPrev(self.ptr, text.ptr, position, &mut _x) }; _x.check(); } pub fn find_case_insensitive<T: ToText>(&self, other: T, position: u32) { let mut _x = fmx__fmxcpt::new(); let text = other.to_text(); unsafe { FM_Text_FindIgnoringCase(self.ptr, text.ptr, position, &mut _x) }; _x.check(); } pub fn find_previous_case_insensitive<T: ToText>(&self, other: T, position: u32) { let mut _x = fmx__fmxcpt::new(); let text = other.to_text(); unsafe { FM_Text_FindPrevIgnoringCase(self.ptr, text.ptr, position, &mut _x) }; _x.check(); } pub fn uppercase<T: ToText>(&mut self) { let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_Uppercase(self.ptr, &mut _x) }; _x.check(); } pub fn lowercase<T: ToText>(&mut self) { let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_Lowercase(self.ptr, &mut _x) }; _x.check(); } pub fn get_style(&self, position: u32) -> TextStyle { let mut _x = fmx__fmxcpt::new(); let style = TextStyle::empty(); unsafe { FM_Text_GetStyle(self.ptr, style.ptr, position, &mut _x) }; _x.check(); style } pub fn get_default_style(&self) -> TextStyle { let mut _x = fmx__fmxcpt::new(); let style = TextStyle::empty(); unsafe { FM_Text_GetDefaultStyle(self.ptr, style.ptr, &mut _x) }; _x.check(); style } pub fn set_style(&mut self, style: TextStyle, position: u32, size: u32) { let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_SetStyle(self.ptr, style.ptr, position, size, &mut _x) }; _x.check(); } pub fn remove_style(&mut self, style: TextStyle) { let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_RemoveStyle(self.ptr, style.ptr, &mut _x) }; _x.check(); } pub fn remove_all_styles(&mut self) { let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_ResetAllStyleBuffers(self.ptr, &mut _x) }; _x.check(); } pub fn assign(&mut self, s: &str) { let c_string: CString = CString::new(s).unwrap(); let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_Assign(self.ptr, c_string.as_ptr(), 1, &mut _x) }; _x.check(); } pub fn assign_unicode_with_length(&mut self, s: &str, len: u32) { let c_string = U16CString::from_str(s).unwrap(); let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_AssignUnicodeWithLength(self.ptr, c_string.as_ptr(), len, &mut _x) }; _x.check(); } pub fn assign_wide(&mut self, s: &str) { let c_string = U16CString::from_str(s).unwrap(); let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_AssignWide(self.ptr, c_string.as_ptr(), &mut _x) }; _x.check(); } pub fn insert<T: ToText>(&mut self, s: T, pos: u32) { let mut _x = fmx__fmxcpt::new(); let s = s.to_text(); unsafe { FM_Text_InsertText(self.ptr, s.ptr, pos, &mut _x) }; _x.check(); } pub fn append<T: ToText>(&mut self, s: T) { let mut _x = fmx__fmxcpt::new(); let s = s.to_text(); unsafe { FM_Text_AppendText(self.ptr, s.ptr, 0, s.size(), &mut _x) }; _x.check(); } pub fn get_unicode(&self, position: u32, size: u32) -> U16CString { let mut _x = fmx__fmxcpt::new(); let out_vec: Vec<u16> = vec![1; size as usize]; let out_buffer = U16CString::new(out_vec).unwrap(); unsafe { FM_Text_GetUnicode( self.ptr, out_buffer.as_ptr() as *mut u16, position, size, &mut _x, ) }; _x.check(); out_buffer } pub fn get_bytes(&self, position: u32, size: u32) -> Vec<u8> { self.get_bytes_with_encoding(position, size, TextEncoding::UTF8) } pub fn get_bytes_with_encoding( &self, position: u32, size: u32, encoding: TextEncoding, ) -> Vec<u8> { let mut _x = fmx__fmxcpt::new(); let buffer: Vec<i8> = Vec::with_capacity(size as usize); let mut buffer = ManuallyDrop::new(buffer); let buffer_ptr = buffer.as_mut_ptr(); let bytes_written = unsafe { FM_Text_GetBytesEx( self.ptr, buffer_ptr, size as u32, position, size as u32, encoding as i32, &mut _x, ) }; _x.check(); unsafe { Vec::from_raw_parts(buffer_ptr as *mut u8, bytes_written as usize, size as usize) } } } impl Drop for Text { fn drop(&mut self) { if self.drop { let mut _x = fmx__fmxcpt::new(); unsafe { FM_Text_Delete(self.ptr, &mut _x) }; _x.check(); } } } impl Default for Text { fn default() -> Self { Self::new() } } impl fmt::Display for Text { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let str = self.get_unicode(0, self.size()); write!(f, "{}", str.to_string_lossy()) } } pub trait ToText { fn to_text(self) -> Text; } impl ToText for Text { fn to_text(self) -> Self { self } } impl ToText for String { fn to_text(self) -> Text { let mut txt = Text::new(); txt.assign(&self); txt } } impl ToText for &String { fn to_text(self) -> Text { let mut txt = Text::new(); txt.assign(&self); txt } } impl ToText for &str { fn to_text(self) -> Text { let mut txt = Text::new(); txt.assign(self); txt } } impl From<Text> for u16 { fn from(txt: Text) -> u16 { unsafe { *txt.get_unicode(0, txt.size()).as_ptr() } } } impl From<&String> for Text { fn from(txt: &String) -> Text { let mut text = Text::new(); text.assign(txt); text } } impl From<String> for Text { fn from(txt: String) -> Text { let mut text = Text::new(); text.assign(&txt); text } } impl From<&str> for Text { fn from(txt: &str) -> Text { let mut text = Text::new(); text.assign(txt); text } } impl From<&OsStr> for Text { fn from(txt: &OsStr) -> Text { let mut text = Text::new(); text.assign(&*txt.to_string_lossy()); text } } impl ToText for &OsStr { fn to_text(self) -> Text { let mut txt = Text::new(); txt.assign(&*self.to_string_lossy()); txt } } impl PartialEq for Text { fn eq(&self, other: &Text) -> bool { let mut _x = fmx__fmxcpt::new(); let result = unsafe { FM_Text_operatorEQ(self.ptr, other.ptr, &mut _x) }; _x.check(); result } #[allow(clippy::partialeq_ne_impl)] fn ne(&self, other: &Text) -> bool { let mut _x = fmx__fmxcpt::new(); let result = unsafe { FM_Text_operatorNE(self.ptr, other.ptr, &mut _x) }; _x.check(); result } } impl PartialOrd for Text { fn partial_cmp(&self, other: &Text) -> Option<Ordering> { Some(self.cmp(other)) } fn lt(&self, other: &Self) -> bool { let mut _x = fmx__fmxcpt::new(); let lt = unsafe { FM_Text_operatorLT(self.ptr, other.ptr, &mut _x) }; _x.check(); lt } fn le(&self, other: &Self) -> bool { let mut _x = fmx__fmxcpt::new(); let le = unsafe { FM_Text_operatorLE(self.ptr, other.ptr, &mut _x) }; _x.check(); le } fn gt(&self, other: &Self) -> bool { let mut _x = fmx__fmxcpt::new(); let gt = unsafe { FM_Text_operatorGT(self.ptr, other.ptr, &mut _x) }; _x.check(); gt } fn ge(&self, other: &Self) -> bool { let mut _x = fmx__fmxcpt::new(); let ge = unsafe { FM_Text_operatorGE(self.ptr, other.ptr, &mut _x) }; _x.check(); ge } } impl Ord for Text { fn cmp(&self, other: &Self) -> Ordering { if self == other { return Ordering::Equal; } match self > other { true => Ordering::Greater, false => Ordering::Less, } } } impl PartialEq<&str> for Text { #[allow(clippy::clippy::cmp_owned)] fn eq(&self, other: &&str) -> bool { self.to_string() == *other } } impl PartialEq<String> for Text { #[allow(clippy::clippy::cmp_owned)] fn eq(&self, other: &String) -> bool { self.to_string() == *other } } #[repr(i32)] pub enum TextEncoding { Native = 0, UTF8 = 1, ASCIIDOS = 2, ASCIIWindows = 3, ASCIIMac = 4, ISO8859_1 = 5, ShiftJISMac = 6, ShiftJISWin = 7, KoreanMac = 8, KoreanWin = 9, KoreanJohab = 10, ChineseTradMac = 11, ChineseTradWin = 12, ChineseSimpMac = 13, ChineseSimpWin = 14, CyrillicMac = 15, CyrillicWin = 16, ISO8859_5 = 17, CentralEuropeMac = 18, EasternEuropeWin = 19, ISO8859_2 = 20, TurkishMac = 21, TurkishWin = 22, ISO8859_3 = 23, ISO8859_9 = 24, BalticWin = 25, ISO8859_4 = 26, ArabicMac = 27, ArabicWin = 28, ISO8859_6 = 29, GreekMac = 30, GreekWin = 31, ISO88597 = 32, HebrewMac = 33, HebrewWin = 34, ISO8859_8 = 35, ISO8859_15 = 36, }
extern crate openssl; use openssl::symm::{encrypt, Cipher, Crypter,decrypt, Mode}; use std::io::prelude::*; use std::fs::File; //iphertext: [32, 136, 124, 97, 212, 176, 15, 167, 9, 112, 240, 103, 131, 31, 215, 153,|| 253, 26, 84, 75, 222, 71, 255, 255, 66, 49, 153, 18, 25, 115, 185, 62,||| 36, 162, 83, 129, 135, 172, 231, 243, 113, 11, 115, 245, 13, 49, 9, 69,|||| 89, 193, 6, 255, 158, 206, 247, 104, 94, 67, 66, 88, 104, 184, 97, 57, 141, 69, 135, 13, 200, 32, 157, 44, 101, 110, 41, 71, 179, 128, 157, 241, 42, 6, 128, 168, 45, 114, 99, 46, 222, 181, 158, 87, 163, 192, 115, 255] // xor: [0, 2, 11, 0, 4, 11, 83, 0, 64, 72, 64, 9] fn main() { let mut plaintext = profile("234567".as_bytes());/*get_text_from_file()*//*vec![0,2,11,0,4,11,83,0,64,72,64,9,4,3,2,1]*/; //ciphertext = pad(ciphertext,16); let mut plaintext = b"yellow submarine high gasoline monster palpatine"; let iv = b"YELLOW SUBMARINE"; let key = b"YELLOW SUBMARINE"; let mut ciphertext = aes_cbc_encrypt(plaintext,iv,key); println!("ciphertext: {:?}",ciphertext.len()); for i in 16..32{ ciphertext[i] = 0; } for i in 32..48{ ciphertext[i] = ciphertext[i-32]; } //println!("plaintext before: {:?}",plaintext); let plaintext = &aes_cbc(ciphertext,iv, key); println!("plaintext after: {:?}",plaintext); //println!("{:?}",plaintext); //println!("{}",73 as char); //print!("{}", String::from_utf8_lossy(&plaintext)); /*for i in 0..plaintext.len(){ println!("{}",plaintext[i] as char); }*/ println!("xor: {:?}",String::from_utf8_lossy(&byte_xor(&[121, 101, 108, 108, 111, 119, 32, 115, 117, 98, 109, 97, 114, 105, 110, 101],&[32, 32, 32, 32, 32, 32, 0, 32, 32, 32, 32, 32, 32, 32, 32, 32]))); println!("{}",String::from_utf8(plaintext.to_vec()).unwrap()); //println!("{}",String::from_utf8(plaintext).unwrap()); } fn profile(text: &[u8]) -> Vec<u8> { let mut input = "comment1=cooking%20MCs;userdata=".as_bytes().to_vec(); input.extend_from_slice(text); input.extend_from_slice(";comment2=%20like%20a%20pound%20of%20bacon".as_bytes()); input } fn pad(text: Vec<u8>, length: u8) -> Vec<u8>{ let mut padded = text.clone(); let mut i = 1; while (length as i8*i-text.len() as i8) <0 { i += 1; } let padding = length*i as u8-text.len() as u8; for i in text.len()..(padding as usize +text.len()){ padded.push(padding); } padded } fn get_text_from_file() -> Vec<u8>{ let mut file = match File::open("/home/zeegomo/Documents/hack/cryptopals/set2/challenge2/src/data.txt") { Ok(file) => file, Err(_) => panic!("no such file"), }; let mut text = String::new(); file.read_to_string(&mut text) .ok() .expect("failed to read!"); text.as_bytes().to_vec() //base64::decode(&text).unwrap() } fn byte_xor(byte1: &[u8], byte2: &[u8]) -> Vec<u8> { if byte1.len() != byte2.len() { panic!("INCOMPATIBLE SIZES"); } let mut xor = Vec::new(); for i in 0..byte1.len() { xor.push(byte1[i] ^ byte2[i]); } xor } fn aes_cbc(text: Vec<u8>, iv: &[u8], key: &[u8]) ->Vec<u8>{ let mut decrypter = Crypter::new( Cipher::aes_128_ecb(), Mode::Decrypt, key, None, ).unwrap(); let mut last = iv; let mut decrypted = vec![0;32]; let mut plaintext = Vec::new(); let mut xored = Vec::new(); let mut count = 0; for i in 0..text.len()/16{ //println!("{}",i); decrypter.update(&text[16*i..16*i+16],&mut decrypted); //println!("finalize error"); //decrypter.finalize(&mut decrypted[count..]).unwrap(); //decrypted = aes_ebc(&text[16*i..16*i+16],key); if i>0 {xored = byte_xor(&decrypted[16..],last);} else {xored = byte_xor(&decrypted[0..16],last);} //println!("text: {:?}",&text[16*i..16*i+16]); //println!("last: {:?}",last); //println!("decrypted: {:?}",decrypted); //println!("xored: {:?}",xored); last = &text[16*i..16*i+16]; for z in 0..16 as usize{ plaintext.push(xored[z]); } } plaintext } fn aes_cbc_encrypt(text: &[u8], iv: &[u8], key: &[u8]) -> Vec<u8>{ let mut decrypter = Crypter::new( Cipher::aes_128_ecb(), Mode::Encrypt, key, None, ).unwrap(); let mut input = pad((&text).to_vec(),16); let mut ciphertext = Vec::new(); let mut last = iv.to_vec(); let mut encrypted = vec![0;32]; let mut xored = Vec::new(); for i in 0..input.len()/16{ //println!("{}",i); xored = byte_xor(&input[16*i..16*i+16],&last); //println!("input size: {}",input.len()); decrypter.update(&xored,&mut encrypted); //println!("encrypted: {:?}, len:{}",encrypted, encrypted.len()); last.clear(); for z in 0..16 as usize{ ciphertext.push(encrypted[z]); last.push(encrypted[z]); } } ciphertext } /* fn aes_ebc(block: &[u8], key: &[u8]) -> Vec<u8>{ let cipher = Cipher::aes_128_ecb(); let plaintext = decrypt( cipher, &key, None, &block ).expect("AES_ECB error"); plaintext }*/
use slog; use std; use r2d2; use r2d2_postgres::{PostgresConnectionManager, TlsMode}; use r2d2::Pool; use iron::typemap::Key; use config; pub struct DalPostgresPool { pub rw_pool: Pool<PostgresConnectionManager>, pub ro_pool: Option<Pool<PostgresConnectionManager>>, } impl DalPostgresPool { pub fn get_postgres_pool(logger: slog::Logger, dbcfg: &config::Config) -> DalPostgresPool { info!(logger, "Creating Postgres connection pool"); let mut url = "postgres://".to_string(); if "" != dbcfg.database.user { url += &dbcfg.database.user; if "" != dbcfg.database.password { url += ":"; url += &dbcfg.database.password; } url += "@"; } url += &dbcfg.database.url; let manager = match PostgresConnectionManager::new(url, TlsMode::None) { Ok(x) => x, Err(e) => { error!( logger, "Unable to create Postgres connection manager, error message [{}]", e ); std::process::exit(1); } }; match r2d2::Pool::builder().build(manager) { Err(e) => { error!( logger, "Unable to create Postgres connection pool. error message [{}]", e ); std::process::exit(1); } Ok(p) => { info!(logger, "Successfully created connection pool"); DalPostgresPool { rw_pool: p, ro_pool: None, } } } } } impl Key for DalPostgresPool { type Value = DalPostgresPool; }
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_lint_allowed; use clippy_utils::source::snippet; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, HirId}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Span; use unicode_normalization::UnicodeNormalization; declare_clippy_lint! { /// ### What it does /// Checks for invisible Unicode characters in the code. /// /// ### Why is this bad? /// Having an invisible character in the code makes for all /// sorts of April fools, but otherwise is very much frowned upon. /// /// ### Example /// You don't see it, but there may be a zero-width space or soft hyphen /// some­where in this text. #[clippy::version = "1.49.0"] pub INVISIBLE_CHARACTERS, correctness, "using an invisible character in a string literal, which is confusing" } declare_clippy_lint! { /// ### What it does /// Checks for non-ASCII characters in string literals. /// /// ### Why is this bad? /// Yeah, we know, the 90's called and wanted their charset /// back. Even so, there still are editors and other programs out there that /// don't work well with Unicode. So if the code is meant to be used /// internationally, on multiple operating systems, or has other portability /// requirements, activating this lint could be useful. /// /// ### Example /// ```rust /// let x = String::from("€"); /// ``` /// Could be written as: /// ```rust /// let x = String::from("\u{20ac}"); /// ``` #[clippy::version = "pre 1.29.0"] pub NON_ASCII_LITERAL, restriction, "using any literal non-ASCII chars in a string literal instead of using the `\\u` escape" } declare_clippy_lint! { /// ### What it does /// Checks for string literals that contain Unicode in a form /// that is not equal to its /// [NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms). /// /// ### Why is this bad? /// If such a string is compared to another, the results /// may be surprising. /// /// ### Example /// You may not see it, but "à"" and "à"" aren't the same string. The /// former when escaped is actually `"a\u{300}"` while the latter is `"\u{e0}"`. #[clippy::version = "pre 1.29.0"] pub UNICODE_NOT_NFC, pedantic, "using a Unicode literal not in NFC normal form (see [Unicode tr15](http://www.unicode.org/reports/tr15/) for further information)" } declare_lint_pass!(Unicode => [INVISIBLE_CHARACTERS, NON_ASCII_LITERAL, UNICODE_NOT_NFC]); impl LateLintPass<'_> for Unicode { fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { if let ExprKind::Lit(ref lit) = expr.kind { if let LitKind::Str(_, _) = lit.node { check_str(cx, lit.span, expr.hir_id); } } } } fn escape<T: Iterator<Item = char>>(s: T) -> String { let mut result = String::new(); for c in s { if c as u32 > 0x7F { for d in c.escape_unicode() { result.push(d); } } else { result.push(c); } } result } fn check_str(cx: &LateContext<'_>, span: Span, id: HirId) { let string = snippet(cx, span, ""); if string.chars().any(|c| ['\u{200B}', '\u{ad}', '\u{2060}'].contains(&c)) { span_lint_and_sugg( cx, INVISIBLE_CHARACTERS, span, "invisible character detected", "consider replacing the string with", string .replace("\u{200B}", "\\u{200B}") .replace("\u{ad}", "\\u{AD}") .replace("\u{2060}", "\\u{2060}"), Applicability::MachineApplicable, ); } if string.chars().any(|c| c as u32 > 0x7F) { span_lint_and_sugg( cx, NON_ASCII_LITERAL, span, "literal non-ASCII character detected", "consider replacing the string with", if is_lint_allowed(cx, UNICODE_NOT_NFC, id) { escape(string.chars()) } else { escape(string.nfc()) }, Applicability::MachineApplicable, ); } if is_lint_allowed(cx, NON_ASCII_LITERAL, id) && string.chars().zip(string.nfc()).any(|(a, b)| a != b) { span_lint_and_sugg( cx, UNICODE_NOT_NFC, span, "non-NFC Unicode sequence detected", "consider replacing the string with", string.nfc().collect::<String>(), Applicability::MachineApplicable, ); } }
use crate::db::DriverType; ///the stmt replace str convert pub trait StmtConvert { fn stmt_convert(&self, index: usize) -> String; } impl StmtConvert for DriverType { fn stmt_convert(&self, index: usize) -> String { match &self { DriverType::Postgres => { format!(" ${} ", index + 1) } DriverType::Mysql => { " ? ".to_string() } DriverType::Sqlite => { " ? ".to_string() } DriverType::None => { panic!("[rbatis] un support none for driver type!") } } } }
//! PE Linker/Loader use crate::architecture::{Amd64, Mips, X86}; use crate::loader::*; use crate::memory::backing::Memory; use crate::memory::MemoryPermissions; use std::fs::File; use std::io::Read; use std::path::Path; /// Loader for a single PE file. #[derive(Debug)] pub struct Pe { bytes: Vec<u8>, architecture: Box<dyn Architecture>, } impl Pe { /// Create a new PE from the given bytes. This PE will be rebased to the given /// base address. pub fn new(bytes: Vec<u8>) -> Result<Pe, Error> { let architecture: Box<dyn Architecture> = { let pe = goblin::pe::PE::parse(&bytes).map_err(|_| "Not a valid PE")?; if pe.header.coff_header.machine == goblin::pe::header::COFF_MACHINE_X86 { Box::new(X86::new()) } else if pe.header.coff_header.machine == goblin::pe::header::COFF_MACHINE_X86_64 { Box::new(Amd64::new()) } else if pe.header.coff_header.machine == goblin::pe::header::COFF_MACHINE_R4000 { Box::new(Mips::new()) } else { return Err(Error::UnsupprotedArchitecture); } }; Ok(Pe { bytes, architecture, }) } /// Load an PE from a file and use the base address of 0. pub fn from_file(filename: &Path) -> Result<Pe, Error> { let mut file = match File::open(filename) { Ok(file) => file, Err(e) => { return Err(Error::FalconInternal(format!( "Error opening {}: {}", filename.to_str().unwrap(), e ))) } }; let mut buf = Vec::new(); file.read_to_end(&mut buf)?; Pe::new(buf) } /// Return the goblin::pe::PE for this PE. fn pe(&self) -> goblin::pe::PE { goblin::pe::PE::parse(&self.bytes).unwrap() } } impl Loader for Pe { fn memory(&self) -> Result<Memory, Error> { let mut memory = Memory::new(self.architecture().endian()); let pe = self.pe(); for section in pe.sections { let file_offset = section.pointer_to_raw_data as usize; let file_size = section.size_of_raw_data as usize; let file_bytes = self .bytes .get(file_offset..(file_offset + file_size)) .expect("Malformed PE") .to_vec(); let address = section.virtual_address as u64 + pe.image_base as u64; let mut permissions = memory::MemoryPermissions::NONE; if section.characteristics & goblin::pe::section_table::IMAGE_SCN_MEM_READ != 0 { permissions |= MemoryPermissions::READ; } if section.characteristics & goblin::pe::section_table::IMAGE_SCN_MEM_WRITE != 0 { permissions |= MemoryPermissions::WRITE; } if section.characteristics & goblin::pe::section_table::IMAGE_SCN_MEM_EXECUTE != 0 { permissions |= MemoryPermissions::EXECUTE; } memory.set_memory(address, file_bytes, permissions); } Ok(memory) } fn function_entries(&self) -> Result<Vec<FunctionEntry>, Error> { let pe = self.pe(); let mut function_entries = Vec::new(); for symbol in pe.exports { let function_entry = FunctionEntry::new( (symbol.rva + pe.image_base) as u64, symbol.name.map(|s| s.to_string()), ); function_entries.push(function_entry); } let entry = pe.entry as u64; if !function_entries.iter().any(|fe| fe.address() == entry) { function_entries.push(FunctionEntry::new((pe.entry + pe.image_base) as u64, None)); } Ok(function_entries) } fn program_entry(&self) -> u64 { (self.pe().entry + self.pe().image_base) as u64 } fn architecture(&self) -> &dyn Architecture { self.architecture.as_ref() } fn as_any(&self) -> &dyn Any { self } fn symbols(&self) -> Vec<Symbol> { let pe = self.pe(); let mut symbols = Vec::new(); for export in pe.exports { let offset = match export.offset { Some(offset) => offset, None => continue, }; if let Some(name) = export.name { symbols.push(Symbol::new(name.to_string(), offset as u64)); } } symbols } }
//! [rocket_governor_derive](crate) was part of a [rocket] guard implementation of the //! [governor] rate limiter. //! //! It got replaced completely by only [rocket_governor]. //! //! [governor]: https://docs.rs/governor //! [rocket]: https://docs.rs/rocket/ //! [rocket_governor]: https://docs.rs/rocket_governor/ #![deny(unsafe_code)] #![deny(warnings)] #![deny(clippy::all)] #![deny(missing_docs)] #![deny(missing_doc_code_examples)]
fn read_line() -> String { let mut buf = String::new(); std::io::stdin().read_line(&mut buf).expect("failed to readline"); buf } fn create_num_vec() -> Vec<i64> { let buf = read_line(); let iter = buf.split_whitespace().map(|x| x.parse().expect("unable to parse")); let num_vec : Vec<i64> = iter.collect(); num_vec } fn calculate_score(alice_score_vec:Vec<i64>, bob_score_vec:Vec<i64>) -> (i64, i64) { let (mut alice_comparison_score, mut bob_comparison_score) = (0i64, 0i64); let score_iter = alice_score_vec.iter().zip(bob_score_vec.iter()); for (alice_score, bob_score) in score_iter { if alice_score > bob_score { alice_comparison_score += 1; } else if alice_score < bob_score { bob_comparison_score += 1; } else { // do nothing } } (alice_comparison_score, bob_comparison_score) } fn main() { let alice_score_vec : Vec<i64> = create_num_vec(); let bob_score_vec : Vec<i64> = create_num_vec(); let (alice_comparison_points, bob_comparison_points) = calculate_score(alice_score_vec, bob_score_vec); println!("{} {}", alice_comparison_points, bob_comparison_points); }
// Copyright 2022 Datafuse Labs. // // 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 std::collections::HashMap; use common_exception::ErrorCode; use common_exception::Result; use common_expression::types::DataType; use common_expression::types::NumberDataType; use common_expression::types::NumberScalar; use common_expression::Scalar; use common_functions::aggregates::AggregateCountFunction; use crate::binder::wrap_cast; use crate::binder::ColumnBinding; use crate::binder::Visibility; use crate::optimizer::RelExpr; use crate::optimizer::SExpr; use crate::plans::Aggregate; use crate::plans::AggregateFunction; use crate::plans::AggregateMode; use crate::plans::AndExpr; use crate::plans::BoundColumnRef; use crate::plans::CastExpr; use crate::plans::ComparisonExpr; use crate::plans::ComparisonOp; use crate::plans::ConstantExpr; use crate::plans::Filter; use crate::plans::FunctionCall; use crate::plans::Join; use crate::plans::JoinType; use crate::plans::Limit; use crate::plans::NotExpr; use crate::plans::OrExpr; use crate::plans::RelOperator; use crate::plans::ScalarExpr; use crate::plans::ScalarItem; use crate::plans::SubqueryExpr; use crate::plans::SubqueryType; use crate::IndexType; use crate::MetadataRef; #[allow(clippy::enum_variant_names)] pub enum UnnestResult { // Semi/Anti Join, Cross join for EXISTS SimpleJoin, MarkJoin { marker_index: IndexType }, SingleJoin, } pub struct FlattenInfo { pub from_count_func: bool, } /// Rewrite subquery into `Apply` operator pub struct SubqueryRewriter { pub(crate) metadata: MetadataRef, pub(crate) derived_columns: HashMap<IndexType, IndexType>, } impl SubqueryRewriter { pub fn new(metadata: MetadataRef) -> Self { Self { metadata, derived_columns: Default::default(), } } pub fn rewrite(&mut self, s_expr: &SExpr) -> Result<SExpr> { match s_expr.plan().clone() { RelOperator::EvalScalar(mut plan) => { let mut input = self.rewrite(s_expr.child(0)?)?; for item in plan.items.iter_mut() { let res = self.try_rewrite_subquery(&item.scalar, &input, false)?; input = res.1; item.scalar = res.0; } Ok(SExpr::create_unary(plan.into(), input)) } RelOperator::Filter(mut plan) => { let mut input = self.rewrite(s_expr.child(0)?)?; for pred in plan.predicates.iter_mut() { let res = self.try_rewrite_subquery(pred, &input, true)?; input = res.1; *pred = res.0; } Ok(SExpr::create_unary(plan.into(), input)) } RelOperator::Aggregate(mut plan) => { let mut input = self.rewrite(s_expr.child(0)?)?; for item in plan.group_items.iter_mut() { let res = self.try_rewrite_subquery(&item.scalar, &input, false)?; input = res.1; item.scalar = res.0; } for item in plan.aggregate_functions.iter_mut() { let res = self.try_rewrite_subquery(&item.scalar, &input, false)?; input = res.1; item.scalar = res.0; } Ok(SExpr::create_unary(plan.into(), input)) } RelOperator::Join(_) | RelOperator::UnionAll(_) => Ok(SExpr::create_binary( s_expr.plan().clone(), self.rewrite(s_expr.child(0)?)?, self.rewrite(s_expr.child(1)?)?, )), RelOperator::Limit(_) | RelOperator::Sort(_) => Ok(SExpr::create_unary( s_expr.plan().clone(), self.rewrite(s_expr.child(0)?)?, )), RelOperator::DummyTableScan(_) | RelOperator::Scan(_) => Ok(s_expr.clone()), _ => Err(ErrorCode::Internal("Invalid plan type")), } } /// Try to extract subquery from a scalar expression. Returns replaced scalar expression /// and the subqueries. fn try_rewrite_subquery( &mut self, scalar: &ScalarExpr, s_expr: &SExpr, is_conjunctive_predicate: bool, ) -> Result<(ScalarExpr, SExpr)> { match scalar { ScalarExpr::BoundColumnRef(_) => Ok((scalar.clone(), s_expr.clone())), ScalarExpr::BoundInternalColumnRef(_) => Ok((scalar.clone(), s_expr.clone())), ScalarExpr::ConstantExpr(_) => Ok((scalar.clone(), s_expr.clone())), ScalarExpr::AndExpr(expr) => { // Notice that the conjunctions has been flattened in binder, if we encounter // a AND here, we can't treat it as a conjunction. let (left, s_expr) = self.try_rewrite_subquery(&expr.left, s_expr, false)?; let (right, s_expr) = self.try_rewrite_subquery(&expr.right, &s_expr, false)?; Ok(( AndExpr { left: Box::new(left), right: Box::new(right), } .into(), s_expr, )) } ScalarExpr::OrExpr(expr) => { let (left, s_expr) = self.try_rewrite_subquery(&expr.left, s_expr, false)?; let (right, s_expr) = self.try_rewrite_subquery(&expr.right, &s_expr, false)?; Ok(( OrExpr { left: Box::new(left), right: Box::new(right), } .into(), s_expr, )) } ScalarExpr::NotExpr(expr) => { let (argument, s_expr) = self.try_rewrite_subquery(&expr.argument, s_expr, false)?; Ok(( NotExpr { argument: Box::new(argument), } .into(), s_expr, )) } ScalarExpr::ComparisonExpr(expr) => { let (left, s_expr) = self.try_rewrite_subquery(&expr.left, s_expr, false)?; let (right, s_expr) = self.try_rewrite_subquery(&expr.right, &s_expr, false)?; Ok(( ComparisonExpr { op: expr.op.clone(), left: Box::new(left), right: Box::new(right), } .into(), s_expr, )) } ScalarExpr::WindowFunction(_) => Ok((scalar.clone(), s_expr.clone())), ScalarExpr::AggregateFunction(_) => Ok((scalar.clone(), s_expr.clone())), ScalarExpr::FunctionCall(func) => { let mut args = vec![]; let mut s_expr = s_expr.clone(); for arg in func.arguments.iter() { let res = self.try_rewrite_subquery(arg, &s_expr, false)?; s_expr = res.1; args.push(res.0); } let expr: ScalarExpr = FunctionCall { span: func.span, params: func.params.clone(), arguments: args, func_name: func.func_name.clone(), } .into(); Ok((expr, s_expr)) } ScalarExpr::CastExpr(cast) => { let (scalar, s_expr) = self.try_rewrite_subquery(&cast.argument, s_expr, false)?; Ok(( CastExpr { span: cast.span, is_try: cast.is_try, argument: Box::new(scalar), target_type: cast.target_type.clone(), } .into(), s_expr, )) } ScalarExpr::SubqueryExpr(subquery) => { // Rewrite subquery recursively let mut subquery = subquery.clone(); subquery.subquery = Box::new(self.rewrite(&subquery.subquery)?); // Check if the subquery is a correlated subquery. // If it is, we'll try to flatten it and rewrite to join. // If it is not, we'll just rewrite it to join let rel_expr = RelExpr::with_s_expr(&subquery.subquery); let prop = rel_expr.derive_relational_prop()?; let mut flatten_info = FlattenInfo { from_count_func: false, }; let (s_expr, result) = if prop.outer_columns.is_empty() { self.try_rewrite_uncorrelated_subquery(s_expr, &subquery)? } else { self.try_decorrelate_subquery( s_expr, &subquery, &mut flatten_info, is_conjunctive_predicate, )? }; // If we unnest the subquery into a simple join, then we can replace the // original predicate with a `TRUE` literal to eliminate the conjunction. if matches!(result, UnnestResult::SimpleJoin) { return Ok(( ScalarExpr::ConstantExpr(ConstantExpr { span: subquery.span, value: Scalar::Boolean(true), }), s_expr, )); } let (index, name) = if let UnnestResult::MarkJoin { marker_index } = result { (marker_index, marker_index.to_string()) } else if let UnnestResult::SingleJoin = result { let mut output_column = subquery.output_column; if let Some(index) = self.derived_columns.get(&output_column.index) { output_column.index = *index; } ( output_column.index, format!("scalar_subquery_{:?}", output_column.index), ) } else { let index = subquery.output_column.index; (index, format!("subquery_{}", index)) }; let data_type = if subquery.typ == SubqueryType::Scalar { Box::new(subquery.data_type.wrap_nullable()) } else if matches! {result, UnnestResult::MarkJoin {..}} { Box::new(DataType::Nullable(Box::new(DataType::Boolean))) } else { subquery.data_type.clone() }; let column_ref = ScalarExpr::BoundColumnRef(BoundColumnRef { span: subquery.span, column: ColumnBinding { database_name: None, table_name: None, column_name: name, index, data_type, visibility: Visibility::Visible, }, }); let scalar = if flatten_info.from_count_func { // convert count aggregate function to `if(count() is not null, count(), 0)` let is_not_null = ScalarExpr::FunctionCall(FunctionCall { span: subquery.span, func_name: "is_not_null".to_string(), params: vec![], arguments: vec![column_ref.clone()], }); let cast_column_ref_to_uint64 = ScalarExpr::CastExpr(CastExpr { span: subquery.span, is_try: true, argument: Box::new(column_ref), target_type: Box::new( DataType::Number(NumberDataType::UInt64).wrap_nullable(), ), }); let zero = ScalarExpr::ConstantExpr(ConstantExpr { span: subquery.span, value: Scalar::Number(NumberScalar::UInt8(0)), }); ScalarExpr::CastExpr(CastExpr { span: subquery.span, is_try: true, argument: Box::new(ScalarExpr::FunctionCall(FunctionCall { span: subquery.span, params: vec![], arguments: vec![is_not_null, cast_column_ref_to_uint64, zero], func_name: "if".to_string(), })), target_type: Box::new( DataType::Number(NumberDataType::UInt64).wrap_nullable(), ), }) } else if subquery.typ == SubqueryType::NotExists { ScalarExpr::NotExpr(NotExpr { argument: Box::new(column_ref), }) } else { column_ref }; Ok((scalar, s_expr)) } } } fn try_rewrite_uncorrelated_subquery( &mut self, left: &SExpr, subquery: &SubqueryExpr, ) -> Result<(SExpr, UnnestResult)> { match subquery.typ { SubqueryType::Scalar => { let join_plan = Join { left_conditions: vec![], right_conditions: vec![], non_equi_conditions: vec![], join_type: JoinType::Single, marker_index: None, from_correlated_subquery: false, contain_runtime_filter: false, } .into(); let s_expr = SExpr::create_binary(join_plan, left.clone(), *subquery.subquery.clone()); Ok((s_expr, UnnestResult::SingleJoin)) } SubqueryType::Exists | SubqueryType::NotExists => { let mut subquery_expr = *subquery.subquery.clone(); // Wrap Limit to current subquery let limit = Limit { limit: Some(1), offset: 0, }; subquery_expr = SExpr::create_unary(limit.into(), subquery_expr.clone()); // We will rewrite EXISTS subquery into the form `COUNT(*) = 1`. // For example, `EXISTS(SELECT a FROM t WHERE a > 1)` will be rewritten into // `(SELECT COUNT(*) = 1 FROM t WHERE a > 1 LIMIT 1)`. let agg_func = AggregateCountFunction::try_create("", vec![], vec![])?; let agg_func_index = self .metadata .write() .add_derived_column("count(*)".to_string(), agg_func.return_type()?); let agg = Aggregate { group_items: vec![], aggregate_functions: vec![ScalarItem { scalar: AggregateFunction { display_name: "count(*)".to_string(), func_name: "count".to_string(), distinct: false, params: vec![], args: vec![], return_type: Box::new(agg_func.return_type()?), } .into(), index: agg_func_index, }], from_distinct: false, mode: AggregateMode::Initial, limit: None, grouping_id_index: 0, grouping_sets: vec![], }; let compare = ComparisonExpr { op: if subquery.typ == SubqueryType::Exists { ComparisonOp::Equal } else { ComparisonOp::NotEqual }, left: Box::new( BoundColumnRef { span: subquery.span, column: ColumnBinding { database_name: None, table_name: None, column_name: "count(*)".to_string(), index: agg_func_index, data_type: Box::new(agg_func.return_type()?), visibility: Visibility::Visible, }, } .into(), ), right: Box::new( ConstantExpr { span: subquery.span, value: common_expression::Scalar::Number(NumberScalar::UInt64(1)), } .into(), ), }; let filter = Filter { predicates: vec![compare.into()], is_having: false, }; // Filter: COUNT(*) = 1 or COUNT(*) != 1 // Aggregate: COUNT(*) let rewritten_subquery = SExpr::create_unary( filter.into(), SExpr::create_unary(agg.into(), subquery_expr), ); let cross_join = Join { left_conditions: vec![], right_conditions: vec![], non_equi_conditions: vec![], join_type: JoinType::Cross, marker_index: None, from_correlated_subquery: false, contain_runtime_filter: false, } .into(); Ok(( SExpr::create_binary(cross_join, left.clone(), rewritten_subquery), UnnestResult::SimpleJoin, )) } SubqueryType::Any => { let output_column = subquery.output_column.clone(); let column_name = format!("subquery_{}", output_column.index); let left_condition = wrap_cast( &ScalarExpr::BoundColumnRef(BoundColumnRef { span: subquery.span, column: ColumnBinding { database_name: None, table_name: None, column_name, index: output_column.index, data_type: output_column.data_type, visibility: Visibility::Visible, }, }), &subquery.data_type, ); let child_expr = *subquery.child_expr.as_ref().unwrap().clone(); let op = subquery.compare_op.as_ref().unwrap().clone(); let (right_condition, is_non_equi_condition) = check_child_expr_in_subquery(&child_expr, &op)?; let (left_conditions, right_conditions, non_equi_conditions) = if !is_non_equi_condition { (vec![left_condition], vec![right_condition], vec![]) } else { let other_condition = ScalarExpr::ComparisonExpr(ComparisonExpr { op, left: Box::new(right_condition), right: Box::new(left_condition), }); (vec![], vec![], vec![other_condition]) }; // Add a marker column to save comparison result. // The column is Nullable(Boolean), the data value is TRUE, FALSE, or NULL. // If subquery contains NULL, the comparison result is TRUE or NULL. // Such as t1.a => {1, 3, 4}, select t1.a in (1, 2, NULL) from t1; The sql will return {true, null, null}. // If subquery doesn't contain NULL, the comparison result is FALSE, TRUE, or NULL. let marker_index = if let Some(idx) = subquery.projection_index { idx } else { self.metadata.write().add_derived_column( "marker".to_string(), DataType::Nullable(Box::new(DataType::Boolean)), ) }; // Consider the sql: select * from t1 where t1.a = any(select t2.a from t2); // Will be transferred to:select t1.a, t2.a, marker_index from t1, t2 where t2.a = t1.a; // Note that subquery is the right table, and it'll be the build side. let mark_join = Join { left_conditions: right_conditions, right_conditions: left_conditions, non_equi_conditions, join_type: JoinType::RightMark, marker_index: Some(marker_index), from_correlated_subquery: false, contain_runtime_filter: false, } .into(); let s_expr = SExpr::create_binary(mark_join, left.clone(), *subquery.subquery.clone()); Ok((s_expr, UnnestResult::MarkJoin { marker_index })) } _ => unreachable!(), } } } pub fn check_child_expr_in_subquery( child_expr: &ScalarExpr, op: &ComparisonOp, ) -> Result<(ScalarExpr, bool)> { match child_expr { ScalarExpr::BoundColumnRef(_) => Ok((child_expr.clone(), op != &ComparisonOp::Equal)), ScalarExpr::ConstantExpr(_) => Ok((child_expr.clone(), true)), ScalarExpr::CastExpr(cast) => { let arg = &cast.argument; let (_, is_non_equi_condition) = check_child_expr_in_subquery(arg, op)?; Ok((child_expr.clone(), is_non_equi_condition)) } other => Err(ErrorCode::Internal(format!( "Invalid child expr in subquery: {:?}", other ))), } }
use regex::Regex; use unidecode::unidecode; fn remove_tokens<'a>(s: &str) -> String { let corp_toks = Regex::new(r"\b(llc|inc|ltd|pte|intl|gmbh|corp|domaine|chateau|corporation|company|co|sa|sl|winery|wines|bodega|slu|vineyard|winework|cellar|the)\b").unwrap(); let rm_ch = Regex::new(r"\bch\b").unwrap().replace_all(s, "chateau"); let rm_dom = Regex::new(r"\bdom\b").unwrap().replace_all(&rm_ch, "domaine"); let rm_mt = Regex::new(r"\bmtn\b").unwrap().replace_all(&rm_dom, "mountain"); let s3 = corp_toks.replace_all(&rm_mt, " "); s3.replace("&", " ") .replace(" de ", " de") .replace(".", " ") .replace(",", "") .trim().to_string() } pub fn normalize(s: &str) -> String { let lower = &unidecode(s).to_lowercase(); let trailing_s = Regex::new(r"'?s\b").unwrap(); let x = trailing_s.replace_all(lower, ""); remove_tokens(&x) } #[cfg(test)] mod tests { use super::normalize; #[test] fn removes_llc() { assert_eq!(normalize("Peach LLC"), normalize("Peach")) } #[test] fn removes_domaine() { assert_eq!(normalize("Domaine FFF"), normalize("FFF")) } #[test] fn removes_trailing_s() { assert_eq!(normalize("Strands"), normalize("Strand")); assert_eq!(normalize("Strand's"), normalize("Strand")); assert!(normalize("Strandes") != normalize("Strand")); } }
use crate::mechanics::attack::Attack; use crate::mechanics::damage::Damage; pub trait ReceiveDamage { fn calculate_inflicted_damage(&self, incoming_attack: Attack) -> Damage; }
use crate::{ extensions::ResolveInfo, parser::types::Field, ContextSelectionSet, OutputType, Positioned, ServerResult, Value, }; /// Resolve an list by executing each of the items concurrently. pub async fn resolve_list<'a, T: OutputType + 'a>( ctx: &ContextSelectionSet<'a>, field: &Positioned<Field>, iter: impl IntoIterator<Item = T>, len: Option<usize>, ) -> ServerResult<Value> { let extensions = &ctx.query_env.extensions; if !extensions.is_empty() { let mut futures = len.map(Vec::with_capacity).unwrap_or_default(); for (idx, item) in iter.into_iter().enumerate() { futures.push({ let ctx = ctx.clone(); async move { let ctx_idx = ctx.with_index(idx); let extensions = &ctx.query_env.extensions; let resolve_info = ResolveInfo { path_node: ctx_idx.path_node.as_ref().unwrap(), parent_type: &Vec::<T>::type_name(), return_type: &T::qualified_type_name(), name: field.node.name.node.as_str(), alias: field.node.alias.as_ref().map(|alias| alias.node.as_str()), is_for_introspection: ctx_idx.is_for_introspection, }; let resolve_fut = async { OutputType::resolve(&item, &ctx_idx, field) .await .map(Option::Some) .map_err(|err| ctx_idx.set_error_path(err)) }; futures_util::pin_mut!(resolve_fut); extensions .resolve(resolve_info, &mut resolve_fut) .await .map(|value| value.expect("You definitely encountered a bug!")) } }); } Ok(Value::List( futures_util::future::try_join_all(futures).await?, )) } else { let mut futures = len.map(Vec::with_capacity).unwrap_or_default(); for (idx, item) in iter.into_iter().enumerate() { let ctx_idx = ctx.with_index(idx); futures.push(async move { OutputType::resolve(&item, &ctx_idx, field) .await .map_err(|err| ctx_idx.set_error_path(err)) }); } Ok(Value::List( futures_util::future::try_join_all(futures).await?, )) } }
use crate::error::Error; use crate::resolve_import::resolve_import; use std::sync::Arc; use std::sync::Mutex; use swc_common::comments::SingleThreadedComments; use swc_common::errors::Diagnostic; use swc_common::errors::DiagnosticBuilder; use swc_common::errors::Emitter; use swc_common::errors::Handler; use swc_common::errors::HandlerFlags; use swc_common::input::StringInput; use swc_common::FileName; use swc_common::SourceMap; use swc_ecmascript::ast::Program; use swc_ecmascript::dep_graph::analyze_dependencies; use swc_ecmascript::dep_graph::DependencyKind; use swc_ecmascript::parser::lexer::Lexer; use swc_ecmascript::parser::EsConfig; use swc_ecmascript::parser::JscTarget; use swc_ecmascript::parser::Parser; use swc_ecmascript::parser::Syntax; use swc_ecmascript::parser::TsConfig; use url::Url; // Returns (deps, transpiled source code) pub fn get_deps_and_transpile( url: &Url, source: &str, content_type: &Option<String>, ) -> Result<(Vec<Url>, Option<String>), Error> { let comments = SingleThreadedComments::default(); let source_map = SourceMap::default(); let source_file = source_map .new_source_file(FileName::Custom(url.to_string()), source.to_string()); let input = StringInput::from(&*source_file); let syntax = get_syntax(url, content_type); let lexer = Lexer::new(syntax, JscTarget::Es2020, input, Some(&comments)); let mut parser = Parser::new_from(lexer); let module = parser .parse_module() .map_err(|e| ParseError::new(e, &source_map))?; let mut deps = Vec::new(); for import in analyze_dependencies(&module, &source_map, &comments) { if (import.kind == DependencyKind::Import || import.kind == DependencyKind::Export) && import.is_dynamic == false { let specifier = import.specifier.to_string(); deps.push(resolve_import(&specifier, url.as_str())?); } } // If the file is not jsx, ts, or tsx we do not need to transform it. In that // case source == transformed. if !syntax.jsx() && !syntax.typescript() { return Ok((deps, None)); } use swc_ecmascript::transforms::react; let program = Program::Module(module); let options = EmitOptions::default(); let source_map = std::rc::Rc::new(source_map); let jsx_pass = react::react( source_map.clone(), Some(&comments), react::Options { pragma: options.jsx_factory.clone(), pragma_frag: options.jsx_fragment_factory.clone(), // this will use `Object.assign()` instead of the `_extends` helper // when spreading props. use_builtins: true, ..Default::default() }, ); use swc_common::chain; use swc_common::Globals; use swc_ecmascript::transforms::fixer; use swc_ecmascript::transforms::helpers; use swc_ecmascript::transforms::pass::Optional; use swc_ecmascript::transforms::proposals; use swc_ecmascript::transforms::typescript; use swc_ecmascript::visit::FoldWith; let mut passes = chain!( Optional::new(jsx_pass, options.transform_jsx), proposals::decorators::decorators(proposals::decorators::Config { legacy: true, emit_metadata: options.emit_metadata }), helpers::inject_helpers(), typescript::strip(), fixer(Some(&comments)), ); let program = swc_common::GLOBALS.set(&Globals::new(), || { helpers::HELPERS.set(&helpers::Helpers::new(false), || { program.fold_with(&mut passes) }) }); use swc_ecmascript::codegen::text_writer::JsWriter; use swc_ecmascript::codegen::Node; let mut src_map_buf = vec![]; let mut buf = vec![]; { let writer = Box::new(JsWriter::new( source_map.clone(), "\n", &mut buf, Some(&mut src_map_buf), )); let config = swc_ecmascript::codegen::Config { minify: false }; let mut emitter = swc_ecmascript::codegen::Emitter { cfg: config, comments: Some(&comments), cm: source_map.clone(), wr: writer, }; program .emit_with(&mut emitter) .map_err(|err| Error::Other(Box::new(err)))?; } let mut src = String::from_utf8(buf).map_err(|err| Error::Other(Box::new(err)))?; { let mut buf = Vec::new(); source_map .build_source_map_from(&mut src_map_buf, None) .to_writer(&mut buf) .map_err(|err| Error::Other(Box::new(err)))?; src.push_str("//# sourceMappingURL=data:application/json;base64,"); let encoded_map = base64::encode(buf); src.push_str(&encoded_map); } Ok((deps, Some(src))) } fn get_syntax(url: &Url, maybe_content_type: &Option<String>) -> Syntax { fn get_es_config(jsx: bool) -> EsConfig { EsConfig { class_private_methods: true, class_private_props: true, class_props: true, dynamic_import: true, export_default_from: true, export_namespace_from: true, import_meta: true, jsx, nullish_coalescing: true, num_sep: true, optional_chaining: true, top_level_await: true, ..EsConfig::default() } } fn get_ts_config(tsx: bool, dts: bool) -> TsConfig { TsConfig { decorators: true, dts, dynamic_import: true, tsx, ..TsConfig::default() } } let maybe_extension = if let Some(content_type) = maybe_content_type { match content_type .split(";") .next() .unwrap() .trim() .to_lowercase() .as_ref() { "application/typescript" | "text/typescript" | "video/vnd.dlna.mpeg-tts" | "video/mp2t" | "application/x-typescript" => Some("ts"), "application/javascript" | "text/javascript" | "application/ecmascript" | "text/ecmascript" | "application/x-javascript" | "application/node" => Some("js"), "text/jsx" => Some("jsx"), "text/tsx" => Some("tsx"), _ => None, } } else { None }; let extension = if maybe_extension.is_some() { maybe_extension } else { let parts: Vec<&str> = url.as_str().split('.').collect(); parts.last().copied() }; match extension { Some("js") => Syntax::Es(get_es_config(false)), Some("jsx") => Syntax::Es(get_es_config(true)), Some("ts") => Syntax::Typescript(get_ts_config(false, false)), Some("tsx") => Syntax::Typescript(get_ts_config(true, false)), _ => Syntax::Typescript(get_ts_config(false, false)), } } pub struct ParseError { lines: Vec<String>, } impl ParseError { fn new( err: swc_ecmascript::parser::error::Error, source_map: &SourceMap, ) -> Self { let error_buffer = ErrorBuffer::default(); let handler = Handler::with_emitter_and_flags( Box::new(error_buffer.clone()), HandlerFlags { can_emit_warnings: true, dont_buffer_diagnostics: true, ..HandlerFlags::default() }, ); let mut diagnostic = err.into_diagnostic(&handler); diagnostic.emit(); let v = error_buffer.0.lock().unwrap(); let lines = v .iter() .map(|d| { if let Some(span) = d.span.primary_span() { let loc = source_map.lookup_char_pos(span.lo); let file_name = match &loc.file.name { FileName::Custom(n) => n, _ => unreachable!(), }; format!( "{} at {}:{}:{}", d.message(), file_name, loc.line, loc.col_display ) } else { d.message() } }) .collect::<Vec<_>>(); Self { lines } } } impl std::error::Error for ParseError {} impl std::fmt::Display for ParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for line in &self.lines { writeln!(f, "{}", line)?; } Ok(()) } } impl std::fmt::Debug for ParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(self, f) } } /// A buffer for collecting errors from the AST parser. #[derive(Debug, Clone, Default)] pub struct ErrorBuffer(Arc<Mutex<Vec<Diagnostic>>>); impl Emitter for ErrorBuffer { fn emit(&mut self, db: &DiagnosticBuilder) { self.0.lock().unwrap().push((**db).clone()); } } /// Options which can be adjusted when transpiling a module. #[derive(Debug, Clone)] pub struct EmitOptions { /// Indicate if JavaScript is being checked/transformed as well, or if it is /// only TypeScript. pub check_js: bool, /// When emitting a legacy decorator, also emit experimental decorator meta /// data. Defaults to `false`. pub emit_metadata: bool, /// Should the source map be inlined in the emitted code file, or provided /// as a separate file. Defaults to `true`. pub inline_source_map: bool, /// When transforming JSX, what value should be used for the JSX factory. /// Defaults to `React.createElement`. pub jsx_factory: String, /// When transforming JSX, what value should be used for the JSX fragment /// factory. Defaults to `React.Fragment`. pub jsx_fragment_factory: String, /// Should JSX be transformed or preserved. Defaults to `true`. pub transform_jsx: bool, } impl Default for EmitOptions { fn default() -> Self { EmitOptions { check_js: false, emit_metadata: false, inline_source_map: true, jsx_factory: "h".into(), jsx_fragment_factory: "Fragment".into(), transform_jsx: true, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_syntax() { // Prefer content-type over extension. let url = Url::parse("https://deno.land/x/foo@0.1.0/bar.js").unwrap(); let content_type = Some("text/jsx".to_string()); let syntax = get_syntax(&url, &content_type); assert!(syntax.jsx()); assert!(!syntax.typescript()); // Fallback to extension if content-type is unsupported. let url = Url::parse("https://deno.land/x/foo@0.1.0/bar.tsx").unwrap(); let content_type = Some("text/unsupported".to_string()); let syntax = get_syntax(&url, &content_type); assert!(syntax.jsx()); assert!(syntax.typescript()); } #[test] fn jsx() { let url = Url::parse( "https://deno.land/x/dext@0.10.3/example/pages/dynamic/%5Bname%5D.tsx", ) .unwrap(); let source = r#" import { Fragment, h } from "../../deps.ts"; import type { PageProps } from "../../deps.ts"; function UserPage(props: PageProps) { const name = props.route?.name ?? ""; return ( <> <h1>This is the page for {name}</h1> <p> <a href="/">Go home</a> </p> </> ); } export default UserPage; "#; let (deps, _transpiled) = get_deps_and_transpile(&url, source, &None).unwrap(); assert_eq!(deps.len(), 1); } #[test] #[ignore] fn complex_types() { let url = Url::parse("https://deno.land/x/oak@v6.4.2/router.ts").unwrap(); let source = r#" delete<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; "#; let (deps, _transpiled) = get_deps_and_transpile(&url, source, &None).unwrap(); assert_eq!(deps.len(), 0); } #[test] #[ignore] fn dynamic_import() { let url = Url::parse("https://deno.land/x/oak@v6.4.2/router.ts").unwrap(); let source = r#" await import("fs"); await import("https://deno.land/std/version.ts"); "#; let (deps, _transpiled) = get_deps_and_transpile(&url, source, &None).unwrap(); assert_eq!(deps.len(), 0); } }
use efm32gg_hal::gpio; use embedded_hal::digital::OutputPin; use efm32gg_hal::gpio::EFM32Pin; /// A representation of the two user LEDs on the STK3700 pub struct LEDs { led0: gpio::pins::PE2<gpio::Output>, led1: gpio::pins::PE3<gpio::Output>, } impl LEDs { pub fn new(pe2: gpio::pins::PE2<gpio::Disabled>, pe3: gpio::pins::PE3<gpio::Disabled>) -> Self { LEDs { led0: pe2.as_output(), led1: pe3.as_output() } } pub fn led0_on(&mut self) { self.led0.set_high(); } pub fn led0_off(&mut self) { self.led0.set_low(); } pub fn led1_on(&mut self) { self.led1.set_high(); } pub fn led1_off(&mut self) { self.led1.set_low(); } }
use std::fs::File; use std::io::BufReader; use std::io::Read; use std::fmt; use std::env; use std::collections::HashSet; use std::collections::HashMap; use std::cmp::Ordering; #[derive(Copy, Clone)] enum Direction { North, South, East, West } #[derive(Copy, Clone)] enum Turn { Left, Straight, Right } #[derive(PartialEq, Eq, Hash, Copy, Clone)] struct Coord { row: usize, col: usize, } #[derive(Copy, Clone)] struct Cart { row: usize, col: usize, direction: Direction, next_turn: Turn, } impl Cart { fn new(row: usize, col: usize, direction: Direction) -> Cart { Cart{row, col, direction, next_turn: Turn::Left} } fn to_char(&self) -> char { match self.direction { Direction::North => '^', Direction::South => 'v', Direction::West => '<', Direction::East => '>', } } } struct TrackSystem { rows: Vec<Vec<char>>, carts: HashMap<Coord,Cart>, crashes: HashSet<Coord>, errors: HashSet<Coord>, } impl TrackSystem { fn new(s: &str) -> TrackSystem { let mut rows = Vec::new(); let mut carts = HashMap::new(); for (row, line) in s.lines().enumerate() { let mut cols = Vec::new(); for (col, c) in line.chars().enumerate() { let coord = Coord{row, col}; match c { '^' => { cols.push('|'); carts.insert(coord, Cart::new(row, col,Direction::North)); }, 'v' => { cols.push('|'); carts.insert(coord, Cart::new(row, col, Direction::South)); }, '<' => { cols.push('-'); carts.insert(coord, Cart::new(row, col, Direction::West)); }, '>' => { cols.push('-'); carts.insert(coord, Cart::new(row, col, Direction::East)); }, _ => { cols.push(c) }, } } rows.push(cols); } TrackSystem{rows, carts, crashes: HashSet::new(), errors: HashSet::new()} } fn forward(&mut self) { let mut positions = Vec::new(); for position in self.carts.keys() { positions.push(position.clone()); } positions.sort_unstable_by(|a,b| { if a.row < b.row { Ordering::Less } else if a.row > b.row { Ordering::Greater } else { if a.col < b.col { Ordering::Less } else if a.col > b.col { Ordering::Greater } else { Ordering::Equal } } }); for old_position in positions { if !self.carts.contains_key(&old_position) { continue; } let mut cart = self.carts.remove(&old_position).unwrap(); match cart.direction { Direction::North => cart.row -= 1, Direction::South => cart.row += 1, Direction::West => cart.col -= 1, Direction::East => cart.col += 1, } let new_position = Coord{row: cart.row, col: cart.col}; let track_piece = self.rows[cart.row][cart.col]; if track_piece == ' ' { self.errors.insert(new_position.clone()); } if track_piece == '+' { match cart.next_turn { Turn::Left => { cart.next_turn = Turn::Straight; cart.direction = match cart.direction { Direction::North => Direction::West, Direction::South => Direction::East, Direction::West => Direction::South, Direction::East => Direction::North, } }, Turn::Straight => { cart.next_turn = Turn::Right; }, Turn::Right => { cart.next_turn = Turn::Left; cart.direction = match cart.direction { Direction::North => Direction::East, Direction::South => Direction::West, Direction::West => Direction::North, Direction::East => Direction::South, } }, } } else if track_piece == '/' { cart.direction = match cart.direction { Direction::North => Direction::East, Direction::South => Direction::West, Direction::West => Direction::South, Direction::East => Direction::North, } } else if track_piece == '\\' { cart.direction = match cart.direction { Direction::North => Direction::West, Direction::South => Direction::East, Direction::West => Direction::North, Direction::East => Direction::South, } } if self.carts.contains_key(&new_position) { self.carts.remove(&new_position); self.crashes.insert(new_position); } else { self.carts.insert(new_position, cart); } } } } impl fmt::Display for TrackSystem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (r, row) in self.rows.iter().enumerate() { write!(f, "{:03}", r); for (c, col) in row.iter().enumerate() { let coord = Coord{row: r, col: c}; if self.crashes.contains(&coord) { write!(f, "X"); } else if self.carts.contains_key(&coord) { let cart = self.carts.get(&coord).unwrap(); write!(f, "{}", cart.to_char()); } else { write!(f, "{}", col); } } writeln!(f, ""); } write!(f, "") } } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 3 { panic!("Too few arguments!") } let part = args[2].parse::<usize>().unwrap(); let mut s = String::new(); let f = File::open(&args[1]).expect("File not found!"); let mut reader = BufReader::new(&f); reader.read_to_string(&mut s).expect("Error reading file into string!"); let mut track_system = TrackSystem::new(&s); if part == 1 { while track_system.errors.len() < 1 && track_system.crashes.len() < 1 { track_system.forward(); } let first_crash = track_system.crashes.iter().next().unwrap(); println!("{},{}", first_crash.col, first_crash.row); } else { while track_system.errors.len() < 1 && track_system.carts.len() > 1 { track_system.forward(); } if track_system.carts.len() == 1 { let (&last_coord,_) = track_system.carts.iter().next().unwrap(); println!("{},{}", last_coord.col, last_coord.row); } else { println!("Even number of carts!"); } } }
use super::*; #[test] fn without_registered_returns_empty_list() { with_process_arc(|unregistered_process_arc| { assert_eq!( result( &unregistered_process_arc, unregistered_process_arc.pid_term(), item() ), Ok(Term::NIL) ); }); } #[test] fn with_registered_returns_empty_list() { with_process_arc(|registered_process_arc| { let registered_name = registered_name(); let registered_name_atom: Atom = registered_name.try_into().unwrap(); assert!(registry::put_atom_to_process( registered_name_atom, registered_process_arc.clone() )); assert_eq!( result( &registered_process_arc, registered_process_arc.pid_term(), item() ), Ok(registered_process_arc.tuple_from_slice(&[item(), registered_name])) ); }); }
#[doc = "Reader of register EXTICR4"] pub type R = crate::R<u32, super::EXTICR4>; #[doc = "Writer for register EXTICR4"] pub type W = crate::W<u32, super::EXTICR4>; #[doc = "Register EXTICR4 `reset()`'s with value 0"] impl crate::ResetValue for super::EXTICR4 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "EXTI x configuration (x = 12 to 15)\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EXTI15_A { #[doc = "0: Select PA15 as the source input for the EXTI15 external interrupt"] PA15 = 0, #[doc = "1: Select PB15 as the source input for the EXTI15 external interrupt"] PB15 = 1, #[doc = "2: Select PC15 as the source input for the EXTI15 external interrupt"] PC15 = 2, #[doc = "3: Select PD15 as the source input for the EXTI15 external interrupt"] PD15 = 3, #[doc = "4: Select PE15 as the source input for the EXTI15 external interrupt"] PE15 = 4, } impl From<EXTI15_A> for u8 { #[inline(always)] fn from(variant: EXTI15_A) -> Self { variant as _ } } #[doc = "Reader of field `EXTI15`"] pub type EXTI15_R = crate::R<u8, EXTI15_A>; impl EXTI15_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, EXTI15_A> { use crate::Variant::*; match self.bits { 0 => Val(EXTI15_A::PA15), 1 => Val(EXTI15_A::PB15), 2 => Val(EXTI15_A::PC15), 3 => Val(EXTI15_A::PD15), 4 => Val(EXTI15_A::PE15), i => Res(i), } } #[doc = "Checks if the value of the field is `PA15`"] #[inline(always)] pub fn is_pa15(&self) -> bool { *self == EXTI15_A::PA15 } #[doc = "Checks if the value of the field is `PB15`"] #[inline(always)] pub fn is_pb15(&self) -> bool { *self == EXTI15_A::PB15 } #[doc = "Checks if the value of the field is `PC15`"] #[inline(always)] pub fn is_pc15(&self) -> bool { *self == EXTI15_A::PC15 } #[doc = "Checks if the value of the field is `PD15`"] #[inline(always)] pub fn is_pd15(&self) -> bool { *self == EXTI15_A::PD15 } #[doc = "Checks if the value of the field is `PE15`"] #[inline(always)] pub fn is_pe15(&self) -> bool { *self == EXTI15_A::PE15 } } #[doc = "Write proxy for field `EXTI15`"] pub struct EXTI15_W<'a> { w: &'a mut W, } impl<'a> EXTI15_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTI15_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Select PA15 as the source input for the EXTI15 external interrupt"] #[inline(always)] pub fn pa15(self) -> &'a mut W { self.variant(EXTI15_A::PA15) } #[doc = "Select PB15 as the source input for the EXTI15 external interrupt"] #[inline(always)] pub fn pb15(self) -> &'a mut W { self.variant(EXTI15_A::PB15) } #[doc = "Select PC15 as the source input for the EXTI15 external interrupt"] #[inline(always)] pub fn pc15(self) -> &'a mut W { self.variant(EXTI15_A::PC15) } #[doc = "Select PD15 as the source input for the EXTI15 external interrupt"] #[inline(always)] pub fn pd15(self) -> &'a mut W { self.variant(EXTI15_A::PD15) } #[doc = "Select PE15 as the source input for the EXTI15 external interrupt"] #[inline(always)] pub fn pe15(self) -> &'a mut W { self.variant(EXTI15_A::PE15) } #[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 << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "EXTI14\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EXTI14_A { #[doc = "0: Select PA14 as the source input for the EXTI14 external interrupt"] PA14 = 0, #[doc = "1: Select PB14 as the source input for the EXTI14 external interrupt"] PB14 = 1, #[doc = "2: Select PC14 as the source input for the EXTI14 external interrupt"] PC14 = 2, #[doc = "3: Select PD14 as the source input for the EXTI14 external interrupt"] PD14 = 3, #[doc = "4: Select PE14 as the source input for the EXTI14 external interrupt"] PE14 = 4, } impl From<EXTI14_A> for u8 { #[inline(always)] fn from(variant: EXTI14_A) -> Self { variant as _ } } #[doc = "Reader of field `EXTI14`"] pub type EXTI14_R = crate::R<u8, EXTI14_A>; impl EXTI14_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, EXTI14_A> { use crate::Variant::*; match self.bits { 0 => Val(EXTI14_A::PA14), 1 => Val(EXTI14_A::PB14), 2 => Val(EXTI14_A::PC14), 3 => Val(EXTI14_A::PD14), 4 => Val(EXTI14_A::PE14), i => Res(i), } } #[doc = "Checks if the value of the field is `PA14`"] #[inline(always)] pub fn is_pa14(&self) -> bool { *self == EXTI14_A::PA14 } #[doc = "Checks if the value of the field is `PB14`"] #[inline(always)] pub fn is_pb14(&self) -> bool { *self == EXTI14_A::PB14 } #[doc = "Checks if the value of the field is `PC14`"] #[inline(always)] pub fn is_pc14(&self) -> bool { *self == EXTI14_A::PC14 } #[doc = "Checks if the value of the field is `PD14`"] #[inline(always)] pub fn is_pd14(&self) -> bool { *self == EXTI14_A::PD14 } #[doc = "Checks if the value of the field is `PE14`"] #[inline(always)] pub fn is_pe14(&self) -> bool { *self == EXTI14_A::PE14 } } #[doc = "Write proxy for field `EXTI14`"] pub struct EXTI14_W<'a> { w: &'a mut W, } impl<'a> EXTI14_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTI14_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Select PA14 as the source input for the EXTI14 external interrupt"] #[inline(always)] pub fn pa14(self) -> &'a mut W { self.variant(EXTI14_A::PA14) } #[doc = "Select PB14 as the source input for the EXTI14 external interrupt"] #[inline(always)] pub fn pb14(self) -> &'a mut W { self.variant(EXTI14_A::PB14) } #[doc = "Select PC14 as the source input for the EXTI14 external interrupt"] #[inline(always)] pub fn pc14(self) -> &'a mut W { self.variant(EXTI14_A::PC14) } #[doc = "Select PD14 as the source input for the EXTI14 external interrupt"] #[inline(always)] pub fn pd14(self) -> &'a mut W { self.variant(EXTI14_A::PD14) } #[doc = "Select PE14 as the source input for the EXTI14 external interrupt"] #[inline(always)] pub fn pe14(self) -> &'a mut W { self.variant(EXTI14_A::PE14) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "EXTI13\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EXTI13_A { #[doc = "0: Select PA13 as the source input for the EXTI13 external interrupt"] PA13 = 0, #[doc = "1: Select PB13 as the source input for the EXTI13 external interrupt"] PB13 = 1, #[doc = "2: Select PC13 as the source input for the EXTI13 external interrupt"] PC13 = 2, #[doc = "3: Select PD13 as the source input for the EXTI13 external interrupt"] PD13 = 3, #[doc = "4: Select PE13 as the source input for the EXTI13 external interrupt"] PE13 = 4, } impl From<EXTI13_A> for u8 { #[inline(always)] fn from(variant: EXTI13_A) -> Self { variant as _ } } #[doc = "Reader of field `EXTI13`"] pub type EXTI13_R = crate::R<u8, EXTI13_A>; impl EXTI13_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, EXTI13_A> { use crate::Variant::*; match self.bits { 0 => Val(EXTI13_A::PA13), 1 => Val(EXTI13_A::PB13), 2 => Val(EXTI13_A::PC13), 3 => Val(EXTI13_A::PD13), 4 => Val(EXTI13_A::PE13), i => Res(i), } } #[doc = "Checks if the value of the field is `PA13`"] #[inline(always)] pub fn is_pa13(&self) -> bool { *self == EXTI13_A::PA13 } #[doc = "Checks if the value of the field is `PB13`"] #[inline(always)] pub fn is_pb13(&self) -> bool { *self == EXTI13_A::PB13 } #[doc = "Checks if the value of the field is `PC13`"] #[inline(always)] pub fn is_pc13(&self) -> bool { *self == EXTI13_A::PC13 } #[doc = "Checks if the value of the field is `PD13`"] #[inline(always)] pub fn is_pd13(&self) -> bool { *self == EXTI13_A::PD13 } #[doc = "Checks if the value of the field is `PE13`"] #[inline(always)] pub fn is_pe13(&self) -> bool { *self == EXTI13_A::PE13 } } #[doc = "Write proxy for field `EXTI13`"] pub struct EXTI13_W<'a> { w: &'a mut W, } impl<'a> EXTI13_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTI13_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Select PA13 as the source input for the EXTI13 external interrupt"] #[inline(always)] pub fn pa13(self) -> &'a mut W { self.variant(EXTI13_A::PA13) } #[doc = "Select PB13 as the source input for the EXTI13 external interrupt"] #[inline(always)] pub fn pb13(self) -> &'a mut W { self.variant(EXTI13_A::PB13) } #[doc = "Select PC13 as the source input for the EXTI13 external interrupt"] #[inline(always)] pub fn pc13(self) -> &'a mut W { self.variant(EXTI13_A::PC13) } #[doc = "Select PD13 as the source input for the EXTI13 external interrupt"] #[inline(always)] pub fn pd13(self) -> &'a mut W { self.variant(EXTI13_A::PD13) } #[doc = "Select PE13 as the source input for the EXTI13 external interrupt"] #[inline(always)] pub fn pe13(self) -> &'a mut W { self.variant(EXTI13_A::PE13) } #[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 = "EXTI12\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EXTI12_A { #[doc = "0: Select PA12 as the source input for the EXTI12 external interrupt"] PA12 = 0, #[doc = "1: Select PB12 as the source input for the EXTI12 external interrupt"] PB12 = 1, #[doc = "2: Select PC12 as the source input for the EXTI12 external interrupt"] PC12 = 2, #[doc = "3: Select PD12 as the source input for the EXTI12 external interrupt"] PD12 = 3, #[doc = "4: Select PE12 as the source input for the EXTI12 external interrupt"] PE12 = 4, } impl From<EXTI12_A> for u8 { #[inline(always)] fn from(variant: EXTI12_A) -> Self { variant as _ } } #[doc = "Reader of field `EXTI12`"] pub type EXTI12_R = crate::R<u8, EXTI12_A>; impl EXTI12_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, EXTI12_A> { use crate::Variant::*; match self.bits { 0 => Val(EXTI12_A::PA12), 1 => Val(EXTI12_A::PB12), 2 => Val(EXTI12_A::PC12), 3 => Val(EXTI12_A::PD12), 4 => Val(EXTI12_A::PE12), i => Res(i), } } #[doc = "Checks if the value of the field is `PA12`"] #[inline(always)] pub fn is_pa12(&self) -> bool { *self == EXTI12_A::PA12 } #[doc = "Checks if the value of the field is `PB12`"] #[inline(always)] pub fn is_pb12(&self) -> bool { *self == EXTI12_A::PB12 } #[doc = "Checks if the value of the field is `PC12`"] #[inline(always)] pub fn is_pc12(&self) -> bool { *self == EXTI12_A::PC12 } #[doc = "Checks if the value of the field is `PD12`"] #[inline(always)] pub fn is_pd12(&self) -> bool { *self == EXTI12_A::PD12 } #[doc = "Checks if the value of the field is `PE12`"] #[inline(always)] pub fn is_pe12(&self) -> bool { *self == EXTI12_A::PE12 } } #[doc = "Write proxy for field `EXTI12`"] pub struct EXTI12_W<'a> { w: &'a mut W, } impl<'a> EXTI12_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTI12_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Select PA12 as the source input for the EXTI12 external interrupt"] #[inline(always)] pub fn pa12(self) -> &'a mut W { self.variant(EXTI12_A::PA12) } #[doc = "Select PB12 as the source input for the EXTI12 external interrupt"] #[inline(always)] pub fn pb12(self) -> &'a mut W { self.variant(EXTI12_A::PB12) } #[doc = "Select PC12 as the source input for the EXTI12 external interrupt"] #[inline(always)] pub fn pc12(self) -> &'a mut W { self.variant(EXTI12_A::PC12) } #[doc = "Select PD12 as the source input for the EXTI12 external interrupt"] #[inline(always)] pub fn pd12(self) -> &'a mut W { self.variant(EXTI12_A::PD12) } #[doc = "Select PE12 as the source input for the EXTI12 external interrupt"] #[inline(always)] pub fn pe12(self) -> &'a mut W { self.variant(EXTI12_A::PE12) } #[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 } } impl R { #[doc = "Bits 12:15 - EXTI x configuration (x = 12 to 15)"] #[inline(always)] pub fn exti15(&self) -> EXTI15_R { EXTI15_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 8:11 - EXTI14"] #[inline(always)] pub fn exti14(&self) -> EXTI14_R { EXTI14_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 4:7 - EXTI13"] #[inline(always)] pub fn exti13(&self) -> EXTI13_R { EXTI13_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 0:3 - EXTI12"] #[inline(always)] pub fn exti12(&self) -> EXTI12_R { EXTI12_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bits 12:15 - EXTI x configuration (x = 12 to 15)"] #[inline(always)] pub fn exti15(&mut self) -> EXTI15_W { EXTI15_W { w: self } } #[doc = "Bits 8:11 - EXTI14"] #[inline(always)] pub fn exti14(&mut self) -> EXTI14_W { EXTI14_W { w: self } } #[doc = "Bits 4:7 - EXTI13"] #[inline(always)] pub fn exti13(&mut self) -> EXTI13_W { EXTI13_W { w: self } } #[doc = "Bits 0:3 - EXTI12"] #[inline(always)] pub fn exti12(&mut self) -> EXTI12_W { EXTI12_W { w: self } } }
use std::collections::HashMap; use id::Id; use timestamp::Timestamp; /// Temporary structure to encode object details. /// /// I'm still thinking about how objects should be structured, but I want to /// tinker with other pieces of the codebase. #[derive(Debug, Clone)] pub enum ObjectDetails { Forest { // This isn't relevant outside the battlefield tapped: bool, }, } /// A super simplified view of abilities; this will need to be separated into /// mana abilities and not, represent priority, and actually represent /// descriptors of what these abilities do. #[derive(Debug, Clone)] pub enum Ability { AddGreen, } /// Describes an object that exists anywhere in the game. /// /// The game dictates that when objects move to different zones, they actually /// become new objects (with new IDs!). That motivates the idea that the object /// itself should be lightweight and replacable, with most of the interesting /// data living inside another, persistent object. /// /// We'll need to represent several kinds of object: /// * Cards /// * Permanents and non-permanents on the battlefield /// * Cards in a graveyard, library, or hand /// * Spells on the stack /// * Tokens /// * Unique tokens, like 2/2 zombies /// * Copies of cards /// * Emblems /// * Abilities on the stack, never represented by a card /// * Copies of spells on the stack #[derive(Debug, Clone)] pub struct Object { pub id: Id, pub zone: Id, /// A monotonically-increasing value describing when the object entered the /// zone. pub timestamp: Timestamp, /// Temporary field denoting object details pub details: ObjectDetails, /// All of the abilities that this object has available to activate pub abilities: HashMap<Id, Ability>, // TODO: Types // TODO: Supertypes // TODO: Subtypes // TODO: Owner, a player ID // TODO: Controller, a player ID // TODO: Counters of various types }
use futures::stream::StreamExt; use rtnetlink::{ new_connection, packet::{rtnl::link::nlas::Nla, LinkMessage, NetlinkPayload, RtnlMessage, RtnlMessage::*}, sys::{constants::*, SocketAddr}, }; use zoomies::{Client, ConfigBuilder, Event}; #[tokio::main(max_threads = 1, core_threads = 1)] async fn main() -> Result<(), String> { // conn - `Connection` that has a netlink socket which is a `Future` that polls the socket // and thus must have an event loop // // handle - `Handle` to the `Connection`. Used to send/recv netlink messages. // // messages - A channel receiver. let (mut conn, mut _handle, mut messages) = new_connection().map_err(|e| format!("{}", e))?; // Create a datadog client. let dd = Client::with_config(ConfigBuilder::new().finish()) .await .map_err(|e| format!("{}", e))?; // These flags specify what kinds of broadcast messages we want to listen for. let groups = RTNLGRP_LINK | RTNLGRP_IPV4_IFADDR | RTNLGRP_IPV6_IFADDR | RTNLGRP_IPV4_ROUTE | RTNLGRP_IPV6_ROUTE | RTNLGRP_MPLS_ROUTE | RTNLGRP_IPV4_MROUTE | RTNLGRP_IPV6_MROUTE | RTNLGRP_NEIGH | RTNLGRP_IPV4_NETCONF | RTNLGRP_IPV6_NETCONF | RTNLGRP_IPV4_RULE | RTNLGRP_IPV6_RULE | RTNLGRP_NSID | RTNLGRP_MPLS_NETCONF; // Create new socket that listens for the messages described above. let addr = SocketAddr::new(0, groups); conn.socket_mut().bind(&addr).expect("Failed to bind"); // Spawn `Connection` to start polling netlink socket. tokio::spawn(conn); // Start receiving events through `messages` channel. while let Some((message, _)) = messages.next().await { match message.payload { NetlinkPayload::Done => { println!("Done"); } NetlinkPayload::Error(em) => { eprintln!("Error: {:?}", em); } NetlinkPayload::Ack(_am) => {} NetlinkPayload::Noop => {} NetlinkPayload::Overrun(_bytes) => {} NetlinkPayload::InnerMessage(m) => { handle_message(&dd, m).await; } } } Ok(()) } fn find_ifname(lm: LinkMessage) -> Option<String> { for nla in lm.nlas.into_iter() { match nla { Nla::IfName(name) => return Some(name), _ => continue, } } None } async fn on_link_deleted(dd: &Client, lm: LinkMessage) { println!("Interface Deleted"); if let Some(name) = find_ifname(lm) { println!("{:?} was deleted", name); let event = Event::new().title("Interface Deleted").text(&name).build().expect("nice"); dd.send(&event).await.expect("failed"); } } async fn on_link_created(dd: &Client, lm: LinkMessage) { if let Some(name) = find_ifname(lm) { println!("Interface {} is up", name); let event = Event::new().title("Interface Created").text(&name).build().expect("nice"); dd.send(&event).await.expect("failed"); } } async fn on_link_set(dd: &Client, lm: LinkMessage) { if let Some(name) = find_ifname(lm) { println!("Interface {:?} was set.", name); let event = Event::new().title("Interface Set").text(&name).build().expect("nice"); dd.send(&event).await.expect("failed"); } } async fn handle_message(dd: &Client, msg: RtnlMessage) { match msg { NewLink(lm) => on_link_created(dd, lm).await, DelLink(lm) => on_link_deleted(dd, lm).await, SetLink(lm) => on_link_set(dd, lm).await, GetLink(_lm) => {} NewAddress(_am) => {} DelAddress(_am) => {} GetAddress(_am) => {} NewNeighbour(_nm) => {} GetNeighbour(_nm) => {} DelNeighbour(_nm) => {} NewRule(_rm) => {} DelRule(_rm) => {} GetRule(_rm) => {} NewRoute(_rm) => {} DelRoute(_rm) => {} GetRoute(_rm) => {} _ => { // NewNeighbourTable(NeighbourTableMessage), // GetNeighbourTable(NeighbourTableMessage), // SetNeighbourTable(NeighbourTableMessage), // NewQueueDiscipline(TcMessage), // DelQueueDiscipline(TcMessage), // GetQueueDiscipline(TcMessage), // NewTrafficClass(TcMessage), // DelTrafficClass(TcMessage), // GetTrafficClass(TcMessage), // NewTrafficFilter(TcMessage), // DelTrafficFilter(TcMessage), // GetTrafficFilter(TcMessage), // NewTrafficChain(TcMessage), // DelTrafficChain(TcMessage), // GetTrafficChain(TcMessage), // NewNsId(NsidMessage), // DelNsId(NsidMessage), // GetNsId(NsidMessage), println!("Unhandled Message: {:?}", msg); } } }
//! Query planner wrapper for use in IOx services use std::sync::Arc; use bytes::Bytes; use datafusion::{ arrow::datatypes::SchemaRef, error::DataFusionError, physical_plan::ExecutionPlan, }; use flightsql::{FlightSQLCommand, FlightSQLPlanner}; use iox_query::{ exec::IOxSessionContext, frontend::sql::SqlQueryPlanner, plan::{fieldlist::FieldListPlan, seriesset::SeriesSetPlans, stringset::StringSetPlan}, Aggregate, QueryNamespace, WindowDuration, }; use iox_query_influxrpc::InfluxRpcPlanner; pub use datafusion::error::{DataFusionError as Error, Result}; use iox_query_influxql::frontend::planner::InfluxQLQueryPlanner; use predicate::rpc_predicate::InfluxRpcPredicate; /// Query planner that plans queries on a separate threadpool. /// /// Query planning was, at time of writing, a single threaded affair. In order /// to avoid tying up the tokio executor that is handling API requests, IOx plan /// queries using a separate thread pool. #[derive(Debug)] pub struct Planner { /// Executors (whose threadpool to use) ctx: IOxSessionContext, } impl Planner { /// Create a new planner that will plan queries using the provided context pub fn new(ctx: &IOxSessionContext) -> Self { Self { ctx: ctx.child_ctx("Planner"), } } /// Plan a SQL query against the data in a namespace, and return a /// DataFusion physical execution plan. pub async fn sql(&self, query: impl Into<String> + Send) -> Result<Arc<dyn ExecutionPlan>> { let planner = SqlQueryPlanner::new(); let query = query.into(); let ctx = self.ctx.child_ctx("planner sql"); self.ctx .run(async move { planner.query(&query, &ctx).await }) .await } /// Plan an InfluxQL query against the data in `database`, and return a /// DataFusion physical execution plan. pub async fn influxql( &self, query: impl Into<String> + Send, ) -> Result<Arc<dyn ExecutionPlan>> { let planner = InfluxQLQueryPlanner::new(); let query = query.into(); let ctx = self.ctx.child_ctx("planner influxql"); self.ctx .run(async move { planner.query(&query, &ctx).await }) .await } /// Creates a plan for a `DoGet` FlightSQL message, as described on /// [`FlightSQLPlanner::do_get`], on a separate threadpool pub async fn flight_sql_do_get<N>( &self, namespace_name: impl Into<String> + Send, namespace: Arc<N>, cmd: FlightSQLCommand, ) -> Result<Arc<dyn ExecutionPlan>> where N: QueryNamespace + 'static, { let namespace_name = namespace_name.into(); let ctx = self.ctx.child_ctx("planner flight_sql_do_get"); self.ctx .run(async move { FlightSQLPlanner::do_get(namespace_name, namespace, cmd, &ctx) .await .map_err(DataFusionError::from) }) .await } /// Creates a plan for a `DoAction` FlightSQL message, as described on /// [`FlightSQLPlanner::do_action`], on a separate threadpool pub async fn flight_sql_do_action<N>( &self, namespace_name: impl Into<String> + Send, namespace: Arc<N>, cmd: FlightSQLCommand, ) -> Result<Bytes> where N: QueryNamespace + 'static, { let namespace_name = namespace_name.into(); let ctx = self.ctx.child_ctx("planner flight_sql_do_get"); self.ctx .run(async move { FlightSQLPlanner::do_action(namespace_name, namespace, cmd, &ctx) .await .map_err(DataFusionError::from) }) .await } /// Returns the [`SchemaRef`] to be included in the response to a /// `GetFlightInfo` FlightSQL message as described on /// [`FlightSQLPlanner::get_schema`], on a separate threadpool. pub async fn flight_sql_get_flight_info_schema( &self, namespace_name: impl Into<String> + Send, cmd: FlightSQLCommand, ) -> Result<SchemaRef> { let namespace_name = namespace_name.into(); let ctx = self.ctx.child_ctx("planner flight_sql_get_flight_info"); self.ctx .run(async move { FlightSQLPlanner::get_schema(namespace_name, cmd, &ctx) .await .map_err(DataFusionError::from) }) .await } /// Creates a plan as described on [`InfluxRpcPlanner::table_names`], on a /// separate threadpool pub async fn table_names<N>( &self, namespace: Arc<N>, predicate: InfluxRpcPredicate, ) -> Result<StringSetPlan> where N: QueryNamespace + 'static, { let planner = InfluxRpcPlanner::new(self.ctx.child_ctx("planner table_names")).await; self.ctx .run(async move { planner .table_names(namespace, predicate) .await .map_err(|e| e.to_df_error("table_names")) }) .await } /// Creates a plan as described on [`InfluxRpcPlanner::tag_keys`], on a /// separate threadpool pub async fn tag_keys<N>( &self, namespace: Arc<N>, predicate: InfluxRpcPredicate, ) -> Result<StringSetPlan> where N: QueryNamespace + 'static, { let planner = InfluxRpcPlanner::new(self.ctx.child_ctx("planner tag_keys")).await; self.ctx .run(async move { planner .tag_keys(namespace, predicate) .await .map_err(|e| e.to_df_error("tag_keys")) }) .await } /// Creates a plan as described on [`InfluxRpcPlanner::tag_values`], on a /// separate threadpool pub async fn tag_values<N>( &self, namespace: Arc<N>, tag_name: impl Into<String> + Send, predicate: InfluxRpcPredicate, ) -> Result<StringSetPlan> where N: QueryNamespace + 'static, { let tag_name = tag_name.into(); let planner = InfluxRpcPlanner::new(self.ctx.child_ctx("planner tag_values")).await; self.ctx .run(async move { planner .tag_values(namespace, &tag_name, predicate) .await .map_err(|e| e.to_df_error("tag_values")) }) .await } /// Creates a plan as described on [`InfluxRpcPlanner::field_columns`], on a /// separate threadpool pub async fn field_columns<N>( &self, namespace: Arc<N>, predicate: InfluxRpcPredicate, ) -> Result<FieldListPlan> where N: QueryNamespace + 'static, { let planner = InfluxRpcPlanner::new(self.ctx.child_ctx("planner field_columns")).await; self.ctx .run(async move { planner .field_columns(namespace, predicate) .await .map_err(|e| e.to_df_error("field_columns")) }) .await } /// Creates a plan as described on [`InfluxRpcPlanner::read_filter`], on a /// separate threadpool pub async fn read_filter<N>( &self, namespace: Arc<N>, predicate: InfluxRpcPredicate, ) -> Result<SeriesSetPlans> where N: QueryNamespace + 'static, { let planner = InfluxRpcPlanner::new(self.ctx.child_ctx("planner read_filter")).await; self.ctx .run(async move { planner .read_filter(namespace, predicate) .await .map_err(|e| e.to_df_error("read_filter")) }) .await } /// Creates a plan as described on [`InfluxRpcPlanner::read_group`], on a /// separate threadpool pub async fn read_group<N>( &self, namespace: Arc<N>, predicate: InfluxRpcPredicate, agg: Aggregate, group_columns: Vec<String>, ) -> Result<SeriesSetPlans> where N: QueryNamespace + 'static, { let planner = InfluxRpcPlanner::new(self.ctx.child_ctx("planner read_group")).await; self.ctx .run(async move { planner .read_group(namespace, predicate, agg, &group_columns) .await .map_err(|e| e.to_df_error("read_group")) }) .await } /// Creates a plan as described on /// [`InfluxRpcPlanner::read_window_aggregate`], on a separate threadpool pub async fn read_window_aggregate<N>( &self, namespace: Arc<N>, predicate: InfluxRpcPredicate, agg: Aggregate, every: WindowDuration, offset: WindowDuration, ) -> Result<SeriesSetPlans> where N: QueryNamespace + 'static, { let planner = InfluxRpcPlanner::new(self.ctx.child_ctx("planner read_window_aggregate")).await; self.ctx .run(async move { planner .read_window_aggregate(namespace, predicate, agg, every, offset) .await .map_err(|e| e.to_df_error("read_window_aggregate")) }) .await } }
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! This mod is the key point about compatibility. //! Everytime update anything in this file, update the `VER` and let the tests pass. use common_expression as ex; use common_expression::types::NumberDataType; use common_expression::TableDataType; use common_protos::pb; use common_protos::pb::data_type::Dt; use common_protos::pb::data_type::Dt24; use common_protos::pb::number::Num; use crate::reader_check_msg; use crate::FromToProto; use crate::Incompatible; use crate::MIN_READER_VER; use crate::VER; impl FromToProto for ex::TableSchema { type PB = pb::DataSchema; fn get_pb_ver(p: &Self::PB) -> u64 { p.ver } fn from_pb(p: pb::DataSchema) -> Result<Self, Incompatible> { reader_check_msg(p.ver, p.min_reader_ver)?; let mut fs = Vec::with_capacity(p.fields.len()); for f in p.fields { fs.push(ex::TableField::from_pb(f)?); } let v = Self::new_from_column_ids(fs, p.metadata, p.next_column_id); Ok(v) } fn to_pb(&self) -> Result<pb::DataSchema, Incompatible> { let mut fs = Vec::with_capacity(self.fields().len()); for f in self.fields() { fs.push(f.to_pb()?); } let p = pb::DataSchema { ver: VER, min_reader_ver: MIN_READER_VER, fields: fs, metadata: self.meta().clone(), next_column_id: self.next_column_id(), }; Ok(p) } } impl FromToProto for ex::TableField { type PB = pb::DataField; fn get_pb_ver(p: &Self::PB) -> u64 { p.ver } fn from_pb(p: pb::DataField) -> Result<Self, Incompatible> { reader_check_msg(p.ver, p.min_reader_ver)?; let v = ex::TableField::new_from_column_id( &p.name, ex::TableDataType::from_pb(p.data_type.ok_or_else(|| Incompatible { reason: "DataField.data_type can not be None".to_string(), })?)?, p.column_id, ) .with_default_expr(p.default_expr); Ok(v) } fn to_pb(&self) -> Result<pb::DataField, Incompatible> { let p = pb::DataField { ver: VER, min_reader_ver: MIN_READER_VER, name: self.name().clone(), default_expr: self.default_expr().cloned(), data_type: Some(self.data_type().to_pb()?), column_id: self.column_id(), }; Ok(p) } } impl FromToProto for ex::TableDataType { type PB = pb::DataType; fn get_pb_ver(p: &Self::PB) -> u64 { p.ver } fn from_pb(p: pb::DataType) -> Result<Self, Incompatible> { reader_check_msg(p.ver, p.min_reader_ver)?; match (&p.dt, &p.dt24) { (None, None) => Err(Incompatible { reason: "DataType .dt and .dt24 are both None".to_string(), }), (Some(_), None) => { // Convert from version 23 or lower: let x = match p.dt.unwrap() { Dt::NullType(_) => ex::TableDataType::Null, Dt::NullableType(nullable_type) => { // reader_check_msg(nullable_type.ver, nullable_type.min_reader_ver)?; let inner = Box::into_inner(nullable_type).inner; let inner = inner.ok_or_else(|| Incompatible { reason: "NullableType.inner can not be None".to_string(), })?; let inner = Box::into_inner(inner); ex::TableDataType::Nullable(Box::new(ex::TableDataType::from_pb(inner)?)) } Dt::BoolType(_) => ex::TableDataType::Boolean, Dt::Int8Type(_) => ex::TableDataType::Number(NumberDataType::Int8), Dt::Int16Type(_) => ex::TableDataType::Number(NumberDataType::Int16), Dt::Int32Type(_) => ex::TableDataType::Number(NumberDataType::Int32), Dt::Int64Type(_) => ex::TableDataType::Number(NumberDataType::Int64), Dt::Uint8Type(_) => ex::TableDataType::Number(NumberDataType::UInt8), Dt::Uint16Type(_) => ex::TableDataType::Number(NumberDataType::UInt16), Dt::Uint32Type(_) => ex::TableDataType::Number(NumberDataType::UInt32), Dt::Uint64Type(_) => ex::TableDataType::Number(NumberDataType::UInt64), Dt::Float32Type(_) => ex::TableDataType::Number(NumberDataType::Float32), Dt::Float64Type(_) => ex::TableDataType::Number(NumberDataType::Float64), Dt::DateType(_) => ex::TableDataType::Date, Dt::TimestampType(_) => ex::TableDataType::Timestamp, Dt::StringType(_) => ex::TableDataType::String, Dt::StructType(stt) => { reader_check_msg(stt.ver, stt.min_reader_ver)?; let mut types = vec![]; for x in stt.types { let vv = ex::TableDataType::from_pb(x)?; types.push(vv); } ex::TableDataType::Tuple { fields_name: stt.names, fields_type: types, } } Dt::ArrayType(a) => { reader_check_msg(a.ver, a.min_reader_ver)?; let inner = Box::into_inner(a).inner; let inner = inner.ok_or_else(|| Incompatible { reason: "Array.inner can not be None".to_string(), })?; let inner = Box::into_inner(inner); ex::TableDataType::Array(Box::new(ex::TableDataType::from_pb(inner)?)) } Dt::VariantType(_) => ex::TableDataType::Variant, Dt::VariantArrayType(_) => ex::TableDataType::Variant, Dt::VariantObjectType(_) => ex::TableDataType::Variant, // NOTE: No Interval type is ever stored in meta-service. // This variant should never be matched. // Thus it is safe for this conversion to map it to any type. Dt::IntervalType(_) => ex::TableDataType::Null, }; Ok(x) } (None, Some(_)) => { // Convert from version 24 or higher: let x = match p.dt24.unwrap() { Dt24::NullT(_) => ex::TableDataType::Null, Dt24::EmptyArrayT(_) => ex::TableDataType::EmptyArray, Dt24::BoolT(_) => ex::TableDataType::Boolean, Dt24::StringT(_) => ex::TableDataType::String, Dt24::NumberT(n) => { ex::TableDataType::Number(ex::types::NumberDataType::from_pb(n)?) } Dt24::TimestampT(_) => ex::TableDataType::Timestamp, Dt24::DateT(_) => ex::TableDataType::Date, Dt24::NullableT(x) => ex::TableDataType::Nullable(Box::new( ex::TableDataType::from_pb(Box::into_inner(x))?, )), Dt24::ArrayT(x) => ex::TableDataType::Array(Box::new( ex::TableDataType::from_pb(Box::into_inner(x))?, )), Dt24::MapT(x) => ex::TableDataType::Map(Box::new(ex::TableDataType::from_pb( Box::into_inner(x), )?)), Dt24::TupleT(t) => { reader_check_msg(t.ver, t.min_reader_ver)?; let mut types = vec![]; for x in t.field_types { let vv = ex::TableDataType::from_pb(x)?; types.push(vv); } ex::TableDataType::Tuple { fields_name: t.field_names, fields_type: types, } } Dt24::VariantT(_) => ex::TableDataType::Variant, Dt24::DecimalT(x) => { ex::TableDataType::Decimal(ex::types::decimal::DecimalDataType::from_pb(x)?) } Dt24::EmptyMapT(_) => ex::TableDataType::EmptyMap, }; Ok(x) } (Some(_), Some(_)) => Err(Incompatible { reason: "Invalid DataType: at most only one of .dt and .dt23 can be Some" .to_string(), }), } } fn to_pb(&self) -> Result<pb::DataType, Incompatible> { let x = match self { TableDataType::Null => new_pb_dt24(Dt24::NullT(pb::Empty {})), TableDataType::EmptyArray => new_pb_dt24(Dt24::EmptyArrayT(pb::Empty {})), TableDataType::EmptyMap => new_pb_dt24(Dt24::EmptyMapT(pb::Empty {})), TableDataType::Boolean => new_pb_dt24(Dt24::BoolT(pb::Empty {})), TableDataType::String => new_pb_dt24(Dt24::StringT(pb::Empty {})), TableDataType::Number(n) => { let x = n.to_pb()?; new_pb_dt24(Dt24::NumberT(x)) } TableDataType::Decimal(n) => { let x = n.to_pb()?; new_pb_dt24(Dt24::DecimalT(x)) } TableDataType::Timestamp => new_pb_dt24(Dt24::TimestampT(pb::Empty {})), TableDataType::Date => new_pb_dt24(Dt24::DateT(pb::Empty {})), TableDataType::Nullable(v) => { let x = v.to_pb()?; new_pb_dt24(Dt24::NullableT(Box::new(x))) } TableDataType::Array(v) => { let x = v.to_pb()?; new_pb_dt24(Dt24::ArrayT(Box::new(x))) } TableDataType::Map(v) => { let x = v.to_pb()?; new_pb_dt24(Dt24::MapT(Box::new(x))) } TableDataType::Tuple { fields_name, fields_type, } => { // let mut types = vec![]; for t in fields_type { let p = t.to_pb()?; types.push(p); } let x = pb::Tuple { ver: VER, min_reader_ver: MIN_READER_VER, field_names: fields_name.clone(), field_types: types, }; new_pb_dt24(Dt24::TupleT(x)) } TableDataType::Variant => new_pb_dt24(Dt24::VariantT(pb::Empty {})), }; Ok(x) } } impl FromToProto for ex::types::NumberDataType { type PB = pb::Number; fn get_pb_ver(p: &Self::PB) -> u64 { p.ver } fn from_pb(p: pb::Number) -> Result<Self, Incompatible> { reader_check_msg(p.ver, p.min_reader_ver)?; let num = match p.num { None => { return Err(Incompatible { reason: "Invalid Number: .num can not be None".to_string(), }); } Some(x) => x, }; let x = match num { Num::Uint8Type(_) => Self::UInt8, Num::Uint16Type(_) => Self::UInt16, Num::Uint32Type(_) => Self::UInt32, Num::Uint64Type(_) => Self::UInt64, Num::Int8Type(_) => Self::Int8, Num::Int16Type(_) => Self::Int16, Num::Int32Type(_) => Self::Int32, Num::Int64Type(_) => Self::Int64, Num::Float32Type(_) => Self::Float32, Num::Float64Type(_) => Self::Float64, }; Ok(x) } fn to_pb(&self) -> Result<pb::Number, Incompatible> { let x = match self { ex::types::NumberDataType::UInt8 => Num::Uint8Type(pb::Empty {}), ex::types::NumberDataType::UInt16 => Num::Uint16Type(pb::Empty {}), ex::types::NumberDataType::UInt32 => Num::Uint32Type(pb::Empty {}), ex::types::NumberDataType::UInt64 => Num::Uint64Type(pb::Empty {}), ex::types::NumberDataType::Int8 => Num::Int8Type(pb::Empty {}), ex::types::NumberDataType::Int16 => Num::Int16Type(pb::Empty {}), ex::types::NumberDataType::Int32 => Num::Int32Type(pb::Empty {}), ex::types::NumberDataType::Int64 => Num::Int64Type(pb::Empty {}), ex::types::NumberDataType::Float32 => Num::Float32Type(pb::Empty {}), ex::types::NumberDataType::Float64 => Num::Float64Type(pb::Empty {}), }; Ok(pb::Number { ver: VER, min_reader_ver: MIN_READER_VER, num: Some(x), }) } } impl FromToProto for ex::types::DecimalDataType { type PB = pb::Decimal; fn get_pb_ver(p: &Self::PB) -> u64 { p.ver } fn from_pb(p: pb::Decimal) -> Result<Self, Incompatible> { reader_check_msg(p.ver, p.min_reader_ver)?; let num = match p.decimal { None => { return Err(Incompatible { reason: "Invalid Decimal: .decimal can not be None".to_string(), }); } Some(x) => x, }; let x = match num { pb::decimal::Decimal::Decimal128(x) => { ex::types::DecimalDataType::Decimal128(ex::types::decimal::DecimalSize::from_pb(x)?) } pb::decimal::Decimal::Decimal256(x) => { ex::types::DecimalDataType::Decimal256(ex::types::decimal::DecimalSize::from_pb(x)?) } }; Ok(x) } fn to_pb(&self) -> Result<pb::Decimal, Incompatible> { let x = match self { ex::types::DecimalDataType::Decimal128(x) => { pb::decimal::Decimal::Decimal128(ex::types::decimal::DecimalSize::to_pb(x)?) } ex::types::DecimalDataType::Decimal256(x) => { pb::decimal::Decimal::Decimal256(ex::types::decimal::DecimalSize::to_pb(x)?) } }; Ok(pb::Decimal { ver: VER, min_reader_ver: MIN_READER_VER, decimal: Some(x), }) } } impl FromToProto for ex::types::decimal::DecimalSize { type PB = pb::DecimalSize; fn get_pb_ver(p: &Self::PB) -> u64 { p.ver } fn from_pb(p: Self::PB) -> Result<Self, Incompatible> where Self: Sized { reader_check_msg(p.ver, p.min_reader_ver)?; Ok(ex::types::decimal::DecimalSize { precision: p.precision as u8, scale: p.scale as u8, }) } fn to_pb(&self) -> Result<Self::PB, Incompatible> { Ok(pb::DecimalSize { ver: VER, min_reader_ver: MIN_READER_VER, precision: self.precision as i32, scale: self.scale as i32, }) } } /// Create a pb::DataType with version-24 data type schema fn new_pb_dt24(dt24: Dt24) -> pb::DataType { pb::DataType { ver: VER, min_reader_ver: MIN_READER_VER, dt: None, dt24: Some(dt24), } }
use actix_web::actix::{Actor, Addr, SyncArbiter, SyncContext}; use actix_web::{actix::Handler, actix::Message, Error}; use futures::Future; use juniper::http::GraphQLRequest; use crate::model::db::Database; use crate::model::user::UserById; use crate::share::common::Claims; use crate::share::gql_schema::{create_schema, Schema, SchemaContext}; #[derive(Serialize, Deserialize)] pub struct GraphQLData(GraphQLRequest, Claims); impl GraphQLData { pub fn new(request: GraphQLRequest, claims: Claims) -> GraphQLData { GraphQLData(request, claims) } } impl Message for GraphQLData { type Result = Result<String, Error>; } pub struct GraphQLExecutor { schema: std::sync::Arc<Schema>, db_addr: Addr<Database>, } impl GraphQLExecutor { fn new(schema: std::sync::Arc<Schema>, db_addr: Addr<Database>) -> GraphQLExecutor { GraphQLExecutor { schema: schema, db_addr: db_addr, } } } impl Actor for GraphQLExecutor { type Context = SyncContext<Self>; } impl Handler<GraphQLData> for GraphQLExecutor { type Result = Result<String, Error>; fn handle(&mut self, msg: GraphQLData, _: &mut Self::Context) -> Self::Result { let user = match self .db_addr .send(UserById { user_id: msg.1.user_id.clone(), }) .wait() .unwrap() { Ok(user) => Some(user), Err(_e) => None, }; let res = msg.0.execute( &self.schema, &SchemaContext { current_user: user, db_addr: self.db_addr.clone(), }, ); let res_text = serde_json::to_string(&res)?; Ok(res_text) } } pub fn init(db_addr: Addr<Database>) -> Addr<GraphQLExecutor> { let schema = std::sync::Arc::new(create_schema()); SyncArbiter::start(4, move || { GraphQLExecutor::new(schema.clone(), db_addr.clone()) }) }
#![allow(non_snake_case)] extern crate regex; extern crate winit; use regex::Regex; mod stuff; fn showGui() { let mut events_loop = winit::EventsLoop::new(); let window = winit::Window::new(&events_loop).unwrap(); events_loop.run_forever(|event| { match event { winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => winit::ControlFlow::Break, _ => winit::ControlFlow::Continue, } }); } fn main() { stuff::test(); showGui(); let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); println!("Did our date match? {}", re.is_match("2014-01-01")); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct CurrentSessionChangedEventArgs(pub ::windows::core::IInspectable); impl CurrentSessionChangedEventArgs {} unsafe impl ::windows::core::RuntimeType for CurrentSessionChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.CurrentSessionChangedEventArgs;{6969cb39-0bfa-5fe0-8d73-09cc5e5408e1})"); } unsafe impl ::windows::core::Interface for CurrentSessionChangedEventArgs { type Vtable = ICurrentSessionChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6969cb39_0bfa_5fe0_8d73_09cc5e5408e1); } impl ::windows::core::RuntimeName for CurrentSessionChangedEventArgs { const NAME: &'static str = "Windows.Media.Control.CurrentSessionChangedEventArgs"; } impl ::core::convert::From<CurrentSessionChangedEventArgs> for ::windows::core::IUnknown { fn from(value: CurrentSessionChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&CurrentSessionChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &CurrentSessionChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CurrentSessionChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a CurrentSessionChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<CurrentSessionChangedEventArgs> for ::windows::core::IInspectable { fn from(value: CurrentSessionChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&CurrentSessionChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &CurrentSessionChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CurrentSessionChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a CurrentSessionChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for CurrentSessionChangedEventArgs {} unsafe impl ::core::marker::Sync for CurrentSessionChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GlobalSystemMediaTransportControlsSession(pub ::windows::core::IInspectable); impl GlobalSystemMediaTransportControlsSession { pub fn SourceAppUserModelId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn TryGetMediaPropertiesAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<GlobalSystemMediaTransportControlsSessionMediaProperties>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<GlobalSystemMediaTransportControlsSessionMediaProperties>>(result__) } } pub fn GetTimelineProperties(&self) -> ::windows::core::Result<GlobalSystemMediaTransportControlsSessionTimelineProperties> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GlobalSystemMediaTransportControlsSessionTimelineProperties>(result__) } } pub fn GetPlaybackInfo(&self) -> ::windows::core::Result<GlobalSystemMediaTransportControlsSessionPlaybackInfo> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GlobalSystemMediaTransportControlsSessionPlaybackInfo>(result__) } } #[cfg(feature = "Foundation")] pub fn TryPlayAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryPauseAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryStopAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryRecordAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryFastForwardAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryRewindAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TrySkipNextAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TrySkipPreviousAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryChangeChannelUpAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryChangeChannelDownAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryTogglePlayPauseAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryChangeAutoRepeatModeAsync(&self, requestedautorepeatmode: super::MediaPlaybackAutoRepeatMode) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), requestedautorepeatmode, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryChangePlaybackRateAsync(&self, requestedplaybackrate: f64) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), requestedplaybackrate, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryChangeShuffleActiveAsync(&self, requestedshufflestate: bool) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), requestedshufflestate, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryChangePlaybackPositionAsync(&self, requestedplaybackposition: i64) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), requestedplaybackposition, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TimelinePropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<GlobalSystemMediaTransportControlsSession, TimelinePropertiesChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveTimelinePropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn PlaybackInfoChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<GlobalSystemMediaTransportControlsSession, PlaybackInfoChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemovePlaybackInfoChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn MediaPropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<GlobalSystemMediaTransportControlsSession, MediaPropertiesChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveMediaPropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for GlobalSystemMediaTransportControlsSession { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.GlobalSystemMediaTransportControlsSession;{7148c835-9b14-5ae2-ab85-dc9b1c14e1a8})"); } unsafe impl ::windows::core::Interface for GlobalSystemMediaTransportControlsSession { type Vtable = IGlobalSystemMediaTransportControlsSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7148c835_9b14_5ae2_ab85_dc9b1c14e1a8); } impl ::windows::core::RuntimeName for GlobalSystemMediaTransportControlsSession { const NAME: &'static str = "Windows.Media.Control.GlobalSystemMediaTransportControlsSession"; } impl ::core::convert::From<GlobalSystemMediaTransportControlsSession> for ::windows::core::IUnknown { fn from(value: GlobalSystemMediaTransportControlsSession) -> Self { value.0 .0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSession> for ::windows::core::IUnknown { fn from(value: &GlobalSystemMediaTransportControlsSession) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GlobalSystemMediaTransportControlsSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GlobalSystemMediaTransportControlsSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GlobalSystemMediaTransportControlsSession> for ::windows::core::IInspectable { fn from(value: GlobalSystemMediaTransportControlsSession) -> Self { value.0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSession> for ::windows::core::IInspectable { fn from(value: &GlobalSystemMediaTransportControlsSession) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GlobalSystemMediaTransportControlsSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GlobalSystemMediaTransportControlsSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GlobalSystemMediaTransportControlsSession {} unsafe impl ::core::marker::Sync for GlobalSystemMediaTransportControlsSession {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GlobalSystemMediaTransportControlsSessionManager(pub ::windows::core::IInspectable); impl GlobalSystemMediaTransportControlsSessionManager { pub fn GetCurrentSession(&self) -> ::windows::core::Result<GlobalSystemMediaTransportControlsSession> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GlobalSystemMediaTransportControlsSession>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetSessions(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<GlobalSystemMediaTransportControlsSession>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<GlobalSystemMediaTransportControlsSession>>(result__) } } #[cfg(feature = "Foundation")] pub fn CurrentSessionChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<GlobalSystemMediaTransportControlsSessionManager, CurrentSessionChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveCurrentSessionChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SessionsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<GlobalSystemMediaTransportControlsSessionManager, SessionsChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveSessionsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn RequestAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<GlobalSystemMediaTransportControlsSessionManager>> { Self::IGlobalSystemMediaTransportControlsSessionManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<GlobalSystemMediaTransportControlsSessionManager>>(result__) }) } pub fn IGlobalSystemMediaTransportControlsSessionManagerStatics<R, F: FnOnce(&IGlobalSystemMediaTransportControlsSessionManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<GlobalSystemMediaTransportControlsSessionManager, IGlobalSystemMediaTransportControlsSessionManagerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for GlobalSystemMediaTransportControlsSessionManager { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager;{cace8eac-e86e-504a-ab31-5ff8ff1bce49})"); } unsafe impl ::windows::core::Interface for GlobalSystemMediaTransportControlsSessionManager { type Vtable = IGlobalSystemMediaTransportControlsSessionManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcace8eac_e86e_504a_ab31_5ff8ff1bce49); } impl ::windows::core::RuntimeName for GlobalSystemMediaTransportControlsSessionManager { const NAME: &'static str = "Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager"; } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionManager> for ::windows::core::IUnknown { fn from(value: GlobalSystemMediaTransportControlsSessionManager) -> Self { value.0 .0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionManager> for ::windows::core::IUnknown { fn from(value: &GlobalSystemMediaTransportControlsSessionManager) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GlobalSystemMediaTransportControlsSessionManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GlobalSystemMediaTransportControlsSessionManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionManager> for ::windows::core::IInspectable { fn from(value: GlobalSystemMediaTransportControlsSessionManager) -> Self { value.0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionManager> for ::windows::core::IInspectable { fn from(value: &GlobalSystemMediaTransportControlsSessionManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GlobalSystemMediaTransportControlsSessionManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GlobalSystemMediaTransportControlsSessionManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GlobalSystemMediaTransportControlsSessionManager {} unsafe impl ::core::marker::Sync for GlobalSystemMediaTransportControlsSessionManager {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GlobalSystemMediaTransportControlsSessionMediaProperties(pub ::windows::core::IInspectable); impl GlobalSystemMediaTransportControlsSessionMediaProperties { pub fn Title(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Subtitle(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn AlbumArtist(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Artist(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn AlbumTitle(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn TrackNumber(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Genres(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } pub fn AlbumTrackCount(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } #[cfg(feature = "Foundation")] pub fn PlaybackType(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::MediaPlaybackType>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::MediaPlaybackType>>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn Thumbnail(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStreamReference> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IRandomAccessStreamReference>(result__) } } } unsafe impl ::windows::core::RuntimeType for GlobalSystemMediaTransportControlsSessionMediaProperties { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.GlobalSystemMediaTransportControlsSessionMediaProperties;{68856cf6-adb4-54b2-ac16-05837907acb6})"); } unsafe impl ::windows::core::Interface for GlobalSystemMediaTransportControlsSessionMediaProperties { type Vtable = IGlobalSystemMediaTransportControlsSessionMediaProperties_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x68856cf6_adb4_54b2_ac16_05837907acb6); } impl ::windows::core::RuntimeName for GlobalSystemMediaTransportControlsSessionMediaProperties { const NAME: &'static str = "Windows.Media.Control.GlobalSystemMediaTransportControlsSessionMediaProperties"; } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionMediaProperties> for ::windows::core::IUnknown { fn from(value: GlobalSystemMediaTransportControlsSessionMediaProperties) -> Self { value.0 .0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionMediaProperties> for ::windows::core::IUnknown { fn from(value: &GlobalSystemMediaTransportControlsSessionMediaProperties) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GlobalSystemMediaTransportControlsSessionMediaProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GlobalSystemMediaTransportControlsSessionMediaProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionMediaProperties> for ::windows::core::IInspectable { fn from(value: GlobalSystemMediaTransportControlsSessionMediaProperties) -> Self { value.0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionMediaProperties> for ::windows::core::IInspectable { fn from(value: &GlobalSystemMediaTransportControlsSessionMediaProperties) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GlobalSystemMediaTransportControlsSessionMediaProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GlobalSystemMediaTransportControlsSessionMediaProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GlobalSystemMediaTransportControlsSessionMediaProperties {} unsafe impl ::core::marker::Sync for GlobalSystemMediaTransportControlsSessionMediaProperties {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GlobalSystemMediaTransportControlsSessionPlaybackControls(pub ::windows::core::IInspectable); impl GlobalSystemMediaTransportControlsSessionPlaybackControls { pub fn IsPlayEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsPauseEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsStopEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsRecordEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsFastForwardEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsRewindEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsNextEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsPreviousEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsChannelUpEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsChannelDownEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsPlayPauseToggleEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsShuffleEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsRepeatEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsPlaybackRateEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsPlaybackPositionEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for GlobalSystemMediaTransportControlsSessionPlaybackControls { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.GlobalSystemMediaTransportControlsSessionPlaybackControls;{6501a3e6-bc7a-503a-bb1b-68f158f3fb03})"); } unsafe impl ::windows::core::Interface for GlobalSystemMediaTransportControlsSessionPlaybackControls { type Vtable = IGlobalSystemMediaTransportControlsSessionPlaybackControls_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6501a3e6_bc7a_503a_bb1b_68f158f3fb03); } impl ::windows::core::RuntimeName for GlobalSystemMediaTransportControlsSessionPlaybackControls { const NAME: &'static str = "Windows.Media.Control.GlobalSystemMediaTransportControlsSessionPlaybackControls"; } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionPlaybackControls> for ::windows::core::IUnknown { fn from(value: GlobalSystemMediaTransportControlsSessionPlaybackControls) -> Self { value.0 .0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionPlaybackControls> for ::windows::core::IUnknown { fn from(value: &GlobalSystemMediaTransportControlsSessionPlaybackControls) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GlobalSystemMediaTransportControlsSessionPlaybackControls { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GlobalSystemMediaTransportControlsSessionPlaybackControls { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionPlaybackControls> for ::windows::core::IInspectable { fn from(value: GlobalSystemMediaTransportControlsSessionPlaybackControls) -> Self { value.0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionPlaybackControls> for ::windows::core::IInspectable { fn from(value: &GlobalSystemMediaTransportControlsSessionPlaybackControls) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GlobalSystemMediaTransportControlsSessionPlaybackControls { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GlobalSystemMediaTransportControlsSessionPlaybackControls { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GlobalSystemMediaTransportControlsSessionPlaybackControls {} unsafe impl ::core::marker::Sync for GlobalSystemMediaTransportControlsSessionPlaybackControls {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GlobalSystemMediaTransportControlsSessionPlaybackInfo(pub ::windows::core::IInspectable); impl GlobalSystemMediaTransportControlsSessionPlaybackInfo { pub fn Controls(&self) -> ::windows::core::Result<GlobalSystemMediaTransportControlsSessionPlaybackControls> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GlobalSystemMediaTransportControlsSessionPlaybackControls>(result__) } } pub fn PlaybackStatus(&self) -> ::windows::core::Result<GlobalSystemMediaTransportControlsSessionPlaybackStatus> { let this = self; unsafe { let mut result__: GlobalSystemMediaTransportControlsSessionPlaybackStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GlobalSystemMediaTransportControlsSessionPlaybackStatus>(result__) } } #[cfg(feature = "Foundation")] pub fn PlaybackType(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::MediaPlaybackType>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::MediaPlaybackType>>(result__) } } #[cfg(feature = "Foundation")] pub fn AutoRepeatMode(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::MediaPlaybackAutoRepeatMode>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::MediaPlaybackAutoRepeatMode>>(result__) } } #[cfg(feature = "Foundation")] pub fn PlaybackRate(&self) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<f64>>(result__) } } #[cfg(feature = "Foundation")] pub fn IsShuffleActive(&self) -> ::windows::core::Result<super::super::Foundation::IReference<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<bool>>(result__) } } } unsafe impl ::windows::core::RuntimeType for GlobalSystemMediaTransportControlsSessionPlaybackInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.GlobalSystemMediaTransportControlsSessionPlaybackInfo;{94b4b6cf-e8ba-51ad-87a7-c10ade106127})"); } unsafe impl ::windows::core::Interface for GlobalSystemMediaTransportControlsSessionPlaybackInfo { type Vtable = IGlobalSystemMediaTransportControlsSessionPlaybackInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x94b4b6cf_e8ba_51ad_87a7_c10ade106127); } impl ::windows::core::RuntimeName for GlobalSystemMediaTransportControlsSessionPlaybackInfo { const NAME: &'static str = "Windows.Media.Control.GlobalSystemMediaTransportControlsSessionPlaybackInfo"; } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionPlaybackInfo> for ::windows::core::IUnknown { fn from(value: GlobalSystemMediaTransportControlsSessionPlaybackInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionPlaybackInfo> for ::windows::core::IUnknown { fn from(value: &GlobalSystemMediaTransportControlsSessionPlaybackInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GlobalSystemMediaTransportControlsSessionPlaybackInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GlobalSystemMediaTransportControlsSessionPlaybackInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionPlaybackInfo> for ::windows::core::IInspectable { fn from(value: GlobalSystemMediaTransportControlsSessionPlaybackInfo) -> Self { value.0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionPlaybackInfo> for ::windows::core::IInspectable { fn from(value: &GlobalSystemMediaTransportControlsSessionPlaybackInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GlobalSystemMediaTransportControlsSessionPlaybackInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GlobalSystemMediaTransportControlsSessionPlaybackInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GlobalSystemMediaTransportControlsSessionPlaybackInfo {} unsafe impl ::core::marker::Sync for GlobalSystemMediaTransportControlsSessionPlaybackInfo {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GlobalSystemMediaTransportControlsSessionPlaybackStatus(pub i32); impl GlobalSystemMediaTransportControlsSessionPlaybackStatus { pub const Closed: GlobalSystemMediaTransportControlsSessionPlaybackStatus = GlobalSystemMediaTransportControlsSessionPlaybackStatus(0i32); pub const Opened: GlobalSystemMediaTransportControlsSessionPlaybackStatus = GlobalSystemMediaTransportControlsSessionPlaybackStatus(1i32); pub const Changing: GlobalSystemMediaTransportControlsSessionPlaybackStatus = GlobalSystemMediaTransportControlsSessionPlaybackStatus(2i32); pub const Stopped: GlobalSystemMediaTransportControlsSessionPlaybackStatus = GlobalSystemMediaTransportControlsSessionPlaybackStatus(3i32); pub const Playing: GlobalSystemMediaTransportControlsSessionPlaybackStatus = GlobalSystemMediaTransportControlsSessionPlaybackStatus(4i32); pub const Paused: GlobalSystemMediaTransportControlsSessionPlaybackStatus = GlobalSystemMediaTransportControlsSessionPlaybackStatus(5i32); } impl ::core::convert::From<i32> for GlobalSystemMediaTransportControlsSessionPlaybackStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GlobalSystemMediaTransportControlsSessionPlaybackStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GlobalSystemMediaTransportControlsSessionPlaybackStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Control.GlobalSystemMediaTransportControlsSessionPlaybackStatus;i4)"); } impl ::windows::core::DefaultType for GlobalSystemMediaTransportControlsSessionPlaybackStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GlobalSystemMediaTransportControlsSessionTimelineProperties(pub ::windows::core::IInspectable); impl GlobalSystemMediaTransportControlsSessionTimelineProperties { #[cfg(feature = "Foundation")] pub fn StartTime(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn EndTime(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn MinSeekTime(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn MaxSeekTime(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn Position(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn LastUpdatedTime(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__) } } } unsafe impl ::windows::core::RuntimeType for GlobalSystemMediaTransportControlsSessionTimelineProperties { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.GlobalSystemMediaTransportControlsSessionTimelineProperties;{ede34136-6f25-588d-8ecf-ea5b6735aaa5})"); } unsafe impl ::windows::core::Interface for GlobalSystemMediaTransportControlsSessionTimelineProperties { type Vtable = IGlobalSystemMediaTransportControlsSessionTimelineProperties_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xede34136_6f25_588d_8ecf_ea5b6735aaa5); } impl ::windows::core::RuntimeName for GlobalSystemMediaTransportControlsSessionTimelineProperties { const NAME: &'static str = "Windows.Media.Control.GlobalSystemMediaTransportControlsSessionTimelineProperties"; } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionTimelineProperties> for ::windows::core::IUnknown { fn from(value: GlobalSystemMediaTransportControlsSessionTimelineProperties) -> Self { value.0 .0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionTimelineProperties> for ::windows::core::IUnknown { fn from(value: &GlobalSystemMediaTransportControlsSessionTimelineProperties) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GlobalSystemMediaTransportControlsSessionTimelineProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a GlobalSystemMediaTransportControlsSessionTimelineProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GlobalSystemMediaTransportControlsSessionTimelineProperties> for ::windows::core::IInspectable { fn from(value: GlobalSystemMediaTransportControlsSessionTimelineProperties) -> Self { value.0 } } impl ::core::convert::From<&GlobalSystemMediaTransportControlsSessionTimelineProperties> for ::windows::core::IInspectable { fn from(value: &GlobalSystemMediaTransportControlsSessionTimelineProperties) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GlobalSystemMediaTransportControlsSessionTimelineProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a GlobalSystemMediaTransportControlsSessionTimelineProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GlobalSystemMediaTransportControlsSessionTimelineProperties {} unsafe impl ::core::marker::Sync for GlobalSystemMediaTransportControlsSessionTimelineProperties {} #[repr(transparent)] #[doc(hidden)] pub struct ICurrentSessionChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICurrentSessionChangedEventArgs { type Vtable = ICurrentSessionChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6969cb39_0bfa_5fe0_8d73_09cc5e5408e1); } #[repr(C)] #[doc(hidden)] pub struct ICurrentSessionChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSession(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGlobalSystemMediaTransportControlsSession { type Vtable = IGlobalSystemMediaTransportControlsSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7148c835_9b14_5ae2_ab85_dc9b1c14e1a8); } #[repr(C)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSession_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestedautorepeatmode: super::MediaPlaybackAutoRepeatMode, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestedplaybackrate: f64, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestedshufflestate: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestedplaybackposition: i64, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionManager(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGlobalSystemMediaTransportControlsSessionManager { type Vtable = IGlobalSystemMediaTransportControlsSessionManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcace8eac_e86e_504a_ab31_5ff8ff1bce49); } #[repr(C)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionManager_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionManagerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGlobalSystemMediaTransportControlsSessionManagerStatics { type Vtable = IGlobalSystemMediaTransportControlsSessionManagerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2050c4ee_11a0_57de_aed7_c97c70338245); } #[repr(C)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionManagerStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionMediaProperties(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGlobalSystemMediaTransportControlsSessionMediaProperties { type Vtable = IGlobalSystemMediaTransportControlsSessionMediaProperties_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x68856cf6_adb4_54b2_ac16_05837907acb6); } #[repr(C)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionMediaProperties_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionPlaybackControls(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGlobalSystemMediaTransportControlsSessionPlaybackControls { type Vtable = IGlobalSystemMediaTransportControlsSessionPlaybackControls_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6501a3e6_bc7a_503a_bb1b_68f158f3fb03); } #[repr(C)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionPlaybackControls_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionPlaybackInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGlobalSystemMediaTransportControlsSessionPlaybackInfo { type Vtable = IGlobalSystemMediaTransportControlsSessionPlaybackInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x94b4b6cf_e8ba_51ad_87a7_c10ade106127); } #[repr(C)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionPlaybackInfo_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut GlobalSystemMediaTransportControlsSessionPlaybackStatus) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionTimelineProperties(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGlobalSystemMediaTransportControlsSessionTimelineProperties { type Vtable = IGlobalSystemMediaTransportControlsSessionTimelineProperties_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xede34136_6f25_588d_8ecf_ea5b6735aaa5); } #[repr(C)] #[doc(hidden)] pub struct IGlobalSystemMediaTransportControlsSessionTimelineProperties_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMediaPropertiesChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMediaPropertiesChangedEventArgs { type Vtable = IMediaPropertiesChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d3741cb_adf0_5cef_91ba_cfabcdd77678); } #[repr(C)] #[doc(hidden)] pub struct IMediaPropertiesChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlaybackInfoChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlaybackInfoChangedEventArgs { type Vtable = IPlaybackInfoChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x786756c2_bc0d_50a5_8807_054291fef139); } #[repr(C)] #[doc(hidden)] pub struct IPlaybackInfoChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ISessionsChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISessionsChangedEventArgs { type Vtable = ISessionsChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbbf0cd32_42c4_5a58_b317_f34bbfbd26e0); } #[repr(C)] #[doc(hidden)] pub struct ISessionsChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITimelinePropertiesChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITimelinePropertiesChangedEventArgs { type Vtable = ITimelinePropertiesChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x29033a2f_c923_5a77_bcaf_055ff415ad32); } #[repr(C)] #[doc(hidden)] pub struct ITimelinePropertiesChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MediaPropertiesChangedEventArgs(pub ::windows::core::IInspectable); impl MediaPropertiesChangedEventArgs {} unsafe impl ::windows::core::RuntimeType for MediaPropertiesChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.MediaPropertiesChangedEventArgs;{7d3741cb-adf0-5cef-91ba-cfabcdd77678})"); } unsafe impl ::windows::core::Interface for MediaPropertiesChangedEventArgs { type Vtable = IMediaPropertiesChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d3741cb_adf0_5cef_91ba_cfabcdd77678); } impl ::windows::core::RuntimeName for MediaPropertiesChangedEventArgs { const NAME: &'static str = "Windows.Media.Control.MediaPropertiesChangedEventArgs"; } impl ::core::convert::From<MediaPropertiesChangedEventArgs> for ::windows::core::IUnknown { fn from(value: MediaPropertiesChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&MediaPropertiesChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &MediaPropertiesChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MediaPropertiesChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MediaPropertiesChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MediaPropertiesChangedEventArgs> for ::windows::core::IInspectable { fn from(value: MediaPropertiesChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&MediaPropertiesChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &MediaPropertiesChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MediaPropertiesChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MediaPropertiesChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MediaPropertiesChangedEventArgs {} unsafe impl ::core::marker::Sync for MediaPropertiesChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlaybackInfoChangedEventArgs(pub ::windows::core::IInspectable); impl PlaybackInfoChangedEventArgs {} unsafe impl ::windows::core::RuntimeType for PlaybackInfoChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.PlaybackInfoChangedEventArgs;{786756c2-bc0d-50a5-8807-054291fef139})"); } unsafe impl ::windows::core::Interface for PlaybackInfoChangedEventArgs { type Vtable = IPlaybackInfoChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x786756c2_bc0d_50a5_8807_054291fef139); } impl ::windows::core::RuntimeName for PlaybackInfoChangedEventArgs { const NAME: &'static str = "Windows.Media.Control.PlaybackInfoChangedEventArgs"; } impl ::core::convert::From<PlaybackInfoChangedEventArgs> for ::windows::core::IUnknown { fn from(value: PlaybackInfoChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&PlaybackInfoChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &PlaybackInfoChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlaybackInfoChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlaybackInfoChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlaybackInfoChangedEventArgs> for ::windows::core::IInspectable { fn from(value: PlaybackInfoChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&PlaybackInfoChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &PlaybackInfoChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlaybackInfoChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlaybackInfoChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PlaybackInfoChangedEventArgs {} unsafe impl ::core::marker::Sync for PlaybackInfoChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SessionsChangedEventArgs(pub ::windows::core::IInspectable); impl SessionsChangedEventArgs {} unsafe impl ::windows::core::RuntimeType for SessionsChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.SessionsChangedEventArgs;{bbf0cd32-42c4-5a58-b317-f34bbfbd26e0})"); } unsafe impl ::windows::core::Interface for SessionsChangedEventArgs { type Vtable = ISessionsChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbbf0cd32_42c4_5a58_b317_f34bbfbd26e0); } impl ::windows::core::RuntimeName for SessionsChangedEventArgs { const NAME: &'static str = "Windows.Media.Control.SessionsChangedEventArgs"; } impl ::core::convert::From<SessionsChangedEventArgs> for ::windows::core::IUnknown { fn from(value: SessionsChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&SessionsChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &SessionsChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SessionsChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SessionsChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SessionsChangedEventArgs> for ::windows::core::IInspectable { fn from(value: SessionsChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&SessionsChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &SessionsChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SessionsChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SessionsChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SessionsChangedEventArgs {} unsafe impl ::core::marker::Sync for SessionsChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TimelinePropertiesChangedEventArgs(pub ::windows::core::IInspectable); impl TimelinePropertiesChangedEventArgs {} unsafe impl ::windows::core::RuntimeType for TimelinePropertiesChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Control.TimelinePropertiesChangedEventArgs;{29033a2f-c923-5a77-bcaf-055ff415ad32})"); } unsafe impl ::windows::core::Interface for TimelinePropertiesChangedEventArgs { type Vtable = ITimelinePropertiesChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x29033a2f_c923_5a77_bcaf_055ff415ad32); } impl ::windows::core::RuntimeName for TimelinePropertiesChangedEventArgs { const NAME: &'static str = "Windows.Media.Control.TimelinePropertiesChangedEventArgs"; } impl ::core::convert::From<TimelinePropertiesChangedEventArgs> for ::windows::core::IUnknown { fn from(value: TimelinePropertiesChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&TimelinePropertiesChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &TimelinePropertiesChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TimelinePropertiesChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TimelinePropertiesChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TimelinePropertiesChangedEventArgs> for ::windows::core::IInspectable { fn from(value: TimelinePropertiesChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&TimelinePropertiesChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &TimelinePropertiesChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TimelinePropertiesChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TimelinePropertiesChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TimelinePropertiesChangedEventArgs {} unsafe impl ::core::marker::Sync for TimelinePropertiesChangedEventArgs {}
//! Implements [`SequentialSpec`] for [`Register`] operational semantics. use super::SequentialSpec; use std::fmt::Debug; /// A simple register used to define reference operational semantics via /// [`SequentialSpec`]. #[derive(Clone, Default, Debug, Hash, PartialEq, serde::Serialize)] pub struct Register<T>(pub T); /// An operation that can be invoked upon a [`Register`], resulting in a /// [`RegisterRet`] #[derive(Clone, Debug, Hash, PartialEq, serde::Serialize)] pub enum RegisterOp<T> { Write(T), Read, } /// A return value for a [`RegisterOp`] invoked upon a [`Register`]. #[derive(Clone, Debug, Hash, PartialEq, serde::Serialize)] pub enum RegisterRet<T> { WriteOk, ReadOk(T), } impl<T: Clone + Debug + PartialEq> SequentialSpec for Register<T> { type Op = RegisterOp<T>; type Ret = RegisterRet<T>; fn invoke(&mut self, op: &Self::Op) -> Self::Ret { match op { RegisterOp::Write(v) => { self.0 = v.clone(); RegisterRet::WriteOk } RegisterOp::Read => RegisterRet::ReadOk(self.0.clone()), } } fn is_valid_step(&mut self, op: &Self::Op, ret: &Self::Ret) -> bool { // Override to avoid unnecessary `clone` on `Read`. match (op, ret) { (RegisterOp::Write(v), RegisterRet::WriteOk) => { self.0 = v.clone(); true } (RegisterOp::Read, RegisterRet::ReadOk(v)) => &self.0 == v, _ => false, } } } #[cfg(test)] #[rustfmt::skip] mod test { use super::*; #[test] fn models_expected_semantics() { let mut r = Register('A'); assert_eq!(r.invoke(&RegisterOp::Read), RegisterRet::ReadOk('A')); assert_eq!(r.invoke(&RegisterOp::Write('B')), RegisterRet::WriteOk); assert_eq!(r.invoke(&RegisterOp::Read), RegisterRet::ReadOk('B')); } #[test] fn accepts_valid_histories() { assert!(Register('A').is_valid_history(vec![])); assert!(Register('A').is_valid_history(vec![ (RegisterOp::Read, RegisterRet::ReadOk('A')), (RegisterOp::Write('B'), RegisterRet::WriteOk), (RegisterOp::Read, RegisterRet::ReadOk('B')), (RegisterOp::Write('C'), RegisterRet::WriteOk), (RegisterOp::Read, RegisterRet::ReadOk('C')), ])); } #[test] fn rejects_invalid_histories() { assert!(!Register('A').is_valid_history(vec![ (RegisterOp::Read, RegisterRet::ReadOk('B')), (RegisterOp::Write('B'), RegisterRet::WriteOk), ])); assert!(!Register('A').is_valid_history(vec![ (RegisterOp::Write('B'), RegisterRet::WriteOk), (RegisterOp::Read, RegisterRet::ReadOk('A')), ])); } }
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; use num_traits::Zero; use std::convert::From; #[repr(transparent)] #[derive(Debug, Clone, Copy, PartialEq)] pub struct Voxel { iso_value: f32, } impl Voxel { pub fn new(value: f32) -> Voxel { Voxel { iso_value: value, } } } impl From<f32> for Voxel { fn from(f: f32) -> Self { Voxel { iso_value: f, } } } impl Add for Voxel { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self { Self { iso_value: self.iso_value + rhs.iso_value, } } } impl AddAssign for Voxel { #[inline] fn add_assign(&mut self, rhs: Self) { *self = Self { iso_value: self.iso_value + rhs.iso_value, } } } impl Sub for Voxel { type Output = Self; #[inline] fn sub(self, rhs: Self) -> Self { Self { iso_value: self.iso_value - rhs.iso_value, } } } impl SubAssign for Voxel { #[inline] fn sub_assign(&mut self, rhs: Self) { *self = Self { iso_value: self.iso_value - rhs.iso_value, } } } impl Mul for Voxel { type Output = Self; #[inline] fn mul(self, rhs: Self) -> Self { Self { iso_value: self.iso_value * rhs.iso_value, } } } impl MulAssign for Voxel { #[inline] fn mul_assign(&mut self, rhs: Self) { *self = Self { iso_value: self.iso_value * rhs.iso_value, } } } impl Div for Voxel { type Output = Self; #[inline] fn div(self, rhs: Self) -> Self { Self { iso_value: self.iso_value / rhs.iso_value, } } } impl DivAssign for Voxel { #[inline] fn div_assign(&mut self, rhs: Self) { *self = Self { iso_value: self.iso_value / rhs.iso_value, } } } impl Zero for Voxel { #[inline] fn zero() -> Voxel { Voxel { iso_value: 0.0, } } #[inline] fn is_zero(&self) -> bool { self.iso_value == 0.0 } } #[cfg(test)] mod tests { use float_cmp::{ApproxEq, F32Margin}; use super::*; impl ApproxEq for Voxel { type Margin = F32Margin; fn approx_eq<T: Into<Self::Margin>>(self, other: Self, margin: T) -> bool { let margin = margin.into(); self.iso_value.approx_eq(other.iso_value, margin) } } }
//! An example of a multisig to execute arbitrary Solana transactions. //! //! This program can be used to allow a multisig to govern anything a regular //! Pubkey can govern. One can use the multisig as a BPF program upgrade //! authority, a mint authority, etc. //! //! To use, one must first create a `Multisig` account, specifying two important //! parameters: //! //! 1. Owners - the set of addresses that sign transactions for the multisig. //! 2. Threshold - the number of signers required to execute a transaction. //! //! Once the `Multisig` account is created, one can create a `Transaction` //! account, specifying the parameters for a normal solana transaction. //! //! To sign, owners should invoke the `approve` instruction, and finally, //! the `execute_transaction`, once enough (i.e. `threhsold`) of the owners have //! signed. use anchor_lang::prelude::*; use anchor_lang::solana_program; use anchor_lang::solana_program::instruction::Instruction; use std::convert::Into; #[program] pub mod multisig { use super::*; // Initializes a new multisig account with a set of owners and a threshold. pub fn create_multisig( ctx: Context<CreateMultisig>, owners: Vec<Pubkey>, threshold: u64, nonce: u8, ) -> Result<()> { let multisig = &mut ctx.accounts.multisig; multisig.owners = owners; multisig.threshold = threshold; multisig.nonce = nonce; multisig.owner_set_seqno = 0; Ok(()) } // Creates a new transaction account, automatically signed by the creator, // which must be one of the owners of the multisig. pub fn create_transaction( ctx: Context<CreateTransaction>, pid: Pubkey, accs: Vec<TransactionAccount>, data: Vec<u8>, ) -> Result<()> { let owner_index = ctx .accounts .multisig .owners .iter() .position(|a| a == ctx.accounts.proposer.key) .ok_or(ErrorCode::InvalidOwner)?; let mut signers = Vec::new(); signers.resize(ctx.accounts.multisig.owners.len(), false); signers[owner_index] = true; let tx = &mut ctx.accounts.transaction; tx.program_id = pid; tx.accounts = accs; tx.data = data; tx.signers = signers; tx.multisig = *ctx.accounts.multisig.to_account_info().key; tx.did_execute = false; tx.owner_set_seqno = ctx.accounts.multisig.owner_set_seqno; Ok(()) } // Approves a transaction on behalf of an owner of the multisig. pub fn approve(ctx: Context<Approve>) -> Result<()> { let owner_index = ctx .accounts .multisig .owners .iter() .position(|a| a == ctx.accounts.owner.key) .ok_or(ErrorCode::InvalidOwner)?; ctx.accounts.transaction.signers[owner_index] = true; Ok(()) } // Set owners and threshold at once. pub fn set_owners_and_change_threshold<'info>( ctx: Context<'_, '_, '_, 'info, Auth<'info>>, owners: Vec<Pubkey>, threshold: u64, ) -> Result<()> { set_owners( Context::new(ctx.program_id, ctx.accounts, ctx.remaining_accounts), owners, )?; change_threshold(ctx, threshold) } // Sets the owners field on the multisig. The only way this can be invoked // is via a recursive call from execute_transaction -> set_owners. pub fn set_owners(ctx: Context<Auth>, owners: Vec<Pubkey>) -> Result<()> { let multisig = &mut ctx.accounts.multisig; if (owners.len() as u64) < multisig.threshold { multisig.threshold = owners.len() as u64; } multisig.owners = owners; multisig.owner_set_seqno += 1; Ok(()) } // Changes the execution threshold of the multisig. The only way this can be // invoked is via a recursive call from execute_transaction -> // change_threshold. pub fn change_threshold(ctx: Context<Auth>, threshold: u64) -> Result<()> { if threshold > ctx.accounts.multisig.owners.len() as u64 { return Err(ErrorCode::InvalidThreshold.into()); } let multisig = &mut ctx.accounts.multisig; multisig.threshold = threshold; Ok(()) } // Executes the given transaction if threshold owners have signed it. pub fn execute_transaction(ctx: Context<ExecuteTransaction>) -> Result<()> { // Has this been executed already? if ctx.accounts.transaction.did_execute { return Err(ErrorCode::AlreadyExecuted.into()); } // Do we have enough signers. let sig_count = ctx .accounts .transaction .signers .iter() .filter(|&did_sign| *did_sign) .count() as u64; if sig_count < ctx.accounts.multisig.threshold { return Err(ErrorCode::NotEnoughSigners.into()); } // Execute the transaction signed by the multisig. let mut ix: Instruction = (&*ctx.accounts.transaction).into(); ix.accounts = ix .accounts .iter() .map(|acc| { if &acc.pubkey == ctx.accounts.multisig_signer.key { AccountMeta::new_readonly(acc.pubkey, true) } else { acc.clone() } }) .collect(); let seeds = &[ ctx.accounts.multisig.to_account_info().key.as_ref(), &[ctx.accounts.multisig.nonce], ]; let signer = &[&seeds[..]]; let accounts = ctx.remaining_accounts; solana_program::program::invoke_signed(&ix, &accounts, signer)?; // Burn the transaction to ensure one time use. ctx.accounts.transaction.did_execute = true; Ok(()) } } #[derive(Accounts)] pub struct CreateMultisig<'info> { #[account(init)] multisig: ProgramAccount<'info, Multisig>, rent: Sysvar<'info, Rent>, } #[derive(Accounts)] pub struct CreateTransaction<'info> { multisig: ProgramAccount<'info, Multisig>, #[account(init)] transaction: ProgramAccount<'info, Transaction>, // One of the owners. Checked in the handler. #[account(signer)] proposer: AccountInfo<'info>, rent: Sysvar<'info, Rent>, } #[derive(Accounts)] pub struct Approve<'info> { #[account("multisig.owner_set_seqno == transaction.owner_set_seqno")] multisig: ProgramAccount<'info, Multisig>, #[account(mut, belongs_to = multisig)] transaction: ProgramAccount<'info, Transaction>, // One of the multisig owners. Checked in the handler. #[account(signer)] owner: AccountInfo<'info>, } #[derive(Accounts)] pub struct Auth<'info> { #[account(mut)] multisig: ProgramAccount<'info, Multisig>, #[account(signer, seeds = [ multisig.to_account_info().key.as_ref(), &[multisig.nonce], ])] multisig_signer: AccountInfo<'info>, } #[derive(Accounts)] pub struct ExecuteTransaction<'info> { #[account("multisig.owner_set_seqno == transaction.owner_set_seqno")] multisig: ProgramAccount<'info, Multisig>, #[account(seeds = [ multisig.to_account_info().key.as_ref(), &[multisig.nonce], ])] multisig_signer: AccountInfo<'info>, #[account(mut, belongs_to = multisig)] transaction: ProgramAccount<'info, Transaction>, } #[account] pub struct Multisig { pub owners: Vec<Pubkey>, pub threshold: u64, pub nonce: u8, pub owner_set_seqno: u32, } #[account] pub struct Transaction { // The multisig account this transaction belongs to. pub multisig: Pubkey, // Target program to execute against. pub program_id: Pubkey, // Accounts requried for the transaction. pub accounts: Vec<TransactionAccount>, // Instruction data for the transaction. pub data: Vec<u8>, // signers[index] is true iff multisig.owners[index] signed the transaction. pub signers: Vec<bool>, // Boolean ensuring one time execution. pub did_execute: bool, // Owner set sequence number. pub owner_set_seqno: u32, } impl From<&Transaction> for Instruction { fn from(tx: &Transaction) -> Instruction { Instruction { program_id: tx.program_id, accounts: tx.accounts.iter().map(AccountMeta::from).collect(), data: tx.data.clone(), } } } #[derive(AnchorSerialize, AnchorDeserialize, Clone)] pub struct TransactionAccount { pub pubkey: Pubkey, pub is_signer: bool, pub is_writable: bool, } impl From<&TransactionAccount> for AccountMeta { fn from(account: &TransactionAccount) -> AccountMeta { match account.is_writable { false => AccountMeta::new_readonly(account.pubkey, account.is_signer), true => AccountMeta::new(account.pubkey, account.is_signer), } } } impl From<&AccountMeta> for TransactionAccount { fn from(account_meta: &AccountMeta) -> TransactionAccount { TransactionAccount { pubkey: account_meta.pubkey, is_signer: account_meta.is_signer, is_writable: account_meta.is_writable, } } } #[error] pub enum ErrorCode { #[msg("The given owner is not part of this multisig.")] InvalidOwner, #[msg("Not enough owners signed this transaction.")] NotEnoughSigners, #[msg("Cannot delete a transaction that has been signed by an owner.")] TransactionAlreadySigned, #[msg("Overflow when adding.")] Overflow, #[msg("Cannot delete a transaction the owner did not create.")] UnableToDelete, #[msg("The given transaction has already been executed.")] AlreadyExecuted, #[msg("Threshold must be less than or equal to the number of owners.")] InvalidThreshold, }
use super::super::super::exec::frame::ObjectBody; use super::super::super::gc::gc::GcType; #[derive(Debug, Clone)] pub enum ConstantType { Class, Fieldref, Methodref, InterfaceMethodref, String, Integer, Float, Long, Double, NameAndType, Utf8, MethodHandle, MethodType, InvokeDynamic, } impl ConstantType { pub fn value(&self) -> usize { match self { ConstantType::Class => 7, ConstantType::Fieldref => 9, ConstantType::Methodref => 10, ConstantType::InterfaceMethodref => 11, ConstantType::String => 8, ConstantType::Integer => 3, ConstantType::Float => 4, ConstantType::Long => 5, ConstantType::Double => 6, ConstantType::NameAndType => 12, ConstantType::Utf8 => 1, ConstantType::MethodHandle => 15, ConstantType::MethodType => 16, ConstantType::InvokeDynamic => 18, } } } pub fn u8_to_constant_type(val: u8) -> Option<ConstantType> { match val { 7 => Some(ConstantType::Class), 9 => Some(ConstantType::Fieldref), 10 => Some(ConstantType::Methodref), 11 => Some(ConstantType::InterfaceMethodref), 8 => Some(ConstantType::String), 3 => Some(ConstantType::Integer), 4 => Some(ConstantType::Float), 5 => Some(ConstantType::Long), 6 => Some(ConstantType::Double), 12 => Some(ConstantType::NameAndType), 1 => Some(ConstantType::Utf8), 15 => Some(ConstantType::MethodHandle), 16 => Some(ConstantType::MethodType), 18 => Some(ConstantType::InvokeDynamic), _ => None, } } #[derive(Clone, Debug)] pub enum Constant { MethodrefInfo { class_index: u16, name_and_type_index: u16, }, FieldrefInfo { class_index: u16, name_and_type_index: u16, }, InterfaceMethodrefInfo { class_index: u16, name_and_type_index: u16, }, String { string_index: u16, }, ClassInfo { name_index: u16, }, Utf8 { s: String, java_string: Option<GcType<ObjectBody>>, }, NameAndTypeInfo { name_index: u16, descriptor_index: u16, }, IntegerInfo { i: i32, }, FloatInfo { f: f32, }, LongInfo { i: i64, }, DoubleInfo { f: f64, }, MethodHandleInfo { reference_kind: u8, reference_index: u16, }, MethodTypeInfo { descriptor_index: u16, }, InvokeDynamicInfo { bootstrap_method_attr_index: u16, name_and_type_index: u16, }, None, } impl Constant { pub fn get_utf8(&self) -> Option<&String> { match self { Constant::Utf8 { s, .. } => Some(s), _ => None, } } pub fn get_java_string_utf8(&self) -> Option<GcType<ObjectBody>> { match self { Constant::Utf8 { java_string, .. } => Some(java_string.unwrap()), _ => None, } } pub fn get_class_name_index(&self) -> Option<usize> { match self { Constant::ClassInfo { name_index } => Some(*name_index as usize), _ => None, } } }
#[derive(Clone, Debug)] pub struct Error { inner: String, backtrace: Option<Backtrace>, } impl Error { pub fn new(inner: impl std::fmt::Display) -> Self { Self::with_string(inner.to_string()) } fn with_string(inner: String) -> Self { Self { inner, backtrace: Backtrace::new(), } } } impl PartialEq for Error { fn eq(&self, other: &Self) -> bool { self.inner == other.inner } } impl Eq for Error {} impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "{}", self.inner)?; if let Some(backtrace) = self.backtrace.as_ref() { writeln!(f)?; writeln!(f, "Backtrace:")?; writeln!(f, "{}", backtrace)?; } Ok(()) } } impl std::error::Error for Error {} impl<'s> From<&'s str> for Error { fn from(other: &'s str) -> Self { Self::with_string(other.to_owned()) } } impl<'s> From<&'s String> for Error { fn from(other: &'s String) -> Self { Self::with_string(other.clone()) } } impl From<String> for Error { fn from(other: String) -> Self { Self::with_string(other) } } #[cfg(feature = "debug")] #[derive(Debug, Clone)] struct Backtrace(backtrace::Backtrace); #[cfg(feature = "debug")] impl Backtrace { fn new() -> Option<Self> { Some(Self(backtrace::Backtrace::new())) } } #[cfg(feature = "debug")] impl std::fmt::Display for Backtrace { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { // `backtrace::Backtrace` uses `Debug` instead of `Display` write!(f, "{:?}", self.0) } } #[cfg(not(feature = "debug"))] #[derive(Debug, Copy, Clone)] struct Backtrace; #[cfg(not(feature = "debug"))] impl Backtrace { fn new() -> Option<Self> { None } } #[cfg(not(feature = "debug"))] impl std::fmt::Display for Backtrace { fn fmt(&self, _: &mut std::fmt::Formatter) -> std::fmt::Result { Ok(()) } }
// Copyright 2021 Datafuse Labs. // // 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 common_datavalues as dv; use serde::Deserialize; use serde::Serialize; use super::statistics::Statistics; use crate::meta::SnapshotId; pub type Location = String; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct TableSnapshot { pub snapshot_id: SnapshotId, pub prev_snapshot_id: Option<SnapshotId>, /// For each snapshot, we keep a schema for it (in case of schema evolution) pub schema: dv::DataSchema, /// Summary Statistics pub summary: Statistics, /// Pointers to SegmentInfos (may be of different format) pub segments: Vec<Location>, } impl TableSnapshot { #[must_use] pub fn append_segment(mut self, location: Location) -> TableSnapshot { self.segments.push(location); self } }
// Copyright 2022 Datafuse Labs. // // 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. pub use common_pipeline_core::processors::*; pub(crate) mod transforms; pub use transforms::AggregatorParams; pub use transforms::BlockCompactor; pub use transforms::HashJoinDesc; pub use transforms::HashJoinState; pub use transforms::HashTable; pub use transforms::JoinHashTable; pub use transforms::LeftJoinCompactor; pub use transforms::MarkJoinCompactor; pub use transforms::ProfileWrapper; pub use transforms::RightJoinCompactor; pub use transforms::SerializerHashTable; pub use transforms::SinkBuildHashTable; pub use transforms::SinkRuntimeFilterSource; pub use transforms::SortMergeCompactor; pub use transforms::TransformBlockCompact; pub use transforms::TransformCastSchema; pub use transforms::TransformCompact; pub use transforms::TransformCreateSets; pub use transforms::TransformExpandGroupingSets; pub use transforms::TransformHashJoinProbe; pub use transforms::TransformLimit; pub use transforms::TransformResortAddOn; pub use transforms::TransformRuntimeFilter; pub use transforms::TransformSortPartial;
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT use crate::Session; use glib::object::IsA; use glib::translate::*; use std::fmt; glib::wrapper! { #[doc(alias = "SoupSessionFeature")] pub struct SessionFeature(Interface<ffi::SoupSessionFeature, ffi::SoupSessionFeatureInterface>); match fn { type_ => || ffi::soup_session_feature_get_type(), } } pub const NONE_SESSION_FEATURE: Option<&SessionFeature> = None; pub trait SessionFeatureExt: 'static { #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] #[doc(alias = "soup_session_feature_add_feature")] fn add_feature(&self, type_: glib::types::Type) -> bool; #[doc(alias = "soup_session_feature_attach")] fn attach<P: IsA<Session>>(&self, session: &P); #[doc(alias = "soup_session_feature_detach")] fn detach<P: IsA<Session>>(&self, session: &P); #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] #[doc(alias = "soup_session_feature_has_feature")] fn has_feature(&self, type_: glib::types::Type) -> bool; #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] #[doc(alias = "soup_session_feature_remove_feature")] fn remove_feature(&self, type_: glib::types::Type) -> bool; } impl<O: IsA<SessionFeature>> SessionFeatureExt for O { #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] fn add_feature(&self, type_: glib::types::Type) -> bool { unsafe { from_glib(ffi::soup_session_feature_add_feature(self.as_ref().to_glib_none().0, type_.into_glib())) } } fn attach<P: IsA<Session>>(&self, session: &P) { unsafe { ffi::soup_session_feature_attach(self.as_ref().to_glib_none().0, session.as_ref().to_glib_none().0); } } fn detach<P: IsA<Session>>(&self, session: &P) { unsafe { ffi::soup_session_feature_detach(self.as_ref().to_glib_none().0, session.as_ref().to_glib_none().0); } } #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] fn has_feature(&self, type_: glib::types::Type) -> bool { unsafe { from_glib(ffi::soup_session_feature_has_feature(self.as_ref().to_glib_none().0, type_.into_glib())) } } #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] fn remove_feature(&self, type_: glib::types::Type) -> bool { unsafe { from_glib(ffi::soup_session_feature_remove_feature(self.as_ref().to_glib_none().0, type_.into_glib())) } } } impl fmt::Display for SessionFeature { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("SessionFeature") } }
use crate::mq; use log::{Level, Metadata, Record}; use std::sync::{Arc, RwLock}; type Log = Arc<RwLock<Vec<(Level, f64, String)>>>; static mut LOG: Option<Log> = None; pub struct Logger; static LOGGER: Logger = Logger; static mut INNER: Option<env_logger::Logger> = None; impl Logger { pub fn init() { unsafe { LOG.replace(Arc::new(RwLock::new(Vec::new()))); } let mut builder = env_logger::Builder::from_env(env_logger::Env::default()); let logger = builder.build(); let max_level = logger.filter(); unsafe { INNER.replace(logger); } if let Ok(()) = log::set_logger(&LOGGER) { log::set_max_level(max_level) } } pub fn get_log() -> Log { unsafe { LOG.as_ref().unwrap() }.clone() } } impl log::Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool { unsafe { INNER.as_ref().unwrap() }.enabled(metadata) } fn log(&self, record: &Record) { if record.level() <= Level::Info { unsafe { LOG.as_ref().unwrap() }.write().unwrap().push(( record.level(), mq::date::now(), format!("{}", record.args()), )); } unsafe { INNER.as_ref().unwrap() }.log(record) } fn flush(&self) { unsafe { INNER.as_ref().unwrap() }.flush() } }
// Copyright 2019, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::message::DhtOutboundRequest; use crate::{ domain_message::OutboundDomainMessage, envelope::NodeDestination, outbound::{ message::{OutboundEncryption, SendMessageResponse}, message_params::{FinalSendMessageParams, SendMessageParams}, DhtOutboundError, }, }; use futures::{ channel::{mpsc, oneshot}, SinkExt, }; use log::*; use tari_comms::{message::MessageExt, peer_manager::NodeId, types::CommsPublicKey, wrap_in_envelope_body}; const LOG_TARGET: &str = "comms::dht::requests::outbound"; #[derive(Clone)] pub struct OutboundMessageRequester { sender: mpsc::Sender<DhtOutboundRequest>, } impl OutboundMessageRequester { pub fn new(sender: mpsc::Sender<DhtOutboundRequest>) -> Self { Self { sender } } /// Send directly to a peer. pub async fn send_direct<T>( &mut self, dest_public_key: CommsPublicKey, encryption: OutboundEncryption, message: OutboundDomainMessage<T>, ) -> Result<SendMessageResponse, DhtOutboundError> where T: prost::Message, { self.send_message( SendMessageParams::new() .direct_public_key(dest_public_key) .with_encryption(encryption) .with_discovery(true) .finish(), message, ) .await } /// Send directly to a peer. pub async fn send_direct_node_id<T>( &mut self, dest_node_id: NodeId, encryption: OutboundEncryption, message: OutboundDomainMessage<T>, ) -> Result<SendMessageResponse, DhtOutboundError> where T: prost::Message, { self.send_message( SendMessageParams::new() .direct_node_id(dest_node_id.clone()) .with_destination(NodeDestination::NodeId(Box::new(dest_node_id))) .with_encryption(encryption) .finish(), message, ) .await } /// Send to a pre-configured number of closest peers. /// /// Each message is destined for each peer. pub async fn send_direct_neighbours<T>( &mut self, encryption: OutboundEncryption, exclude_peers: Vec<CommsPublicKey>, message: OutboundDomainMessage<T>, ) -> Result<SendMessageResponse, DhtOutboundError> where T: prost::Message, { self.propagate(NodeDestination::Unknown, encryption, exclude_peers, message) .await } /// Send to a pre-configured number of closest peers, for further message propagation. /// /// Optionally, the NodeDestination can be set to propagate to a particular peer, or network region /// in addition to each peer directly (Same as send_direct_neighbours). pub async fn propagate<T>( &mut self, destination: NodeDestination, encryption: OutboundEncryption, exclude_peers: Vec<CommsPublicKey>, message: OutboundDomainMessage<T>, ) -> Result<SendMessageResponse, DhtOutboundError> where T: prost::Message, { self.send_message( SendMessageParams::new() .neighbours(exclude_peers) .with_encryption(encryption) .with_destination(destination) .finish(), message, ) .await } /// Send to _ALL_ known peers. /// /// This should be used with caution as, depending on the number of known peers, a lot of network /// traffic could be generated from this node. pub async fn send_flood<T>( &mut self, destination: NodeDestination, encryption: OutboundEncryption, message: OutboundDomainMessage<T>, ) -> Result<SendMessageResponse, DhtOutboundError> where T: prost::Message, { self.send_message( SendMessageParams::new() .flood() .with_destination(destination) .with_encryption(encryption) .finish(), message, ) .await } /// Send to a random subset of peers of size _n_. pub async fn send_random<T>( &mut self, n: usize, destination: NodeDestination, encryption: OutboundEncryption, message: OutboundDomainMessage<T>, ) -> Result<SendMessageResponse, DhtOutboundError> where T: prost::Message, { self.send_message( SendMessageParams::new() .random(n) .with_destination(destination) .with_encryption(encryption) .finish(), message, ) .await } /// Send a message with custom parameters pub async fn send_message<T>( &mut self, params: FinalSendMessageParams, message: OutboundDomainMessage<T>, ) -> Result<SendMessageResponse, DhtOutboundError> where T: prost::Message, { if cfg!(debug_assertions) { trace!( target: LOG_TARGET, "Send Message: params:{} message:{:?}", params, message ); } let body = wrap_in_envelope_body!(message.to_header(), message.into_inner()).to_encoded_bytes(); self.send_raw(params, body).await } /// Send a message without a domain header part pub async fn send_message_no_header<T>( &mut self, params: FinalSendMessageParams, message: T, ) -> Result<SendMessageResponse, DhtOutboundError> where T: prost::Message, { if cfg!(debug_assertions) { trace!(target: LOG_TARGET, "Send Message: {} {:?}", params, message); } let body = wrap_in_envelope_body!(message).to_encoded_bytes(); self.send_raw(params, body).await } /// Send a raw message pub async fn send_raw( &mut self, params: FinalSendMessageParams, body: Vec<u8>, ) -> Result<SendMessageResponse, DhtOutboundError> { let (reply_tx, reply_rx) = oneshot::channel(); self.sender .send(DhtOutboundRequest::SendMessage(Box::new(params), body.into(), reply_tx)) .await?; reply_rx .await .map_err(|_| DhtOutboundError::RequesterReplyChannelClosed) } #[cfg(test)] pub fn get_mpsc_sender(&self) -> mpsc::Sender<DhtOutboundRequest> { self.sender.clone() } }
use std::collections::hash_map::{HashMap, Entry}; use std::io; use std::mem; use std::os::windows::prelude::*; use std::sync::{Arc, Mutex}; use slab::Index; use winapi::*; use wio::Overlapped; use wio::iocp::{CompletionPort, CompletionStatus}; use {Token, PollOpt}; use event::{IoEvent, EventSet}; /// The guts of the Windows event loop, this is the struct which actually owns /// a completion port. /// /// Internally this is just an `Arc`, and this allows handing out references to /// the internals to I/O handles registered on this selector. This is /// required to schedule I/O operations independently of being inside the event /// loop (e.g. when a call to `write` is seen we're not "in the event loop"). pub struct Selector { inner: Arc<SelectorInner>, } pub struct SelectorInner { /// The actual completion port that's used to manage all I/O port: CompletionPort, /// A list of all registered handles with this selector. /// /// The key of this map is either a `SOCKET` or a `HANDLE`, and the value is /// `None` if the handle was registered with `oneshot` and it expired, or /// `Some` if the handle is registered and receiving events. handles: Mutex<HashMap<usize, Option<Registration>>>, /// A list of all active I/O operations currently on this selector. /// /// The key of this map is the address of the `OVERLAPPED` operation and the /// value is a completion callback to be invoked when it's done. Using raw /// pointers as keys here should be ok for two reasons: /// /// 1. The kernel already requires that the pointer to the `OVERLAPPED` is /// stable and valid for the entire duration of the I/O operation. /// 2. It is required that an `OVERLAPPED` instance is associated with at /// most one concurrent I/O operation. /// /// Consequently, an `OVERLAPPED` pointer should uniquely identify a pending /// I/O request and be valid while it's running. io: Mutex<HashMap<usize, Box<Callback>>>, /// A list of deferred events to be generated on the next call to `select`. /// /// Events can sometimes be generated without an associated I/O operation /// having completed, and this list is emptied out and returned on each turn /// of the event loop. defers: Mutex<Vec<(usize, EventSet, Token)>>, } #[derive(Copy, Clone)] struct Registration { token: Token, opts: PollOpt, interest: EventSet, } impl Selector { pub fn new() -> io::Result<Selector> { CompletionPort::new(1).map(|cp| { Selector { inner: Arc::new(SelectorInner { port: cp, handles: Mutex::new(HashMap::new()), io: Mutex::new(HashMap::new()), defers: Mutex::new(Vec::new()), }), } }) } pub fn select(&mut self, events: &mut Events, timeout_ms: usize) -> io::Result<()> { // If we have some deferred events then we only want to poll for I/O // events, so clamp the timeout to 0 in that case. let timeout = if self.inner.defers.lock().unwrap().len() > 0 { 0 } else { timeout_ms as u32 }; // Clear out the previous list of I/O events and get some more! events.events.truncate(0); let inner = self.inner.clone(); let n = match inner.port.get_many(&mut events.statuses, Some(timeout)) { Ok(statuses) => statuses.len(), Err(ref e) if e.raw_os_error() == Some(WAIT_TIMEOUT as i32) => 0, Err(e) => return Err(e), }; // First up, process all completed I/O events. Lookup the callback // associated with the I/O and invoke it. Also, carefully don't hold any // locks while we invoke a callback in case more I/O is scheduled to // prevent deadlock. // // Note that if we see an I/O completion with a null OVERLAPPED pointer // then it means it was our awakener, so just generate a readable // notification for it and carry on. let dst = &mut events.events; for status in events.statuses[..n].iter_mut() { if status.overlapped() as usize == 0 { dst.push(IoEvent::new(EventSet::readable(), Token(status.token()))); continue } let callback = inner.io.lock().unwrap() .remove(&(status.overlapped() as usize)) .expect("I/O finished with no handler"); callback.call(status, &mut |handle, set| { inner.push_event(dst, handle, set, Token(status.token())); }, self); } // Finally, clear out the list of deferred events and process them all // here. let defers = mem::replace(&mut *inner.defers.lock().unwrap(), Vec::new()); for (handle, set, token) in defers { inner.push_event(dst, handle as HANDLE, set, token); } Ok(()) } pub fn inner(&self) -> &Arc<SelectorInner> { &self.inner } } impl SelectorInner { pub fn port(&self) -> &CompletionPort { &self.port } /// Given a handle, token, and an event set describing how its ready, /// translate that to an `IoEvent` and process accordingly. /// /// This function will mask out all ignored events (e.g. ignore `writable` /// events if they weren't requested) and also handle properties such as /// `oneshot`. /// /// Eventually this function will probably also be modified to handle the /// `level()` polling option. fn push_event(&self, events: &mut Vec<IoEvent>, handle: HANDLE, set: EventSet, token: Token) { // A vacant handle means it's been deregistered, so just skip this // event. let mut handles = self.handles.lock().unwrap(); let mut e = match handles.entry(handle as usize) { Entry::Vacant(..) => return, Entry::Occupied(e) => e, }; // A handle in the map without a registration is one that's become idle // as a result of a `oneshot`, so just use a registration that will turn // this function into a noop. let reg = e.get().unwrap_or(Registration { token: Token(0), interest: EventSet::none(), opts: PollOpt::oneshot(), }); // If we're not actually interested in any of these events, // discard the event, and then if we're actually delivering an event we // stop listening if it's also a oneshot. let set = reg.interest & set; if set != EventSet::none() { events.push(IoEvent::new(set, token)); if reg.opts.is_oneshot() { trace!("deregistering because of oneshot"); e.insert(None); } } } pub fn register_socket(&self, socket: &AsRawSocket, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { if opts.contains(PollOpt::level()) { return Err(io::Error::new(io::ErrorKind::Other, "level opt not implemented on windows")) } else if !opts.contains(PollOpt::edge()) { return Err(other("must have edge opt")) } let mut handles = self.handles.lock().unwrap(); match handles.entry(socket.as_raw_socket() as usize) { Entry::Occupied(..) => return Err(other("socket already registered")), Entry::Vacant(v) => { try!(self.port.add_socket(token.as_usize(), socket)); v.insert(Some(Registration { token: token, interest: set2mask(interest), opts: opts, })); } } Ok(()) } pub fn reregister_socket(&self, socket: &AsRawSocket, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { if opts.contains(PollOpt::level()) { return Err(io::Error::new(io::ErrorKind::Other, "level opt not implemented on windows")) } else if !opts.contains(PollOpt::edge()) { return Err(other("must have edge opt")) } let mut handles = self.handles.lock().unwrap(); match handles.entry(socket.as_raw_socket() as usize) { Entry::Vacant(..) => return Err(other("socket not registered")), Entry::Occupied(mut v) => { match v.get().as_ref().map(|t| t.token) { Some(t) if t == token => {} Some(..) => return Err(other("cannot change tokens")), None => {} } v.insert(Some(Registration { token: token, interest: set2mask(interest), opts: opts, })); } } Ok(()) } pub fn deregister_socket(&self, socket: &AsRawSocket) -> io::Result<()> { // Note that we can't actually deregister the socket from the completion // port here, so we just remove our own internal metadata about it. let mut handles = self.handles.lock().unwrap(); match handles.entry(socket.as_raw_socket() as usize) { Entry::Vacant(..) => return Err(other("socket not registered")), Entry::Occupied(v) => { v.remove(); } } Ok(()) } /// Schedules some events for a handle to be delivered on the next turn of /// the event loop (without an associated I/O event). /// /// This function will discard this if: /// /// * The handle has been de-registered /// * The handle doesn't have an active registration (e.g. its oneshot /// expired) pub fn defer(&self, handle: HANDLE, set: EventSet) { debug!("defer {:?} {:?}", handle, set); let handles = self.handles.lock().unwrap(); let reg = handles.get(&(handle as usize)).and_then(|t| t.as_ref()) .map(|t| t.token); let token = match reg { Some(token) => token, None => return, }; self.defers.lock().unwrap().push((handle as usize, set, token)); } /// Register a callback to be executed after some I/O has been issued. /// /// Callbacks are keyed off the `OVERLAPPED` pointer (or in this case /// `wio::Overlapped`). The arguments to the callback are: /// /// * The status of the I/O operation (e.g. number of bytes transferred) /// * A thunk to invoke to generate `IoEvent` structures /// * The outer selector at the time of the I/O completion pub fn register<F>(&self, overlapped: *mut Overlapped, handler: F) where F: FnOnce(&CompletionStatus, &mut FnMut(HANDLE, EventSet), &mut Selector) + Send + Sync + 'static { let prev = self.io.lock().unwrap() .insert(overlapped as usize, Box::new(handler)); debug_assert!(prev.is_none()); } } /// From a given interest set return the event set mask used to generate events. /// /// The only currently interesting thing this function does is ensure that hup /// events are generated for interests that only include the readable event. fn set2mask(e: EventSet) -> EventSet { if e.is_readable() { e | EventSet::hup() } else { e } } fn other(s: &str) -> io::Error { io::Error::new(io::ErrorKind::Other, s) } #[derive(Debug)] pub struct Events { /// Raw I/O event completions are filled in here by the call to `get_many` /// on the completion port above. These are then postprocessed into the /// vector below. statuses: Box<[CompletionStatus]>, /// Literal events returned by `get` to the upwards `EventLoop` events: Vec<IoEvent>, } impl Events { pub fn new() -> Events { // Use a nice large space for receiving I/O events (currently the same // as unix's 1024) and then also prepare the output vector to have the // same space. // // Note that it's possible for the output `events` to grow beyond 1024 // capacity as it can also include deferred events, but that's certainly // not the end of the world! Events { statuses: vec![CompletionStatus::zero(); 1024].into_boxed_slice(), events: Vec::with_capacity(1024), } } pub fn len(&self) -> usize { self.events.len() } pub fn get(&self, idx: usize) -> IoEvent { self.events[idx] } } trait Callback: Send + Sync + 'static { fn call(self: Box<Self>, status: &CompletionStatus, push: &mut FnMut(HANDLE, EventSet), selector: &mut Selector); } impl<F> Callback for F where F: FnOnce(&CompletionStatus, &mut FnMut(HANDLE, EventSet), &mut Selector) + Send + Sync + 'static { fn call(self: Box<Self>, status: &CompletionStatus, push: &mut FnMut(HANDLE, EventSet), selector: &mut Selector) { (*self)(status, push, selector) } }
use model::controll::{ClientControll, ServerControll}; use model::session::Session; use tokio::prelude::*; use util::futu::*; pub trait IntoMachine where Self: Sized, { fn machine(self, name: String) -> Machine<Self> { Machine::new(self, name) } } impl<S> IntoMachine for S where S: Stream, { } pub struct Machine<S> { stream: S, state: Session, } impl<S> Machine<S> { pub fn new(stream: S, name: String) -> Self { let mut me = Self { stream, state: Session::new(), }; me.state.set_name(name); me } } impl<S> Stream for Machine<S> where S: Stream<Item = ServerControll>, { type Item = ClientControll; type Error = S::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { match self.state.answer() { Some(a) => { trace!("Answer: {:?}", a); return ok(a); } _ => {} }; match try_ready!(self.stream.poll()) { None => none(), Some(ctrl) => { trace!("Controll: {:?}", ctrl); self.state.controll(ctrl); match self.state.answer() { Some(a) => { trace!("Answer: {:?}", a); ok(a) } None => pending(), } } } } }
// PartialOrd is for the exercise. // Copy is for the list values function. // pub struct LinkedList<T: PartialOrd + Copy>(Option<(T, Box<LinkedList<T>>)>); impl<T: PartialOrd + Copy> LinkedList<T> { pub fn new() -> LinkedList<T> { LinkedList(None) } pub fn push_front(&mut self, data: T) { let previous = self.0.take(); self.0 = Some((data, Box::new(LinkedList(previous)))); } pub fn push_back_iterative(&mut self, data: T) { let mut current = self; while let Some((_, ref mut child)) = current.0 { current = child; } current.push_front(data); } pub fn push_back_recursive(&mut self, data: T) { match self.0 { Some((_, ref mut child)) => child.push_back_recursive(data), None => self.push_front(data), } } // Exercise // pub fn sorted_push_iterative(&mut self, value: T) { let mut current = self; loop { // The split `Some` arms are required due to limitations of the BCK; with Polonius, the // code works with a single `Some` arm. // match current.0 { Some((ref current_value, _)) if *current_value > value => { break; } Some((_, ref mut child)) => { current = child; } _ => { break; } } } current.push_front(value); } pub fn values(&self) -> Vec<T> { let mut values = vec![]; let mut current = self; while let Some((ref child_data, ref child)) = current.0 { values.push(*child_data); current = child; } values } } #[cfg(test)] mod tests { use super::*; #[test] fn test_push_back_iterative() { let values = vec![ 1273, 18273, 8273, 827, 11, 213, 9172397, 2373, 2, 4, 20983, 29831093, 287, 2837, 11, 92900, ]; let mut list = LinkedList::new(); for value in &values { list.push_back_iterative(*value); } assert_eq!(list.values()[..], values[..]); } #[test] fn sorted_insert() { let values = vec![ 1273, 18273, 8273, 827, 11, 213, 9172397, 2373, 2, 4, 20983, 29831093, 287, 2837, 11, 92900, ]; let mut sorted_values = values.clone(); sorted_values.sort(); let mut list = LinkedList::new(); for value in values { list.sorted_push_iterative(value); } assert_eq!(list.values()[..], sorted_values[..]); } }
use crate::render::{DrawCtx, DrawTurn}; use ezgui::{ Color, EventCtx, GeomBatch, GfxCtx, Line, ModalMenu, ScreenDims, ScreenPt, Scroller, Text, }; use geom::{Circle, Distance, Duration, PolyLine, Polygon, Pt2D}; use map_model::{Cycle, IntersectionID, Map, TurnPriority, TurnType, LANE_THICKNESS}; use ordered_float::NotNan; // Only draws a box when time_left is present pub fn draw_signal_cycle( cycle: &Cycle, time_left: Option<Duration>, batch: &mut GeomBatch, ctx: &DrawCtx, ) { if false { draw_signal_cycle_with_icons(cycle, batch, ctx); return; } let priority_color = ctx .cs .get_def("turns protected by traffic signal right now", Color::GREEN); let yield_color = ctx.cs.get_def( "turns allowed with yielding by traffic signal right now", Color::rgba(255, 105, 180, 0.8), ); for (id, crosswalk) in &ctx.draw_map.get_i(cycle.parent).crosswalks { if cycle.get_priority(*id) == TurnPriority::Priority { batch.append(crosswalk); } } for t in &cycle.priority_turns { let turn = ctx.map.get_t(*t); if !turn.between_sidewalks() { DrawTurn::full_geom(turn, batch, priority_color); } } for t in &cycle.yield_turns { let turn = ctx.map.get_t(*t); // Lane-changing as yield is implied and very messy to show. if !turn.between_sidewalks() && turn.turn_type != TurnType::LaneChangeLeft && turn.turn_type != TurnType::LaneChangeRight { DrawTurn::outline_geom(turn, batch, yield_color); } } if time_left.is_none() { return; } let radius = Distance::meters(0.5); let box_width = 2.5 * radius; let box_height = 6.5 * radius; let center = ctx.map.get_i(cycle.parent).polygon.center(); let top_left = center.offset(-box_width / 2.0, -box_height / 2.0); let percent = time_left.unwrap() / cycle.duration; // TODO Tune colors. batch.push( ctx.cs.get_def("traffic signal box", Color::grey(0.2)), Polygon::rectangle_topleft(top_left, box_width, box_height), ); batch.push( Color::RED, Circle::new(center.offset(Distance::ZERO, -2.0 * radius), radius).to_polygon(), ); batch.push(Color::grey(0.4), Circle::new(center, radius).to_polygon()); batch.push( Color::YELLOW, Circle::new(center, radius).to_partial_polygon(percent), ); batch.push( Color::GREEN, Circle::new(center.offset(Distance::ZERO, 2.0 * radius), radius).to_polygon(), ); } fn draw_signal_cycle_with_icons(cycle: &Cycle, batch: &mut GeomBatch, ctx: &DrawCtx) { for l in &ctx.map.get_i(cycle.parent).incoming_lanes { let lane = ctx.map.get_l(*l); // TODO Show a hand or a walking sign for crosswalks if lane.is_parking() || lane.is_sidewalk() { continue; } let lane_line = lane.last_line(); let mut _right_ok = true; // if not, no right turn on red let mut straight_green = true; // if not, the main light is red // TODO Multiple lefts? let mut left_priority: Option<TurnPriority> = None; for (turn, _) in ctx.map.get_next_turns_and_lanes(lane.id, cycle.parent) { match turn.turn_type { TurnType::SharedSidewalkCorner | TurnType::Crosswalk => unreachable!(), TurnType::Right => { if cycle.get_priority(turn.id) == TurnPriority::Banned { _right_ok = false; } } TurnType::Straight | TurnType::LaneChangeLeft | TurnType::LaneChangeRight => { // TODO Can we ever have Straight as Yield? if cycle.get_priority(turn.id) == TurnPriority::Banned { straight_green = false; } } TurnType::Left => { left_priority = Some(cycle.get_priority(turn.id)); } }; } let radius = LANE_THICKNESS / 2.0; // TODO Ignore right_ok... { let center1 = lane_line.unbounded_dist_along(lane_line.length() + radius); let color = if straight_green { ctx.cs.get_def("traffic light go", Color::GREEN) } else { ctx.cs.get_def("traffic light stop", Color::RED) }; batch.push(color, Circle::new(center1, radius).to_polygon()); } if let Some(pri) = left_priority { let center2 = lane_line.unbounded_dist_along(lane_line.length() + (radius * 3.0)); let color = match pri { TurnPriority::Priority => ctx.cs.get("traffic light go"), // TODO flashing green TurnPriority::Yield => ctx.cs.get_def("traffic light permitted", Color::YELLOW), TurnPriority::Banned => ctx.cs.get("traffic light stop"), TurnPriority::Stop => unreachable!(), }; batch.push( ctx.cs.get_def("traffic light box", Color::BLACK), Circle::new(center2, radius).to_polygon(), ); batch.push( color, PolyLine::new(vec![ center2.project_away(radius, lane_line.angle().rotate_degs(90.0)), center2.project_away(radius, lane_line.angle().rotate_degs(-90.0)), ]) .make_arrow(Distance::meters(0.1)) .unwrap(), ); } } } const PADDING: f64 = 5.0; const ZOOM: f64 = 10.0; pub struct TrafficSignalDiagram { pub i: IntersectionID, labels: Vec<Text>, top_left: Pt2D, intersection_width: f64, // TODO needed? // The usizes are cycle indices scroller: Scroller<usize>, } impl TrafficSignalDiagram { pub fn new( i: IntersectionID, current_cycle: usize, map: &Map, ctx: &EventCtx, ) -> TrafficSignalDiagram { let (top_left, intersection_width, intersection_height) = { let b = map.get_i(i).polygon.get_bounds(); ( Pt2D::new(b.min_x, b.min_y), b.max_x - b.min_x, // Vertically pad b.max_y - b.min_y, ) }; let cycles = &map.get_traffic_signal(i).cycles; // Precalculate maximum text width. let mut labels = Vec::new(); for (idx, cycle) in cycles.iter().enumerate() { labels.push(Text::from(Line(format!( "Cycle {}: {}", idx + 1, cycle.duration )))); } let label_length = labels .iter() .map(|l| ctx.canvas.text_dims(l).0) .max_by_key(|w| NotNan::new(*w).unwrap()) .unwrap(); let item_dims = ScreenDims::new( (intersection_width * ZOOM) + label_length + 10.0, (PADDING + intersection_height) * ZOOM, ); let scroller = Scroller::new( ScreenPt::new(0.0, 0.0), std::iter::repeat(item_dims) .take(cycles.len()) .enumerate() .collect(), current_cycle, ); TrafficSignalDiagram { i, labels, top_left, intersection_width, scroller, } } pub fn event(&mut self, ctx: &mut EventCtx, menu: &mut ModalMenu) { self.scroller.event(ctx); if self.scroller.current_idx() != 0 && menu.action("select previous cycle") { self.scroller.select_previous(); return; } if self.scroller.current_idx() != self.scroller.num_items() - 1 && menu.action("select next cycle") { self.scroller.select_next(ctx.canvas); return; } } pub fn current_cycle(&self) -> usize { self.scroller.current_idx() } pub fn draw(&self, g: &mut GfxCtx, ctx: &DrawCtx) { let cycles = &ctx.map.get_traffic_signal(self.i).cycles; for (idx, rect) in self.scroller.draw(g) { g.fork(self.top_left, ScreenPt::new(rect.x1, rect.y1), ZOOM); let mut batch = GeomBatch::new(); draw_signal_cycle(&cycles[idx], None, &mut batch, ctx); batch.draw(g); g.draw_text_at_screenspace_topleft( &self.labels[idx], // TODO The x here is weird... ScreenPt::new(10.0 + (self.intersection_width * ZOOM), rect.y1), ); } g.unfork(); } }
use ::glutin_window::{GlutinWindow}; use ::conrod; use ::opengl_graphics::glyph_cache::GlyphCache; use ::opengl_graphics::{OpenGL, GlGraphics}; use ::sheet::{Coord, Value, Formula}; use ::std::sync::mpsc::{sync_channel, Receiver, SyncSender}; use ::std::sync::Mutex; const WINDOW_WIDTH: u32 = 800; const WINDOW_HEIGHT: u32 = 600; const CELL_WIDTH: usize = WINDOW_WIDTH as usize / 5; const CELL_HEIGHT: usize = WINDOW_HEIGHT as usize / 20; const GRID_COLUMNS: usize = WINDOW_WIDTH as usize / CELL_WIDTH - 1; const GRID_ROWS: usize = WINDOW_HEIGHT as usize / CELL_HEIGHT - 1; const NUM_CELLS: usize = GRID_COLUMNS * GRID_ROWS; const TEXTBOX_ID: usize = NUM_CELLS + 1; struct CellGrid(Vec<Option<String>>); impl CellGrid { fn new() -> Self { let mut m = Vec::with_capacity(NUM_CELLS); for _ in 0 .. m.capacity() { m.push(None); } CellGrid(m) } fn get_str(&self, col: usize, row: usize) -> &str { match self[Coord(col, row)] { Some(ref x) => x.as_str(), None => "" } } fn set<'a, 'b>(&'a mut self, coord: Coord, val: &'b str) { self[coord] = match val { "" => None, x => Some(x.to_string()), } } } impl ::std::ops::Index<Coord> for CellGrid { type Output = Option<String>; fn index<'a>(&'a self, Coord(col, row): Coord) -> &'a Self::Output { let &CellGrid(ref m) = self; &m[col * GRID_ROWS + row] } } impl ::std::ops::IndexMut<Coord> for CellGrid { fn index_mut<'a>(&'a mut self, Coord(col, row): Coord) -> &'a mut Self::Output { let &mut CellGrid(ref mut m) = self; &mut m[col * GRID_ROWS + row] } } struct State { editing: Option<Coord>, editing_text: String, } pub fn run<F>(sheet_select: &mut F, event_stream: SyncSender<UIEvent>) where F: Send + FnMut(Coord, Coord) -> Receiver<(Coord, Value)> { use event::*; let grid = Mutex::new(CellGrid::new()); let grid_ref = &grid; let (events_sender, events_recv) = sync_channel(0); let guard = ::std::thread::scoped(move|| { let sheet_selection = sheet_select(Coord(0, 0), Coord(GRID_COLUMNS-1, GRID_ROWS-1)); let mut running = true; while running { select! { x = events_recv.recv() => { match x { Ok(x) => if let Err(_) = event_stream.send(x) { running = false; }, Err(_) => { running = false; }, } }, x = sheet_selection.recv() => { match x { Ok((Coord(col, row), value)) => { let mut g = grid_ref.lock().unwrap(); match value { Ok(v) => { g.set(Coord(col, row), ::parser::format_formula(&Formula::Atom(*v)).as_str()); }, Err(x) => { g.set(Coord(col, row), format!("<E:{:?}>", x).as_str()) } } }, Err(_) => { running = false; }, } } }; }; }); let mut state = State{ editing: None, editing_text: "".to_string(), }; let opengl = OpenGL::_3_2; let window = make_window(opengl); let mut ui = make_ui(); let mut gl = GlGraphics::new(opengl); let event_iter = window.events().ups(180).max_fps(60); for event in event_iter { ui.handle_event(&event); if let Some(args) = event.render_args() { gl.draw(args.viewport(), |_, gl| { draw_ui(gl, &mut ui, &*grid.lock().unwrap(), &mut state, &events_sender); }); } } guard.join(); } fn make_window(opengl: OpenGL) -> GlutinWindow { use glutin_window::GlutinWindow; use window::{WindowSettings, Size}; GlutinWindow::new( opengl, WindowSettings::new( "Sheets".to_string(), Size{width: WINDOW_WIDTH, height: WINDOW_HEIGHT} ) ) } fn make_ui<'a>() -> conrod::Ui<GlyphCache<'a>> { use std::path::Path; use opengl_graphics::glyph_cache::GlyphCache; let font_path = Path::new("./assets/NotoSans-Regular.ttf"); let theme = conrod::Theme::default(); let glyph_cache = GlyphCache::new(&font_path).unwrap(); conrod::Ui::new(glyph_cache, theme) } fn draw_ui<'a>(gl: &mut GlGraphics, ui: &mut conrod::Ui<GlyphCache<'a>>, grid: &CellGrid, state: &mut State, events: &SyncSender<UIEvent>) { use conrod::{Background, Colorable, WidgetMatrix, Button, Labelable, Positionable, Sizeable, Widget, TextBox}; Background::new().rgb(1.0, 1.0, 1.0).draw(ui, gl); WidgetMatrix::new(GRID_COLUMNS, GRID_ROWS) .xy(0.0, 0.0) .dimensions(WINDOW_WIDTH as f64, WINDOW_HEIGHT as f64) .each_widget(ui, |ui, num, col, row, pos, dim| { let &mut State{ref mut editing, ref mut editing_text} = state; Button::new() .label(grid.get_str(col, row)) .point(pos) .dim(dim) .react(|| { *editing = Some(Coord(col, row)); *editing_text = grid.get_str(col, row).to_string(); }) .enabled(if let Some(_) = state.editing { false } else { true }) .set(num, ui); }); if let Some(coord) = state.editing { let &mut State{ref mut editing, ref mut editing_text} = state; TextBox::new(editing_text) .middle() .width(500.0).height(100.0) .react(|s: &mut String| { println!("REACT {}", s); match ::parser::parse_formula(s.as_str()) { Ok(f) => { events.send(UIEvent::EditCell(coord, Box::new(f))).unwrap(); *editing = None; }, Err(x) => println!("{}", x), } }) .set(TEXTBOX_ID, ui); } ui.draw(gl); } pub enum UIEvent { EditCell(Coord, Box<Formula>), }
#![doc = include_str!("multi_view_open_exr.md")]
/// Parts contained within an Envelope. This is used to tell if an encrypted /// message was successfully decrypted, by decrypting the envelope body and checking /// if deserialization succeeds. #[derive(Clone, PartialEq, ::prost::Message)] pub struct EnvelopeBody { #[prost(bytes, repeated, tag = "1")] pub parts: ::std::vec::Vec<std::vec::Vec<u8>>, }
pub mod force; pub mod grouping; use crate::force::group_many_body_force::GroupManyBodyForceArgument; use petgraph::graph::{Graph, IndexType, NodeIndex}; use petgraph::EdgeType; use petgraph_layout_force::link_force::LinkArgument; use petgraph_layout_force_simulation::{Force, Point}; use std::collections::HashMap; pub fn force_grouped< N, E, Ty: EdgeType, Ix: IndexType, F: FnMut(&Graph<N, E, Ty, Ix>, NodeIndex<Ix>) -> usize, >( graph: &Graph<N, E, Ty, Ix>, mut group_accessor: F, ) -> Vec<Box<dyn Force>> { let groups = graph .node_indices() .map(|u| (u, group_accessor(graph, u))) .collect::<HashMap<_, _>>(); let group_pos = grouping::force_directed_grouping(graph, |_, u| groups[&u]); vec![ Box::new(force::GroupManyBodyForce::new(&graph, |_, u| { GroupManyBodyForceArgument { group: groups[&u], strength: Some(-30.), } })), Box::new(force::GroupLinkForce::new( &graph, |_, u| groups[&u], |_, _| LinkArgument { distance: Some(30.), strength: Some(0.1), }, |_, _| LinkArgument { distance: Some(30.), strength: Some(0.01), }, )), Box::new(force::GroupPositionForce::new( &graph, |_, u| force::group_position_force::NodeArgument { group: groups[&u], strength: 0.1, }, |_, g| force::group_position_force::GroupArgument { x: group_pos[&g].x, y: group_pos[&g].y, }, )), // Box::new(force::GroupCenterForce::new( // &graph, // |_, u| groups[&u], // |g| group_pos[&g].x, // |g| group_pos[&g].y, // )), ] }
mod upc; fn main() { let input = std::env::args().nth(1).expect("arg1 should be the UPC to calculate the check digit for"); println!("{}", upc::calc_check_digit(&input)); } #[cfg(test)] mod tests { use super::upc::calc_check_digit; #[test] fn test_upc() { assert_eq!(calc_check_digit("4210000526"), 4); assert_eq!(calc_check_digit("3600029145"), 2); assert_eq!(calc_check_digit("12345678910"), 4); assert_eq!(calc_check_digit("1234567"), 0); } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::{ buffer_writer::{BufferWriter, ByteSliceMut, LayoutVerified}, mac::{ self, Addr4, DataHdr, FrameControl, HtControl, QosControl, RawHtControl, RawQosControl, }, }, failure::{ensure, Error}, }; type MacAddr = [u8; 6]; #[derive(PartialEq)] pub struct FixedFields { pub frame_ctrl: FrameControl, pub addr1: MacAddr, pub addr2: MacAddr, pub addr3: MacAddr, pub seq_ctrl: u16, } impl FixedFields { pub fn sent_from_client( mut frame_ctrl: FrameControl, bssid: MacAddr, client_addr: MacAddr, seq_ctrl: u16, ) -> FixedFields { frame_ctrl.set_to_ds(true); FixedFields { frame_ctrl, addr1: bssid.clone(), addr2: client_addr, addr3: bssid, seq_ctrl } } } impl std::fmt::Debug for FixedFields { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { writeln!( f, "fc: {:#b}, addr1: {:02X?}, addr2: {:02X?}, addr3: {:02X?}, seq: {}", self.frame_ctrl.value(), self.addr1, self.addr2, self.addr3, self.seq_ctrl )?; Ok(()) } } pub struct OptionalFields { pub addr4: Option<Addr4>, pub qos_ctrl: Option<QosControl>, pub ht_ctrl: Option<HtControl>, } impl OptionalFields { pub fn none() -> OptionalFields { OptionalFields { addr4: None, qos_ctrl: None, ht_ctrl: None } } } pub fn write_data_hdr<B: ByteSliceMut>( w: BufferWriter<B>, mut fixed: FixedFields, optional: OptionalFields, ) -> Result<BufferWriter<B>, Error> { fixed.frame_ctrl.set_frame_type(mac::FRAME_TYPE_DATA); if optional.addr4.is_some() { fixed.frame_ctrl.set_from_ds(true); fixed.frame_ctrl.set_to_ds(true); } else { ensure!( fixed.frame_ctrl.from_ds() != fixed.frame_ctrl.to_ds(), "addr4 is absent but to- and from-ds bit are present" ); } if optional.qos_ctrl.is_some() { fixed.frame_ctrl.set_frame_subtype(fixed.frame_ctrl.frame_subtype() | mac::BITMASK_QOS); } else { ensure!( fixed.frame_ctrl.frame_subtype() & mac::BITMASK_QOS == 0, "QoS bit set while QoS-Control is absent" ); } if optional.ht_ctrl.is_some() { fixed.frame_ctrl.set_htc_order(true); } else { ensure!(!fixed.frame_ctrl.htc_order(), "htc_order bit set while HT-Control is absent"); } let (mut data_hdr, mut w) = w.reserve_zeroed::<DataHdr>()?; data_hdr.set_frame_ctrl(fixed.frame_ctrl.value()); data_hdr.addr1 = fixed.addr1; data_hdr.addr2 = fixed.addr2; data_hdr.addr3 = fixed.addr3; data_hdr.set_seq_ctrl(fixed.seq_ctrl); let mut w = match optional.addr4 { None => w, Some(addr4_value) => { let (mut addr4, mut w) = w.reserve_zeroed::<Addr4>()?; *addr4 = addr4_value; w } }; let mut w = match optional.qos_ctrl { None => w, Some(qos_ctrl_bitfield) => { let (mut qos_ctrl, mut w) = w.reserve_zeroed::<RawQosControl>()?; qos_ctrl.set(qos_ctrl_bitfield.value()); w } }; let mut w = match optional.ht_ctrl { None => w, Some(ht_ctrl_bitfield) => { let (mut ht_ctrl, mut w) = w.reserve_zeroed::<RawHtControl>()?; ht_ctrl.set(ht_ctrl_bitfield.value()); w } }; Ok(w) } pub fn write_snap_llc_hdr<B: ByteSliceMut>( w: BufferWriter<B>, protocol_id: u16, ) -> Result<BufferWriter<B>, Error> { let (mut llc_hdr, w) = w.reserve_zeroed::<mac::LlcHdr>()?; llc_hdr.dsap = mac::LLC_SNAP_EXTENSION; llc_hdr.ssap = mac::LLC_SNAP_EXTENSION; llc_hdr.control = mac::LLC_SNAP_UNNUMBERED_INFO; llc_hdr.oui = mac::LLC_SNAP_OUI; llc_hdr.set_protocol_id(protocol_id); Ok(w) } #[cfg(test)] mod tests { use super::*; #[test] fn fixed_fields_sent_from_client() { let got = FixedFields::sent_from_client(FrameControl(0b00110000_00110000), [1; 6], [2; 6], 4321); let expected = FixedFields { frame_ctrl: FrameControl(0b00110001_00110000), addr1: [1; 6], addr2: [2; 6], addr3: [1; 6], seq_ctrl: 4321, }; assert_eq!(got, expected); } #[test] fn too_small_buffer() { let mut bytes = vec![0u8; 20]; let result = write_data_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110001_00110000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, OptionalFields::none(), ); assert!(result.is_err(), "expected failure when writing into too small buffer"); } #[test] fn invalid_ht_configuration() { let mut bytes = vec![0u8; 30]; let result = write_data_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b10110001_00110000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, OptionalFields::none(), ); assert!(result.is_err(), "expected failure due to invalid ht configuration"); } #[test] fn invalid_addr4_configuration() { let mut bytes = vec![0u8; 30]; let result = write_data_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110011_00110000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, OptionalFields::none(), ); assert!(result.is_err(), "expected failure due to invalid addr4 configuration"); } #[test] fn invalid_qos_configuration() { let mut bytes = vec![0u8; 30]; let result = write_data_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110000_10110000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, OptionalFields::none(), ); assert!(result.is_err(), "expected failure due to invalid qos configuration"); } #[test] fn write_fixed_fields_only() { let mut bytes = vec![0u8; 30]; let w = write_data_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110001_0011_00_00), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, OptionalFields::none(), ) .expect("Failed writing data frame"); assert_eq!(w.written_bytes(), 24); #[rustfmt::skip] assert_eq!( bytes, [ // Data Header 0b0011_10_00u8, 0b00110001, // Frame Control 0, 0, // duration 1, 1, 1, 1, 1, 1, // addr1 2, 2, 2, 2, 2, 2, // addr2 3, 3, 3, 3, 3, 3, // addr3 0b10010000, 0b11000000, // Sequence Control // Trailing bytes 0, 0, 0, 0, 0, 0, ] ); } #[test] fn write_addr4_ht_ctrl() { let mut bytes = vec![0u8; 35]; let w = write_data_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110001_00111000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, OptionalFields { addr4: Some([4u8; 6]), qos_ctrl: None, ht_ctrl: Some(HtControl(0b10101111_11000011_11110000_10101010)), }, ) .expect("Failed writing data frame"); assert_eq!(w.written_bytes(), 34); #[rustfmt::skip] assert_eq!( &bytes[..], &[ // Data Header 0b00111000u8, 0b10110011, // Frame Control 0, 0, // duration 1, 1, 1, 1, 1, 1, // addr1 2, 2, 2, 2, 2, 2, // addr2 3, 3, 3, 3, 3, 3, // addr3 0b10010000, 0b11000000, // Sequence Control // Addr4 4, 4, 4, 4, 4, 4, // Ht Control 0b10101010, 0b11110000, 0b11000011, 0b10101111, // Trailing byte 0, ][..] ); } #[test] fn write_qos_ctrl() { let mut bytes = vec![0u8; 30]; let w = write_data_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110001_00111000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, OptionalFields { addr4: None, qos_ctrl: Some(QosControl(0b11110000_10101010)), ht_ctrl: None, }, ) .expect("Failed writing data frame"); assert_eq!(w.written_bytes(), 26); #[rustfmt::skip] assert_eq!( &bytes[..], &[ // Data Header 0b10111000u8, 0b00110001, // Frame Control 0, 0, // duration 1, 1, 1, 1, 1, 1, // addr1 2, 2, 2, 2, 2, 2, // addr2 3, 3, 3, 3, 3, 3, // addr3 0b10010000, 0b11000000, // Sequence Control // Qos Control 0b10101010, 0b11110000, // Trailing bytes 0, 0, 0, 0, ][..] ); } #[test] fn write_llc_hdr() { let mut bytes = vec![0u8; 10]; let w = write_snap_llc_hdr(BufferWriter::new(&mut bytes[..]), 0x888E) .expect("Failed writing LLC header"); assert_eq!(w.written_bytes(), 8); #[rustfmt::skip] assert_eq!( bytes, [ 0xAA, 0xAA, 0x03, // DSAP, SSAP, Control 0, 0, 0, // OUI 0x88, 0x8E, // Protocol ID // Trailing bytes 0, 0, ] ); } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::_3_FLTSEN { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct PWM_3_FLTSEN_FAULT0R { bits: bool, } impl PWM_3_FLTSEN_FAULT0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _PWM_3_FLTSEN_FAULT0W<'a> { w: &'a mut W, } impl<'a> _PWM_3_FLTSEN_FAULT0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_FLTSEN_FAULT1R { bits: bool, } impl PWM_3_FLTSEN_FAULT1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _PWM_3_FLTSEN_FAULT1W<'a> { w: &'a mut W, } impl<'a> _PWM_3_FLTSEN_FAULT1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_FLTSEN_FAULT2R { bits: bool, } impl PWM_3_FLTSEN_FAULT2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _PWM_3_FLTSEN_FAULT2W<'a> { w: &'a mut W, } impl<'a> _PWM_3_FLTSEN_FAULT2W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_FLTSEN_FAULT3R { bits: bool, } impl PWM_3_FLTSEN_FAULT3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _PWM_3_FLTSEN_FAULT3W<'a> { w: &'a mut W, } impl<'a> _PWM_3_FLTSEN_FAULT3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Fault0 Sense"] #[inline(always)] pub fn pwm_3_fltsen_fault0(&self) -> PWM_3_FLTSEN_FAULT0R { let bits = ((self.bits >> 0) & 1) != 0; PWM_3_FLTSEN_FAULT0R { bits } } #[doc = "Bit 1 - Fault1 Sense"] #[inline(always)] pub fn pwm_3_fltsen_fault1(&self) -> PWM_3_FLTSEN_FAULT1R { let bits = ((self.bits >> 1) & 1) != 0; PWM_3_FLTSEN_FAULT1R { bits } } #[doc = "Bit 2 - Fault2 Sense"] #[inline(always)] pub fn pwm_3_fltsen_fault2(&self) -> PWM_3_FLTSEN_FAULT2R { let bits = ((self.bits >> 2) & 1) != 0; PWM_3_FLTSEN_FAULT2R { bits } } #[doc = "Bit 3 - Fault3 Sense"] #[inline(always)] pub fn pwm_3_fltsen_fault3(&self) -> PWM_3_FLTSEN_FAULT3R { let bits = ((self.bits >> 3) & 1) != 0; PWM_3_FLTSEN_FAULT3R { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Fault0 Sense"] #[inline(always)] pub fn pwm_3_fltsen_fault0(&mut self) -> _PWM_3_FLTSEN_FAULT0W { _PWM_3_FLTSEN_FAULT0W { w: self } } #[doc = "Bit 1 - Fault1 Sense"] #[inline(always)] pub fn pwm_3_fltsen_fault1(&mut self) -> _PWM_3_FLTSEN_FAULT1W { _PWM_3_FLTSEN_FAULT1W { w: self } } #[doc = "Bit 2 - Fault2 Sense"] #[inline(always)] pub fn pwm_3_fltsen_fault2(&mut self) -> _PWM_3_FLTSEN_FAULT2W { _PWM_3_FLTSEN_FAULT2W { w: self } } #[doc = "Bit 3 - Fault3 Sense"] #[inline(always)] pub fn pwm_3_fltsen_fault3(&mut self) -> _PWM_3_FLTSEN_FAULT3W { _PWM_3_FLTSEN_FAULT3W { w: self } } }
//! **S**tructured **r**epresentation of various SPIR-V language constructs. pub use self::autogen_decoration::Decoration; pub use self::autogen_instructions as instructions; pub use self::autogen_ops as ops; pub use self::constants::Constant; pub use self::types::{StructMember, Type}; mod autogen_decoration; pub mod autogen_instructions; pub mod autogen_ops; mod constants; pub mod module; pub mod storage; mod types;
use std::collections::HashSet; use chrono::offset::{FixedOffset, TimeZone}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Addr, Api, Coin, Uint128}; use cw0::Expiration; use crate::cron::CronCompiled; use crate::error::ContractError; const MAX_DESCRIPTION_LENGTH: usize = 5000; const MAX_TITLE_LENGTH: usize = 140; #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] pub struct Params { /// Minimal native tokens deposit need for each plan, will refunded after deleted pub required_deposit_plan: Vec<Coin>, /// Minimal native tokens deposit need for each subscription, will refunded after deleted pub required_deposit_subscription: Vec<Coin>, } fn has_duplicate_denom(items: &[Coin]) -> bool { let set = items.iter().map(|coin| &coin.denom).collect::<HashSet<_>>(); set.len() != items.len() } impl Params { pub fn validate(&self) -> Result<(), ContractError> { if has_duplicate_denom(&self.required_deposit_plan) { return Err(ContractError::InvalidCoins); } if has_duplicate_denom(&self.required_deposit_subscription) { return Err(ContractError::InvalidCoins); } if self .required_deposit_plan .iter() .any(|coin| coin.amount == 0u128.into()) { return Err(ContractError::InvalidCoins); } if self .required_deposit_subscription .iter() .any(|coin| coin.amount == 0u128.into()) { return Err(ContractError::InvalidCoins); } Ok(()) } } #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] pub struct InitMsg { pub params: Params, } #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] pub enum ExecuteMsg { /// create plan, sender will be the plan owner CreatePlan(PlanContent<String>), /// stop plan, sender must be the plan owner StopPlan { plan_id: Uint128 }, /// sender subscribe to some plan /// If expiration is set, update if subscription exists Subscribe { plan_id: Uint128, expires: Expiration, next_collection_time: i64, }, /// sender unsubscribe to some plan Unsubscribe { plan_id: Uint128 }, /// Stop subscription on user's behalf, sender must be the plan owner UnsubscribeUser { plan_id: Uint128, subscriber: String, }, /// Update expires of subscription UpdateExpires { plan_id: Uint128, expires: Expiration, }, /// Trigger collection of a batch of subscriptions Collection { items: Vec<CollectOne> }, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] pub struct PlanContent<A> { pub title: String, pub description: String, /// cw20 token address pub token: A, /// Amount to be collected for each period pub amount: Uint128, /// Crontab like specification for the plan pub cron: CronCompiled, /// timezone for the crontab logic pub tzoffset: i32, } impl PlanContent<String> { pub fn validate(self, api: &dyn Api) -> Result<PlanContent<Addr>, ContractError> { if self.title.len() > MAX_TITLE_LENGTH { return Err(ContractError::TitleTooLong); } if self.description.len() > MAX_DESCRIPTION_LENGTH { return Err(ContractError::DescriptionTooLong); } FixedOffset::east_opt(self.tzoffset).ok_or(ContractError::InvalidTimeZoneOffset)?; let token = api.addr_validate(&self.token)?; Ok(PlanContent::<Addr> { title: self.title, description: self.description, token, amount: self.amount, cron: self.cron, tzoffset: self.tzoffset, }) } } impl<A> PlanContent<A> { pub fn verify_timestamp(&self, ts: i64) -> bool { let datetime = FixedOffset::east(self.tzoffset) .timestamp(ts, 0) .naive_utc(); self.cron.verify(datetime) } } #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] pub struct CollectOne { pub plan_id: Uint128, pub subscriber: String, pub current_collection_time: i64, pub next_collection_time: i64, }
use super::period::Period; #[derive(Debug, Clone)] pub struct TaskData { pub name: String, pub count: i32, pub period: Period, }
//! ttyecho is a crate that lets you write data into a Linux kernel pseudoterminal buffer. //! This crate will not work on a non-Linux platform. //! //! # Example //! //! ```rust //! fn main() { //! // You can put whatever you want, not only commands. //! let command = "echo ttyecho!"; //! // Target tty //! let tty = "/dev/pts/27"; //! // We want to append new line as we want to run echo without user interaction. //! let append_new_line = true; //! //! ttyecho(tty, command, append_new_line); //! } //! ``` //! #[cfg(target_os = "linux")] use libc::{ ioctl, open, close, TIOCSTI, O_RDWR }; /// Appends given data into given pseudoterminal buffer by using [ioctl] syscall with [TIOCSTI] parameter. /// It will append a null terminator to the tty path if there isn't one, /// because most libc functions expect strings to be null terminated. #[allow(unused_variables)] pub fn ttyecho<S: Into<String>>(tty: S, data: S, new_line: bool) { #[cfg(target_os = "linux")] { let mut tty = tty.into(); let mut command = data.into(); if ! tty.ends_with('\0') { tty.push('\0'); } if new_line && ! command.ends_with('\0') { command.push('\r'); } unsafe { let fd = open(tty.as_ptr() as *const i8, O_RDWR); for ch in command.as_bytes() { ioctl(fd, TIOCSTI, ch); } close(fd); } } }
pub use VkSubpassContents::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkSubpassContents { VK_SUBPASS_CONTENTS_INLINE = 0, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS = 1, }
use crate::{ ast::{self, AstNode}, T, }; use crate::{SmolStr, SyntaxNode}; impl ast::Name { pub fn text(&self) -> &SmolStr { text_of_first_token(self.syntax()) } } impl ast::NameRef { pub fn text(&self) -> &SmolStr { text_of_first_token(self.syntax()) } } fn text_of_first_token(node: &SyntaxNode) -> &SmolStr { match node.0.green().children().first() { Some(rowan::GreenElement::Token(it)) => it.text(), _ => panic!(), } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum PathSegmentKind { Name(ast::NameRef), SelfKw, SuperKw, } impl ast::PathSegment { pub fn parent_path(&self) -> ast::Path { self.syntax() .parent() .and_then(ast::Path::cast) .expect("segments are always nested in paths") } pub fn kind(&self) -> Option<PathSegmentKind> { let res = if let Some(name_ref) = self.name_ref() { PathSegmentKind::Name(name_ref) } else { match self.syntax().first_child_or_token()?.kind() { T![self] => PathSegmentKind::SelfKw, T![super] => PathSegmentKind::SuperKw, _ => return None, } }; Some(res) } pub fn has_colon_colon(&self) -> bool { match self.syntax.first_child_or_token().map(|s| s.kind()) { Some(T![::]) => true, _ => false, } } }
// https://www.reddit.com/r/rust/comments/d5i74n/accessing_zipped_file/ use std::fs::File; // use std::fs; fn doit() -> zip::result::ZipResult<()> { use std::io::prelude::*; let mut f = File::open("download.zip")?; let mut zip = zip::ZipArchive::new(f)?; for i in 0..zip.len() { if i == 0 { let mut buffer = String::new(); zip.by_index(0).unwrap().read_to_string(&mut buffer) .expect("Something went wrong reading the file"); println!("With text:\n{:?}", buffer); } let mut file = zip.by_index(i).unwrap(); println!("Filename: {}", file.name()); let first_byte = file.bytes().next().unwrap()?; println!("{}", first_byte); } Ok(()) } fn main() { doit(); }
// Name: Farhan Sami // RSN: 500892031 pub fn deal(cards:[u32;10]) -> [String;5] { let mut hand1:[u32;5] = [cards[0],cards[2],cards[4],cards[6],cards[8]]; let mut hand2:[u32;5] = [cards[1],cards[3],cards[5],cards[7],cards[9]]; hand1.sort(); hand1.reverse(); hand2.sort(); hand2.reverse(); let royalFlush1:bool = royalFlush(hand1); let royalFlush2:bool = royalFlush(hand2); let straightFlush1:bool = straightFlush(hand1); let straightFlush2:bool = straightFlush(hand2); let fourKind1:bool = fourKind(hand1); let fourKind2:bool = fourKind(hand2); let fullHouse1:bool = fullHouse(hand1); let fullHouse2:bool = fullHouse(hand2); let flush1:bool = flush(hand1); let flush2:bool = flush(hand2); let straight1:bool = straight(hand1); let straight2:bool = straight(hand2); let threeKind1:bool = threeKind(hand1); let threeKind2:bool = threeKind(hand2); let twoPairs1:bool = twoPairs(hand1); let twoPairs2:bool = twoPairs(hand2); let pairs1:bool = pairs(hand1); let pairs2:bool = pairs(hand2); let mut winner:[u32;5] = [0,0,0,0,0]; if royalFlush1 || royalFlush2 { if royalFlush1 && royalFlush2 { winner = highCard(hand1, hand2); } else if royalFlush1 && !royalFlush2 { winner = hand1; } else { winner = hand2; } } else if straightFlush1 || straightFlush2 { if straightFlush1 && straightFlush2 { winner = highCard(hand1, hand2); } else if straightFlush1 && !straightFlush2 { winner = hand1; } else { winner = hand2; } } else if fourKind1 || fourKind2 { if fourKind1 && fourKind2 { winner = highCard(hand1, hand2); } else if fourKind1 && !fourKind2 { winner = hand1; } else { winner = hand2; } } else if fullHouse1 || fullHouse2 { if fullHouse1 && fullHouse2 { winner = highCard(hand1, hand2); } else if fullHouse1 && !fullHouse2 { winner = hand1; } else { winner = hand2; } } else if flush1 || flush2 { if flush1 && flush2 { winner = highCard(hand1, hand2); } else if flush1 && !flush2 { winner = hand1; } else { winner = hand2; } } else if straight1 || straight2 { if straight1 && straight2 { winner = highCard(hand1, hand2); } else if straight1 && !straight2 { winner = hand1; } else { winner = hand2; } } else if threeKind1 || threeKind2 { if threeKind1 && threeKind2 { winner = highCard(hand1, hand2); } else if threeKind1 && !threeKind2 { winner = hand1; } else { winner = hand2; } } else if twoPairs1 || twoPairs2 { if twoPairs1 && twoPairs2 { winner = highCard(hand1, hand2); } else if twoPairs1 && !twoPairs2 { winner = hand1; } else { winner = hand2; } } else if pairs1 || pairs2 { if pairs1 && pairs2 { winner = highCard(hand1, hand2); } else if pairs1 && !pairs2 { winner = hand1; } else { winner = hand2; } } else { winner = highCard(hand1, hand2); } let mut answer:[String;5] = [String::from(""), String::from(""), String::from(""), String::from(""), String::from("")]; for card in 0..5 { let x = winner[card]; if x > 0 && x < 11 { let mut s:String = x.to_string(); s.push('C'); answer[card] = s; } else if x > 13 && x < 24 { let mut s:String = x.to_string(); s.push('D'); answer[card] = s; } else if x > 26 && x < 37 { let mut s:String = x.to_string(); s.push('H'); answer[card] = s; } else if x > 39 && x < 50 { let mut s:String = x.to_string(); s.push('S'); answer[card] = s; } else { let s:String = x.to_string(); answer[card] = s; } } answer.reverse(); answer } pub fn royalFlush(hand: [u32;5]) -> bool { let royals1: [u32; 5] = [1,10,11,12,13]; let royals2: [u32; 5] = [14,23,24,25,26]; let royals3: [u32; 5] = [27,36,37,38,39]; let royals4: [u32; 5] = [40,49,50,51,52]; let mut ret: bool = true; let mut ord:[u32;5] = hand; ord.sort(); if !((ord == royals1) || (ord == royals2) || (ord == royals3) || (ord == royals4)) { ret = false; } ret } pub fn straightFlush(hand: [u32;5]) -> bool { flush(hand) && straight(hand) } pub fn fourKind(hand: [u32;5]) -> bool { let mut ret:bool = false; let kind:[u32;5] = rank(hand); if (kind[0]==kind[1] && kind[1]==kind[2] && kind[2]==kind[3]) || (kind[4]==kind[1] && kind[1]==kind[2] && kind[2]==kind[3]) {ret = true;} ret } pub fn fullHouse(hand: [u32;5]) -> bool { let mut ret:bool = false; let kind:[u32;5] = rank(hand); if ( kind[0] == kind[1] && kind[2] == kind [3] && kind[3] == kind[4] ) || ( kind[0] == kind[1] && kind[1] == kind [2] && kind[3] == kind[4] ) {ret = true;} ret } pub fn flush(hand: [u32;5]) -> bool { let mut ret:bool = false; let set1:[u32;13] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; let set2:[u32;13] = [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]; let set3:[u32;13] = [27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]; let set4:[u32;13] = [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]; if (set1.contains(&hand[0]) && set1.contains(&hand[1]) && set1.contains(&hand[2]) && set1.contains(&hand[3]) && set1.contains(&hand[4])) || (set2.contains(&hand[0]) && set2.contains(&hand[1]) && set2.contains(&hand[2]) && set2.contains(&hand[3]) && set2.contains(&hand[4])) || (set3.contains(&hand[0]) && set3.contains(&hand[1]) && set3.contains(&hand[2]) && set3.contains(&hand[3]) && set3.contains(&hand[4])) || (set4.contains(&hand[0]) && set4.contains(&hand[1]) && set4.contains(&hand[2]) && set4.contains(&hand[3]) && set4.contains(&hand[4])) {ret = true;} ret } pub fn straight(hand: [u32;5]) -> bool { let mut ret: bool = true; let mut ord:[u32;5] = rank(hand); ord.sort(); for x in 0..4 { if ord[x] + 1 != ord[x+1]{ ret = false; break; } } ret } pub fn threeKind(hand: [u32;5]) -> bool { let mut ret:bool = false; let kind:[u32;5] = rank(hand); if (kind[2] == kind [0] && kind[2] == kind[1]) || (kind[2] == kind [3] && kind[2] == kind[4]) {ret = true;} ret } pub fn twoPairs(hand: [u32;5]) -> bool { let mut ret:bool = false; let kind:[u32;5] = rank(hand); let mut ind0 = 0; let mut ind1 = 0; let mut ind2 = 0; let mut ind3 = 0; let mut ind4 = 0; let couple = 2; for x in 0..5 { if kind[x] == kind[0] {ind0 = ind0+1;} if kind[x] == kind[1] {ind1 = ind1+1;} if kind[x] == kind[2] {ind2 = ind2+1;} if kind[x] == kind[3] {ind3 = ind3+1;} if kind[x] == kind[4] {ind4 = ind4+1;} } if (ind0==couple && ((kind[0] != kind[1] && ind1==couple) || ind2==couple || ind3==couple || ind4==couple)) || (ind1==couple && ((kind[0]!=kind[1] && ind0==couple) || (kind[2]!=kind[1] && ind2==couple) || ind3==couple || ind4==couple)) || (ind2==couple && ((kind[1]!=kind[2] && ind1==couple) || (kind[3]!=kind[2] && kind[3]==couple) || ind0==couple || ind4==couple)) || (ind3==couple && ((kind[2]!=kind[3] && ind2==couple) || (kind[4]!=kind[3] && ind4==couple) || ind0==couple || ind1==couple)) || (ind4==couple && ((kind[4] != kind[3] && ind3==couple) || ind1==couple || ind2==couple || ind3==couple)) {ret = true;} ret } pub fn pairs(hand: [u32;5]) -> bool { let mut ret:bool = false; let kind:[u32;5] = rank(hand); let mut ind0 = 0; let mut ind2 = 0; let mut ind4 = 0; for x in 0..5 { if kind[x] == kind[0] {ind0 = ind0+1;} if kind[x] == kind[2] {ind2 = ind2+1;} if kind[x] == kind[4] {ind4 = ind4+1;} } if ind0 == 2 || ind2 == 2 || ind4 == 2 {ret = true;} ret } pub fn highCard(hand1:[u32;5], hand2:[u32;5]) -> [u32;5] { let kind1:[u32;5] = rank(hand1); let kind2:[u32;5] = rank(hand2); let mut ret:[u32;5] = best(hand1, hand2); for x in 0..5 { if kind1[x] != kind2[x] { if kind1[x]>kind2[x] { ret = hand1; break; } ret = hand2; break; } } ret } pub fn best(hand1:[u32;5], hand2:[u32;5]) -> [u32;5] { let total1: u32 = hand1.iter().sum(); let total2: u32 = hand2.iter().sum(); let mut ret:[u32;5] = [0,0,0,0,0]; if total1 > total2 { ret = hand1; } ret = hand2; ret } pub fn rank(hand: [u32;5]) -> [u32;5]{ let mut kind: [u32;5] = [0,0,0,0,0]; for x in 0..5{ let mut val:u32 = hand[x] % 13; if val == 0 {val = 13;} kind[x] = val; } kind.sort(); kind.reverse(); kind }
use std::ffi::c_void; use std::fmt::{self, Display}; use std::iter::FusedIterator; use crate::support::{self, LogicalResult, MlirStringCallback, StringRef}; use crate::{Context, SymbolTable, Visibility}; use super::*; extern "C" { pub(crate) type MlirOperation; } /// Indicates that an API was given/returned an invalid (null) OperationBase handle #[derive(thiserror::Error, Debug)] #[error("invalid operation, expected non-null reference")] pub struct InvalidOperationError; /// This trait is implemented by all concrete implementations of an MLIR operation in Rust. pub trait Operation { /// Returns the context in which this Operation was created fn context(&self) -> Context { unsafe { mlir_operation_get_context(self.base()) } } /// Returns the name of this operation as an identifier/StringAttr fn name(&self) -> StringAttr { unsafe { mlir_operation_get_name(self.base()) } } /// Returns the dialect namespace in which this operation is defined fn dialect_name(&self) -> StringRef { unsafe { mlir_operation_get_dialect_name(self.base()) } } /// Verifies this operation and any nested operations to ensure invariants are upheld /// /// NOTE: This can be expensive, so it should only be used for dev/debugging fn is_valid(&self) -> bool { match unsafe { mlir_operation_verify(self.base()) } { LogicalResult::Success => true, _ => false, } } /// Gets the block containing this operation, if there is one fn get_block(&self) -> Option<Block> { let block = unsafe { mlir_operation_get_block(self.base()) }; if block.is_null() { None } else { Some(block) } } /// Gets the parent operation which contains this operation, if there is one fn get_parent(&self) -> Option<OperationBase> { let op = unsafe { mlir_operation_get_parent_operation(self.base()) }; if op.is_null() { None } else { Some(op) } } /// Returns the module in which this operation is defined, if it was defined in one fn get_parent_module(&self) -> Option<Module> { let op = unsafe { mlir_operation_get_parent_module(self.base()) }; if op.is_null() { None } else { Some(op) } } /// Gets the number of regions in this operation fn num_regions(&self) -> usize { unsafe { mlir_operation_get_num_regions(self.base()) } } /// Gets the region at the given index /// /// NOTE: This function will panic if the index is out of bounds fn get_region(&self, index: usize) -> Region { let region = unsafe { mlir_operation_get_region(self.base(), index) }; assert!( !region.is_null(), "invalid region index {}, out of bounds", index ); region } /// Gets the entry block in the first region of this operation, if it contains one /// /// NOTE: This function will panic if this op has no regions fn get_body(&self) -> Option<Block> { self.get_region(0).entry() } /// Gets the next operation following this one in its containing region, if there is one fn next(&self) -> Option<OperationBase> { let op = unsafe { mlir_operation_get_next_in_block(self.base()) }; if op.is_null() { None } else { Some(op) } } /// Gets the number of operands provided to this operation fn num_operands(&self) -> usize { unsafe { mlir_operation_get_num_operands(self.base()) } } /// Gets the operand at the given index /// /// NOTE: This function will panic if the index is out of bounds fn get_operand(&self, index: usize) -> ValueBase { let val = unsafe { mlir_operation_get_operand(self.base(), index) }; assert!( !val.is_null(), "invalid operand index {}, out of bounds", index ); val } /// Returns an iterator over the operation operands fn operands(&self) -> OpOperandIter { OpOperandIter::new(self.base()) } /// Gets the number of results produced by this operation fn num_results(&self) -> usize { unsafe { mlir_operation_get_num_results(self.base()) } } /// Gets the result at the given index /// /// NOTE: This function will panic if the index is out of bounds fn get_result(&self, index: usize) -> OpResult { let val = unsafe { mlir_operation_get_result(self.base(), index) }; assert!( !val.is_null(), "invalid result index {}, out of bounds", index ); val } /// Returns an iterator over the operation operands fn results(&self) -> OpResultIter { OpResultIter::new(self.base()) } /// Returns the number of successor blocks reachable from this operation fn num_successors(&self) -> usize { unsafe { mlir_operation_get_num_successors(self.base()) } } /// Gets the successor block at the given index /// /// NOTE: This function will panic if the index is out of bounds fn get_successor(&self, index: usize) -> Block { let block = unsafe { mlir_operation_get_successor(self.base(), index) }; assert!( !block.is_null(), "invalid block index {}, out of bounds", index ); block } /// Gets an iterator of the successor blocks of this operation fn successors(&self) -> OpSuccessorIter { OpSuccessorIter::new(self.base()) } /// Returns the number of attributes this operation has fn num_attributes(&self) -> usize { unsafe { mlir_operation_get_num_attributes(self.base()) } } /// Gets the attribute at the given index /// /// NOTE: This function will panic if the index is out of bounds fn get_attribute(&self, index: usize) -> NamedAttribute { let attr = unsafe { mlir_operation_get_attribute(self.base(), index) }; assert!( !attr.is_null(), "invalid attribute index {}, out of bounds", index ); attr } /// Gets an iterator of the named attributes associated with this operation fn attributes(&self) -> OpAttrIter { OpAttrIter::new(self.base()) } /// Gets the attribute with the given name, if it exists fn get_attribute_by_name<S: Into<StringRef>>(&self, name: S) -> Option<AttributeBase> { let attr = unsafe { mlir_operation_get_attribute_by_name(self.base(), name.into()) }; if attr.is_null() { None } else { Some(attr) } } /// Sets the attribute with the given name, if it exists fn set_attribute_by_name<S: Into<StringRef>, A: Attribute>(&self, name: S, attr: A) { unsafe { mlir_operation_set_attribute_by_name(self.base(), name.into(), attr.base()); } } /// Removes the attribute with the given name, if it exists fn remove_attribute_by_name<S: Into<StringRef>>(&self, name: S) { unsafe { mlir_operation_remove_attribute_by_name(self.base(), name.into()); } } /// Returns true if this Operation has a symbol fn is_symbol(&self) -> bool { self.get_attribute_by_name(SymbolTable::get_symbol_visibility_name()) .is_some() } /// Returns the visibility of this symbol (if this operation is a symbol) fn visibility(&self) -> Option<Visibility> { if self.is_symbol() { Some(SymbolTable::get_symbol_visibility(self.base())) } else { None } } /// Dump the textual representation of this operation to stderr fn dump(&self) { unsafe { mlir_operation_dump(self.base()); } } /// Walk the operations in the current block starting from the current one fn iter(&self) -> OperationIter { let op = self.base(); OperationIter::new(if op.is_null() { None } else { Some(op) }) } /// Return the OperationBase value underlying this operation fn base(&self) -> OperationBase; } /// Represents any MLIR operation type. /// /// Corresponds to MLIR's `Operation` class #[repr(transparent)] #[derive(Copy, Clone)] pub struct OperationBase(*mut MlirOperation); impl From<*mut MlirOperation> for OperationBase { #[inline(always)] fn from(ptr: *mut MlirOperation) -> Self { Self(ptr) } } impl Operation for OperationBase { fn base(&self) -> OperationBase { *self } } impl OperationBase { #[inline(always)] pub fn is_null(&self) -> bool { self.0.is_null() } #[inline(always)] pub fn isa<T>(self) -> bool where T: TryFrom<OperationBase>, { T::try_from(self).is_ok() } #[inline(always)] pub fn dyn_cast<T>(self) -> Result<T, InvalidTypeCastError> where T: TryFrom<OperationBase, Error = InvalidTypeCastError>, { T::try_from(self) } } impl fmt::Debug for OperationBase { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { mlir_operation_print( *self, support::write_to_formatter, f as *mut _ as *mut c_void, ); } Ok(()) } } impl fmt::Pointer for OperationBase { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:p}", self.0) } } impl Eq for OperationBase {} impl PartialEq for OperationBase { fn eq(&self, other: &Self) -> bool { unsafe { mlir_operation_equal(*self, *other) } } } impl Display for OperationBase { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { mlir_operation_print( *self, support::write_to_formatter, f as *mut _ as *mut c_void, ); } Ok(()) } } /// Represents an owned reference to an Operation #[repr(transparent)] pub struct OwnedOperation(OperationBase); impl OwnedOperation { #[inline(always)] pub fn is_null(&self) -> bool { self.0.is_null() } pub fn release(self) -> OperationBase { let op = self.0; std::mem::forget(self); op } } impl Operation for OwnedOperation { fn base(&self) -> OperationBase { self.0 } } impl Drop for OwnedOperation { fn drop(&mut self) { unsafe { mlir_operation_destroy(self.0); } } } extern "C" { #[link_name = "mlirOperationDestroy"] fn mlir_operation_destroy(op: OperationBase); #[link_name = "mlirOperationEqual"] fn mlir_operation_equal(a: OperationBase, b: OperationBase) -> bool; #[link_name = "mlirOperationGetName"] fn mlir_operation_get_name(op: OperationBase) -> StringAttr; #[link_name = "mlirOperationGetBlock"] fn mlir_operation_get_block(op: OperationBase) -> Block; #[link_name = "mlirOperationGetParentOperation"] fn mlir_operation_get_parent_operation(op: OperationBase) -> OperationBase; #[link_name = "mlirOperationGetParentModule"] fn mlir_operation_get_parent_module(op: OperationBase) -> Module; #[link_name = "mlirOperationGetNumRegions"] fn mlir_operation_get_num_regions(op: OperationBase) -> usize; #[link_name = "mlirOperationGetRegion"] fn mlir_operation_get_region(op: OperationBase, index: usize) -> Region; #[link_name = "mlirOperationGetNextInBlock"] fn mlir_operation_get_next_in_block(op: OperationBase) -> OperationBase; #[link_name = "mlirOperationGetNumOperands"] fn mlir_operation_get_num_operands(op: OperationBase) -> usize; #[link_name = "mlirOperationGetOperand"] fn mlir_operation_get_operand(op: OperationBase, index: usize) -> ValueBase; #[link_name = "mlirOperationGetNumResults"] fn mlir_operation_get_num_results(op: OperationBase) -> usize; #[link_name = "mlirOperationGetResult"] fn mlir_operation_get_result(op: OperationBase, index: usize) -> OpResult; #[link_name = "mlirOperationGetNumSuccessors"] fn mlir_operation_get_num_successors(op: OperationBase) -> usize; #[link_name = "mlirOperationGetSuccessor"] fn mlir_operation_get_successor(op: OperationBase, index: usize) -> Block; #[link_name = "mlirOperationGetNumAttributes"] fn mlir_operation_get_num_attributes(op: OperationBase) -> usize; #[link_name = "mlirOperationGetAttribute"] fn mlir_operation_get_attribute(op: OperationBase, index: usize) -> NamedAttribute; #[link_name = "mlirOperationGetAttributeByName"] fn mlir_operation_get_attribute_by_name(op: OperationBase, name: StringRef) -> AttributeBase; #[link_name = "mlirOperationSetAttributeByName"] fn mlir_operation_set_attribute_by_name( op: OperationBase, name: StringRef, attr: AttributeBase, ); #[link_name = "mlirOperationRemoveAttributeByName"] fn mlir_operation_remove_attribute_by_name(op: OperationBase, name: StringRef) -> bool; #[link_name = "mlirOperationPrint"] fn mlir_operation_print( op: OperationBase, callback: MlirStringCallback, userdata: *const c_void, ); #[link_name = "mlirOperationDump"] fn mlir_operation_dump(op: OperationBase); } /// OperationState represents the intermediate state of an operation /// under construction. It is the means by which we are able to construct /// arbitrary MLIR operations without concrete types for each one. /// /// For convenience, we provide those "wrapper" types in dialect-specific /// modules within this crate. #[repr(C)] pub struct OperationState { name: StringRef, loc: Location, num_results: usize, results: *const TypeBase, num_operands: usize, operands: *const ValueBase, num_regions: usize, regions: *const Region, num_successors: usize, successors: *const Block, num_attributes: usize, attributes: *const NamedAttribute, enable_result_type_inference: bool, } impl OperationState { /// Creates a new operation state with the given name and location pub fn get<S: Into<StringRef>>(name: S, loc: Location) -> Self { unsafe { mlir_operation_state_get(name.into(), loc) } } /// Creates an Operation using the current OperationState pub fn create(self) -> OwnedOperation { let op = unsafe { mlir_operation_create(&self) }; assert!(!op.is_null(), "operation validation error"); op } /// Returns the name of this operation #[inline] pub fn name(&self) -> &StringRef { &self.name } /// Returns the location of this operation #[inline] pub fn location(&self) -> Location { self.loc } /// Returns a slice containing the result types associated with this operation #[inline] pub fn results(&self) -> &[TypeBase] { unsafe { core::slice::from_raw_parts(self.results, self.num_results) } } /// Adds the given result types to this operation pub fn add_results(&mut self, results: &[TypeBase]) { unsafe { mlir_operation_state_add_results(self, results.len(), results.as_ptr()); } } /// Returns a slice containing the operands passed to this operation #[inline] pub fn operands(&self) -> &[ValueBase] { unsafe { core::slice::from_raw_parts(self.operands, self.num_operands) } } /// Adds the given operands to this operation pub fn add_operands(&mut self, operands: &[ValueBase]) { unsafe { mlir_operation_state_add_operands(self, operands.len(), operands.as_ptr()); } } /// Returns a slice containing the regions this operation contains #[inline] pub fn regions(&self) -> &[Region] { unsafe { core::slice::from_raw_parts(self.regions, self.num_regions) } } /// Adds the given regions to this operation pub fn add_owned_regions(&mut self, regions: &[Region]) { unsafe { mlir_operation_state_add_owned_regions(self, regions.len(), regions.as_ptr()); } } /// Returns a slice containing the successor blocks of this operation #[inline] pub fn successors(&self) -> &[Block] { unsafe { core::slice::from_raw_parts(self.successors, self.num_successors) } } /// Adds the given successors to this operation pub fn add_successors(&mut self, successors: &[Block]) { unsafe { mlir_operation_state_add_successors(self, successors.len(), successors.as_ptr()); } } /// Returns a slice containing the attributes associated to this operation #[inline] pub fn attributes(&self) -> &[NamedAttribute] { unsafe { core::slice::from_raw_parts(self.attributes, self.num_attributes) } } /// Adds the given attributes to this operation pub fn add_attributes(&mut self, attrs: &[NamedAttribute]) { unsafe { mlir_operation_state_add_attributes(self, attrs.len(), attrs.as_ptr()); } } #[inline] pub fn enable_result_type_inference(&mut self) { self.enable_result_type_inference = true; } #[inline] pub fn disable_result_type_inference(&mut self) { self.enable_result_type_inference = false; } } extern "C" { #[link_name = "mlirOperationGetContext"] fn mlir_operation_get_context(op: OperationBase) -> Context; #[link_name = "mlirOperationStateGet"] fn mlir_operation_state_get(name: StringRef, loc: Location) -> OperationState; #[link_name = "mlirOperationGetDialectName"] fn mlir_operation_get_dialect_name(op: OperationBase) -> StringRef; #[link_name = "mlirOperationStateAddResults"] fn mlir_operation_state_add_results( state: &mut OperationState, len: usize, results: *const TypeBase, ); #[link_name = "mlirOperationStateAddOperands"] fn mlir_operation_state_add_operands( state: &mut OperationState, len: usize, operands: *const ValueBase, ); #[link_name = "mlirOperationStateAddOwnedRegions"] fn mlir_operation_state_add_owned_regions( state: &mut OperationState, len: usize, operands: *const Region, ); #[link_name = "mlirOperationStateAddSuccessors"] fn mlir_operation_state_add_successors( state: &mut OperationState, len: usize, succesors: *const Block, ); #[link_name = "mlirOperationStateAddAttributes"] fn mlir_operation_state_add_attributes( state: &mut OperationState, len: usize, attrs: *const NamedAttribute, ); #[link_name = "mlirOperationCreate"] fn mlir_operation_create(state: *const OperationState) -> OwnedOperation; #[link_name = "mlirOperationVerify"] fn mlir_operation_verify(op: OperationBase) -> LogicalResult; } // For internal use only, provides common methods for iterators on operands/results struct OpElementIter { op: OperationBase, len: usize, pos: usize, } impl OpElementIter { #[inline(always)] fn get_operand(&self, index: usize) -> ValueBase { self.op.get_operand(index) } #[inline(always)] fn get_result(&self, index: usize) -> OpResult { self.op.get_result(index) } #[inline(always)] fn get_attribute(&self, index: usize) -> NamedAttribute { self.op.get_attribute(index) } #[inline(always)] fn get_successor(&self, index: usize) -> Block { self.op.get_successor(index) } #[inline(always)] fn next(&mut self) -> Option<usize> { if self.len - self.pos > 0 { let pos = self.pos; self.pos += 1; Some(pos) } else { None } } } /// Iterator over operands of an operation pub struct OpOperandIter(OpElementIter); impl OpOperandIter { fn new(op: OperationBase) -> Self { let len = if op.is_null() { 0 } else { op.num_operands() }; Self(OpElementIter { op, len, pos: 0 }) } } impl Iterator for OpOperandIter { type Item = ValueBase; fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|pos| self.0.get_operand(pos)) } } impl FusedIterator for OpOperandIter {} /// Iterator over results of an operation pub struct OpResultIter(OpElementIter); impl OpResultIter { fn new(op: OperationBase) -> Self { let len = if op.is_null() { 0 } else { op.num_results() }; Self(OpElementIter { op, len, pos: 0 }) } } impl Iterator for OpResultIter { type Item = OpResult; fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|pos| self.0.get_result(pos)) } } impl FusedIterator for OpResultIter {} /// Iterator over successor blocks of an operation pub struct OpSuccessorIter(OpElementIter); impl OpSuccessorIter { fn new(op: OperationBase) -> Self { let len = if op.is_null() { 0 } else { op.num_successors() }; Self(OpElementIter { op, len, pos: 0 }) } } impl Iterator for OpSuccessorIter { type Item = Block; fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|pos| self.0.get_successor(pos)) } } impl FusedIterator for OpSuccessorIter {} /// Iterator over named attributes associated to an operation pub struct OpAttrIter(OpElementIter); impl OpAttrIter { fn new(op: OperationBase) -> Self { let len = if op.is_null() { 0 } else { op.num_attributes() }; Self(OpElementIter { op, len, pos: 0 }) } } impl Iterator for OpAttrIter { type Item = NamedAttribute; fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|pos| self.0.get_attribute(pos)) } } impl FusedIterator for OpAttrIter {} /// Iterator used for walking some set of linked operations pub struct OperationIter { op: Option<OperationBase>, } impl OperationIter { #[inline] pub fn new(op: Option<OperationBase>) -> Self { Self { op } } } impl Iterator for OperationIter { type Item = OperationBase; fn next(&mut self) -> Option<Self::Item> { match self.op { None => None, Some(op) => { self.op = op.next(); self.op } } } } impl FusedIterator for OperationIter {}
use mysql::chrono::*; pub trait LladreDAO { fn obtenir_denuncies(&self) -> Vec<Denuncia>; fn obtenir_visites(&self, museu_id: u32, hora: DateTime<Utc>) -> Vec<Visitant>; } #[derive(Debug, PartialEq, Eq)] pub struct Denuncia { pub museu_id: u32, pub museu_nom: String, pub hora: DateTime<Utc>, } #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub struct Visitant { pub visitant_id: String, pub visitant_nom: String, } pub mod mysql;
use std::sync::Arc; use datafusion::{execution::context::SessionState, physical_optimizer::PhysicalOptimizerRule}; use self::{ combine_chunks::CombineChunks, dedup::{ dedup_null_columns::DedupNullColumns, dedup_sort_order::DedupSortOrder, partition_split::PartitionSplit, remove_dedup::RemoveDedup, time_split::TimeSplit, }, predicate_pushdown::PredicatePushdown, projection_pushdown::ProjectionPushdown, sort::parquet_sortness::ParquetSortness, union::{nested_union::NestedUnion, one_union::OneUnion}, }; mod chunk_extraction; mod combine_chunks; mod dedup; mod predicate_pushdown; mod projection_pushdown; mod sort; mod union; #[cfg(test)] mod test_util; /// Register IOx-specific [`PhysicalOptimizerRule`]s with the SessionContext pub fn register_iox_physical_optimizers(state: SessionState) -> SessionState { // prepend IOx-specific rules to DataFusion builtins // The optimizer rules have to be done in this order let mut optimizers: Vec<Arc<dyn PhysicalOptimizerRule + Sync + Send>> = vec![ Arc::new(PartitionSplit), Arc::new(TimeSplit), Arc::new(RemoveDedup), Arc::new(CombineChunks), Arc::new(DedupNullColumns), Arc::new(DedupSortOrder), Arc::new(PredicatePushdown), Arc::new(ProjectionPushdown), Arc::new(ParquetSortness) as _, Arc::new(NestedUnion), Arc::new(OneUnion), ]; optimizers.append(&mut state.physical_optimizers().to_vec()); state.with_physical_optimizer_rules(optimizers) }
//! An `Operation` captures the semantics of the IL. use crate::il::*; use serde::{Deserialize, Serialize}; use std::fmt; /// An IL Operation updates some state. #[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] pub enum Operation { /// Assign the value given in expression to the variable indicated. Assign { dst: Scalar, src: Expression }, /// Store the value in src at the address given in index. Store { index: Expression, src: Expression }, /// Load the value in memory at index and place the result in the variable dst. Load { dst: Scalar, index: Expression }, /// Branch to the value given by target. Branch { target: Expression }, /// Holds an Intrinsic for unmodellable instructions Intrinsic { intrinsic: Intrinsic }, /// An operation that does nothing, and allows for a placeholder `Instruction` Nop { placeholder: Option<Box<Operation>> }, } impl Default for Operation { fn default() -> Self { Self::Nop { placeholder: None } } } impl Operation { /// Create a new `Operation::Assign`. pub fn assign(dst: Scalar, src: Expression) -> Operation { Operation::Assign { dst, src } } /// Create a new `Operation::Store`. pub fn store(index: Expression, src: Expression) -> Operation { Operation::Store { index, src } } /// Create a new `Operation::Load`. pub fn load(dst: Scalar, index: Expression) -> Operation { Operation::Load { dst, index } } /// Create a new `Operation::Brc`. pub fn branch(target: Expression) -> Operation { Operation::Branch { target } } /// Create a new `Operation::Intrinsic`. pub fn intrinsic(intrinsic: Intrinsic) -> Operation { Operation::Intrinsic { intrinsic } } /// Create a new `Operation::Nop` pub fn nop() -> Operation { Operation::Nop { placeholder: None } } /// Create a new `Operation::Nop` as placeholder for the given `Operation` pub fn placeholder(operation: Operation) -> Operation { Operation::Nop { placeholder: Some(Box::new(operation)), } } pub fn is_assign(&self) -> bool { matches!(self, Operation::Assign { .. }) } pub fn is_store(&self) -> bool { matches!(self, Operation::Store { .. }) } pub fn is_load(&self) -> bool { matches!(self, Operation::Load { .. }) } pub fn is_branch(&self) -> bool { matches!(self, Operation::Branch { .. }) } pub fn is_intrinsic(&self) -> bool { matches!(self, Operation::Intrinsic { .. }) } pub fn is_nop(&self) -> bool { matches!(self, Operation::Nop { .. }) } /// Get each `Scalar` read by this `Operation`. pub fn scalars_read(&self) -> Option<Vec<&Scalar>> { match *self { Operation::Assign { ref src, .. } => Some(src.scalars()), Operation::Store { ref index, ref src } => Some( index .scalars() .into_iter() .chain(src.scalars().into_iter()) .collect(), ), Operation::Load { ref index, .. } => Some(index.scalars()), Operation::Branch { ref target } => Some(target.scalars()), Operation::Intrinsic { ref intrinsic } => intrinsic.scalars_read(), Operation::Nop { .. } => Some(Vec::new()), } } /// Get a mutable reference to each `Scalar` read by this `Operation`. pub fn scalars_read_mut(&mut self) -> Option<Vec<&mut Scalar>> { match *self { Operation::Assign { ref mut src, .. } => Some(src.scalars_mut()), Operation::Store { ref mut index, ref mut src, } => Some( index .scalars_mut() .into_iter() .chain(src.scalars_mut().into_iter()) .collect(), ), Operation::Load { ref mut index, .. } => Some(index.scalars_mut()), Operation::Branch { ref mut target } => Some(target.scalars_mut()), Operation::Intrinsic { ref mut intrinsic } => intrinsic.scalars_read_mut(), Operation::Nop { .. } => Some(Vec::new()), } } /// Get a Vec of the `Scalar`s written by this `Operation` pub fn scalars_written(&self) -> Option<Vec<&Scalar>> { match *self { Operation::Assign { ref dst, .. } | Operation::Load { ref dst, .. } => Some(vec![dst]), Operation::Store { .. } | Operation::Branch { .. } => Some(Vec::new()), Operation::Intrinsic { ref intrinsic } => intrinsic.scalars_written(), Operation::Nop { .. } => Some(Vec::new()), } } /// Get a Vec of mutable referencer to the `Scalar`s written by this /// `Operation` pub fn scalars_written_mut(&mut self) -> Option<Vec<&mut Scalar>> { match *self { Operation::Assign { ref mut dst, .. } | Operation::Load { ref mut dst, .. } => { Some(vec![dst]) } Operation::Store { .. } | Operation::Branch { .. } => Some(Vec::new()), Operation::Intrinsic { ref mut intrinsic } => intrinsic.scalars_written_mut(), Operation::Nop { .. } => Some(Vec::new()), } } } impl fmt::Display for Operation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Operation::Assign { ref dst, ref src } => write!(f, "{} = {}", dst, src), Operation::Store { ref index, ref src } => write!(f, "[{}] = {}", index, src), Operation::Load { ref dst, ref index } => write!(f, "{} = [{}]", dst, index), Operation::Branch { ref target } => write!(f, "branch {}", target), Operation::Intrinsic { ref intrinsic } => write!(f, "intrinsic {}", intrinsic), Operation::Nop { .. } => write!(f, "nop"), } } }
use std::collections::HashSet; use darling::{util::SpannedValue, FromMeta}; use proc_macro2::{Span, TokenStream, TokenTree}; use proc_macro_crate::{crate_name, FoundCrate}; use quote::quote; use syn::{ visit::Visit, visit_mut, visit_mut::VisitMut, Attribute, Error, Expr, ExprPath, FnArg, Ident, ImplItemMethod, Lifetime, Lit, LitStr, Meta, Pat, PatIdent, Type, TypeGroup, TypeParamBound, TypeReference, }; use thiserror::Error; use crate::args::{self, Deprecation, Visible}; #[derive(Error, Debug)] pub enum GeneratorError { #[error("{0}")] Syn(#[from] syn::Error), #[error("{0}")] Darling(#[from] darling::Error), } impl GeneratorError { pub fn write_errors(self) -> TokenStream { match self { GeneratorError::Syn(err) => err.to_compile_error(), GeneratorError::Darling(err) => err.write_errors(), } } } pub type GeneratorResult<T> = std::result::Result<T, GeneratorError>; pub fn get_crate_name(internal: bool) -> TokenStream { if internal { quote! { crate } } else { let name = match crate_name("async-graphql") { Ok(FoundCrate::Name(name)) => name, Ok(FoundCrate::Itself) | Err(_) => "async_graphql".to_string(), }; TokenTree::from(Ident::new(&name, Span::call_site())).into() } } pub fn generate_guards( crate_name: &TokenStream, code: &SpannedValue<String>, map_err: TokenStream, ) -> GeneratorResult<TokenStream> { let expr: Expr = syn::parse_str(code).map_err(|err| Error::new(code.span(), err.to_string()))?; let code = quote! {{ use #crate_name::GuardExt; #expr }}; Ok(quote! { #crate_name::Guard::check(&#code, &ctx).await #map_err ?; }) } pub fn get_rustdoc(attrs: &[Attribute]) -> GeneratorResult<Option<String>> { let mut full_docs = String::new(); for attr in attrs { match attr.parse_meta()? { Meta::NameValue(nv) if nv.path.is_ident("doc") => { if let Lit::Str(doc) = nv.lit { let doc = doc.value(); let doc_str = doc.trim(); if !full_docs.is_empty() { full_docs += "\n"; } full_docs += doc_str; } } _ => {} } } Ok(if full_docs.is_empty() { None } else { Some(full_docs) }) } fn generate_default_value(lit: &Lit) -> GeneratorResult<TokenStream> { match lit { Lit::Str(value) =>{ let value = value.value(); Ok(quote!({ ::std::borrow::ToOwned::to_owned(#value) })) } Lit::Int(value) => { let value = value.base10_parse::<i32>()?; Ok(quote!({ ::std::convert::TryInto::try_into(#value).unwrap_or_default() })) } Lit::Float(value) => { let value = value.base10_parse::<f64>()?; Ok(quote!({ ::std::convert::TryInto::try_into(#value).unwrap_or_default() })) } Lit::Bool(value) => { let value = value.value; Ok(quote!({ #value })) } _ => Err(Error::new_spanned( lit, "The default value type only be string, integer, float and boolean, other types should use default_with", ).into()), } } fn generate_default_with(lit: &LitStr) -> GeneratorResult<TokenStream> { let str = lit.value(); let tokens: TokenStream = str .parse() .map_err(|err| GeneratorError::Syn(syn::Error::from(err)))?; Ok(quote! { (#tokens) }) } pub fn generate_default( default: &Option<args::DefaultValue>, default_with: &Option<LitStr>, ) -> GeneratorResult<Option<TokenStream>> { match (default, default_with) { (Some(args::DefaultValue::Default), _) => { Ok(Some(quote! { ::std::default::Default::default() })) } (Some(args::DefaultValue::Value(lit)), _) => Ok(Some(generate_default_value(lit)?)), (None, Some(lit)) => Ok(Some(generate_default_with(lit)?)), (None, None) => Ok(None), } } pub fn get_cfg_attrs(attrs: &[Attribute]) -> Vec<Attribute> { attrs .iter() .filter(|attr| !attr.path.segments.is_empty() && attr.path.segments[0].ident == "cfg") .cloned() .collect() } pub fn parse_graphql_attrs<T: FromMeta + Default>( attrs: &[Attribute], ) -> GeneratorResult<Option<T>> { for attr in attrs { if attr.path.is_ident("graphql") { let meta = attr.parse_meta()?; return Ok(Some(T::from_meta(&meta)?)); } } Ok(None) } pub fn remove_graphql_attrs(attrs: &mut Vec<Attribute>) { if let Some((idx, _)) = attrs .iter() .enumerate() .find(|(_, a)| a.path.is_ident("graphql")) { attrs.remove(idx); } } pub fn get_type_path_and_name(ty: &Type) -> GeneratorResult<(&Type, String)> { match ty { Type::Path(path) => Ok(( ty, path.path .segments .last() .map(|s| s.ident.to_string()) .unwrap(), )), Type::Group(TypeGroup { elem, .. }) => get_type_path_and_name(elem), Type::TraitObject(trait_object) => Ok(( ty, trait_object .bounds .iter() .find_map(|bound| match bound { TypeParamBound::Trait(t) => { Some(t.path.segments.last().map(|s| s.ident.to_string()).unwrap()) } _ => None, }) .unwrap(), )), _ => Err(Error::new_spanned(ty, "Invalid type").into()), } } pub fn visible_fn(visible: &Option<Visible>) -> TokenStream { match visible { None | Some(Visible::None) => quote! { ::std::option::Option::None }, Some(Visible::HiddenAlways) => quote! { ::std::option::Option::Some(|_| false) }, Some(Visible::FnName(name)) => { quote! { ::std::option::Option::Some(#name) } } } } pub fn parse_complexity_expr(s: &str) -> GeneratorResult<(HashSet<String>, Expr)> { #[derive(Default)] struct VisitComplexityExpr { variables: HashSet<String>, } impl<'a> Visit<'a> for VisitComplexityExpr { fn visit_expr_path(&mut self, i: &'a ExprPath) { if let Some(ident) = i.path.get_ident() { if ident != "child_complexity" { self.variables.insert(ident.to_string()); } } } } let expr: Expr = syn::parse_str(s)?; let mut visit = VisitComplexityExpr::default(); visit.visit_expr(&expr); Ok((visit.variables, expr)) } pub fn gen_deprecation(deprecation: &Deprecation, crate_name: &TokenStream) -> TokenStream { match deprecation { Deprecation::NoDeprecated => { quote! { #crate_name::registry::Deprecation::NoDeprecated } } Deprecation::Deprecated { reason: Some(reason), } => { quote! { #crate_name::registry::Deprecation::Deprecated { reason: ::std::option::Option::Some(::std::string::ToString::to_string(#reason)) } } } Deprecation::Deprecated { reason: None } => { quote! { #crate_name::registry::Deprecation::Deprecated { reason: ::std::option::Option::None } } } } } pub fn extract_input_args<T: FromMeta + Default>( crate_name: &proc_macro2::TokenStream, method: &mut ImplItemMethod, ) -> GeneratorResult<Vec<(PatIdent, Type, T)>> { let mut args = Vec::new(); let mut create_ctx = true; if method.sig.inputs.is_empty() { return Err(Error::new_spanned( &method.sig, "The self receiver must be the first parameter.", ) .into()); } for (idx, arg) in method.sig.inputs.iter_mut().enumerate() { if let FnArg::Receiver(receiver) = arg { if idx != 0 { return Err(Error::new_spanned( receiver, "The self receiver must be the first parameter.", ) .into()); } } else if let FnArg::Typed(pat) = arg { if idx == 0 { return Err(Error::new_spanned( pat, "The self receiver must be the first parameter.", ) .into()); } match (&*pat.pat, &*pat.ty) { (Pat::Ident(arg_ident), Type::Reference(TypeReference { elem, .. })) => { if let Type::Path(path) = elem.as_ref() { if idx != 1 || path.path.segments.last().unwrap().ident != "Context" { args.push(( arg_ident.clone(), pat.ty.as_ref().clone(), parse_graphql_attrs::<T>(&pat.attrs)?.unwrap_or_default(), )); } else { create_ctx = false; } } } (Pat::Ident(arg_ident), ty) => { args.push(( arg_ident.clone(), ty.clone(), parse_graphql_attrs::<T>(&pat.attrs)?.unwrap_or_default(), )); remove_graphql_attrs(&mut pat.attrs); } _ => { return Err(Error::new_spanned(arg, "Invalid argument type.").into()); } } } } if create_ctx { let arg = syn::parse2::<FnArg>(quote! { _: &#crate_name::Context<'_> }).unwrap(); method.sig.inputs.insert(1, arg); } Ok(args) } pub struct RemoveLifetime; impl VisitMut for RemoveLifetime { fn visit_lifetime_mut(&mut self, i: &mut Lifetime) { i.ident = Ident::new("_", Span::call_site()); visit_mut::visit_lifetime_mut(self, i); } }
use crate::{ sdk::export::{ trace::{ExportResult, SpanData, SpanExporter}, ExportError, }, sdk::{ trace::{Config, EvictedHashMap, EvictedQueue}, InstrumentationLibrary, }, trace::{Span, SpanContext, SpanId, SpanKind, StatusCode}, KeyValue, }; use async_trait::async_trait; use std::borrow::Cow; use std::fmt::{Display, Formatter}; use std::sync::mpsc::{channel, Receiver, Sender}; #[derive(Debug)] pub struct TestSpan(pub SpanContext); impl Span for TestSpan { fn add_event_with_timestamp<T>( &mut self, _name: T, _timestamp: std::time::SystemTime, _attributes: Vec<KeyValue>, ) where T: Into<Cow<'static, str>>, { } fn span_context(&self) -> &SpanContext { &self.0 } fn is_recording(&self) -> bool { false } fn set_attribute(&mut self, _attribute: KeyValue) {} fn set_status(&mut self, _code: StatusCode, _message: String) {} fn update_name<T>(&mut self, _new_name: T) where T: Into<Cow<'static, str>>, { } fn end_with_timestamp(&mut self, _timestamp: std::time::SystemTime) {} } pub fn new_test_export_span_data() -> SpanData { let config = Config::default(); SpanData { span_context: SpanContext::empty_context(), parent_span_id: SpanId::from_u64(0), span_kind: SpanKind::Internal, name: "opentelemetry".into(), start_time: crate::time::now(), end_time: crate::time::now(), attributes: EvictedHashMap::new(config.span_limits.max_attributes_per_span, 0), events: EvictedQueue::new(config.span_limits.max_events_per_span), links: EvictedQueue::new(config.span_limits.max_links_per_span), status_code: StatusCode::Unset, status_message: "".into(), resource: config.resource, instrumentation_lib: InstrumentationLibrary::default(), } } #[derive(Debug)] pub struct TestSpanExporter { tx_export: Sender<SpanData>, tx_shutdown: Sender<()>, } #[async_trait] impl SpanExporter for TestSpanExporter { async fn export(&mut self, batch: Vec<SpanData>) -> ExportResult { for span_data in batch { self.tx_export .send(span_data) .map_err::<TestExportError, _>(Into::into)?; } Ok(()) } fn shutdown(&mut self) { self.tx_shutdown.send(()).unwrap(); } } pub fn new_test_exporter() -> (TestSpanExporter, Receiver<SpanData>, Receiver<()>) { let (tx_export, rx_export) = channel(); let (tx_shutdown, rx_shutdown) = channel(); let exporter = TestSpanExporter { tx_export, tx_shutdown, }; (exporter, rx_export, rx_shutdown) } #[derive(Debug)] pub struct TokioSpanExporter { tx_export: tokio::sync::mpsc::UnboundedSender<SpanData>, tx_shutdown: tokio::sync::mpsc::UnboundedSender<()>, } #[async_trait] impl SpanExporter for TokioSpanExporter { async fn export(&mut self, batch: Vec<SpanData>) -> ExportResult { for span_data in batch { self.tx_export .send(span_data) .map_err::<TestExportError, _>(Into::into)?; } Ok(()) } fn shutdown(&mut self) { self.tx_shutdown.send(()).unwrap(); } } pub fn new_tokio_test_exporter() -> ( TokioSpanExporter, tokio::sync::mpsc::UnboundedReceiver<SpanData>, tokio::sync::mpsc::UnboundedReceiver<()>, ) { let (tx_export, rx_export) = tokio::sync::mpsc::unbounded_channel(); let (tx_shutdown, rx_shutdown) = tokio::sync::mpsc::unbounded_channel(); let exporter = TokioSpanExporter { tx_export, tx_shutdown, }; (exporter, rx_export, rx_shutdown) } #[derive(Debug)] pub struct TestExportError(String); impl std::error::Error for TestExportError {} impl ExportError for TestExportError { fn exporter_name(&self) -> &'static str { "test" } } impl Display for TestExportError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl<T> From<tokio::sync::mpsc::error::SendError<T>> for TestExportError { fn from(err: tokio::sync::mpsc::error::SendError<T>) -> Self { TestExportError(err.to_string()) } } impl<T> From<std::sync::mpsc::SendError<T>> for TestExportError { fn from(err: std::sync::mpsc::SendError<T>) -> Self { TestExportError(err.to_string()) } }
use super::LED; use core::future::Future; use drogue_device::{ actors::{button::*, led::*}, kernel::actor::*, }; #[derive(Debug)] pub enum Command { Toggle, } pub struct App { address: Option<Address<'static, App>>, led1: Option<Address<'static, Led<LED>>>, led2: Option<Address<'static, Led<LED>>>, state: bool, } impl Default for App { fn default() -> Self { Self { state: false, address: Default::default(), led1: Default::default(), led2: Default::default(), } } } impl FromButtonEvent<Command> for App { fn from(event: ButtonEvent) -> Option<Command> where Self: Sized, { match event { ButtonEvent::Pressed => Some(Command::Toggle), _ => None, } } } impl Actor for App { type Configuration = (Address<'static, Led<LED>>, Address<'static, Led<LED>>); #[rustfmt::skip] type Message<'m> = Command; #[rustfmt::skip] type OnMountFuture<'m, M> where M: 'm = impl Future<Output = ()> + 'm; fn on_mount<'m, M>( &'m mut self, config: Self::Configuration, address: Address<'static, Self>, inbox: &'m mut M, ) -> Self::OnMountFuture<'m, M> where M: Inbox<'m, Self> + 'm, { self.address.replace(address); self.view_state(&config.0, &config.1).ok(); self.led1.replace(config.0); self.led2.replace(config.1); async move { loop { match inbox.next().await { Some(mut m) => match m.message() { Command::Toggle => { self.toggle().ok(); } }, _ => {} } } } } } impl App { fn toggle(&mut self) -> Result<(), ActorError> { self.state = !self.state; match (self.led1, self.led2) { (Some(led1), Some(led2)) => { self.view_state(&led1, &led2)?; } _ => {} } Ok(()) } fn view_state( &self, led1: &Address<Led<LED>>, led2: &Address<Led<LED>>, ) -> Result<(), ActorError> { led1.notify(LedMessage::State(self.state))?; led2.notify(LedMessage::State(!self.state))?; Ok(()) } }
use std::cell::RefCell; use std::rc::Rc; use input::Input; use parser::evaluator::TagEvaluator; use sensor::evaluator::NamedSensors; use input::cutoff::EvalCutoff; use input::maximum::EvalMaximum; use input::panic::EvalPanic; use input::sensor::EvalSensorInput; use input::smooth::EvalSmooth; use input::step::EvalSteps; // Reference to input evaluator pub type InputEvaluatorRef = Rc<RefCell<InputEvaluator>>; pub type InputEvaluator = TagEvaluator<Box<Input>>; impl InputEvaluator { pub fn create(named_sensors: Rc<RefCell<NamedSensors>>) -> InputEvaluatorRef { let input_evaluator = Rc::new(RefCell::new(InputEvaluator::new())); InputEvaluator::init(input_evaluator.clone(), named_sensors); input_evaluator } fn init(input_evaluator: Rc<RefCell<InputEvaluator>>, named_sensors: Rc<RefCell<NamedSensors>>) { let mut input_borrow = input_evaluator.borrow_mut(); input_borrow.add("cutoff", Rc::new(EvalCutoff ::new(input_evaluator.clone()))); input_borrow.add("maximum", Rc::new(EvalMaximum ::new(input_evaluator.clone()))); input_borrow.add("panic", Rc::new(EvalPanic ::new(input_evaluator.clone()))); input_borrow.add("sensor-input", Rc::new(EvalSensorInput::new(named_sensors))); input_borrow.add("smooth", Rc::new(EvalSmooth ::new(input_evaluator.clone()))); input_borrow.add("steps", Rc::new(EvalSteps ::new(input_evaluator.clone()))); } }
pub use crate::ccu::CcuExt as _pine64_hal_ccu_CcuExt; pub use crate::dma::DmaExt as _pine64_hal_dma_DmaExt; pub use crate::gpio::GpioExt as _pine64_hal_gpio_GpioExt; pub use crate::hal::digital::v2::InputPin as _embedded_hal_digital_InputPin; pub use crate::hal::digital::v2::OutputPin as _embedded_hal_digital_OutputPin; pub use crate::hal::digital::v2::StatefulOutputPin as _embedded_hal_digital_StatefulOutputPin; pub use crate::hal::prelude::*; pub use crate::time::duration::Extensions as _pine64_hal_time_duration_Extensions; pub use crate::time::rate::Extensions as _pine64_hal_time_rate_Extensions; pub use crate::timer::TimerExt as _pine64_hal_timer_TimerExt;
extern crate iostream; use iostream::io::*; use std::io::Write; use std::fs::remove_file; fn make_file() { let mut file = FileStream::new("1.data", FileMode::CreateNew, FileAccess::Write).expect("not make 1.data"); let data: [u8; 1024] = [1; 1024]; file.file.write_all(&data).expect("not write data to 1.data"); } #[test] fn read_test() { make_file(); let mut fs=FileStream::new("1.data",FileMode::Open,FileAccess::Read).expect("not read 1.data"); let mut data=Vec::new(); let lengt= fs.read_all(&mut data).unwrap(); println!("\n"); for i in data.iter(){ print!("{}",i); } println!("\n"); assert_eq!(lengt,data.len()); fs.set_position(0).unwrap(); let mut readlengt=0; let mut data:[u8;100]=[0;100]; let lengt= fs.read(&mut data,50,20).unwrap(); readlengt+=lengt; for i in data.iter(){ print!("{}",i); } println!("\n"); assert_eq!(lengt,20,"{}",lengt); assert_eq!(readlengt as u64 ,fs.position()); let mut data=Vec::new(); let lengt= fs.read_all(&mut data).unwrap(); println!("{}",lengt); assert_eq!((lengt+readlengt) as u64,fs.length()); remove_file("1.data").unwrap(); }
use crate::byte::{ByteChar, ByteString}; use std::fmt::{self, Debug, Display, Formatter}; use std::ops::{Deref, DerefMut}; /// A single-byte string slice. #[derive(PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct ByteStr([ByteChar]); macro_rules! cast { (mut $x:expr, $($T:ty)=>*) => { unsafe { &mut *($x $(as *mut $T)*) } }; ($x:expr, $($T:ty)=>*) => { unsafe { &*($x $(as *const $T)*) } }; } impl ByteStr { /// Converts a slice of bytes to a `ByteStr`. pub fn from_bytes(s: &[u8]) -> &Self { cast!(s, [u8] => [ByteChar] => ByteStr) } /// Converts a mutable slice of bytes to a mutable `ByteStr`. pub fn from_bytes_mut(s: &mut [u8]) -> &mut Self { cast!(mut s, [u8] => [ByteChar] => ByteStr) } /// Converts a slice of `ByteChar` to a `ByteStr`. pub fn from_byte_chars(s: &[ByteChar]) -> &Self { cast!(s, [ByteChar] => ByteStr) } /// Converts a mutable slice of `ByteChar` to a mutable `ByteStr`. pub fn from_byte_chars_mut(s: &mut [ByteChar]) -> &mut Self { cast!(mut s, [ByteChar] => ByteStr) } /// Converts this `ByteStr` to a slice of bytes. pub fn as_bytes(&self) -> &[u8] { cast!(self, ByteStr => [ByteChar] => [u8]) } /// Converts this `ByteStr` to a mutable slice of bytes. pub fn as_bytes_mut(&mut self) -> &mut [u8] { cast!(mut self, ByteStr => [ByteChar] => [u8]) } } impl ToOwned for ByteStr { type Owned = ByteString; fn to_owned(&self) -> ByteString { ByteString::from(self.0.to_owned()) } } impl Debug for ByteStr { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "b\"")?; for &c in &self.0 { write!(f, "{}", c)?; } write!(f, "\"") } } impl Display for ByteStr { fn fmt(&self, f: &mut Formatter) -> fmt::Result { for &c in &self.0 { write!(f, "{}", c)?; } Ok(()) } } impl Deref for ByteStr { type Target = [ByteChar]; fn deref(&self) -> &[ByteChar] { &self.0 } } impl DerefMut for ByteStr { fn deref_mut(&mut self) -> &mut [ByteChar] { &mut self.0 } } #[cfg(test)] mod tests { use super::*; #[test] fn test() { let mut bytes = b"abcd".to_owned(); let s = ByteStr::from_bytes_mut(&mut bytes); s.swap(1, 3); // b"adcb" s[0] = ByteChar::new(b'e'); // b"edcb" s.as_bytes_mut()[1] = b'f'; // b"efcb" assert_eq!(s.as_bytes(), b"efcb"); assert_eq!(format!("{}", s), "efcb"); assert_eq!(format!("{:?}", s), "b\"efcb\""); } }
// `without_arity_errors_badarity` in unit tests test_stdout!(with_arity_returns_function_return, "from_fun\n");
use crate::G; use wizardscastle::armor::ArmorType; use wizardscastle::game::Stairs; use wizardscastle::monster::MonsterType; use wizardscastle::player::{Gender, Race, Stat}; use wizardscastle::room::RoomType; use wizardscastle::treasure::TreasureType; use wizardscastle::weapon::WeaponType; use rand::Rng; impl G { pub fn player_race_name(&self) -> &str { match self.game.player_race() { Race::Hobbit => "Hobbit", Race::Elf => "Elf", Race::Human => "Human", Race::Dwarf => "Dwarf", } } pub fn stat_name(s: Stat) -> String { match s { Stat::Strength => String::from("Strength"), Stat::Intelligence => String::from("Intelligence"), Stat::Dexterity => String::from("Dexterity"), } } pub fn weapon_name(w: WeaponType) -> String { match w { WeaponType::None => String::from("No weapon"), WeaponType::Dagger => String::from("Dagger"), WeaponType::Mace => String::from("Mace"), WeaponType::Sword => String::from("Sword"), } } pub fn armor_name(a: ArmorType) -> String { match a { ArmorType::None => String::from("No armor"), ArmorType::Leather => String::from("Leather"), ArmorType::Chainmail => String::from("Chainmail"), ArmorType::Plate => String::from("Plate"), } } pub fn rand_monster_name(&mut self) -> String { let monster = [ MonsterType::Kobold, MonsterType::Orc, MonsterType::Wolf, MonsterType::Goblin, MonsterType::Ogre, MonsterType::Troll, MonsterType::Bear, MonsterType::Minotaur, MonsterType::Gargoyle, MonsterType::Chimera, MonsterType::Balrog, MonsterType::Dragon, ]; let i = self.rng.gen_range(0..monster.len()); G::monster_name(monster[i]) } pub fn monster_name(m: MonsterType) -> String { match m { MonsterType::Kobold => String::from("kobold"), MonsterType::Orc => String::from("orc"), MonsterType::Wolf => String::from("wolf"), MonsterType::Goblin => String::from("goblin"), MonsterType::Ogre => String::from("ogre"), MonsterType::Troll => String::from("troll"), MonsterType::Bear => String::from("bear"), MonsterType::Minotaur => String::from("minotaur"), MonsterType::Gargoyle => String::from("gargoyle"), MonsterType::Chimera => String::from("chimera"), MonsterType::Balrog => String::from("balrog"), MonsterType::Dragon => String::from("dragon"), MonsterType::Vendor => String::from("vendor"), } } pub fn treasure_name(t: TreasureType) -> String { match t { TreasureType::RubyRed => String::from("Ruby Red"), TreasureType::NornStone => String::from("Norn Stone"), TreasureType::PalePearl => String::from("Pale Pearl"), TreasureType::OpalEye => String::from("Opal Eye"), TreasureType::GreenGem => String::from("Green Gem"), TreasureType::BlueFlame => String::from("Blue Flame"), TreasureType::Palantir => String::from("Palantir"), TreasureType::Silmaril => String::from("Silmaril"), } } /// Get the printable character for a room pub fn room_char(room_type: &RoomType) -> char { match room_type { RoomType::Empty => '.', RoomType::Entrance => 'E', RoomType::StairsDown => 'D', RoomType::StairsUp => 'U', RoomType::Gold => 'G', RoomType::Pool => 'P', RoomType::Chest => 'C', RoomType::Flares => 'F', RoomType::Warp(_) => 'W', RoomType::Sinkhole => 'S', RoomType::CrystalOrb => 'O', RoomType::Book => 'B', RoomType::Monster(ref m) => { if m.monster_type() == MonsterType::Vendor { 'V' } else { 'M' } } RoomType::Treasure(_) => 'T', } } pub fn room_name(r: &RoomType) -> String { match r { RoomType::Empty => String::from("an empty room"), RoomType::Entrance => String::from("the entrance"), RoomType::StairsDown => String::from("stairs going down"), RoomType::StairsUp => String::from("stairs going up"), RoomType::Gold => String::from("gold pieces"), RoomType::Pool => String::from("a pool"), RoomType::Chest => String::from("a chest"), RoomType::Flares => String::from("flares"), RoomType::Warp(_) => String::from("a warp"), RoomType::Sinkhole => String::from("a sinkhole"), RoomType::CrystalOrb => String::from("a crystal orb"), RoomType::Book => String::from("a book"), RoomType::Monster(m) => { let mon_str = G::monster_name(m.monster_type()); format!("{} {}", G::get_article(&mon_str), mon_str) } RoomType::Treasure(t) => G::treasure_name(*t.treasure_type()), } } /* pub fn gender_name(g: Gender) -> String { match g { Gender::Female => String::from("FEMALE"), Gender::Male => String::from("MALE"), } } */ /// Return player race pub fn race_name(&self) -> &str { match self.game.player_race() { Race::Hobbit => "Hobbit", Race::Elf => "Elf", Race::Human => "Human", Race::Dwarf => "Dwarf", } } /// Return stair name pub fn stair_name(s: Stairs) -> String { match s { Stairs::Up => String::from("up"), Stairs::Down => String::from("down"), } } /// Return player gender pub fn gender_name(g: Gender) -> String { match g { Gender::Female => String::from("female"), Gender::Male => String::from("male"), } } fn starts_with_vowel(s: &str) -> bool { if let Some(c) = String::from(s).to_uppercase().chars().next() { return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } false } pub fn get_article(s: &str) -> String { if G::starts_with_vowel(s) { return String::from("an"); } String::from("a") } pub fn initial_upper(s: &str) -> String { format!( "{}{}", s.get(0..1).unwrap().to_uppercase(), s.get(1..).unwrap() ) } }
//! Defines the basic types to do crypto, committees and hold basic information. use std::borrow::Borrow; use std::collections::HashMap; use std::convert::TryInto; use std::iter::FromIterator; use sha2::{Digest, Sha512}; use serde::{Deserialize, Serialize}; use crate::crypto::{PublicKey, SecretKey, Signature}; use crate::BigArray; pub const DIGEST_SIZE: usize = 32; pub type Address = u16; #[derive(Clone, Serialize, Deserialize, PartialEq)] pub struct BlockData { #[serde(with = "serde_bytes")] pub data: Vec<u8>, } impl From<Vec<u8>> for BlockData { fn from(data: Vec<u8>) -> Self { BlockData { data } } } impl Borrow<[u8]> for BlockData { fn borrow(&self) -> &[u8] { &self.data[..] } } pub type InstanceID = [u8; 16]; pub type RoundID = u64; pub type BlockDataDigest = [u8; DIGEST_SIZE]; #[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] pub struct BlockHeaderDigest( // #[serde(with = "BigArray")] pub [u8; DIGEST_SIZE], ); pub type SigningSecretKey = SecretKey; #[derive(Clone, PartialEq, Serialize, Deserialize)] pub struct SignatureBytes { #[serde(with = "BigArray")] pub bytes: Signature, } impl SignatureBytes { pub fn new(bytes: [u8; 48]) -> SignatureBytes { SignatureBytes { bytes } } } #[derive(Clone)] pub struct VotingPower { total_votes: u64, votes: HashMap<Address, u64>, public_keys: HashMap<Address, PublicKey>, } impl VotingPower { pub fn get_votes(&self, a: &Address) -> Option<u64> { return self.votes.get(a).cloned(); } pub fn get_key(&self, addr: &Address) -> &PublicKey { return &self.public_keys[&addr]; } pub fn num_keys(&self) -> usize { return self.public_keys.len(); } /// The amount of stake to ensure that any two sets with that amount /// intersect on an honest node (honest unit of stake.) pub fn quorum_size(&self) -> u64 { let one_third = self.total_votes / 3; 2 * one_third + 1 } /// The amount of stake to ensure at least one unit of stake is /// controlled by an honest node (honest vote). pub fn one_honest_size(&self) -> u64 { let one_third = self.total_votes / 3; one_third + 1 } /// Checks if an iterator of the form (Addr, _) represents /// votes forming a quorum pub fn sum_stake<'a, X, I>(&self, values: I) -> u64 where I: Iterator<Item = (&'a Address, X)>, { let mut votes = 0; for (addr, _) in values { if !self.votes.contains_key(addr) { continue; } votes += self.votes[addr]; } votes } /// Checks if an iterator of the form (Addr, _) represents /// votes forming a quorum pub fn has_quorum<'a, X, I>(&self, values: I) -> bool where I: Iterator<Item = (&'a Address, X)>, { self.sum_stake(values) >= self.quorum_size() } /// Checks if an iterator of the form (Addr, _) represents /// votes containing at least one honest node. pub fn has_one_honest<'a, X, I>(&self, values: I) -> bool where I: Iterator<Item = (&'a Address, X)>, { self.sum_stake(values) >= self.one_honest_size() } } impl FromIterator<(PublicKey, u64)> for VotingPower { fn from_iter<I: IntoIterator<Item = (PublicKey, u64)>>(iter: I) -> Self { let mut votes = HashMap::new(); let mut public_keys = HashMap::new(); let mut total_votes = 0; for (public_key, vote) in iter { let new_index = votes.len() as u16; votes.insert(new_index, vote); public_keys.insert(new_index, public_key); total_votes += vote; } VotingPower { total_votes, votes, public_keys, } } } pub struct RoundPseudoRandom { pub rand_seed: [u8; 64], } impl RoundPseudoRandom { pub fn new(instance: InstanceID, committee: &VotingPower) -> RoundPseudoRandom { let mut hasher = Sha512::default(); hasher.update("SEED"); hasher.update(instance); for (address, voting_power) in &committee.votes { hasher.update(address.to_le_bytes()); hasher.update(voting_power.to_le_bytes()); } let mut seed = RoundPseudoRandom { rand_seed: [0; 64] }; seed.rand_seed .clone_from_slice(hasher.finalize().as_slice()); seed } pub fn pick_leader<'a>(&self, round: RoundID, committee: &'a VotingPower) -> &'a Address { let mut hasher = Sha512::default(); hasher.update(self.rand_seed); hasher.update(round.to_le_bytes()); let index = u64::from_le_bytes( hasher.finalize().as_slice()[0..8] .try_into() .expect("slice with incorrect length"), ) % committee.total_votes; let mut current_total = 0; for (address, voting_power) in &committee.votes { current_total += voting_power; if current_total > index { return address; } } unreachable!(); } } #[cfg(test)] mod tests { use super::*; use crate::crypto::key_gen; #[test] fn voting_power() { let (pk0, _) = key_gen(); let (pk1, _) = key_gen(); let (pk2, _) = key_gen(); let (pk3, _) = key_gen(); let votes: VotingPower = vec![(pk0, 1), (pk1, 1), (pk2, 1), (pk3, 1)] .into_iter() .collect(); assert!(votes.quorum_size() == 3); } #[test] fn voting_quorum() { let (pk0, _) = key_gen(); let (pk1, _) = key_gen(); let (pk2, _) = key_gen(); let (pk3, _) = key_gen(); let votes: VotingPower = vec![(pk0, 1), (pk1, 1), (pk2, 1), (pk3, 1)] .into_iter() .collect(); assert!(votes.quorum_size() == 3); assert!(votes.one_honest_size() == 2); let hm: HashMap<Address, _> = vec![(0, 'a'), (1, 'b'), (2, 'c')].into_iter().collect(); assert!(votes.has_quorum(hm.iter())); let hm: HashMap<Address, _> = vec![(2, 'b'), (3, 'c')].into_iter().collect(); assert!(!votes.has_quorum(hm.iter())); } }
use super::{NSComparisonResult, NSString}; use crate::objc::{Class, NSInteger, NSObject, NSUInteger, Object, BOOL}; use std::{ cmp::Ordering, ffi::CStr, fmt, ops::Deref, os::raw::{ c_char, c_double, c_float, c_int, c_long, c_longlong, c_short, c_uchar, c_uint, c_ulong, c_ulonglong, c_ushort, }, ptr::NonNull, }; /// An object wrapper for primitive scalar numeric values. /// /// There are [static instances](#static-instances) which make using certain /// numbers much faster. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber). #[repr(transparent)] #[derive(Clone)] pub struct NSNumber(NSObject); impl From<NSNumber> for NSObject { #[inline] fn from(obj: NSNumber) -> Self { obj.0 } } impl Deref for NSNumber { type Target = NSObject; #[inline] fn deref(&self) -> &NSObject { &self.0 } } impl PartialEq for NSNumber { #[inline] fn eq(&self, other: &Self) -> bool { unsafe { _msg_send![self, isEqualToNumber: other as &Object => BOOL] != 0 } } } impl Eq for NSNumber {} impl PartialOrd for NSNumber { #[inline] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for NSNumber { #[inline] fn cmp(&self, other: &Self) -> Ordering { self.compare(other).into() } } impl From<bool> for NSNumber { #[inline] fn from(value: bool) -> Self { Self::number_with_bool(value) } } impl From<c_double> for NSNumber { #[inline] fn from(value: c_double) -> Self { Self::number_with_double(value) } } impl From<c_float> for NSNumber { #[inline] fn from(value: c_float) -> Self { Self::number_with_float(value) } } impl From<NSInteger> for NSNumber { #[inline] fn from(value: NSInteger) -> Self { Self::number_with_integer(value) } } impl From<NSUInteger> for NSNumber { #[inline] fn from(value: NSUInteger) -> Self { Self::number_with_unsigned_integer(value) } } impl From<c_char> for NSNumber { #[inline] fn from(value: c_char) -> Self { Self::number_with_char(value) } } impl From<c_uchar> for NSNumber { #[inline] fn from(value: c_uchar) -> Self { Self::number_with_unsigned_char(value) } } impl From<c_int> for NSNumber { #[inline] fn from(value: c_int) -> Self { Self::number_with_int(value) } } impl From<c_uint> for NSNumber { #[inline] fn from(value: c_uint) -> Self { Self::number_with_unsigned_int(value) } } impl From<c_long> for NSNumber { #[inline] fn from(value: c_long) -> Self { Self::number_with_long(value) } } impl From<c_ulong> for NSNumber { #[inline] fn from(value: c_ulong) -> Self { Self::number_with_unsigned_long(value) } } // TODO: Determine if `c_longlong` and `c_ulonglong` differ from `c_long` and // `c_ulong` on the targeted platforms. If they do, then conditionally add // `From` implementations. impl From<c_short> for NSNumber { #[inline] fn from(value: c_short) -> Self { Self::number_with_short(value) } } impl From<c_ushort> for NSNumber { #[inline] fn from(value: c_ushort) -> Self { Self::number_with_unsigned_short(value) } } impl From<NSNumber> for NSString { #[inline] fn from(number: NSNumber) -> Self { number.string_value() } } impl From<&NSNumber> for NSString { #[inline] fn from(number: &NSNumber) -> Self { number.string_value() } } impl fmt::Debug for NSNumber { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl fmt::Display for NSNumber { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self._cfboolean_value() { Some(false) => "NO".fmt(f), Some(true) => "YES".fmt(f), None => match unsafe { *self.objc_type() as u8 } { // https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html b'f' => self.float_value().fmt(f), b'd' => self.double_value().fmt(f), b'c' | b'i' | b's' | b'l' | b'q' => self.longlong_value().fmt(f), _ => self.unsigned_longlong_value().fmt(f), }, } } } impl fmt::Pointer for NSNumber { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_ptr().fmt(f) } } impl NSNumber { /// Returns the `NSNumber` class. #[inline] pub fn class() -> &'static Class { extern "C" { #[link_name = "OBJC_CLASS_$_NSNumber"] static CLASS: Class; } unsafe { &CLASS } } /// Creates an immutable string object from a raw nullable pointer. /// /// # Safety /// /// The pointer must point to a valid `NSNumber` instance. #[inline] pub const unsafe fn from_ptr(ptr: *mut Object) -> Self { Self(NSObject::from_ptr(ptr)) } /// Creates an immutable object from a raw non-null pointer. /// /// # Safety /// /// The pointer must point to a valid `NSNumber` instance. #[inline] pub const unsafe fn from_non_null_ptr(ptr: NonNull<Object>) -> Self { Self(NSObject::from_non_null_ptr(ptr)) } } /// Scalar constructors. impl NSNumber { // TODO: Add constructors: // - initWithCoder: /// Creates a number object containing a boolean. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551475-numberwithbool). #[inline] pub fn number_with_bool(value: bool) -> Self { unsafe { _msg_send![Self::class(), numberWithBool: value as BOOL] } } /// Creates a number object from a C `float`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551471-numberwithfloat) #[inline] pub fn number_with_float(value: c_float) -> Self { unsafe { _msg_send![Self::class(), numberWithFloat: value] } } /// Creates a number object from a C `double`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551463-numberwithdouble) #[inline] pub fn number_with_double(value: c_double) -> Self { unsafe { _msg_send![Self::class(), numberWithDouble: value] } } /// Creates a number object from a C `char`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551464-numberwithchar) #[inline] pub fn number_with_char(value: c_char) -> Self { unsafe { _msg_send![Self::class(), numberWithChar: value] } } /// Creates a number object from a C `short`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551476-numberwithshort) #[inline] pub fn number_with_short(value: c_short) -> Self { unsafe { _msg_send![Self::class(), numberWithShort: value] } } /// Creates a number object from a C `int`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551470-numberwithint) #[inline] pub fn number_with_int(value: c_int) -> Self { unsafe { _msg_send![Self::class(), numberWithInt: value] } } /// Creates a number object from a C `long`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551474-numberwithlong) #[inline] pub fn number_with_long(value: c_long) -> Self { unsafe { _msg_send![Self::class(), numberWithLong: value] } } /// Creates a number object from a C `long long`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551462-numberwithlonglong) #[inline] pub fn number_with_longlong(value: c_longlong) -> Self { unsafe { _msg_send![Self::class(), numberWithLongLong: value] } } /// Creates a number object from an Objective-C integer. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551473-numberwithinteger) #[inline] pub fn number_with_integer(value: NSInteger) -> Self { unsafe { _msg_send![Self::class(), numberWithInteger: value] } } /// Creates a number object from a C `unsigned char`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551468-numberwithunsignedchar) #[inline] pub fn number_with_unsigned_char(value: c_uchar) -> Self { unsafe { _msg_send![Self::class(), numberWithUnsignedChar: value] } } /// Creates a number object from a C `unsigned short`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551467-numberwithunsignedshort) #[inline] pub fn number_with_unsigned_short(value: c_ushort) -> Self { unsafe { _msg_send![Self::class(), numberWithUnsignedShort: value] } } /// Creates a number object from a C `unsigned int`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551472-numberwithunsignedint) #[inline] pub fn number_with_unsigned_int(value: c_uint) -> Self { unsafe { _msg_send![Self::class(), numberWithUnsignedInt: value] } } /// Creates a number object from a C `unsigned long`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551477-numberwithunsignedlong) #[inline] pub fn number_with_unsigned_long(value: c_ulong) -> Self { unsafe { _msg_send![Self::class(), numberWithUnsignedLong: value] } } /// Creates a number object from a C `unsigned long long`. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551465-numberwithunsignedlonglong) #[inline] pub fn number_with_unsigned_longlong(value: c_ulonglong) -> Self { unsafe { _msg_send![Self::class(), numberWithUnsignedLongLong: value] } } /// Creates a number object from a Objective-C unsigned integer. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1551469-numberwithunsignedinteger) #[inline] pub fn number_with_unsigned_integer(value: NSUInteger) -> Self { unsafe { _msg_send![Self::class(), numberWithUnsignedInteger: value] } } } /// <span id="static-instances">Static instances</span>. /// /// Use these number references over corresponding constructors for better /// performance. impl NSNumber { // SAFETY: NSNumber is toll-free bridged to CFNumber and CFBoolean, the // underlying types of these statics. /// Returns a reference to the equivalent of `@NO`. /// /// This internally references /// [`kCFBooleanFalse`](https://developer.apple.com/documentation/corefoundation/kCFBooleanFalse). #[inline] pub fn no() -> &'static NSNumber { extern "C" { static kCFBooleanFalse: NSNumber; } unsafe { &kCFBooleanFalse } } /// Returns a reference to the equivalent of `@YES`. /// /// This internally references /// [`kCFBooleanTrue`](https://developer.apple.com/documentation/corefoundation/kCFBooleanTrue). #[inline] pub fn yes() -> &'static NSNumber { extern "C" { static kCFBooleanTrue: NSNumber; } unsafe { &kCFBooleanTrue } } /// Returns a reference to a /// [NaN (Not a Number)](https://en.wikipedia.org/wiki/NaN) value. /// /// This internally references /// [`kCFNumberNaN`](https://developer.apple.com/documentation/corefoundation/kCFNumberNaN). #[inline] pub fn nan() -> &'static NSNumber { extern "C" { static kCFNumberNaN: NSNumber; } unsafe { &kCFNumberNaN } } /// Returns a reference to the infinity (∞) value. /// /// This internally references /// [`kCFNumberPositiveInfinity`](https://developer.apple.com/documentation/corefoundation/kcfnumberpositiveinfinity). #[inline] pub fn infinity() -> &'static NSNumber { extern "C" { static kCFNumberPositiveInfinity: NSNumber; } unsafe { &kCFNumberPositiveInfinity } } /// Returns a reference to the negative infinity (−∞) value. /// /// This internally references /// [`kCFNumberNegativeInfinity`](https://developer.apple.com/documentation/corefoundation/kcfnumbernegativeinfinity). #[inline] pub fn neg_infinity() -> &'static NSNumber { extern "C" { static kCFNumberNegativeInfinity: NSNumber; } unsafe { &kCFNumberNegativeInfinity } } } /// Instance operations. impl NSNumber { #[inline] pub(crate) fn _cfboolean_value(&self) -> Option<bool> { let this = self.as_ptr(); if this == Self::no().as_ptr() { Some(false) } else if this == Self::yes().as_ptr() { Some(true) } else { None } } // TODO: Create `NSValue` and move `objc_type` methods into it. /// Returns a pointer to a C string containing the Objective-C type of the /// data contained in the value object. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsvalue/1412365-objctype). #[inline] pub fn objc_type(&self) -> *const c_char { unsafe { _msg_send![self, objCType] } } /// Returns [`objc_type`](#method.objc_type) as a C string reference. #[inline] pub fn objc_type_cstr(&self) -> &CStr { unsafe { CStr::from_ptr(self.objc_type()) } } /// Returns an `NSComparisonResult` value that indicates whether the number /// object’s value is greater than, equal to, or less than a given number. /// /// This method follows the standard C rules for type conversion. For /// example, if you compare an NSNumber object that has an integer value /// with an NSNumber object that has a floating point value, the integer /// value is converted to a floating-point value for comparison. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1413562-compare) #[inline] pub fn compare(&self, other: &NSNumber) -> NSComparisonResult { unsafe { _msg_send![self, compare: other as &Object] } } /// Returns the number object's value expressed as a human-readable string. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1415802-stringvalue) #[inline] pub fn string_value(&self) -> NSString { unsafe { _msg_send![self, stringValue] } } /// Returns a string that represents the contents of the number object for a /// given locale. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1409984-descriptionwithlocale) #[inline] pub fn description_with_locale<L>(&self, locale: Option<L>) -> NSString where L: AsRef<Object>, { let locale: Option<&Object> = match &locale { Some(locale) => Some(locale.as_ref()), None => None, }; unsafe { _msg_send![self, descriptionWithLocale: locale] } } } /// Accessing numeric values. impl NSNumber { // TODO: Implement methods: // - decimalValue /// Returns the number object's value expressed as boolean, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1410865-boolvalue). #[inline] pub fn bool_value(&self) -> bool { unsafe { _msg_send![self, boolValue => BOOL] != 0 } } /// Returns the number object's value expressed as a C `float`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1418317-floatvalue). #[inline] pub fn float_value(&self) -> c_float { unsafe { _msg_send![self, floatValue] } } /// Returns the number object's value expressed as a C `double`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1414104-doublevalue). #[inline] pub fn double_value(&self) -> c_double { unsafe { _msg_send![self, doubleValue] } } /// Returns the number object's value expressed as a C `char`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1407838-charvalue). #[inline] pub fn char_value(&self) -> c_char { unsafe { _msg_send![self, charValue] } } /// Returns the number object's value expressed as a C `short`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1407601-shortvalue). #[inline] pub fn short_value(&self) -> c_short { unsafe { _msg_send![self, shortValue] } } /// Returns the number object's value expressed as a C `int`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1407153-intvalue). #[inline] pub fn int_value(&self) -> c_int { unsafe { _msg_send![self, intValue] } } /// Returns the number object's value expressed as a C `long`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1412566-longvalue). #[inline] pub fn long_value(&self) -> c_long { unsafe { _msg_send![self, longValue] } } /// Returns the number object's value expressed as a C `long long`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1416870-longlongvalue). #[inline] pub fn longlong_value(&self) -> c_longlong { unsafe { _msg_send![self, longLongValue] } } /// Returns the number object's value expressed as an Objective-C integer, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1412554-integervalue). #[inline] pub fn integer_value(&self) -> NSInteger { unsafe { _msg_send![self, integerValue] } } /// Returns the number object's value expressed as a C `unsigned char`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1409016-unsignedcharvalue). #[inline] pub fn unsigned_char_value(&self) -> c_uchar { unsafe { _msg_send![self, unsignedCharValue] } } /// Returns the number object's value expressed as a C `unsigned short`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1410604-unsignedshortvalue). #[inline] pub fn unsigned_short_value(&self) -> c_ushort { unsafe { _msg_send![self, unsignedShortValue] } } /// Returns the number object's value expressed as a C `unsigned int`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1417875-unsignedintvalue). #[inline] pub fn unsigned_int_value(&self) -> c_uint { unsafe { _msg_send![self, unsignedIntValue] } } /// Returns the number object's value expressed as a C `unsigned long`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1415252-unsignedlongvalue). #[inline] pub fn unsigned_long_value(&self) -> c_ulong { unsafe { _msg_send![self, unsignedLongValue] } } /// Returns the number object's value expressed as a C `unsigned long long`, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1414524-unsignedlonglongvalue). #[inline] pub fn unsigned_longlong_value(&self) -> c_ulonglong { unsafe { _msg_send![self, unsignedLongLongValue] } } /// Returns the number object's value expressed as an Objective-C unsigned integer, converted as necessary. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnumber/1413324-unsignedintegervalue). #[inline] pub fn unsigned_integer_value(&self) -> NSUInteger { unsafe { _msg_send![self, unsignedIntegerValue] } } }
mod ast; mod codegen; mod lexer; mod parser; mod semantic; use codegen::CodeGeneratable; use codespan_reporting::files::SimpleFiles; use codespan_reporting::term; use codespan_reporting::term::termcolor::{ColorChoice, StandardStream}; use lexer::Lexer; use parser::parse; use semantic::TypeCheckable; // use std::collections::HashMap; use std::fs; use structopt::StructOpt; use crate::codegen::Context; use crate::semantic::Scope; #[macro_use] extern crate lalrpop_util; /// Search for a pattern in a file and display the lines that contain it. #[derive(StructOpt)] struct Cli { /// The path to the file to read #[structopt(parse(from_os_str))] path: std::path::PathBuf, } fn main() { let args = Cli::from_args(); let path = args .path .to_str() .expect("should be a valid path to a file"); let file_name = args .path .as_path() .file_name() .expect("should be a file not a directory") .to_str() .unwrap(); let source = fs::read_to_string(path).expect("Unable to read file"); let mut files = SimpleFiles::new(); let file_id = files.add(file_name, &source); let writer = StandardStream::stderr(ColorChoice::Auto); let config = codespan_reporting::term::Config::default(); // lexical analysis let tokens = Lexer::new(source.as_str(), file_id); // syntactic analysis let ast = parse(tokens) .map_err(|err| { term::emit(&mut writer.lock(), &config, &files, &err.to_diagnostic()).unwrap() }) .unwrap(); println!("Successfully parsed!\n{:?}\n", ast); // semantic analysis let (global_scope, _) = ast .type_check(Scope::new_global()) .map_err(|err| { // term::emit(&mut writer.lock(), &config, &files, &err.to_diagnostic()).unwrap() panic!("{:?}", err); }) .unwrap(); println!("Succesfully type-checked!"); // these are always true, because if there is any type-checking error // they will not print whatsoever, because it will panic above println!("Arithmetic expressions: ok"); println!("Variable declarations inside scope: ok"); println!("Every break inside a for: ok"); println!("Scope: {:#?}", global_scope); // IR generation(generating 3-address intermediate representation code) let instructions = ast.generate_code(&mut Context::new()); println!( "Succesfully generated code: \n{}", instructions .into_iter() .map(|i| i.to_string()) .filter(|s| s.len() > 0) .collect::<Vec<String>>() .join("\n") ); }
pub struct Solution; pub struct TreeNode { pub val: i32, pub left: Tree, pub right: Tree, } use std::cell::RefCell; use std::rc::Rc; type Tree = Option<Rc<RefCell<TreeNode>>>; impl Solution { pub fn sum_numbers(root: Tree) -> i32 { match root { None => 0, Some(node) => rec(&node.borrow()).0, } } } fn rec(node: &TreeNode) -> (i32, i32) { match (&node.left, &node.right) { (None, None) => (node.val, 10), (Some(node_l), None) => { let (a, b) = rec(&node_l.borrow()); (a + b * node.val, b * 10) } (None, Some(node_r)) => { let (a, b) = rec(&node_r.borrow()); (a + b * node.val, b * 10) } (Some(node_l), Some(node_r)) => { let (a, b) = rec(&node_l.borrow()); let (c, d) = rec(&node_r.borrow()); (a + c + (b + d) * node.val, (b + d) * 10) } } } #[test] fn test0129() { let tree = |val, left, right| Some(Rc::new(RefCell::new(TreeNode { val, left, right }))); assert_eq!( Solution::sum_numbers(tree(1, tree(2, None, None), tree(3, None, None))), 25 ); assert_eq!( Solution::sum_numbers(tree( 4, tree(9, tree(5, None, None), tree(1, None, None)), tree(0, None, None) )), 1026 ); }
pub mod audio; pub mod error; pub mod fs; pub mod graphics; pub mod input; pub mod math; mod context; use std::future::Future; pub use self::{context::*, error::EngineError}; pub mod log { pub use macroquad::miniquad::{debug, error, info, log::Level, trace, warn}; } pub mod utils { pub use macroquad::prelude::{HashMap, HashSet}; pub fn seed() -> u64 { (time() * 10000000.0) as u64 } pub fn time() -> f64 { macroquad::miniquad::date::now() } } #[deprecated] pub extern crate macroquad; // . #[allow(unused_variables)] pub trait State<U: UserContext = ()> { fn start(&mut self, ctx: &mut Context, userctx: &mut U) {} fn update(&mut self, ctx: &mut Context, userctx: &mut U, delta: f32) {} fn draw(&mut self, ctx: &mut Context, userctx: &mut U) {} fn end(&mut self, ctx: &mut Context, userctx: &mut U) {} } pub fn run< U: UserContext, OPEN, OPENFUNC: Future<Output = OPEN> + 'static, LOAD, LOADFUNC: FnOnce(&mut Context, &mut U, OPEN) -> LOAD + 'static, S: State<U>, SFUNC: FnOnce(&mut Context, &mut U, LOAD) -> S + 'static, >( args: ContextBuilder<impl Into<String>>, open: OPENFUNC, load: LOADFUNC, state: SFUNC, ) { macroquad::Window::from_config(args.into(), async move { macroquad::prelude::prevent_quit(); macroquad::prelude::clear_background(graphics::Color::BLACK); macroquad::prelude::draw_text("Loading...", 5.0, 5.0, 20.0, graphics::Color::WHITE); let open = open.await; let mut ctx = Context::new() .unwrap_or_else(|err| panic!("Could not initialize Context with error {}", err)); let mut userctx = U::new(&mut ctx) .unwrap_or_else(|err| panic!("Cannot initialize user context with error {}", err)); let data = (load)(&mut ctx, &mut userctx, open); let mut state = (state)(&mut ctx, &mut userctx, data); state.start(&mut ctx, &mut userctx); loop { ctx.input.update(); state.update(&mut ctx, &mut userctx, macroquad::prelude::get_frame_time()); state.draw(&mut ctx, &mut userctx); if macroquad::prelude::is_quit_requested() || !ctx.running { state.end(&mut ctx, &mut userctx); break; } macroquad::prelude::next_frame().await; } }); }
#![feature(external_doc)] #![doc(include = "../README.md")] pub mod ast; pub mod interpreter; pub mod lexer; pub mod parser; pub mod prelude; pub mod token; use std::fmt; /// The type of an identifier in `tini`. pub type Identifier = String; /// A position in a file, consisting of a line number and a column number. #[derive(Clone, Copy, Default, PartialEq)] pub struct Position { /// The line number in a file. pub line: usize, /// The column number in a file. pub column: usize, } impl Position { /// Create a new `Position`. pub fn new(line: usize, column: usize) -> Position { Position { line, column } } /// Go to the beginning of the next line. pub fn next_line(&mut self) { self.line += 1; self.column = 1; } /// Go to the next column. pub fn next_column(&mut self) { self.column += 1; } } impl fmt::Display for Position { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.line, self.column) } } impl fmt::Debug for Position { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Position({}:{})", self.line, self.column) } }