text
stringlengths
8
4.13M
// 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 { argh::FromArgs, failure::{format_err, Error}, fidl_fuchsia_session::{LauncherMarker, LauncherProxy, SessionConfiguration}, fuchsia_async as fasync, fuchsia_component::client::connect_to_service, }; #[derive(FromArgs)] /// The session control component. pub struct SessionControlArgs { #[argh(option, short = 's')] /// the URL for the session to launch. pub session_url: String, } #[fasync::run_singlethreaded] async fn main() -> Result<(), Error> { let SessionControlArgs { session_url } = argh::from_env(); let launcher = connect_to_service::<LauncherMarker>()?; match launch_session(&session_url, launcher).await { Ok(_) => println!("Launched session: {:?}", session_url), Err(err) => println!("Failed to launch session: {:?}, {:?}", session_url, err), }; Ok(()) } /// Launches a session. /// /// # Parameters /// - `session_url`: The URL of the session to launch. /// - `launcher`: The launcher proxy to use to launch the session. async fn launch_session(session_url: &str, launcher: LauncherProxy) -> Result<(), Error> { let result = launcher .launch_session(SessionConfiguration { session_url: Some(session_url.to_string()) }) .await?; result.map_err(|err: fidl_fuchsia_session::LaunchSessionError| format_err!("{:?}", err))?; Ok(()) } #[cfg(test)] mod tests { use { super::launch_session, fidl::endpoints::create_proxy_and_stream, fidl_fuchsia_session::{LaunchSessionError, LauncherMarker, LauncherRequest}, fuchsia_async as fasync, futures::TryStreamExt, }; #[fasync::run_singlethreaded(test)] async fn test_launch_session() { let (launcher, mut launcher_server) = create_proxy_and_stream::<LauncherMarker>().expect("Failed to create Launcher FIDL."); let session_url = "test_session"; fasync::spawn(async move { if let Some(launch_request) = launcher_server.try_next().await.unwrap() { let LauncherRequest::LaunchSession { configuration, responder } = launch_request; assert_eq!(configuration.session_url, Some(session_url.to_string())); let _ = responder.send(&mut Ok(())); } else { assert!(false); } }); assert!(launch_session(&session_url, launcher).await.is_ok()); } #[fasync::run_singlethreaded(test)] async fn test_launch_session_error() { let (launcher, mut launcher_server) = create_proxy_and_stream::<LauncherMarker>().expect("Failed to create Launcher FIDL."); let session_url = "test_session"; fasync::spawn(async move { if let Some(launch_request) = launcher_server.try_next().await.unwrap() { let LauncherRequest::LaunchSession { configuration: _, responder } = launch_request; let _ = responder.send(&mut Err(LaunchSessionError::Failed)); } else { assert!(false); } }); assert!(launch_session(&session_url, launcher).await.is_err()); } }
use nalgebra::{Point2, Vector2}; use class::{ComponentClass, ComponentClassFactory, BackgroundAttributes}; use render::{Renderer}; use scripting::{ScriptRuntime}; use template::{Attributes, Color, EventHook}; use {EventSink, Error, ComponentAttributes, ComponentId}; /// A button component class, raises events on click. pub struct ButtonClass { background: BackgroundAttributes, attributes: ButtonAttributes, hovering: bool, } impl ComponentClassFactory for ButtonClass { fn new(attributes: &Attributes, runtime: &ScriptRuntime) -> Result<Self, Error> { Ok(ButtonClass { background: BackgroundAttributes::load(attributes, runtime)?, attributes: ButtonAttributes::load(attributes, runtime)?, hovering: false, }) } } impl ComponentClass for ButtonClass { fn update_attributes( &mut self, attributes: &Attributes, runtime: &ScriptRuntime, ) -> Result<(), Error> { self.background = BackgroundAttributes::load(attributes, runtime)?; self.attributes = ButtonAttributes::load(attributes, runtime)?; Ok(()) } fn render( &self, id: ComponentId, attributes: &ComponentAttributes, computed_size: Vector2<f32>, renderer: &mut Renderer, ) -> Result<(), Error> { self.background.render(id, attributes, computed_size, renderer, self.hovering)?; if let Some(ref text) = self.attributes.text { renderer.text( id, &text, self.attributes.text_font.as_ref(), self.attributes.text_size, Point2::new(0.0, 0.0), computed_size, self.attributes.text_color, )?; } Ok(()) } fn is_capturing_cursor(&self) -> bool { true } fn hover_start_event(&mut self, _event_sink: &mut EventSink) -> bool { self.hovering = true; true } fn hover_end_event(&mut self, _event_sink: &mut EventSink) -> bool { self.hovering = false; true } fn pressed_event(&mut self, event_sink: &mut EventSink) { if let Some(ref event) = self.attributes.on_pressed { event_sink.raise(event); } } } struct ButtonAttributes { text: Option<String>, text_color: Color, text_font: Option<String>, text_size: Option<i32>, on_pressed: Option<EventHook>, } impl ButtonAttributes { pub fn load(attributes: &Attributes, runtime: &ScriptRuntime) -> Result<Self, Error> { Ok(ButtonAttributes { text: attributes.attribute_optional("text", |v| v.as_string(runtime))?, text_color: attributes.attribute( "text-color", |v| v.as_color(runtime), Color::new_u8(0, 0, 0, 255) )?, text_font: attributes.attribute_optional("text-font", |v| v.as_string(runtime))?, text_size: attributes.attribute_optional("text-size", |v| v.as_integer(runtime))?, on_pressed: attributes.attribute_optional("on-pressed", |v| v.as_event_hook(runtime))?, }) } }
//! Noisey `Display` impls. use crate::ast::{Binop, Unop}; use crate::builtins::{Function, Variable}; use crate::cfg::{BasicBlock, Ident, PrimExpr, PrimStmt, PrimVal, Transition}; use crate::common::FileSpec; use crate::lexer; use std::fmt::{self, Display, Formatter}; use std::string::String; pub(crate) struct Wrap(pub Ident); impl Display for Wrap { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let Ident { low, sub, .. } = self.0; write!(f, "{}-{}", low, sub) } } impl<'a> Display for Transition<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match &self.0 { Some(v) => write!(f, "{}", v), None => write!(f, "else"), } } } impl<'a> Display for BasicBlock<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { for i in &self.q { writeln!(f, "{}", i)?; } Ok(()) } } impl<'a> Display for PrimStmt<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use PrimStmt::*; match self { AsgnIndex(id, pv, pe) => write!(f, "{}[{}] = {}", Wrap(*id), pv, pe), AsgnVar(id, pe) => write!(f, "{} = {}", Wrap(*id), pe), SetBuiltin(v, pv) => write!(f, "{} = {}", v, pv), Return(v) => write!(f, "return {}", v), Printf(fmt, args, out) => { write!(f, "printf({}", fmt)?; for (i, a) in args.iter().enumerate() { if i == args.len() - 1 { write!(f, "{}", a)?; } else { write!(f, "{}, ", a)?; } } write!(f, ")")?; if let Some((out, ap)) = out { let redirect = match ap { FileSpec::Trunc => ">", FileSpec::Append => ">>", FileSpec::Cmd => "|", }; write!(f, " {} {}", out, redirect)?; } Ok(()) } PrintAll(args, out) => { write!(f, "print(")?; for (i, a) in args.iter().enumerate() { if i == args.len() - 1 { write!(f, "{}", a)?; } else { write!(f, "{}, ", a)?; } } write!(f, ")")?; if let Some((out, ap)) = out { let redirect = match ap { FileSpec::Trunc => ">", FileSpec::Append => ">>", FileSpec::Cmd => "|", }; write!(f, " {} {}", out, redirect)?; } Ok(()) } IterDrop(v) => write!(f, "drop_iter {}", v), } } } impl<'a> Display for PrimExpr<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use PrimExpr::*; fn write_func( f: &mut Formatter, func: impl fmt::Display, os: &[impl fmt::Display], ) -> fmt::Result { write!(f, "{}(", func)?; for (i, o) in os.iter().enumerate() { let is_last = i == os.len() - 1; if is_last { write!(f, "{}", o)?; } else { write!(f, "{}, ", o)?; } } write!(f, ")") } match self { Val(v) => write!(f, "{}", v), Phi(preds) => { write!(f, "phi [")?; for (i, (pred, id)) in preds.iter().enumerate() { let is_last = i == preds.len() - 1; if is_last { write!(f, "←{}:{}", pred.index(), Wrap(*id))? } else { write!(f, "←{}:{}, ", pred.index(), Wrap(*id))? } } write!(f, "]") } CallBuiltin(b, os) => write_func(f, b, &os[..]), CallUDF(func, os) => write_func(f, func, &os[..]), Sprintf(fmt, os) => write_func(f, format!("sprintf[{}]", fmt), &os[..]), Index(m, v) => write!(f, "{}[{}]", m, v), IterBegin(m) => write!(f, "begin({})", m), HasNext(i) => write!(f, "hasnext({})", i), Next(i) => write!(f, "next({})", i), LoadBuiltin(b) => write!(f, "{}", b), } } } impl<'a> Display for PrimVal<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use PrimVal::*; match self { Var(id) => write!(f, "{}", Wrap(*id)), ILit(n) => write!(f, "{}@int", *n), FLit(n) => write!(f, "{}@float", *n), StrLit(s) => write!(f, "\"{}\"", String::from_utf8_lossy(s)), } } } impl Display for Function { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use Function::*; match self { Unop(u) => write!(f, "{}", u), Binop(b) => write!(f, "{}", b), FloatFunc(ff) => write!(f, "{}", ff.func_name()), IntFunc(bw) => write!(f, "{}", bw.func_name()), ReadErr => write!(f, "hasline"), ReadErrCmd => write!(f, "hasline(cmd)"), Nextline => write!(f, "nextline"), NextlineCmd => write!(f, "nextline(cmd)"), ReadErrStdin => write!(f, "hasline(stdin)"), NextlineStdin => write!(f, "nextline(stdin)"), ReadLineStdinFused => write!(f, "stdin-fused"), NextFile => write!(f, "nextfile"), Setcol => write!(f, "$="), Split => write!(f, "split"), Length => write!(f, "length"), Contains => write!(f, "contains"), Delete => write!(f, "delete"), Clear => write!(f, "clear"), Close => write!(f, "close"), Match => write!(f, "match"), SubstrIndex => write!(f, "index"), Sub => write!(f, "sub"), GSub => write!(f, "gsub"), EscapeCSV => write!(f, "escape_csv"), EscapeTSV => write!(f, "escape_tsv"), JoinCSV => write!(f, "join_csv"), JoinTSV => write!(f, "join_tsv"), JoinCols => write!(f, "join_fields"), Substr => write!(f, "substr"), ToInt => write!(f, "int"), HexToInt => write!(f, "hex"), Rand => write!(f, "rand"), Srand => write!(f, "srand"), ReseedRng => write!(f, "srand_reseed"), System => write!(f, "system"), UpdateUsedFields => write!(f, "update_used_fields"), SetFI => write!(f, "set-FI"), ToLower => write!(f, "tolower"), ToUpper => write!(f, "toupper"), IncMap => write!(f, "inc_map"), Exit => write!(f, "exit"), } } } impl Display for Variable { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use Variable::*; write!( f, "{}", match self { ARGC => "ARGC", ARGV => "ARGV", OFS => "OFS", ORS => "ORS", FS => "FS", RS => "RS", NF => "NF", NR => "NR", FNR => "FNR", FILENAME => "FILENAME", RSTART => "RSTART", RLENGTH => "RLENGTH", PID => "PID", FI => "FI", } ) } } impl Display for Unop { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use Unop::*; write!( f, "{}", match self { Column => "$", Not => "!", Neg => "-", Pos => "+", } ) } } impl Display for Binop { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use Binop::*; write!( f, "{}", match self { Plus => "+", Minus => "-", Mult => "*", Div => "/", Mod => "%", Concat => "<concat>", IsMatch => "~", Pow => "^", LT => "<", GT => ">", LTE => "<=", GTE => ">=", EQ => "==", } ) } } impl Display for lexer::Loc { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { write!(fmt, "line {}, column {}", self.line + 1, self.col + 1) } } impl Display for lexer::Error { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { write!(fmt, "{}. {}", self.location, self.desc) } } impl<'a> Display for lexer::Tok<'a> { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { use lexer::Tok::*; let rep = match self { Begin => "BEGIN", Prepare => "PREPARE", End => "END", Break => "break", Continue => "continue", Next => "next", NextFile => "nextfile", For => "for", If => "if", Else => "else", Exit => "exit", ExitLP => "exit(", Print => "print", Printf => "printf", // Separate token for a "print(" and "printf(". PrintLP => "print(", PrintfLP => "printf(", While => "while", Do => "do", // { } LBrace => "{", RBrace => "}", // [ ] LBrack => "[", RBrack => "]", // ( ) LParen => "(", RParen => ")", Getline => "getline", Pipe => "|", Assign => "=", Add => "+", AddAssign => "+=", Sub => "-", SubAssign => "-=", Mul => "*", MulAssign => "*=", Div => "/", DivAssign => "/=", Pow => "^", PowAssign => "^=", Mod => "%", ModAssign => "%=", Match => "~", NotMatch => "!~", EQ => "==", NEQ => "!=", LT => "<", GT => ">", LTE => "<=", GTE => ">=", Incr => "++", Decr => "--", Not => "!", AND => "&&", OR => "||", QUESTION => "?", COLON => ":", Append => ">>", Dollar => "$", Semi => ";", Newline => "\\n", Comma => ",", In => "in", Delete => "delete", Return => "return", Ident(s) => return write!(fmt, "identifier({})", s), StrLit(s) => return write!(fmt, "{:?}", s), PatLit(s) => return write!(fmt, "/{}/", s), CallStart(s) => return write!(fmt, "{}(", s), FunDec(s) => return write!(fmt, "function {}", s), ILit(s) | HexLit(s) | FLit(s) => return write!(fmt, "{}", s), }; write!(fmt, "{}", rep) } }
struct S; // Concrete type `S` #[derive(Debug)] struct GenericVal<T>(T,); // Generic type `GenericVal` // impl of GenericVal where we explicitly specify type parameters: impl GenericVal<f32> {} // Specify `f32` impl GenericVal<S> {} // Specify `S` as defined above // `<T>` Must precede the type to remain generic impl <T> GenericVal<T> {} struct Val<T> { val: T } struct GenVal<T>{ gen_val: T } // impl of Val impl Val<f64> { fn value(&self) -> &f64 { &self.val } } // impl of GenVal for a generic type `T` impl <T> GenVal<T> { fn value(&self) -> &T { &self.gen_val } } fn main() { let x = Val { val: 3.14 }; let y = GenVal { gen_val: 8.6f32 }; let gv = GenericVal("fooby"); println!("{}, {}", x.value(), y.value()); println!("{:?}", gv); }
#[cfg(not(feature = "lib"))] use std::{cell::RefCell, rc::Rc}; use std::collections::HashMap; use mold::Raster; #[cfg(not(feature = "lib"))] use crate::Context; use crate::styling::COMMANDS_LAYER_ID_MAX; #[derive(Debug)] pub struct Composition { #[cfg(not(feature = "lib"))] pub(crate) context: Rc<RefCell<Context>>, placements: HashMap<u32, Vec<Raster>>, layers: HashMap<u32, Raster>, } impl Composition { #[cfg(feature = "lib")] pub fn new() -> Self { Self { placements: HashMap::new(), layers: HashMap::new(), } } #[cfg(not(feature = "lib"))] pub fn new(context: Rc<RefCell<Context>>) -> Self { Self { context, placements: HashMap::new(), layers: HashMap::new(), } } pub fn reset(&mut self) { self.placements.clear(); self.layers.clear(); } pub fn place(&mut self, layer_id: u32, raster: Raster) { if layer_id >= COMMANDS_LAYER_ID_MAX { panic!( "layer_id overflowed the maximum of {}", COMMANDS_LAYER_ID_MAX ); } self.layers.remove(&layer_id); self.placements .entry(layer_id) .and_modify(|layer| layer.push(raster.clone())) .or_insert_with(|| vec![raster]); } pub fn layers(&mut self) -> &HashMap<u32, Raster> { for (&layer_id, rasters) in &self.placements { self.layers .entry(layer_id) .or_insert_with(|| { match rasters.len() { 0 => Raster::empty(), 1 => rasters[0].clone(), _ => Raster::union(rasters.iter()), } }); } &self.layers } }
pub fn run_demo() { let sentences = vec!["VADER is smart, handsome, and funny.", // positive sentence example "VADER is smart, handsome, and funny!", // punctuation emphasis handled correctly (sentiment intensity adjusted) "VADER is very smart, handsome, and funny.", // booster words handled correctly (sentiment intensity adjusted) "VADER is VERY SMART, handsome, and FUNNY.", // emphasis for ALLCAPS handled "VADER is VERY SMART, handsome, and FUNNY!!!", // combination of signals - VADER appropriately adjusts intensity "VADER is VERY SMART, uber handsome, and FRIGGIN FUNNY!!!", // booster words & punctuation make this close to ceiling for score "VADER is not smart, handsome, nor funny.", // negation sentence example "The book was good.", // positive sentence "At least it isn't a horrible book.", // negated negative sentence with contraction "The book was only kind of good.", // qualified positive sentence is handled correctly (intensity adjusted) "The plot was good, but the characters are uncompelling and the dialog is not great.", // mixed negation sentence "Today SUX!", // negative slang with capitalization emphasis "Today only kinda sux! But I'll get by, lol", // mixed sentiment example with slang and constrastive conjunction "but" "Make sure you :) or :D today!", // emoticons handled "Catch utf-8 emoji such as 💘 and 💋 and 😁", // emojis handled "Not bad at all"]; // Capitalized negation let analyzer = ::SentimentIntensityAnalyzer::new(); println!("----------------------------------------------------"); println!(" - Analyze typical example cases, including handling of:"); println!(" -- negations"); println!(" -- punctuation emphasis & punctuation flooding"); println!(" -- word-shape as emphasis (capitalization difference)"); println!(" -- degree modifiers (intensifiers such as 'very' and dampeners such as 'kind of')"); println!(" -- slang words as modifiers such as 'uber' or 'friggin' or 'kinda'"); println!(" -- contrastive conjunction 'but' indicating a shift in sentiment; sentiment of later text is dominant"); println!(" -- use of contractions as negations"); println!(" -- sentiment laden emoticons such as :) and :D"); println!(" -- utf-8 encoded emojis such as 💘 and 💋 and 😁"); println!(" -- sentiment laden slang words (e.g., 'sux')"); println!(" -- sentiment laden initialisms and acronyms (for example: 'lol') \n"); for sentence in sentences{ let scores = analyzer.polarity_scores(sentence); println!("{:-<65} {:#?}", sentence, scores); } println!("----------------------------------------------------"); println!(" - About the scoring: "); println!(" -- The 'compound' score is computed by summing the valence scores of each word in the lexicon, adjusted according to the rules, and then normalized to be between -1 (most extreme negative) and +1 (most extreme positive). This is the most useful metric if you want a single unidimensional measure of sentiment for a given sentence. Calling it a 'normalized, weighted composite score' is accurate."); println!(" -- The 'pos', 'neu', and 'neg' scores are ratios for proportions of text that fall in each category (so these should all add up to be 1... or close to it with float operation). These are the most useful metrics if you want multidimensional measures of sentiment for a given sentence."); println!("----------------------------------------------------"); let tricky_sentences = vec!["Sentiment analysis has never been good.", "Sentiment analysis has never been this good!", "Most automated sentiment analysis tools are shit.", "With VADER, sentiment analysis is the shit!", "Other sentiment analysis tools can be quite bad.", "On the other hand, VADER is quite bad ass", "VADER is such a badass!", // slang with punctuation emphasis "Without a doubt, excellent idea.", "Roger Dodger is one of the most compelling variations on this theme.", "Roger Dodger is at least compelling as a variation on the theme.", "Roger Dodger is one of the least compelling variations on this theme.", "Not such a badass after all.", // Capitalized negation with slang "Without a doubt, an excellent idea."]; // "without {any} doubt" as negation println!("----------------------------------------------------"); println!(" - Analyze examples of tricky sentences that cause trouble to other sentiment analysis tools."); println!(" -- special case idioms - e.g., 'never good' vs 'never this good', or 'bad' vs 'bad ass'."); println!(" -- special uses of 'least' as negation versus comparison \n"); for sentence in tricky_sentences { let scores = analyzer.polarity_scores(sentence); println!("{:-<65} {:#?}", sentence, scores); } println!("----------------------------------------------------"); }
use crate::{ geom::Vector, graphics::{ImageScaleStrategy, ResizeStrategy}, }; ///A builder that constructs a Window #[derive(Debug)] pub struct Settings { /// If the cursor should be visible over the application pub show_cursor: bool, /// The smallest size the user can resize the window to /// /// Does nothing on web pub min_size: Option<Vector>, /// The largest size the user can resize the window to /// /// Does nothing on web pub max_size: Option<Vector>, /// How content should be presented when the window is resized pub resize: ResizeStrategy, /// How images should be scaled pub scale: ImageScaleStrategy, /// If the application should be fullscreen pub fullscreen: bool, /// How many milliseconds should elapse between update calls pub update_rate: f64, /// The maximum number of updates to run in a single frame /// /// See https://gafferongames.com/post/fix_your_timestep/ for an explanation of fixed timesteps pub max_updates: u32, /// How many milliseconds should elapse between draw calls pub draw_rate: f64, /// The icon on the window or the favicon on the tab pub icon_path: Option<&'static str>, // TODO: statiC? /// If VSync should be enabled /// /// Does nothing on web currently pub vsync: bool, /// How many samples to do for MSAA /// /// By default it is None; if it is Some, it should be a non-zero power of two /// /// Does nothing on web currently pub multisampling: Option<u16>, } impl Default for Settings { fn default() -> Settings { Settings { show_cursor: true, min_size: None, max_size: None, resize: ResizeStrategy::default(), scale: ImageScaleStrategy::default(), fullscreen: false, update_rate: 1000. / 60., max_updates: 0, draw_rate: 0., icon_path: None, vsync: true, multisampling: None, } } }
#[doc = "Reader of register CHMAP1"] pub type R = crate::R<u32, super::CHMAP1>; #[doc = "Writer for register CHMAP1"] pub type W = crate::W<u32, super::CHMAP1>; #[doc = "Register CHMAP1 `reset()`'s with value 0"] impl crate::ResetValue for super::CHMAP1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CH8SEL`"] pub type CH8SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH8SEL`"] pub struct CH8SEL_W<'a> { w: &'a mut W, } impl<'a> CH8SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `CH9SEL`"] pub type CH9SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH9SEL`"] pub struct CH9SEL_W<'a> { w: &'a mut W, } impl<'a> CH9SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `CH10SEL`"] pub type CH10SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH10SEL`"] pub struct CH10SEL_W<'a> { w: &'a mut W, } impl<'a> CH10SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `CH11SEL`"] pub type CH11SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH11SEL`"] pub struct CH11SEL_W<'a> { w: &'a mut W, } impl<'a> CH11SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Reader of field `CH12SEL`"] pub type CH12SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH12SEL`"] pub struct CH12SEL_W<'a> { w: &'a mut W, } impl<'a> CH12SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `CH13SEL`"] pub type CH13SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH13SEL`"] pub struct CH13SEL_W<'a> { w: &'a mut W, } impl<'a> CH13SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 20)) | (((value as u32) & 0x0f) << 20); self.w } } #[doc = "Reader of field `CH14SEL`"] pub type CH14SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH14SEL`"] pub struct CH14SEL_W<'a> { w: &'a mut W, } impl<'a> CH14SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Reader of field `CH15SEL`"] pub type CH15SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH15SEL`"] pub struct CH15SEL_W<'a> { w: &'a mut W, } impl<'a> CH15SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28); self.w } } impl R { #[doc = "Bits 0:3 - uDMA Channel 8 Source Select"] #[inline(always)] pub fn ch8sel(&self) -> CH8SEL_R { CH8SEL_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - uDMA Channel 9 Source Select"] #[inline(always)] pub fn ch9sel(&self) -> CH9SEL_R { CH9SEL_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - uDMA Channel 10 Source Select"] #[inline(always)] pub fn ch10sel(&self) -> CH10SEL_R { CH10SEL_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - uDMA Channel 11 Source Select"] #[inline(always)] pub fn ch11sel(&self) -> CH11SEL_R { CH11SEL_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:19 - uDMA Channel 12 Source Select"] #[inline(always)] pub fn ch12sel(&self) -> CH12SEL_R { CH12SEL_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - uDMA Channel 13 Source Select"] #[inline(always)] pub fn ch13sel(&self) -> CH13SEL_R { CH13SEL_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 24:27 - uDMA Channel 14 Source Select"] #[inline(always)] pub fn ch14sel(&self) -> CH14SEL_R { CH14SEL_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:31 - uDMA Channel 15 Source Select"] #[inline(always)] pub fn ch15sel(&self) -> CH15SEL_R { CH15SEL_R::new(((self.bits >> 28) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - uDMA Channel 8 Source Select"] #[inline(always)] pub fn ch8sel(&mut self) -> CH8SEL_W { CH8SEL_W { w: self } } #[doc = "Bits 4:7 - uDMA Channel 9 Source Select"] #[inline(always)] pub fn ch9sel(&mut self) -> CH9SEL_W { CH9SEL_W { w: self } } #[doc = "Bits 8:11 - uDMA Channel 10 Source Select"] #[inline(always)] pub fn ch10sel(&mut self) -> CH10SEL_W { CH10SEL_W { w: self } } #[doc = "Bits 12:15 - uDMA Channel 11 Source Select"] #[inline(always)] pub fn ch11sel(&mut self) -> CH11SEL_W { CH11SEL_W { w: self } } #[doc = "Bits 16:19 - uDMA Channel 12 Source Select"] #[inline(always)] pub fn ch12sel(&mut self) -> CH12SEL_W { CH12SEL_W { w: self } } #[doc = "Bits 20:23 - uDMA Channel 13 Source Select"] #[inline(always)] pub fn ch13sel(&mut self) -> CH13SEL_W { CH13SEL_W { w: self } } #[doc = "Bits 24:27 - uDMA Channel 14 Source Select"] #[inline(always)] pub fn ch14sel(&mut self) -> CH14SEL_W { CH14SEL_W { w: self } } #[doc = "Bits 28:31 - uDMA Channel 15 Source Select"] #[inline(always)] pub fn ch15sel(&mut self) -> CH15SEL_W { CH15SEL_W { w: self } } }
pub fn word_pattern(pattern: String, s: String) -> bool { use std::collections::HashMap; if pattern.len() != s.split_whitespace().count() { return false; } let pattern_word: HashMap<char, &str> = pattern.chars().zip(s.split_whitespace()).collect(); let word_pattern: HashMap<&str, char> = pattern_word.iter().map(|(&k, &v)| (v, k)).collect(); for (pattern, word) in pattern.chars().zip(s.split_whitespace()) { match (word_pattern.get(word), pattern_word.get(&pattern)) { (Some(&a), Some(&b)) => { if a != pattern || b != word { return false; } } _ => return false, } } true } #[cfg(test)] mod word_pattern_tests { use super::*; #[test] fn word_pattern_test_one() { // arrange let pattern = "abba".into(); let s = "dog cat cat dog".into(); // act let result = word_pattern(pattern, s); // assert assert_eq!(result, true); } #[test] fn word_pattern_test_two() { // arrange let pattern = "abba".into(); let s = "dog dog dog dog".into(); // act let result = word_pattern(pattern, s); // assert assert_eq!(result, false); } #[test] fn word_pattern_test_three() { // arrange let pattern = "abc".into(); let s = "dog cat dog".into(); // act let result = word_pattern(pattern, s); // assert assert_eq!(result, false); } }
//! Database elements for all tables #[cfg(feature="rusqlite")] use rusqlite::Row; #[cfg(feature="rusqlite")] use rusqlite::Result; use std::{mem, fmt}; use std::path::PathBuf; #[cfg(feature = "rusqlite")] use sha2::{Digest, Sha256}; #[cfg(feature = "hex-gossip")] use hex_gossip::PeerId; /// Peer id copy #[cfg(not(feature="hex-gossip"))] pub type PeerId = Vec<u8>; /// Track identification #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature="serde", derive(Serialize, Deserialize))] pub struct TrackKey([u8; 16]); impl TrackKey { pub fn from_vec(buf: &[u8]) -> TrackKey { assert_eq!(buf.len(), 16); let mut key = TrackKey([0u8; 16]); key.0.copy_from_slice(buf); key } pub fn from_str(buf: &str) -> TrackKey { assert_eq!(buf.len(), 32); let mut key = TrackKey([0u8; 16]); for i in 0..16 { key.0[i] = u8::from_str_radix(&buf[i*2..i*2+2], 16).unwrap(); } key } pub fn to_vec(&self) -> Vec<u8> { self.0.to_vec() } pub fn to_string(&self) -> String { let mut tmp = String::new(); for i in 0..16 { tmp.push_str(&format!("{:02X}", (self.0)[i])); } tmp } pub fn to_path(&self) -> PathBuf { PathBuf::from(&self.to_string()) } } impl fmt::Display for TrackKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_string()) } } pub type Fingerprint = Vec<u32>; /// A single track with metadata /// /// In case of no interpret and an original composition the interpret is the same as the composer. #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature="serde", derive(Serialize, Deserialize))] pub struct Track { /// A unique key used to access the track (hash of the fingerprint) pub key: TrackKey, /// A unique fingerprint describing the content of the track pub fingerprint: Fingerprint, /// The title of the track pub title: Option<String>, /// The album containing the track pub album: Option<String>, /// The interpret pub interpret: Option<String>, /// All people who helped to perform the track pub people: Option<String>, /// The original composer pub composer: Option<String>, /// Duration in milliseconds pub duration: f64, /// Number of favs pub favs_count: u32 } impl Track { /// Create an empty track with no metadata #[cfg(feature="rusqlite")] pub fn empty(fingerprint: Fingerprint, duration: f64) -> Track { let mut hasher = Sha256::new(); let v_bytes: &[u8] = unsafe { std::slice::from_raw_parts( fingerprint.as_ptr() as *const u8, fingerprint.len() * std::mem::size_of::<i32>(), ) }; hasher.input(v_bytes); let a = hasher.result(); let key = TrackKey::from_vec(&a[0..16]); Track { key: key, fingerprint: fingerprint, title: None, album: None, interpret: None, people: None, composer: None, duration: duration, favs_count: 0 } } /// Create a track from database row #[cfg(feature = "rusqlite")] pub fn from_row(row: &Row) -> Result<Track> { let key: Vec<u8> = row.get_checked(0)?; Ok(Track { key: TrackKey::from_vec(&key), fingerprint:u8_into_u32(row.get_checked(1)?), title: row.get_checked(2)?, album: row.get_checked(3)?, interpret: row.get_checked(4)?, people: row.get_checked(5)?, composer: row.get_checked(6)?, duration: row.get_checked(7)?, favs_count: row.get_checked(8)? }) } } /// Playlist identification pub type PlaylistKey = i64; /// A single playlist containing many tracks #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature="serde", derive(Serialize, Deserialize))] pub struct Playlist { /// A unique key used to access the playlist pub key: PlaylistKey, /// The playlist's title pub title: String, /// A description of the playlist, can be a longer text pub desc: Option<String>, /// Vector of all track keys pub tracks: Vec<TrackKey>, /// The author of this playlist pub origin: PeerId } #[cfg(feature = "rusqlite")] impl Playlist { pub fn new(key: PlaylistKey, title: String, origin: PeerId) -> Playlist { Playlist { key, title, origin, desc: None, tracks: Vec::new() } } pub fn from_row(row: &Row) -> Result<Playlist> { let keys: Vec<u8> = row.get_checked(3)?; let keys: Vec<TrackKey> = keys.chunks(16) .map(|x| TrackKey::from_vec(x)).collect(); Ok(Playlist { key: row.get_checked(0)?, title: row.get_checked(1)?, desc: row.get_checked(2)?, tracks: keys, origin: row.get_checked(4)? }) } } /// Token identification pub type TokenId = i64; /// A single token connecting a token to a playlist #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature="serde", derive(Serialize, Deserialize))] pub struct Token { /// Token number saved on the cardridge pub token: TokenId, /// Key of the playlist pub key: Option<PlaylistKey>, /// All played song (ignored by shuffle) pub played: Vec<TrackKey>, /// Position of the actual song pub pos: Option<f64>, /// Last time the token was used pub last_use: i64 } #[cfg(feature = "rusqlite")] impl Token { pub fn from_row(row: &Row) -> Result<Token> { let keys: Vec<u8> = row.get_checked(2)?; let keys: Vec<TrackKey> = keys.chunks(16) .map(|x| TrackKey::from_vec(x)).collect(); Ok(Token { token: row.get_checked(0)?, key: row.get_checked(1)?, played: keys, pos: row.get_checked(3)?, last_use: row.get_checked(4)? }) } } pub fn u32_into_u8(mut buf: Vec<u32>) -> Vec<u8> { unsafe { let ratio = 4; let length = buf.len() * ratio; let capacity = buf.capacity() * ratio; let ptr = buf.as_mut_ptr() as *mut u8; // Don't run the destructor for vec32 mem::forget(buf); // Construct new Vec Vec::from_raw_parts(ptr, length, capacity) } } pub fn u8_into_u32(mut buf: Vec<u8>) -> Vec<u32> { unsafe { let ratio = 4; let length = buf.len() / ratio; let capacity = buf.capacity() / ratio; let ptr = buf.as_mut_ptr() as *mut u32; // Don't run the destructor for vec32 mem::forget(buf); // Construct new Vec Vec::from_raw_parts(ptr, length, capacity) } } /* pub fn i64_into_u8(mut buf: Vec<i64>) -> Vec<u8> { unsafe { let ratio = 8; let length = buf.len() * ratio; let capacity = buf.capacity() * ratio; let ptr = buf.as_mut_ptr() as *mut u8; // Don't run the destructor for vec32 mem::forget(buf); // Construct new Vec Vec::from_raw_parts(ptr, length, capacity) } } pub fn u8_into_i64(mut buf: Vec<u8>) -> Vec<i64> { unsafe { let ratio = 8; let length = buf.len() / ratio; let capacity = buf.capacity() / ratio; let ptr = buf.as_mut_ptr() as *mut i64; // Don't run the destructor for vec32 mem::forget(buf); // Construct new Vec Vec::from_raw_parts(ptr, length, capacity) } } */
pub use lapin_async::uri::*;
fn main() { println!("Hello, world!"); // Rust中的函数和变量名使用 snake case 规范风格 another_function(5, 6); let _y = 6; // statement // let x = (let y = 6); // let 语句不返回值,不能用来赋值给其他变量 // let y = 6; 中的 6 是一个表达式,它计算出的值是 6 // 函数调用是一个表达式,宏调用也是一个表达式, // 用来创建新作用域代码块的大括号 {},也是一个表达式 let y = { let x = 3; // expression的结尾没有分号,如果加上分号就变成了statement, // 而statement并不会返回值 x + 1 }; println!("The value of y is: {}", y); // let x = five(); let x = plus_one(five()); println!("The value of x is: {}", x) } // Rust 不关心函数定义的前后顺序,只有定义了就行 // 函数签名中,必须声明每个参数的类型,这样编译器就不需要自动推断 // Rust 是一门基于表达式(expression-based)的语言,这是一个不同于其他语言的重要区别 // 函数体由一系列语句和一个可选的结尾表达式构成 // 语句(statements)是执行一些操作但不返回值的指令 // 表达式(expressions)计算并产生一个值 fn another_function(x: i32, y: i32) { println!("The value of x is: {}", x); println!("The value of y is: {}", y); } // Rust 函数的返回值等同于函数体最后一个表达式的值(和 Ruby 相同) // 可以使用 return 关键字和指定值提前返回, // 但大部分函数是隐式的返回最后的表达式 expression // (再次注意区分 statement 和 expression 的不同,一个执行操作但不返回,一个执行计算并返回一个值) fn five() -> i32 { 5 } fn plus_one(x: i32) -> i32 { // (); // 空元组 tuple let (x, y, z) = (1, 2, 3); x + 1 }
#[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::SSCTL3 { #[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 ADC_SSCTL3_D0R { bits: bool, } impl ADC_SSCTL3_D0R { #[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 _ADC_SSCTL3_D0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL3_D0W<'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 ADC_SSCTL3_END0R { bits: bool, } impl ADC_SSCTL3_END0R { #[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 _ADC_SSCTL3_END0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL3_END0W<'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 ADC_SSCTL3_IE0R { bits: bool, } impl ADC_SSCTL3_IE0R { #[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 _ADC_SSCTL3_IE0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL3_IE0W<'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 ADC_SSCTL3_TS0R { bits: bool, } impl ADC_SSCTL3_TS0R { #[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 _ADC_SSCTL3_TS0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL3_TS0W<'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 - Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl3_d0(&self) -> ADC_SSCTL3_D0R { let bits = ((self.bits >> 0) & 1) != 0; ADC_SSCTL3_D0R { bits } } #[doc = "Bit 1 - End of Sequence"] #[inline(always)] pub fn adc_ssctl3_end0(&self) -> ADC_SSCTL3_END0R { let bits = ((self.bits >> 1) & 1) != 0; ADC_SSCTL3_END0R { bits } } #[doc = "Bit 2 - Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl3_ie0(&self) -> ADC_SSCTL3_IE0R { let bits = ((self.bits >> 2) & 1) != 0; ADC_SSCTL3_IE0R { bits } } #[doc = "Bit 3 - 1st Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl3_ts0(&self) -> ADC_SSCTL3_TS0R { let bits = ((self.bits >> 3) & 1) != 0; ADC_SSCTL3_TS0R { 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 - Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl3_d0(&mut self) -> _ADC_SSCTL3_D0W { _ADC_SSCTL3_D0W { w: self } } #[doc = "Bit 1 - End of Sequence"] #[inline(always)] pub fn adc_ssctl3_end0(&mut self) -> _ADC_SSCTL3_END0W { _ADC_SSCTL3_END0W { w: self } } #[doc = "Bit 2 - Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl3_ie0(&mut self) -> _ADC_SSCTL3_IE0W { _ADC_SSCTL3_IE0W { w: self } } #[doc = "Bit 3 - 1st Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl3_ts0(&mut self) -> _ADC_SSCTL3_TS0W { _ADC_SSCTL3_TS0W { w: self } } }
use druid::{ text::{AttributesAdder, RichText, RichTextBuilder, TextStorage}, widget::prelude::*, Color, FontFamily, FontStyle, FontWeight, Point, Selector, TextLayout, }; use pulldown_cmark::{CodeBlockKind, Event as ParseEvent, Parser, Tag}; use syntect::{easy::HighlightLines, highlighting::Style, util::LinesWithEndings}; const BLOCKQUOTE_COLOR: Color = Color::grey8(0x88); const LINK_COLOR: Color = Color::rgb8(0, 0, 0xEE); const OPEN_LINK: Selector<String> = Selector::new("druid-example.open-link"); const PARA_SPACING: f64 = 10.; use crate::{SYNTAX, THEMES}; /// The markdown widget pub struct Markdown { content: Vec<MdPart>, /// The position of each element. pos: Option<Vec<Point>>, } impl Markdown { pub fn new() -> Self { Markdown { content: vec![], pos: None, } } fn calculate_positions(&mut self) -> Size { let mut pos = Vec::with_capacity(self.content.len()); let mut size = Size::new(0., 0.); let mut iter = self.content.iter().peekable(); while let Some(el) = iter.next() { pos.push((0., size.height).into()); size.width = size.width.max(el.size().width); size.height += el.size().height; if iter.peek().is_some() { size.height += PARA_SPACING; } } self.pos = Some(pos); size } } impl<T: TextStorage> Widget<T> for Markdown { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { for el in &mut self.content { el.event(ctx, event, env); } } fn lifecycle(&mut self, _ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, _env: &Env) { match event { LifeCycle::WidgetAdded => { self.content = build_md_content(data); // self.pos is None already } _ => (), } } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { // rebuild the structure of the layout. if old_data.same(data) { for el in &mut self.content { el.needs_rebuild_after_update(ctx); } return; } self.content = build_md_content(data); self.pos = None; } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size { let width = bc.max().width; for el in &mut self.content { el.layout(ctx, bc, env); } let size = self.calculate_positions(); bc.constrain(size) } fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) { // We always calculate positions in layout. for (el, pos) in self.content.iter().zip(self.pos.as_ref().unwrap().iter()) { el.paint(ctx, env, *pos); } } } #[derive(Debug)] pub enum MdPart { Paragraph { layout: TextLayout<RichText>, }, Code { layout: TextLayout<RichText>, }, Heading { level: u32, layout: TextLayout<RichText>, }, Blockquote { content: Vec<MdPart>, }, } impl MdPart { fn event(&mut self, ctx: &mut EventCtx, event: &Event, env: &Env) { match self { MdPart::Paragraph { layout } => link_event(ctx, event, layout), MdPart::Code { layout } => link_event(ctx, event, layout), MdPart::Heading { layout, .. } => link_event(ctx, event, layout), MdPart::Blockquote { content } => { for el in content { el.event(ctx, event, env); } } } } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, env: &Env) { match self { MdPart::Paragraph { layout } | MdPart::Code { layout } | MdPart::Heading { layout, .. } => { layout.set_wrap_width(bc.max().width); layout.rebuild_if_needed(ctx.text(), env); } MdPart::Blockquote { content } => { for part in content { part.layout(ctx, bc, env); } } } } fn needs_rebuild_after_update(&mut self, ctx: &mut UpdateCtx) -> bool { match self { MdPart::Paragraph { layout } | MdPart::Code { layout } | MdPart::Heading { layout, .. } => layout.needs_rebuild_after_update(ctx), MdPart::Blockquote { content } => { let mut all = false; for el in content { all |= el.needs_rebuild_after_update(ctx); } all } } } // Ensure that the layout has been built or rebuilt as necessary before calling this. fn size(&self) -> Size { match self { MdPart::Paragraph { layout } => layout.size(), MdPart::Code { layout } => layout.size(), MdPart::Heading { level, layout } => layout.size(), MdPart::Blockquote { content } => { let mut height = 0.; let mut width: f64 = 0.; for part in content { width = width.max(part.size().width); height += part.size().height + PARA_SPACING; } Size::new(width, height) } } } fn paint(&self, ctx: &mut PaintCtx, env: &Env, pos: Point) { match self { MdPart::Paragraph { layout } => { layout.draw(ctx, pos); } MdPart::Code { layout } => { layout.draw(ctx, pos); } MdPart::Heading { level, layout } => { let pos = Point::new(pos.x, pos.y + PARA_SPACING); layout.draw(ctx, pos); } MdPart::Blockquote { content } => todo!(), } } } fn link_event(ctx: &mut EventCtx, event: &Event, layout: &mut TextLayout<RichText>) { if let Event::MouseDown(evt) = event { if let Some(link) = layout.link_for_pos(evt.pos) { ctx.submit_command(link.command.clone()); } } } // build structure of our display fn build_md_content<T: TextStorage>(data: &T) -> Vec<MdPart> { use pulldown_cmark::{Event, Options, Tag}; let mut content = vec![]; let parser = Parser::new_ext(data.as_str(), Options::all()); let mut event_iter = parser.into_iter(); while let Some(event) = event_iter.next() { match event { Event::Start(tag) => match tag { Tag::Paragraph => { build_paragraph(&mut event_iter, &mut content); } Tag::Heading(level) => build_heading(&mut event_iter, &mut content, level), Tag::BlockQuote => (), Tag::CodeBlock(kind) => build_codeblock(&mut event_iter, &mut content, &kind), Tag::List(_) => (), Tag::Item => (), Tag::FootnoteDefinition(_) => (), Tag::Table(_) => (), Tag::TableHead => (), Tag::TableRow => (), Tag::TableCell => (), Tag::Emphasis => (), Tag::Strong => (), Tag::Strikethrough => (), Tag::Link(_, _, _) => (), Tag::Image(_, _, _) => (), }, Event::Rule => todo!(), Event::Html(s) => tracing::error!("inline html in markdown unsupported, skipping"), evt => panic!("unexpected md event {:?}", evt), } } content } fn build_heading(event_iter: &mut Parser, content: &mut Vec<MdPart>, level: u32) { let (layout, tag) = build_text( event_iter, Some(&|attrs| add_attributes_for_header(level, attrs)), ); // set heading size expect_tag(tag, Tag::Heading(level)); content.push(MdPart::Paragraph { layout }) } fn build_paragraph(event_iter: &mut Parser, content: &mut Vec<MdPart>) { use pulldown_cmark::{Event, Tag}; let (layout, tag) = build_text(event_iter, None); expect_tag(tag, Tag::Paragraph); content.push(MdPart::Paragraph { layout }) } /// Returns the text layout, and the end tag that signified the end of the enclosing context. /// /// The `attrs_adder` allows for attributes to be applied to all the text, if desired. fn build_text<'a>( event_iter: &mut Parser<'a>, attrs_adder: Option<&dyn Fn(AttributesAdder)>, ) -> (TextLayout<RichText>, pulldown_cmark::Tag<'a>) { let mut text = RichTextBuilder::new(); let mut ctx_stack = Vec::new(); let mut current_pos = 0; let mut whitespace_last = true; loop { match event_iter.next() { Some(ParseEvent::Start(tag)) => { ctx_stack.push((current_pos, tag)); } Some(ParseEvent::End(end_tag)) => match ctx_stack.pop() { Some((start_off, tag)) => { if tag == end_tag { add_attribute_for_tag( &tag, text.add_attributes_for_range(start_off..current_pos), ); } else { panic!("expected end of {:?}, found {:?}", tag, end_tag); } } None => { if let Some(f) = attrs_adder { f(text.add_attributes_for_range(..)); } return (TextLayout::from_text(text.build()), end_tag); } }, Some(ParseEvent::Text(string)) => { text.push(&string); current_pos += string.len(); if let Some(ch) = string.chars().next_back() { whitespace_last = ch.is_whitespace(); } } Some(ParseEvent::SoftBreak) => { if !whitespace_last { text.push(" "); current_pos += 1; } } Some(ParseEvent::HardBreak) => { text.push("\n"); current_pos += 1; } evt => panic!("unexpected event {:?}", evt), } } } /// Handle a codeblock, consuming tokens as needed fn build_codeblock(event_iter: &mut Parser, content: &mut Vec<MdPart>, kind: &CodeBlockKind) { let mut builder = RichTextBuilder::new(); let block_name = match kind { CodeBlockKind::Indented => "", CodeBlockKind::Fenced(ty) => *&ty, }; let text = match event_iter.next().expect("expected text") { ParseEvent::Text(code_text) => code_text, ParseEvent::End(Tag::CodeBlock(_)) => { content.push(MdPart::Code { layout: TextLayout::from_text(builder.build()), }); return; } evt => { tracing::warn!("unexpected event: {:?}", evt); content.push(MdPart::Code { layout: TextLayout::from_text(builder.build()), }); return; } }; let theme = &THEMES.themes["Solarized (dark)"]; // Try to guess the type of data let syntax = SYNTAX // like find_syntax_by_name but ignores case .syntaxes() .iter() .find(|syntax| syntax.name.eq_ignore_ascii_case(block_name)) .or_else(|| SYNTAX.find_syntax_by_extension(block_name)) .or_else(|| SYNTAX.find_syntax_by_first_line(&text)) .unwrap_or_else(|| SYNTAX.find_syntax_plain_text()); let mut h = HighlightLines::new(syntax, theme); for line in LinesWithEndings::from(&text) { let ranges: Vec<(Style, &str)> = h.highlight(line, &SYNTAX); for (style, subtext) in ranges { apply_styles(builder.push(subtext), style); } } match event_iter.next() { Some(ParseEvent::End(Tag::CodeBlock(_))) => (), evt => tracing::warn!("unexpected token {:?}", evt), } content.push(MdPart::Code { layout: TextLayout::from_text(builder.build()), }); } fn apply_styles(mut adder: AttributesAdder, style: Style) { adder.text_color(syntect_to_druid_color(style.foreground)); if style .font_style .contains(syntect::highlighting::FontStyle::BOLD) { adder.weight(FontWeight::BOLD); } if style .font_style .contains(syntect::highlighting::FontStyle::ITALIC) { adder.style(FontStyle::Italic); } } fn syntect_to_druid_color(color: syntect::highlighting::Color) -> Color { Color::rgba8(color.r, color.g, color.b, color.a) } fn add_newline_after_tag(tag: &Tag) -> bool { !matches!( tag, Tag::Emphasis | Tag::Strong | Tag::Strikethrough | Tag::Link(..) ) } fn add_attributes_for_header(level: u32, mut attrs: AttributesAdder) { let font_size = match level { 1 => 38., 2 => 32.0, 3 => 26.0, 4 => 20.0, 5 => 16.0, _ => 12.0, }; attrs.size(font_size).weight(FontWeight::BOLD); } fn add_attribute_for_tag(tag: &Tag, mut attrs: AttributesAdder) { match tag { Tag::Heading(lvl) => { let font_size = match lvl { 1 => 38., 2 => 32.0, 3 => 26.0, 4 => 20.0, 5 => 16.0, _ => 12.0, }; attrs.size(font_size).weight(FontWeight::BOLD); } Tag::BlockQuote => { attrs.style(FontStyle::Italic).text_color(BLOCKQUOTE_COLOR); } Tag::CodeBlock(CodeBlockKind::Indented) => { attrs.font_family(FontFamily::MONOSPACE); } Tag::CodeBlock(CodeBlockKind::Fenced(label)) => { attrs.font_family(FontFamily::MONOSPACE); } Tag::Emphasis => { attrs.style(FontStyle::Italic); } Tag::Strong => { attrs.weight(FontWeight::BOLD); } Tag::Link(_link_ty, target, _title) => { attrs .underline(true) .text_color(LINK_COLOR) .link(OPEN_LINK.with(target.to_string())); } // ignore other tags for now _ => (), } } fn expect_tag(tag: pulldown_cmark::Tag, test: pulldown_cmark::Tag) { if !(tag == test) { panic!("expected end event for {:?}, found {:?}", tag, test); } }
use rustler::types::atom::{ok, error}; use rustler::{Encoder, Env, NifResult, Term}; use std::{thread, time}; use rand::prelude::*; #[rustler::nif(schedule = "DirtyCpu")] fn do_work( env: Env ) -> NifResult<Term> { let thread = thread::Builder::new() .name("do_some_work".to_string()) .stack_size(1024 * 1024 * 8) .spawn( move || -> Result<(), String> { thread::sleep(time::Duration::from_secs(5)); Ok(()) }, ) .unwrap(); let _ = thread.join(); let num = rand::thread_rng().gen_range(0..10); if num <= 1 { Ok((error(), String::from("Random Error")).encode(env)) } else { Ok(ok().encode(env)) } } rustler::init!("Elixir.Pubsub.RustExpensiveCode", [do_work]);
use proconio::input; use std::collections::HashMap; fn main() { input! { n: usize, }; let mut pes = Vec::new(); for _ in 0..n { input! { m: usize, pe: [(u32, u32); m], }; pes.push(pe); } let mut max_e = HashMap::new(); for pe in &pes { for &(p, e) in pe { let mx = max_e.entry(p).or_insert(0); *mx = (*mx).max(e); } } let mut max_e_count = HashMap::new(); for pe in &pes { for &(p, e) in pe { if max_e[&p] == e { *max_e_count.entry(p).or_insert(0) += 1; } } } let mut ans = 1; for pe in &pes { let mut ok = false; for &(p, e) in pe { if max_e[&p] == e && max_e_count[&p] == 1 { ok = true; } } if ok { ans += 1; } } println!("{}", ans.min(n)); // ? }
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::alloc::TermAlloc; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; #[native_implemented::function(erlang:tuple_to_list/1)] pub fn result(process: &Process, tuple: Term) -> exception::Result<Term> { let tuple = term_try_into_tuple!(tuple)?; let mut heap = process.acquire_heap(); let mut acc = Term::NIL; for element in tuple.iter().rev() { acc = heap.cons(*element, acc)?.into(); } Ok(acc) }
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt::Debug; trait InTraitDefnParameters { fn in_parameters(_: impl Debug) -> String; } impl InTraitDefnParameters for () { fn in_parameters(v: impl Debug) -> String { format!("() + {:?}", v) } } fn main() { let s = <() as InTraitDefnParameters>::in_parameters(22); assert_eq!(s, "() + 22"); }
use crate::sec_to_display; use ::amethyst::core::Time; use ::amethyst::ecs::{Read, System, Write}; /// Calculates in relative time using the internal engine clock. #[derive(Default, Serialize)] pub struct RelativeTimer { pub start: f64, pub current: f64, pub running: bool, } impl RelativeTimer { pub fn get_text(&self, decimals: usize) -> String { sec_to_display(self.duration(), decimals) } pub fn duration(&self) -> f64 { self.current - self.start } pub fn start(&mut self, cur_time: f64) { self.start = cur_time; self.current = cur_time; self.running = true; } pub fn update(&mut self, cur_time: f64) { if self.running { self.current = cur_time; } } pub fn stop(&mut self) { self.running = false; } } pub struct RelativeTimerSystem; impl<'a> System<'a> for RelativeTimerSystem { type SystemData = (Write<'a, RelativeTimer>, Read<'a, Time>); fn run(&mut self, (mut timer, time): Self::SystemData) { timer.update(time.absolute_time_seconds()); } }
/* Copyright 2020 Timo Saarinen 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 super::*; // ------------------------------------------------------------------------------------------------- /// Type 14: Safety-Related Broadcast Message #[derive(Default, Clone, Debug, PartialEq)] pub struct SafetyRelatedBroadcastMessage { /// True if the data is about own vessel, false if about other. pub own_vessel: bool, /// AIS station type. pub station: Station, /// Source MMSI (30 bits) pub mmsi: u32, /// Text (1-161 ASCII chars) pub text: String, } // ------------------------------------------------------------------------------------------------- /// AIS VDM/VDO type 14: Safety-Related Broadcast Message pub(crate) fn handle( bv: &BitVec, station: Station, own_vessel: bool, ) -> Result<ParsedMessage, ParseError> { Ok(ParsedMessage::SafetyRelatedBroadcastMessage( SafetyRelatedBroadcastMessage { own_vessel: { own_vessel }, station: { station }, mmsi: { pick_u64(&bv, 8, 30) as u32 }, text: { pick_string(&bv, 40, 161) }, }, )) } // ------------------------------------------------------------------------------------------------- #[cfg(test)] mod test { use super::*; #[test] fn test_parse_vdm_type14() { let mut p = NmeaParser::new(); // First message match p.parse_sentence("!AIVDM,1,1,,A,>5?Per18=HB1U:1@E=B0m<L,2*51") { Ok(ps) => { match ps { // The expected result ParsedMessage::SafetyRelatedBroadcastMessage(srbm) => { assert_eq!(srbm.mmsi, 351809000); assert_eq!(srbm.text, "RCVD YR TEST MSG"); } ParsedMessage::Incomplete => { assert!(false); } _ => { assert!(false); } } } Err(e) => { assert_eq!(e.to_string(), "OK"); } } // Second message match p.parse_sentence("!AIVDM,1,1,,A,>3R1p10E3;;R0USCR0HO>0@gN10kGJp,2*7F") { Ok(ps) => { match ps { // The expected result ParsedMessage::SafetyRelatedBroadcastMessage(srbm) => { assert_eq!(srbm.mmsi, 237008900); assert_eq!(srbm.text, "EP228 IX48 FG3 DK7 PL56."); } ParsedMessage::Incomplete => { assert!(false); } _ => { assert!(false); } } } Err(e) => { assert_eq!(e.to_string(), "OK"); } } // Third message match p.parse_sentence("!AIVDM,1,1,,A,>4aDT81@E=@,2*2E") { Ok(ps) => { match ps { // The expected result ParsedMessage::SafetyRelatedBroadcastMessage(srbm) => { assert_eq!(srbm.mmsi, 311764000); assert_eq!(srbm.text, "TEST"); } ParsedMessage::Incomplete => { assert!(false); } _ => { assert!(false); } } } Err(e) => { assert_eq!(e.to_string(), "OK"); } } } }
#[cfg(test)] mod tests;
use sea_schema::migration::prelude::*; pub struct Migration; impl MigrationName for Migration { fn name(&self) -> &str { "m20220616_000001_create_peers_table" } } #[async_trait::async_trait] impl MigrationTrait for Migration { async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { let _res = manager .create_table( Table::create() .table(Peer::Table) .if_not_exists() .col(ColumnDef::new(Peer::Id).string().not_null().primary_key()) .col(ColumnDef::new(Peer::CreatedAt).big_integer().not_null()) .col(ColumnDef::new(Peer::UpdatedAt).big_integer().not_null()) .col(ColumnDef::new(Peer::NodeId).string().not_null()) .col(ColumnDef::new(Peer::Pubkey).string().not_null()) .col(ColumnDef::new(Peer::Alias).string()) .col(ColumnDef::new(Peer::Label).string()) .col(ColumnDef::new(Peer::ZeroConf).boolean().not_null()) .to_owned(), ) .await; manager .create_index( Index::create() .table(Peer::Table) .name("idx-nodeid-pubkey") .col(Peer::NodeId) .col(Peer::Pubkey) .unique() .to_owned(), ) .await } async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { let mut drop_table_stmt = Table::drop(); drop_table_stmt.table(Peer::Table); manager.drop_table(drop_table_stmt).await } } #[derive(Iden)] enum Peer { Table, Id, CreatedAt, UpdatedAt, NodeId, Pubkey, Label, Alias, ZeroConf, }
use std::path::Path; use std::env; mod image_rect; mod utils; pub enum SortKey{ Width, Height, Area, MaxDimension } fn main() { let path = env::args(); println!("path: {:?}", path.collect::<Vec<String>>()); let mut images = match image_rect::image::get_images(&Path::new("./img/.")){ Ok(imgs) => imgs, Err(_) => { println!("Error in getting images"); Vec::new() } }; utils::helpers::sort(&mut images, SortKey::MaxDimension); // let mut ids: Vec<u32> = Vec::new(); // for i in images{ // ids.push(i.id); // } // println!("{:?}", ids); for i in &images{ println!("{:?}", i); } let mut image_tree = image_rect::image::ImageTree::new(0,0,1280,1280); for image in images{ let img = image.clone(); let image_node = image_rect::image::ImageNode::new(0,0,img.width, img.height); image_tree.insert(image_node); } println!("tree: {:?}", image_tree); }
use std::io::Error; use std::io::Result; use std::io::ErrorKind::InvalidInput; use std::collections::HashMap; use irc::client::server::IrcServer; use irc::client::server::Server; use irc::client::prelude::ServerExt; pub struct CommandArg { pub required: bool, pub name: String, } impl CommandArg { pub fn new(name: &str, required: bool) -> Self { CommandArg { name: name.into(), required: required, } } } pub struct CommandParameters<'a> { pub command: &'a Command, pub args: HashMap<String, String>, pub server: &'a IrcServer, pub target: String, pub sender: String, } pub struct Command { pub owner_only: bool, pub group: String, pub args: Vec<CommandArg>, pub handler: Box<Fn(CommandParameters) -> Result<()>>, } impl Command { pub fn new(owner_only: bool, group: &str, args: Vec<CommandArg>, handler: Box<Fn(CommandParameters) -> Result<()>>) -> Self { Command { owner_only: owner_only, group: group.into(), args: args, handler: handler, } } pub fn arguments(&self, input: String) -> Result<HashMap<String, String>> { let mut map = HashMap::new(); let col = input.split_whitespace().map(|word| word.into()).collect::<Vec<String>>(); let mut words = col.iter(); let mut last_arg: Option<String> = None; for arg in &self.args { last_arg = Some(arg.name.clone()); if let Some(word) = words.next().cloned() { map.insert(arg.name.clone(), word); } else if arg.required { return Err(Error::new(InvalidInput, format!("{} is required.", arg.name))); } } // Append anything additional to the last argument (general use-case?) if let Some(arg) = last_arg { if let Some(argv) = map.get(&arg).cloned() { map.insert(arg.clone(), words.fold(argv, |a, b| a + " " + b)); } } Ok(map) } pub fn help(&self) -> String { let mut help: String = "USAGE".into(); for arg in &self.args { if arg.required { help = format!("{} <{}>", help, arg.name); } else { help = format!("{} [{}]", help, arg.name); } } help } pub fn execute(&self, input: String, server: &IrcServer, target: String, sender: String) -> Result<()> { // TODO: Restrict by group (groups.json?) if !self.owner_only || server.config().is_owner(&sender) { let args = self.arguments(input); if let Ok(args) = args { let handler = &self.handler; try!(handler(CommandParameters { command: self, args: args, server: server, target: target, sender: sender, })); } else if let Err(_) = args { try!(server.send_notice(&sender, &self.help())); } } else { try!(server.send_notice(&sender, "You don't have permission to use that command.")); } Ok(()) } }
use crate::{ database::Database, utils::{module_for_path, packages_path}, Exit, ProgramResult, }; use candy_frontend::{ast_to_hir::AstToHir, hir::CollectErrors}; use clap::{arg, Parser, ValueHint}; use std::path::PathBuf; use tracing::warn; /// Check a Candy program for obvious errors. /// /// This command finds very obvious errors in your program. For more extensive /// error reporting, fuzzing the Candy program is recommended instead. #[derive(Parser, Debug)] pub(crate) struct Options { /// The file or package to check. If none is provided, the package of your /// current working directory will be checked. #[arg(value_hint = ValueHint::FilePath)] path: Option<PathBuf>, } pub(crate) fn check(options: Options) -> ProgramResult { let packages_path = packages_path(); let db = Database::new_with_file_system_module_provider(packages_path); let module = module_for_path(options.path)?; // TODO: Once my other PR is merged, update this to get the MIR instead. // This will return a tuple containing the MIR and errors, even from // imported modules. let (hir, _) = db.hir(module).unwrap(); let mut errors = vec![]; hir.collect_errors(&mut errors); let has_errors = !errors.is_empty(); for error in errors { warn!("{}", error.to_string_with_location(&db)); } if has_errors { Err(Exit::CodeContainsErrors) } else { Ok(()) } }
use serde::{Deserialize, Serialize}; use crate::data::Position; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SaveData { pub position: Position, }
use ggez::{event, GameResult}; mod game_state; mod tetromino; use crate::tetromino::{GRID_CELL_SIZE, GRID_SIZE}; use game_state::*; const SCREEN_SIZE: (f32, f32) = ( (GRID_SIZE.0 as f32 + 6.5) * GRID_CELL_SIZE.0 as f32, GRID_SIZE.1 as f32 * GRID_CELL_SIZE.1 as f32, ); fn main() -> GameResult { let (ctx, events_loop) = &mut ggez::ContextBuilder::new("tetris", "me") .window_setup(ggez::conf::WindowSetup::default().title("Tetris!")) .window_mode(ggez::conf::WindowMode::default().dimensions(SCREEN_SIZE.0, SCREEN_SIZE.1)) .build()?; let state = &mut GameState::new(); event::run(ctx, events_loop, state) }
use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use web3::types::{Bytes, Index, Transaction as Web3Transaction, H160, H256, U256, U64}; // source: https://github.com/tomusdrw/rust-web3/blob/9e80f896bb49605079202fa53b6dc1dfd2430c32/src/types/transaction.rs #[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)] pub struct Transaction { /// Hash pub hash: H256, /// Nonce pub nonce: U256, /// Block hash. None when pending. #[serde(rename = "blockHash")] pub block_hash: Option<H256>, /// Block number. None when pending. #[serde(rename = "blockNumber")] pub block_number: Option<U64>, /// Transaction Index. None when pending. #[serde(rename = "transactionIndex")] pub transaction_index: Option<Index>, /// Sender pub from: H160, /// Recipient (None when contract creation) pub to: Option<H160>, /// Transfered value pub value: U256, /// Gas Price #[serde(rename = "gasPrice")] pub gas_price: U256, /// Gas amount pub gas: U256, /// Input data pub input: Bytes, /// Raw transaction data #[serde(default)] pub raw: Option<Bytes>, } impl TryFrom<Web3Transaction> for Transaction { type Error = &'static str; fn try_from(tx: Web3Transaction) -> Result<Self, Self::Error> { let from = match tx.from { Some(f) => f, None => return Err("tx.from should not be empty"), }; Ok(Transaction { hash: tx.hash, nonce: tx.nonce, block_hash: tx.block_hash, block_number: tx.block_number, transaction_index: tx.transaction_index, from, to: tx.to, value: tx.value, gas_price: tx.gas_price, gas: tx.gas, input: tx.input, raw: tx.raw, }) } }
use std::future::Future; use std::io; use std::sync::Arc; use futures_channel::mpsc; use futures_util::lock::{Mutex, MutexGuard}; use futures_util::{select, FutureExt as _, StreamExt as _}; use btknmle_input::event::DeviceEvent; use btknmle_input::event::Event as LibinputEvent; use btknmle_input::event::EventTrait as _; use btknmle_input::event::PointerEvent; use btknmle_input::model::{Device, DeviceCapability}; use btknmle_input::LibinputStream; use super::kbstat::KbStat; use super::mousestat::MouseStat; #[derive(Debug, Clone)] pub enum InputEvent { Keyboard(KbStat), Mouse(MouseStat), } impl From<KbStat> for InputEvent { fn from(v: KbStat) -> Self { Self::Keyboard(v) } } impl From<MouseStat> for InputEvent { fn from(v: MouseStat) -> Self { Self::Mouse(v) } } fn configure_device(device: &mut Device) { if device.has_capability(DeviceCapability::Gesture) { if let Err(e) = device.config_tap_set_enabled(true) { log::warn!("failed to set clickfinger {:?}", e); } } } #[derive(Debug)] pub(crate) struct InputStream<'a> { _guard: MutexGuard<'a, ()>, rx: mpsc::UnboundedReceiver<InputEvent>, control_tx: mpsc::UnboundedSender<Control>, } impl<'a> InputStream<'a> { pub(crate) async fn next(&mut self) -> Option<InputEvent> { self.rx.next().await } } impl<'a> Drop for InputStream<'a> { fn drop(&mut self) { self.control_tx.unbounded_send(Control::EndSubscribe).ok(); } } #[derive(Debug)] enum Control { BeginSubscribe(mpsc::UnboundedSender<InputEvent>), EndSubscribe, } async fn input_loop( mut control_rx: mpsc::UnboundedReceiver<Control>, grab: bool, ) -> anyhow::Result<()> { let mut libinput = LibinputStream::new_from_udev("seat0")?; // TODO seat name let mut kbstat = KbStat::new(); let mut mousestat = MouseStat::new(); let mut stream_tx = Option::<mpsc::UnboundedSender<InputEvent>>::None; loop { select! { event = libinput.next().fuse() => { let event = if let Some(event) = event { event? } else { return Ok(()) }; let event = match event { LibinputEvent::Device(DeviceEvent::Added(evt)) => { let mut device = evt.device(); configure_device(&mut device); None } LibinputEvent::Keyboard(kbd) => { kbstat.recv(&kbd); Some(InputEvent::from(kbstat.clone())) } LibinputEvent::Pointer(PointerEvent::Motion(motion)) => { mousestat.recv_motion(&motion); Some(InputEvent::from(mousestat.clone())) } LibinputEvent::Pointer(PointerEvent::Button(button)) => { mousestat.recv_button(&button); Some(InputEvent::from(mousestat.clone())) } LibinputEvent::Pointer(PointerEvent::Axis(axis)) => { mousestat.recv_axis(&axis); Some(InputEvent::from(mousestat.clone())) } _ => None, }; if let (Some(event), Some(tx)) = (event, stream_tx.as_mut()) { if let Err(err) = tx.unbounded_send(event) { if err.is_disconnected() { stream_tx = None; } } } } control = control_rx.next().fuse() => { match control { Some(Control::BeginSubscribe(new_subscribe)) => { log::debug!("begin capture input."); if grab { libinput.grab()?; } stream_tx = Some(new_subscribe); } Some(Control::EndSubscribe) => { log::debug!("end capture input."); if grab { libinput.ungrab()?; } stream_tx = None; } None => return Ok(()), } } } } } #[derive(Debug, Clone)] pub(crate) struct InputSource { stream_lock: Arc<Mutex<()>>, control_tx: mpsc::UnboundedSender<Control>, } impl InputSource { pub(crate) fn new(grab: bool) -> io::Result<(Self, impl Future<Output = anyhow::Result<()>>)> { let (control_tx, control_rx) = mpsc::unbounded(); let me = Self { stream_lock: Arc::new(Mutex::new(())), control_tx, }; Ok((me, input_loop(control_rx, grab))) } pub(crate) async fn use_stream(&self) -> anyhow::Result<InputStream<'_>> { let guard = self.stream_lock.lock().await; let (tx, rx) = mpsc::unbounded(); self.control_tx .clone() .unbounded_send(Control::BeginSubscribe(tx))?; Ok(InputStream { _guard: guard, rx, control_tx: self.control_tx.clone(), }) } }
// 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 std::collections::HashSet; use std::collections::VecDeque; use common_meta_app::principal::RoleInfo; use crate::role_mgr::BUILTIN_ROLE_ACCOUNT_ADMIN; use crate::role_mgr::BUILTIN_ROLE_PUBLIC; // An role can be granted with multiple roles, find all the related roles in a DFS manner pub fn find_all_related_roles( cache: &HashMap<String, RoleInfo>, role_identities: &[String], ) -> Vec<RoleInfo> { // if it's ACCOUNT_ADMIN, return all roles. if role_identities.contains(&BUILTIN_ROLE_ACCOUNT_ADMIN.to_string()) { return cache.iter().map(|(_, v)| v.clone()).collect(); } // append PUBLIC role, since it's every role's child by default. let mut role_identities = role_identities.to_vec(); role_identities.push(BUILTIN_ROLE_PUBLIC.to_string()); // find all related roles by role_identities in a BFS manner. let mut visited: HashSet<String> = HashSet::new(); let mut result: Vec<RoleInfo> = vec![]; let mut q: VecDeque<String> = role_identities.iter().cloned().collect(); while let Some(role_identity) = q.pop_front() { if visited.contains(&role_identity) { continue; } let cache_key = role_identity.to_string(); visited.insert(role_identity); let role = match cache.get(&cache_key) { None => continue, Some(role) => role, }; result.push(role.clone()); for related_role in role.grants.roles() { q.push_back(related_role); } } result }
#![feature(test)] #![warn(rust_2018_idioms)] extern crate test; #[macro_use] mod common; mod tokio { benchmark_suite!(runtime_tokio::Tokio); } mod tokio_current_thread { benchmark_suite!(runtime_tokio::TokioCurrentThread); }
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:msvc-imp-present.rs // compile-flags: -Z thinlto -C codegen-units=8 // no-prefer-dynamic // On MSVC we have a "hack" where we emit symbols that look like `_imp_$name` // for all exported statics. This is done because we apply `dllimport` to all // imported constants and this allows everything to actually link correctly. // // The ThinLTO passes aggressively remove symbols if they can, and this test // asserts that the ThinLTO passes don't remove these compiler-generated // `_imp_*` symbols. The external library that we link in here is compiled with // ThinLTO and multiple codegen units and has a few exported constants. Note // that we also namely compile the library as both a dylib and an rlib, but we // link the rlib to ensure that we assert those generated symbols exist. extern crate msvc_imp_present as bar; fn main() { println!("{}", bar::A); }
use serde::{Deserialize, Serialize}; use crate::err; #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub struct ConanPackage { pub name: String, pub version: String, pub user: String, pub channel: String, } impl ConanPackage { pub fn new(reference: &str) -> err::Result<(Self)> { let regex = regex::Regex::new(r"^([^/@]+)[/]([^/@]+)(@?$|@([^/@]+)[/]([^/@]+)$)") .expect("Conan Package regex was invalid."); if !regex.is_match(reference) { Err(format!( "Your reference does not match a regex pattern, {}", reference ))? } if reference.len() <= 5 { Err(format!("conan package provided({}) is too short, conan does not handle that 5+ charachters only.", reference))? } let captures = regex.captures(reference).unwrap(); let name = captures.get(1).unwrap().as_str().to_owned(); let version = captures.get(2).unwrap().as_str().to_owned(); let user = captures.get(4).map_or("", |m| m.as_str()).to_owned(); let channel = captures.get(5).map_or("", |m| m.as_str()).to_owned(); Ok(ConanPackage { name, version, user, channel, }) } pub fn full(&self) -> String { format!("{}/{}@{}", self.name, self.version, self.user_channel()) } pub fn user_channel(&self) -> String { if self.user.is_empty() { String::new() } else { format!("{}/{}", self.user, self.channel) } } } #[cfg(test)] mod conan_package_tests { use super::*; fn p(name: &str, ver: &str, user: &str, channel: &str) -> ConanPackage { ConanPackage { name: name.to_owned(), version: ver.to_owned(), user: user.to_owned(), channel: channel.to_owned(), } } fn name_pattern_fail_test(package: &str) { assert_eq!( ConanPackage::new(package).err().unwrap().to_string(), format!("Your reference does not match a regex pattern, {}", package) ); } fn name_pattern_ok(package: &str) { assert!(ConanPackage::new(package).is_ok()); } #[test] fn conan_package_component_extractions() { let pkg = p("abc", "321", "", ""); assert_eq!(pkg, ConanPackage::new("abc/321").unwrap()); assert_eq!("abc/321@", ConanPackage::new("abc/321").unwrap().full()); let pkg = p("abc", "321", "a", "b"); assert_eq!(pkg, ConanPackage::new("abc/321@a/b").unwrap()); } #[test] fn invalid_reference_tests() { name_pattern_fail_test("a"); name_pattern_fail_test("aaaaaa@"); name_pattern_ok("aaaa/aaaa@"); //user channel present without slash name_pattern_fail_test("aaa/aaa@aa"); name_pattern_fail_test("aaa/aaa@aaaa"); name_pattern_ok("aaa/aaa@aaaa/a"); name_pattern_fail_test("aaa/aaa/aaa"); } }
use std::str::from_utf8; use std::io::Read; use byteorder::{ByteOrder, BigEndian}; use protobuf_iter::*; use blob::Blob; pub struct BlobReader<R> { read: R } impl<R: Read> BlobReader<R> { pub fn new(r: R) -> Self { BlobReader { read: r } } pub fn into_inner(self) -> R { self.read } pub fn get_mut(&mut self) -> &mut R { &mut self.read } pub fn read_blob(read: &mut R) -> Option<Blob> { let mut len_buf = [0; 4]; match read.read(&mut len_buf) { Ok(4) => { let len = BigEndian::read_u32(&len_buf) as usize; let mut header_buf = Vec::with_capacity(len); unsafe { header_buf.set_len(len); } match read.read_exact(&mut header_buf) { Ok(()) => (), _ => return None }; let blob_header = match parse_blob_header(&header_buf) { Some(blob_header) => blob_header, None => return None }; let datasize = blob_header.datasize as usize; let mut blob_buf = Vec::with_capacity(datasize); unsafe { blob_buf.set_len(datasize); } match read.read_exact(&mut blob_buf) { Ok(()) => (), _ => return None }; if ! blob_header.is_osm_data { // retry next Self::read_blob(read) } else { match parse_blob(&blob_buf) { Some(blob) => Some(blob), None => // retry next Self::read_blob(read) } } }, _ => None } } } impl<R: Read> Iterator for BlobReader<R> { type Item = Blob; fn next(&mut self) -> Option<Self::Item> { Self::read_blob(&mut self.read) } } struct BlobHeader { is_osm_data: bool, datasize: u32 } fn parse_blob_header(data: &[u8]) -> Option<BlobHeader> { let mut blob_header = BlobHeader { is_osm_data: false, datasize: 0 }; for m in MessageIter::new(&data) { match m.tag { // type 1 => { let value = m.value.get_data(); if value == b"OSMData" { blob_header.is_osm_data = true; } else if value != b"OSMHeader" { println!("Encountered something other than OSM data: {}!", from_utf8(value).unwrap()); // Immediately terminate Iterator return None } }, // datasize 3 => { blob_header.datasize = From::from(m.value); }, _ => () } } Some(blob_header) } fn parse_blob(data: &[u8]) -> Option<Blob> { for m in MessageIter::new(&data) { match m.tag { // raw 1 => { return Some(Blob::Raw(Vec::from(m.value.get_data()))) }, 3 => { return Some(Blob::Zlib(Vec::from(m.value.get_data()))) }, _ => () } } None }
pub type DRendezvousSessionEvents = *mut ::core::ffi::c_void; pub type IRendezvousApplication = *mut ::core::ffi::c_void; pub type IRendezvousSession = *mut ::core::ffi::c_void; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const DISPID_EVENT_ON_CONTEXT_DATA: u32 = 7u32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const DISPID_EVENT_ON_SEND_ERROR: u32 = 8u32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const DISPID_EVENT_ON_STATE_CHANGED: u32 = 5u32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const DISPID_EVENT_ON_TERMINATION: u32 = 6u32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RendezvousApplication: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0b7e019a_b5de_47fa_8966_9082f82fb192); #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub type RENDEZVOUS_SESSION_FLAGS = i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSF_NONE: RENDEZVOUS_SESSION_FLAGS = 0i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSF_INVITER: RENDEZVOUS_SESSION_FLAGS = 1i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSF_INVITEE: RENDEZVOUS_SESSION_FLAGS = 2i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSF_ORIGINAL_INVITER: RENDEZVOUS_SESSION_FLAGS = 4i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSF_REMOTE_LEGACYSESSION: RENDEZVOUS_SESSION_FLAGS = 8i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSF_REMOTE_WIN7SESSION: RENDEZVOUS_SESSION_FLAGS = 16i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub type RENDEZVOUS_SESSION_STATE = i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSS_UNKNOWN: RENDEZVOUS_SESSION_STATE = 0i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSS_READY: RENDEZVOUS_SESSION_STATE = 1i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSS_INVITATION: RENDEZVOUS_SESSION_STATE = 2i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSS_ACCEPTED: RENDEZVOUS_SESSION_STATE = 3i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSS_CONNECTED: RENDEZVOUS_SESSION_STATE = 4i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSS_CANCELLED: RENDEZVOUS_SESSION_STATE = 5i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSS_DECLINED: RENDEZVOUS_SESSION_STATE = 6i32; #[doc = "*Required features: `\"Win32_System_RemoteAssistance\"`*"] pub const RSS_TERMINATED: RENDEZVOUS_SESSION_STATE = 7i32;
//! A simple and fast random number generator. //! //! The implementation uses [Wyrand](https://github.com/wangyi-fudan/wyhash), a simple and fast //! generator but **not** cryptographically secure. //! //! # Examples //! //! Flip a coin: //! //! ``` //! if fastrand::bool() { //! println!("heads"); //! } else { //! println!("tails"); //! } //! ``` //! //! Generate a random `i32`: //! //! ``` //! let num = fastrand::i32(..); //! ``` //! //! Choose a random element in an array: //! //! ``` //! let v = vec![1, 2, 3, 4, 5]; //! let i = fastrand::usize(..v.len()); //! let elem = v[i]; //! ``` //! //! Sample values from an array with `O(n)` complexity (`n` is the length of array): //! //! ``` //! fastrand::choose_multiple(vec![1, 4, 5].iter(), 2); //! fastrand::choose_multiple(0..20, 12); //! ``` //! //! //! Shuffle an array: //! //! ``` //! let mut v = vec![1, 2, 3, 4, 5]; //! fastrand::shuffle(&mut v); //! ``` //! //! Generate a random [`Vec`] or [`String`]: //! //! ``` //! use std::iter::repeat_with; //! //! let v: Vec<i32> = repeat_with(|| fastrand::i32(..)).take(10).collect(); //! let s: String = repeat_with(fastrand::alphanumeric).take(10).collect(); //! ``` //! //! To get reproducible results on every run, initialize the generator with a seed: //! //! ``` //! // Pick an arbitrary number as seed. //! fastrand::seed(7); //! //! // Now this prints the same number on every run: //! println!("{}", fastrand::u32(..)); //! ``` //! //! To be more efficient, create a new [`Rng`] instance instead of using the thread-local //! generator: //! //! ``` //! use std::iter::repeat_with; //! //! let mut rng = fastrand::Rng::new(); //! let mut bytes: Vec<u8> = repeat_with(|| rng.u8(..)).take(10_000).collect(); //! ``` //! //! # Features //! //! - `std` (enabled by default): Enables the `std` library. This is required for the global //! generator and global entropy. Without this feature, [`Rng`] can only be instantiated using //! the [`with_seed`](Rng::with_seed) method. //! - `js`: Assumes that WebAssembly targets are being run in a JavaScript environment. See the //! [WebAssembly Notes](#webassembly-notes) section for more information. //! //! # WebAssembly Notes //! //! For non-WASI WASM targets, there is additional sublety to consider when utilizing the global RNG. //! By default, `std` targets will use entropy sources in the standard library to seed the global RNG. //! However, these sources are not available by default on WASM targets outside of WASI. //! //! If the `js` feature is enabled, this crate will assume that it is running in a JavaScript //! environment. At this point, the [`getrandom`] crate will be used in order to access the available //! entropy sources and seed the global RNG. If the `js` feature is not enabled, the global RNG will //! use a predefined seed. //! //! [`getrandom`]: https://crates.io/crates/getrandom #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg))] #![forbid(unsafe_code)] #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] #[cfg(feature = "alloc")] extern crate alloc; use core::convert::{TryFrom, TryInto}; use core::ops::{Bound, RangeBounds}; #[cfg(feature = "alloc")] use alloc::vec::Vec; #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] mod global_rng; #[cfg(feature = "std")] pub use global_rng::*; /// A random number generator. #[derive(Debug, PartialEq, Eq)] pub struct Rng(u64); impl Clone for Rng { /// Clones the generator by creating a new generator with the same seed. fn clone(&self) -> Rng { Rng::with_seed(self.0) } } impl Rng { /// Generates a random `u32`. #[inline] fn gen_u32(&mut self) -> u32 { self.gen_u64() as u32 } /// Generates a random `u64`. #[inline] fn gen_u64(&mut self) -> u64 { let s = self.0.wrapping_add(0xA0761D6478BD642F); self.0 = s; let t = u128::from(s) * u128::from(s ^ 0xE7037ED1A0B428DB); (t as u64) ^ (t >> 64) as u64 } /// Generates a random `u128`. #[inline] fn gen_u128(&mut self) -> u128 { (u128::from(self.gen_u64()) << 64) | u128::from(self.gen_u64()) } /// Generates a random `u32` in `0..n`. #[inline] fn gen_mod_u32(&mut self, n: u32) -> u32 { // Adapted from: https://lemire.me/blog/2016/06/30/fast-random-shuffling/ let mut r = self.gen_u32(); let mut hi = mul_high_u32(r, n); let mut lo = r.wrapping_mul(n); if lo < n { let t = n.wrapping_neg() % n; while lo < t { r = self.gen_u32(); hi = mul_high_u32(r, n); lo = r.wrapping_mul(n); } } hi } /// Generates a random `u64` in `0..n`. #[inline] fn gen_mod_u64(&mut self, n: u64) -> u64 { // Adapted from: https://lemire.me/blog/2016/06/30/fast-random-shuffling/ let mut r = self.gen_u64(); let mut hi = mul_high_u64(r, n); let mut lo = r.wrapping_mul(n); if lo < n { let t = n.wrapping_neg() % n; while lo < t { r = self.gen_u64(); hi = mul_high_u64(r, n); lo = r.wrapping_mul(n); } } hi } /// Generates a random `u128` in `0..n`. #[inline] fn gen_mod_u128(&mut self, n: u128) -> u128 { // Adapted from: https://lemire.me/blog/2016/06/30/fast-random-shuffling/ let mut r = self.gen_u128(); let mut hi = mul_high_u128(r, n); let mut lo = r.wrapping_mul(n); if lo < n { let t = n.wrapping_neg() % n; while lo < t { r = self.gen_u128(); hi = mul_high_u128(r, n); lo = r.wrapping_mul(n); } } hi } } /// Computes `(a * b) >> 32`. #[inline] fn mul_high_u32(a: u32, b: u32) -> u32 { (((a as u64) * (b as u64)) >> 32) as u32 } /// Computes `(a * b) >> 64`. #[inline] fn mul_high_u64(a: u64, b: u64) -> u64 { (((a as u128) * (b as u128)) >> 64) as u64 } /// Computes `(a * b) >> 128`. #[inline] fn mul_high_u128(a: u128, b: u128) -> u128 { // Adapted from: https://stackoverflow.com/a/28904636 let a_lo = a as u64 as u128; let a_hi = (a >> 64) as u64 as u128; let b_lo = b as u64 as u128; let b_hi = (b >> 64) as u64 as u128; let carry = (a_lo * b_lo) >> 64; let carry = ((a_hi * b_lo) as u64 as u128 + (a_lo * b_hi) as u64 as u128 + carry) >> 64; a_hi * b_hi + ((a_hi * b_lo) >> 64) + ((a_lo * b_hi) >> 64) + carry } macro_rules! rng_integer { ($t:tt, $unsigned_t:tt, $gen:tt, $mod:tt, $doc:tt) => { #[doc = $doc] /// /// Panics if the range is empty. #[inline] pub fn $t(&mut self, range: impl RangeBounds<$t>) -> $t { let panic_empty_range = || { panic!( "empty range: {:?}..{:?}", range.start_bound(), range.end_bound() ) }; let low = match range.start_bound() { Bound::Unbounded => core::$t::MIN, Bound::Included(&x) => x, Bound::Excluded(&x) => x.checked_add(1).unwrap_or_else(panic_empty_range), }; let high = match range.end_bound() { Bound::Unbounded => core::$t::MAX, Bound::Included(&x) => x, Bound::Excluded(&x) => x.checked_sub(1).unwrap_or_else(panic_empty_range), }; if low > high { panic_empty_range(); } if low == core::$t::MIN && high == core::$t::MAX { self.$gen() as $t } else { let len = high.wrapping_sub(low).wrapping_add(1); low.wrapping_add(self.$mod(len as $unsigned_t as _) as $t) } } }; } impl Rng { /// Creates a new random number generator with the initial seed. #[inline] #[must_use = "this creates a new instance of `Rng`; if you want to initialize the thread-local generator, use `fastrand::seed()` instead"] pub fn with_seed(seed: u64) -> Self { let mut rng = Rng(0); rng.seed(seed); rng } /// Clones the generator by deterministically deriving a new generator based on the initial /// seed. /// /// # Example /// /// ``` /// // Seed two generators equally, and clone both of them. /// let mut base1 = fastrand::Rng::new(); /// base1.seed(0x4d595df4d0f33173); /// base1.bool(); // Use the generator once. /// /// let mut base2 = fastrand::Rng::new(); /// base2.seed(0x4d595df4d0f33173); /// base2.bool(); // Use the generator once. /// /// let mut rng1 = base1.clone(); /// let mut rng2 = base2.clone(); /// /// assert_eq!(rng1.u64(..), rng2.u64(..), "the cloned generators are identical"); /// ``` #[inline] #[must_use = "this creates a new instance of `Rng`"] pub fn fork(&mut self) -> Self { Rng::with_seed(self.gen_u64()) } /// Generates a random `char` in ranges a-z and A-Z. #[inline] pub fn alphabetic(&mut self) -> char { const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; *self.choice(CHARS).unwrap() as char } /// Generates a random `char` in ranges a-z, A-Z and 0-9. #[inline] pub fn alphanumeric(&mut self) -> char { const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; *self.choice(CHARS).unwrap() as char } /// Generates a random `bool`. #[inline] pub fn bool(&mut self) -> bool { self.u8(..) % 2 == 0 } /// Generates a random digit in the given `base`. /// /// Digits are represented by `char`s in ranges 0-9 and a-z. /// /// Panics if the base is zero or greater than 36. #[inline] pub fn digit(&mut self, base: u32) -> char { if base == 0 { panic!("base cannot be zero"); } if base > 36 { panic!("base cannot be larger than 36"); } let num = self.u8(..base as u8); if num < 10 { (b'0' + num) as char } else { (b'a' + num - 10) as char } } /// Generates a random `f32` in range `0..1`. pub fn f32(&mut self) -> f32 { let b = 32; let f = core::f32::MANTISSA_DIGITS - 1; f32::from_bits((1 << (b - 2)) - (1 << f) + (self.u32(..) >> (b - f))) - 1.0 } /// Generates a random `f64` in range `0..1`. pub fn f64(&mut self) -> f64 { let b = 64; let f = core::f64::MANTISSA_DIGITS - 1; f64::from_bits((1 << (b - 2)) - (1 << f) + (self.u64(..) >> (b - f))) - 1.0 } /// Collects `amount` values at random from the iterator into a vector. /// /// The length of the returned vector equals `amount` unless the iterator /// contains insufficient elements, in which case it equals the number of /// elements available. /// /// Complexity is `O(n)` where `n` is the length of the iterator. #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub fn choose_multiple<T: Iterator>(&mut self, mut source: T, amount: usize) -> Vec<T::Item> { // Adapted from: https://docs.rs/rand/latest/rand/seq/trait.IteratorRandom.html#method.choose_multiple let mut reservoir = Vec::with_capacity(amount); reservoir.extend(source.by_ref().take(amount)); // Continue unless the iterator was exhausted // // note: this prevents iterators that "restart" from causing problems. // If the iterator stops once, then so do we. if reservoir.len() == amount { for (i, elem) in source.enumerate() { let end = i + 1 + amount; let k = self.usize(0..end); if let Some(slot) = reservoir.get_mut(k) { *slot = elem; } } } else { // If less than one third of the `Vec` was used, reallocate // so that the unused space is not wasted. There is a corner // case where `amount` was much less than `self.len()`. if reservoir.capacity() > 3 * reservoir.len() { reservoir.shrink_to_fit(); } } reservoir } rng_integer!( i8, u8, gen_u32, gen_mod_u32, "Generates a random `i8` in the given range." ); rng_integer!( i16, u16, gen_u32, gen_mod_u32, "Generates a random `i16` in the given range." ); rng_integer!( i32, u32, gen_u32, gen_mod_u32, "Generates a random `i32` in the given range." ); rng_integer!( i64, u64, gen_u64, gen_mod_u64, "Generates a random `i64` in the given range." ); rng_integer!( i128, u128, gen_u128, gen_mod_u128, "Generates a random `i128` in the given range." ); #[cfg(target_pointer_width = "16")] rng_integer!( isize, usize, gen_u32, gen_mod_u32, "Generates a random `isize` in the given range." ); #[cfg(target_pointer_width = "32")] rng_integer!( isize, usize, gen_u32, gen_mod_u32, "Generates a random `isize` in the given range." ); #[cfg(target_pointer_width = "64")] rng_integer!( isize, usize, gen_u64, gen_mod_u64, "Generates a random `isize` in the given range." ); /// Generates a random `char` in range a-z. #[inline] pub fn lowercase(&mut self) -> char { const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; *self.choice(CHARS).unwrap() as char } /// Initializes this generator with the given seed. #[inline] pub fn seed(&mut self, seed: u64) { self.0 = seed; } /// Gives back **current** seed that is being held by this generator. #[inline] pub fn get_seed(&self) -> u64 { self.0 } /// Choose an item from an iterator at random. /// /// This function may have an unexpected result if the `len()` property of the /// iterator does not match the actual number of items in the iterator. If /// the iterator is empty, this returns `None`. #[inline] pub fn choice<I>(&mut self, iter: I) -> Option<I::Item> where I: IntoIterator, I::IntoIter: ExactSizeIterator, { let mut iter = iter.into_iter(); // Get the item at a random index. let len = iter.len(); if len == 0 { return None; } let index = self.usize(0..len); iter.nth(index) } /// Shuffles a slice randomly. #[inline] pub fn shuffle<T>(&mut self, slice: &mut [T]) { for i in 1..slice.len() { slice.swap(i, self.usize(..=i)); } } /// Fill a byte slice with random data. #[inline] pub fn fill(&mut self, slice: &mut [u8]) { // We fill the slice by chunks of 8 bytes, or one block of // WyRand output per new state. let mut chunks = slice.chunks_exact_mut(core::mem::size_of::<u64>()); for chunk in chunks.by_ref() { let n = self.gen_u64().to_ne_bytes(); // Safe because the chunks are always 8 bytes exactly. chunk.copy_from_slice(&n); } let remainder = chunks.into_remainder(); // Any remainder will always be less than 8 bytes. if !remainder.is_empty() { // Generate one last block of 8 bytes of entropy let n = self.gen_u64().to_ne_bytes(); // Use the remaining length to copy from block remainder.copy_from_slice(&n[..remainder.len()]); } } rng_integer!( u8, u8, gen_u32, gen_mod_u32, "Generates a random `u8` in the given range." ); rng_integer!( u16, u16, gen_u32, gen_mod_u32, "Generates a random `u16` in the given range." ); rng_integer!( u32, u32, gen_u32, gen_mod_u32, "Generates a random `u32` in the given range." ); rng_integer!( u64, u64, gen_u64, gen_mod_u64, "Generates a random `u64` in the given range." ); rng_integer!( u128, u128, gen_u128, gen_mod_u128, "Generates a random `u128` in the given range." ); #[cfg(target_pointer_width = "16")] rng_integer!( usize, usize, gen_u32, gen_mod_u32, "Generates a random `usize` in the given range." ); #[cfg(target_pointer_width = "32")] rng_integer!( usize, usize, gen_u32, gen_mod_u32, "Generates a random `usize` in the given range." ); #[cfg(target_pointer_width = "64")] rng_integer!( usize, usize, gen_u64, gen_mod_u64, "Generates a random `usize` in the given range." ); #[cfg(target_pointer_width = "128")] rng_integer!( usize, usize, gen_u128, gen_mod_u128, "Generates a random `usize` in the given range." ); /// Generates a random `char` in range A-Z. #[inline] pub fn uppercase(&mut self) -> char { const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; *self.choice(CHARS).unwrap() as char } /// Generates a random `char` in the given range. /// /// Panics if the range is empty. #[inline] pub fn char(&mut self, range: impl RangeBounds<char>) -> char { let panic_empty_range = || { panic!( "empty range: {:?}..{:?}", range.start_bound(), range.end_bound() ) }; let surrogate_start = 0xd800u32; let surrogate_len = 0x800u32; let low = match range.start_bound() { Bound::Unbounded => 0u8 as char, Bound::Included(&x) => x, Bound::Excluded(&x) => { let scalar = if x as u32 == surrogate_start - 1 { surrogate_start + surrogate_len } else { x as u32 + 1 }; char::try_from(scalar).unwrap_or_else(|_| panic_empty_range()) } }; let high = match range.end_bound() { Bound::Unbounded => core::char::MAX, Bound::Included(&x) => x, Bound::Excluded(&x) => { let scalar = if x as u32 == surrogate_start + surrogate_len { surrogate_start - 1 } else { (x as u32).wrapping_sub(1) }; char::try_from(scalar).unwrap_or_else(|_| panic_empty_range()) } }; if low > high { panic_empty_range(); } let gap = if (low as u32) < surrogate_start && (high as u32) >= surrogate_start { surrogate_len } else { 0 }; let range = high as u32 - low as u32 - gap; let mut val = self.u32(0..=range) + low as u32; if val >= surrogate_start { val += gap; } val.try_into().unwrap() } }
#![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 IDisplayDeviceInterop(pub ::windows::core::IUnknown); impl IDisplayDeviceInterop { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub unsafe fn CreateSharedHandle<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, pobject: Param0, psecurityattributes: *const super::super::super::Security::SECURITY_ATTRIBUTES, access: u32, name: Param3) -> ::windows::core::Result<super::super::super::Foundation::HANDLE> { let mut result__: <super::super::super::Foundation::HANDLE as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pobject.into_param().abi(), ::core::mem::transmute(psecurityattributes), ::core::mem::transmute(access), name.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::HANDLE>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn OpenSharedHandle<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, nthandle: Param0, riid: Param1, ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), nthandle.into_param().abi(), riid.into_param().abi(), ::core::mem::transmute(ppvobj)).ok() } } unsafe impl ::windows::core::Interface for IDisplayDeviceInterop { type Vtable = IDisplayDeviceInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x64338358_366a_471b_bd56_dd8ef48e439b); } impl ::core::convert::From<IDisplayDeviceInterop> for ::windows::core::IUnknown { fn from(value: IDisplayDeviceInterop) -> Self { value.0 } } impl ::core::convert::From<&IDisplayDeviceInterop> for ::windows::core::IUnknown { fn from(value: &IDisplayDeviceInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDisplayDeviceInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDisplayDeviceInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDisplayDeviceInterop_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, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pobject: ::windows::core::RawPtr, psecurityattributes: *const super::super::super::Security::SECURITY_ATTRIBUTES, access: u32, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, phandle: *mut super::super::super::Foundation::HANDLE) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Security")))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nthandle: super::super::super::Foundation::HANDLE, riid: ::windows::core::GUID, ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IDisplayPathInterop(pub ::windows::core::IUnknown); impl IDisplayPathInterop { #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateSourcePresentationHandle(&self) -> ::windows::core::Result<super::super::super::Foundation::HANDLE> { let mut result__: <super::super::super::Foundation::HANDLE as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::HANDLE>(result__) } pub unsafe fn GetSourceId(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for IDisplayPathInterop { type Vtable = IDisplayPathInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa6ba4205_e59e_4e71_b25b_4e436d21ee3d); } impl ::core::convert::From<IDisplayPathInterop> for ::windows::core::IUnknown { fn from(value: IDisplayPathInterop) -> Self { value.0 } } impl ::core::convert::From<&IDisplayPathInterop> for ::windows::core::IUnknown { fn from(value: &IDisplayPathInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDisplayPathInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDisplayPathInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDisplayPathInterop_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, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvalue: *mut super::super::super::Foundation::HANDLE) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psourceid: *mut u32) -> ::windows::core::HRESULT, );
use gl; use nalgebra_glm::{Mat4, Vec2}; use std; use std::ffi::{CStr, CString}; pub struct Program { pub id: gl::types::GLuint, } impl Program { pub fn from_shaders(shaders: &[Shader]) -> Result<Program, String> { let program_id = unsafe { gl::CreateProgram() }; for shader in shaders { unsafe { gl::AttachShader(program_id, shader.id); } } unsafe { gl::LinkProgram(program_id); } let mut success: gl::types::GLint = 1; unsafe { gl::GetProgramiv(program_id, gl::LINK_STATUS, &mut success); } if success == 0 { let mut len: gl::types::GLint = 0; unsafe { gl::GetProgramiv(program_id, gl::INFO_LOG_LENGTH, &mut len); } let error = create_whitespace_cstring_with_len(len as usize); unsafe { gl::GetProgramInfoLog( program_id, len, std::ptr::null_mut(), error.as_ptr() as *mut gl::types::GLchar, ); } return Err(error.to_string_lossy().into_owned()); } for shader in shaders { unsafe { gl::DetachShader(program_id, shader.id); } } Ok(Program { id: program_id }) } pub fn set_int(&self, name: &str, int: i32) { let cname = CString::new(name).expect("expected uniform name to have no nul bytes"); unsafe { gl::Uniform1i( gl::GetUniformLocation(self.id, cname.as_bytes_with_nul().as_ptr() as *const i8), int, ); } } pub fn set_used(&self) { unsafe { gl::UseProgram(self.id); } } } impl Drop for Program { fn drop(&mut self) { unsafe { gl::DeleteProgram(self.id); } } } pub struct Shader { pub id: gl::types::GLuint, } impl Shader { pub fn from_source(source: &CStr, kind: gl::types::GLenum) -> Result<Shader, String> { let id = shader_from_source(source, kind)?; Ok(Shader { id }) } pub fn from_vert_source(source: &CStr) -> Result<Shader, String> { Shader::from_source(source, gl::VERTEX_SHADER) } pub fn from_frag_source(source: &CStr) -> Result<Shader, String> { Shader::from_source(source, gl::FRAGMENT_SHADER) } } impl Drop for Shader { fn drop(&mut self) { unsafe { gl::DeleteShader(self.id); } } } fn shader_from_source(source: &CStr, kind: gl::types::GLenum) -> Result<gl::types::GLuint, String> { let id = unsafe { gl::CreateShader(kind) }; unsafe { gl::ShaderSource(id, 1, &source.as_ptr(), std::ptr::null()); gl::CompileShader(id); } let mut success: gl::types::GLint = 1; unsafe { gl::GetShaderiv(id, gl::COMPILE_STATUS, &mut success); } if success == 0 { let mut len: gl::types::GLint = 0; unsafe { gl::GetShaderiv(id, gl::INFO_LOG_LENGTH, &mut len); } let error = create_whitespace_cstring_with_len(len as usize); unsafe { gl::GetShaderInfoLog( id, len, std::ptr::null_mut(), error.as_ptr() as *mut gl::types::GLchar, ); } return Err(error.to_string_lossy().into_owned()); } Ok(id) } fn create_whitespace_cstring_with_len(len: usize) -> CString { // allocate buffer of correct size let mut buffer: Vec<u8> = Vec::with_capacity(len + 1); // fill it with len spaces buffer.extend([b' '].iter().cycle().take(len)); // convert buffer to CString unsafe { CString::from_vec_unchecked(buffer) } } pub struct gl_entity { pub program_id: gl::types::GLuint, pub vertex_array_object: gl::types::GLuint, } fn render_rect(rect: &gl_entity) { unsafe { gl::UseProgram(rect.program_id); gl::BindVertexArray(rect.vertex_array_object); gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, std::ptr::null()); gl::BindVertexArray(0); } } fn create_rect(program_id: gl::types::GLuint) -> gl_entity { let vertices: Vec<f32> = vec![ 0.5, 0.5, 0.0, // top right 0.5, -0.5, 0.0, // bottom right -0.5, -0.5, 0.0, // bottom left -0.5, 0.5, 0.0, // top left ]; let indices = vec![ // note that we start from 0! 0, 1, 3, // first Triangle 1, 2, 3, // second Triangle ]; let mut vertex_buffer_object: gl::types::GLuint = 0; let mut vertex_array_object: gl::types::GLuint = 0; let mut ebo: gl::types::GLuint = 0; unsafe { gl::GenVertexArrays(1, &mut vertex_array_object); gl::GenBuffers(1, &mut vertex_buffer_object); gl::GenBuffers(1, &mut ebo); gl::BindVertexArray(vertex_array_object); gl::BindBuffer(gl::ARRAY_BUFFER, vertex_buffer_object); gl::BufferData( gl::ARRAY_BUFFER, (vertices.len() * std::mem::size_of::<f32>()) as gl::types::GLsizeiptr, vertices.as_ptr() as *const gl::types::GLvoid, gl::STATIC_DRAW, ); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, (indices.len() * std::mem::size_of::<f32>()) as gl::types::GLsizeiptr, indices.as_ptr() as *const gl::types::GLvoid, gl::STATIC_DRAW, ); // position attribute gl::VertexAttribPointer( 0, 2, gl::FLOAT, gl::FALSE, (3 * std::mem::size_of::<f32>()) as gl::types::GLint, std::ptr::null(), ); gl::EnableVertexAttribArray(0); } gl_entity { vertex_array_object, program_id, } } pub struct Renderer {} impl Renderer { pub fn clear() { unsafe { gl::Clear(gl::COLOR_BUFFER_BIT); } } pub fn clear_color(r: f32, g: f32, b: f32, a: f32) { unsafe { gl::ClearColor(r, g, b, a); } } pub fn set_projection(shader_id: gl::types::GLuint, width: u32, height: u32) { unsafe { gl::UseProgram(shader_id); } let projection = nalgebra_glm::ortho(0.0, width as f32, height as f32, 0.0, -1.0, 100.0); let cname = CString::new("projection").expect("expected uniform name to have no nul bytes"); unsafe { gl::UniformMatrix4fv( gl::GetUniformLocation(shader_id, cname.as_bytes_with_nul().as_ptr() as *const i8), 1, gl::FALSE, nalgebra_glm::value_ptr(&projection).as_ptr(), ); } } pub fn set_view(shader_id: gl::types::GLuint) { let camera_pos = nalgebra_glm::vec3(5.0, 5.0, 3.0); let camera_front = nalgebra_glm::vec3(0.0, 0.0, -1.0); let view = nalgebra_glm::look_at( &camera_pos, &(camera_pos + camera_front), &nalgebra_glm::vec3(0.0, 1.0, 0.0), ); let cname = CString::new("view").expect("expected uniform name to have no nul bytes"); unsafe { gl::UniformMatrix4fv( gl::GetUniformLocation(shader_id, cname.as_bytes_with_nul().as_ptr() as *const i8), 1, gl::FALSE, nalgebra_glm::value_ptr(&view).as_ptr(), ); } } pub fn create_rect(program_id: gl::types::GLuint) -> gl_entity { create_rect(program_id) } pub fn rect(rect: &gl_entity, position: Vec2, size: Vec2) { unsafe { gl::UseProgram(rect.program_id); let mut model = Mat4::identity(); model = nalgebra_glm::translate(&model, &nalgebra_glm::vec3(position.x, position.y, 0.0)); model = nalgebra_glm::translate( &model, &nalgebra_glm::vec3(0.5 * size.x, 0.5 * size.y, 0.0), ); model = nalgebra_glm::rotate(&model, 0.0, &nalgebra_glm::vec3(0.0, 0.0, 1.0)); model = nalgebra_glm::translate( &model, &nalgebra_glm::vec3(-0.5 * size.x, -0.5 * size.y, 0.0), ); model = nalgebra_glm::scale(&model, &nalgebra_glm::vec3(size.x, size.y, 1.0)); let cname = CString::new("model").expect("expected uniform name to have no nul bytes"); gl::UniformMatrix4fv( gl::GetUniformLocation( rect.program_id, cname.as_bytes_with_nul().as_ptr() as *const i8, ), 1, gl::FALSE, nalgebra_glm::value_ptr(&model).as_ptr(), ); gl::BindVertexArray(rect.vertex_array_object); gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, std::ptr::null()); gl::BindVertexArray(0); } } }
use prettytable::Table; use prettytable::{cell, row}; use std::collections::HashMap; static NO_DATA_WARNING: &'static str = "No time track data found"; pub fn display(data: HashMap<String, u64>) { let output_rows = format(data); if output_rows.is_empty() { println!("{}", NO_DATA_WARNING); } else { print_table(output_rows); } } fn format(data: HashMap<String, u64>) -> Vec<(String, String)> { let mut output_rows = vec![]; for (project, time_in_seconds) in data { if time_in_seconds > 0 { output_rows.push((project, to_hms(time_in_seconds))); } } output_rows.sort_by(|(a, _), (b, _)| a.cmp(b)); // alphabetize the output by project name output_rows } fn print_table(output_rows: Vec<(String, String)>) { let mut table = Table::new(); // header row is bold table.add_row(row![b -> "Project Name", b -> "Time"]); for (project, time) in output_rows { table.add_row(row![project, time]); } table.printstd(); } /// Converts a duration in seconds to a human readable string fn to_hms(seconds: u64) -> String { let hours = seconds / (60 * 60); let minutes = (seconds - (hours * 60 * 60)) / 60; let seconds = seconds - (hours * 60 * 60) - (minutes * 60); match (hours, minutes, seconds) { (0, 0, 0) => String::from("None"), (0, 0, 1) => String::from("1 second"), (0, 0, seconds) => format!("{} seconds", seconds), (0, 1, _) => String::from("1 minute"), (0, minutes, _) => format!("{} minutes", minutes), (1, 1, _) => String::from("1 hour 1 minute"), (1, minutes, _) => format!("1 hour {} minutes", minutes), (hours, 1, _) => format!("{} hours 1 minute", hours), (hours, minutes, _) => format!("{} hours {} minutes", hours, minutes), } } #[cfg(test)] mod tests { use super::*; #[test] fn to_hms_string_zero() { assert_eq!("None", to_hms(0)); } #[test] fn to_hms_second() { assert_eq!("1 second", to_hms(1)); } #[test] fn to_hms_seconds() { assert_eq!("30 seconds", to_hms(30)); } #[test] fn to_hms_minute() { assert_eq!("1 minute", to_hms(60)); } #[test] fn to_hms_minutes() { assert_eq!("5 minutes", to_hms(330)); } #[test] fn to_hms_hour_minute() { assert_eq!("1 hour 1 minute", to_hms((1 * 60 * 60) + (1 * 60) + 30)); } #[test] fn to_hms_hour() { assert_eq!("1 hour 10 minutes", to_hms((1 * 60 * 60) + (10 * 60) + 30)); } #[test] fn to_hms_hours_minute() { assert_eq!("5 hours 1 minute", to_hms((5 * 60 * 60) + (1 * 60) + 30)); } #[test] fn to_hms_hours() { assert_eq!("5 hours 10 minutes", to_hms((5 * 60 * 60) + (10 * 60) + 30)); } }
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. //! Provides a wrapper for allocating, handling and interacting with the guest memory regions. #![deny(missing_docs)] extern crate libc; mod bytes; mod guest_address; mod guest_memory; mod mmap; pub use bytes::{ByteValued, Bytes}; pub use guest_address::Address; pub use guest_address::GuestAddress; pub use guest_memory::Error as GuestMemoryError; pub use guest_memory::GuestMemory; pub use guest_memory::MemoryRegion; pub use mmap::{Error as MemoryMappingError, MemoryMapping};
use serde::Deserialize; #[derive(Deserialize, Debug)] struct Ip { origin: String } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let client = reqwest::Client::builder() .build()?; let res = client .get("https://httpbin.org/ip") .send() .await?; let ip = res .json::<Ip>() .await?; println!("Meu IP público: {}", ip.origin); Ok(()) }
use super::Square; pub const ALL_SQUARES: Square = Square(0); pub const UNDEFINED_SQUARE: Square = Square(0xFF); pub const A8: Square = Square(0); pub const B8: Square = Square(1); pub const C8: Square = Square(2); pub const D8: Square = Square(3); pub const E8: Square = Square(4); pub const F8: Square = Square(5); pub const G8: Square = Square(6); pub const H8: Square = Square(7); pub const A7: Square = Square(8); pub const B7: Square = Square(9); pub const C7: Square = Square(10); pub const D7: Square = Square(11); pub const E7: Square = Square(12); pub const F7: Square = Square(13); pub const G7: Square = Square(14); pub const H7: Square = Square(15); pub const A6: Square = Square(16); pub const B6: Square = Square(17); pub const C6: Square = Square(18); pub const D6: Square = Square(19); pub const E6: Square = Square(20); pub const F6: Square = Square(21); pub const G6: Square = Square(22); pub const H6: Square = Square(23); pub const A5: Square = Square(24); pub const B5: Square = Square(25); pub const C5: Square = Square(26); pub const D5: Square = Square(27); pub const E5: Square = Square(28); pub const F5: Square = Square(29); pub const G5: Square = Square(30); pub const H5: Square = Square(31); pub const A4: Square = Square(32); pub const B4: Square = Square(33); pub const C4: Square = Square(34); pub const D4: Square = Square(35); pub const E4: Square = Square(36); pub const F4: Square = Square(37); pub const G4: Square = Square(38); pub const H4: Square = Square(39); pub const A3: Square = Square(40); pub const B3: Square = Square(41); pub const C3: Square = Square(42); pub const D3: Square = Square(43); pub const E3: Square = Square(44); pub const F3: Square = Square(45); pub const G3: Square = Square(46); pub const H3: Square = Square(47); pub const A2: Square = Square(48); pub const B2: Square = Square(49); pub const C2: Square = Square(50); pub const D2: Square = Square(51); pub const E2: Square = Square(52); pub const F2: Square = Square(53); pub const G2: Square = Square(54); pub const H2: Square = Square(55); pub const A1: Square = Square(56); pub const B1: Square = Square(57); pub const C1: Square = Square(58); pub const D1: Square = Square(59); pub const E1: Square = Square(60); pub const F1: Square = Square(61); pub const G1: Square = Square(62); pub const H1: Square = Square(63); impl Iterator for Square { type Item = Square; fn next(&mut self) -> Option<Self::Item> { if self.0 == 64 { None } else { let copy = *self; self.0 += 1; Some(copy) } } } #[cfg(test)] mod test { use super::*; use itertools::*; #[test] fn all_squares() { assert_eq!(ALL_SQUARES.collect_vec(), vec!( A8,B8,C8,D8,E8,F8,G8,H8, A7,B7,C7,D7,E7,F7,G7,H7, A6,B6,C6,D6,E6,F6,G6,H6, A5,B5,C5,D5,E5,F5,G5,H5, A4,B4,C4,D4,E4,F4,G4,H4, A3,B3,C3,D3,E3,F3,G3,H3, A2,B2,C2,D2,E2,F2,G2,H2, A1, B1,C1,D1, E1, F1, G1,H1)); } }
use proconio::input; fn main() { input! { mut x: i64, k: i64, }; for i in 0..k { let t = 10_i64.pow((i + 1) as u32); let (y1, y2) = (x / t * t, (x / t + 1) * t); if (y1 - x).abs() < (y2 - x).abs() { x = y1; } else { x = y2; } } println!("{}", x); }
use crate::models::event::Event; use crate::models::launch::Launch; pub trait Ctx: std::fmt::Display {} impl Ctx for str {} impl Ctx for String {} impl Ctx for i32 {} pub trait ResObject {} impl ResObject for Launch {} impl ResObject for Event {}
use crate::compiling::v1::assemble::prelude::*; /// Compile a continue expression. impl Assemble for ast::ExprContinue { fn assemble(&self, c: &mut Compiler<'_>, _: Needs) -> CompileResult<Asm> { let span = self.span(); log::trace!("ExprContinue => {:?}", c.source.source(span)); let current_loop = match c.loops.last() { Some(current_loop) => current_loop, None => { return Err(CompileError::new( span, CompileErrorKind::ContinueOutsideOfLoop, )); } }; let last_loop = if let Some(label) = &self.label { let (last_loop, _) = c.loops.walk_until_label(c.storage, &*c.source, *label)?; last_loop } else { current_loop }; let vars = c .scopes .total_var_count(span)? .checked_sub(last_loop.continue_var_count) .ok_or_else(|| CompileError::msg(&span, "var count should be larger"))?; c.locals_pop(vars, span); c.asm.jump(last_loop.continue_label, span); Ok(Asm::top(span)) } }
//! The base collection of `Points` onto which Residue's //! can be broadcast. Beyond the creation of points (ie. //! using a Lattice or Poisson Disc generator) all transformations //! of the points belong in this module. use rand; use coord::Coord; /// A collection of points to broadcast residues onto. pub struct Points { /// Box dimensions. pub box_size: Coord, /// Points. pub coords: Vec<Coord>, } impl Points { /// Get a copy of the `Points` in which the positions along z /// have been shifted by a uniform random distribution. /// The positions are shifted on a range of (-std_z, +std_z) /// where std_z is the input deviation. pub fn uniform_distribution(&self, std_z: f64) -> Points { use rand::distributions::IndependentSample; let range = rand::distributions::Range::new(-std_z, std_z); let mut rng = rand::thread_rng(); let coords: Vec<Coord> = self.coords .iter() .map(|&c| { let add_z = range.ind_sample(&mut rng); //c.add(Coord::new(0.0, 0.0, add_z)) c + Coord::new(0.0, 0.0, add_z) }) .collect(); Points { box_size: self.box_size, coords: coords, } } } #[cfg(test)] mod tests { use super::*; #[test] fn uniform_distribution_of_positions() { let z0 = 1.0; let points = Points { box_size: Coord::new(1.0, 1.0, 1.0), coords: vec![Coord::new(0.0, 0.0, z0); 100], }; let dz = 0.1; let distributed_points = points.uniform_distribution(dz); // Assert that the positions are centered around z0 with non-zero variance assert!(distributed_points.coords.iter().all(|&c| c.z.abs() - z0 <= dz)); let len = distributed_points.coords.len(); let var_z: f64 = distributed_points.coords .iter() .map(|c| (c.z - z0) * (c.z - z0)) .sum::<f64>() / (len as f64); assert!(var_z > 0.0); } }
use std::io::Read; pub fn build_dag_from_reader<R: Read>(reader: &mut R, ds:
use crate::Compat; use core::{ pin::Pin, task::{self, Poll}, }; use std::io; impl<T> tokio_io::AsyncRead for Compat<T> where T: futures_io::AsyncRead, { fn poll_read( self: Pin<&mut Self>, cx: &mut task::Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { futures_io::AsyncRead::poll_read(self.project().inner, cx, buf) } } impl<T> futures_io::AsyncRead for Compat<T> where T: tokio_io::AsyncRead, { fn poll_read( self: Pin<&mut Self>, cx: &mut task::Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { tokio_io::AsyncRead::poll_read(self.project().inner, cx, buf) } } impl<T> tokio_io::AsyncBufRead for Compat<T> where T: futures_io::AsyncBufRead, { fn poll_fill_buf<'a>( self: Pin<&'a mut Self>, cx: &mut task::Context, ) -> Poll<io::Result<&'a [u8]>> { futures_io::AsyncBufRead::poll_fill_buf(self.project().inner, cx) } fn consume(self: Pin<&mut Self>, amt: usize) { futures_io::AsyncBufRead::consume(self.project().inner, amt) } } impl<T> futures_io::AsyncBufRead for Compat<T> where T: tokio_io::AsyncBufRead, { fn poll_fill_buf<'a>( self: Pin<&'a mut Self>, cx: &mut task::Context, ) -> Poll<io::Result<&'a [u8]>> { tokio_io::AsyncBufRead::poll_fill_buf(self.project().inner, cx) } fn consume(self: Pin<&mut Self>, amt: usize) { tokio_io::AsyncBufRead::consume(self.project().inner, amt) } } impl<T> tokio_io::AsyncWrite for Compat<T> where T: futures_io::AsyncWrite, { fn poll_write( self: Pin<&mut Self>, cx: &mut task::Context, buf: &[u8], ) -> Poll<io::Result<usize>> { futures_io::AsyncWrite::poll_write(self.project().inner, cx, buf) } fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<io::Result<()>> { futures_io::AsyncWrite::poll_flush(self.project().inner, cx) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<io::Result<()>> { futures_io::AsyncWrite::poll_close(self.project().inner, cx) } } impl<T> futures_io::AsyncWrite for Compat<T> where T: tokio_io::AsyncWrite, { fn poll_write( self: Pin<&mut Self>, cx: &mut task::Context, buf: &[u8], ) -> Poll<io::Result<usize>> { tokio_io::AsyncWrite::poll_write(self.project().inner, cx, buf) } fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<io::Result<()>> { tokio_io::AsyncWrite::poll_flush(self.project().inner, cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<io::Result<()>> { tokio_io::AsyncWrite::poll_shutdown(self.project().inner, cx) } }
module lamp: [ input :[on,off], output:[ligada,desligada,ring], t_signal:[], p_signal:[a,b], var:[], initially:[up(a),activate(rules)], on_exception:[], on#[a]===>[emit(ligada),up(b)], off#[a]===>[emit(ring),up(a)], on#[b]===>[emit(ring),up(b)], off#[b]===>[emit(desligada),up(a)] ].
//! Tests that failed at some point. mod fail0 { use utils::generated_file; define_ir! { struct set_a; type subset_a[subset_b reverse set_a]: set_a; trait set_b; struct subset_b: set_b; } generated_file!(fail0); }
fn fizz_buzz(n: i32) -> String { let mut word = String::new(); if n % 3 == 0 { word += "Fizz"; } if n % 5 == 0 { word += "Buzz"; } if word.len() == 0 { word = n.to_string(); } word } fn main() { for i in 1..=100 { println!("{}", fizz_buzz(i)); } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qsettings.h // dst-file: /src/core/qsettings.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 super::qobject::*; // 773 use std::ops::Deref; use super::qstring::*; // 773 use super::qvariant::*; // 773 use super::qtextcodec::*; // 773 use super::qstringlist::*; // 773 use super::qobjectdefs::*; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QSettings_Class_Size() -> c_int; // proto: void QSettings::QSettings(QObject * parent); fn C_ZN9QSettingsC2EP7QObject(arg0: *mut c_void) -> u64; // proto: bool QSettings::isWritable(); fn C_ZNK9QSettings10isWritableEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QString QSettings::fileName(); fn C_ZNK9QSettings8fileNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QSettings::fallbacksEnabled(); fn C_ZNK9QSettings16fallbacksEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QString QSettings::applicationName(); fn C_ZNK9QSettings15applicationNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QSettings::sync(); fn C_ZN9QSettings4syncEv(qthis: u64 /* *mut c_void*/); // proto: void QSettings::setValue(const QString & key, const QVariant & value); fn C_ZN9QSettings8setValueERK7QStringRK8QVariant(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: void QSettings::setArrayIndex(int i); fn C_ZN9QSettings13setArrayIndexEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: void QSettings::QSettings(const QString & organization, const QString & application, QObject * parent); fn C_ZN9QSettingsC2ERK7QStringS2_P7QObject(arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> u64; // proto: void QSettings::setIniCodec(QTextCodec * codec); fn C_ZN9QSettings11setIniCodecEP10QTextCodec(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QSettings::setIniCodec(const char * codecName); fn C_ZN9QSettings11setIniCodecEPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_char); // proto: int QSettings::beginReadArray(const QString & prefix); fn C_ZN9QSettings14beginReadArrayERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_int; // proto: void QSettings::clear(); fn C_ZN9QSettings5clearEv(qthis: u64 /* *mut c_void*/); // proto: void QSettings::~QSettings(); fn C_ZN9QSettingsD2Ev(qthis: u64 /* *mut c_void*/); // proto: QTextCodec * QSettings::iniCodec(); fn C_ZNK9QSettings8iniCodecEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: static void QSettings::setUserIniPath(const QString & dir); fn C_ZN9QSettings14setUserIniPathERK7QString(arg0: *mut c_void); // proto: QStringList QSettings::childGroups(); fn C_ZNK9QSettings11childGroupsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QVariant QSettings::value(const QString & key, const QVariant & defaultValue); fn C_ZNK9QSettings5valueERK7QStringRK8QVariant(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: QString QSettings::organizationName(); fn C_ZNK9QSettings16organizationNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: const QMetaObject * QSettings::metaObject(); fn C_ZNK9QSettings10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QSettings::setFallbacksEnabled(bool b); fn C_ZN9QSettings19setFallbacksEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: bool QSettings::contains(const QString & key); fn C_ZNK9QSettings8containsERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: void QSettings::remove(const QString & key); fn C_ZN9QSettings6removeERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QSettings::endGroup(); fn C_ZN9QSettings8endGroupEv(qthis: u64 /* *mut c_void*/); // proto: void QSettings::beginWriteArray(const QString & prefix, int size); fn C_ZN9QSettings15beginWriteArrayERK7QStringi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int); // proto: void QSettings::beginGroup(const QString & prefix); fn C_ZN9QSettings10beginGroupERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QStringList QSettings::childKeys(); fn C_ZNK9QSettings9childKeysEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QSettings::endArray(); fn C_ZN9QSettings8endArrayEv(qthis: u64 /* *mut c_void*/); // proto: static void QSettings::setSystemIniPath(const QString & dir); fn C_ZN9QSettings16setSystemIniPathERK7QString(arg0: *mut c_void); // proto: QStringList QSettings::allKeys(); fn C_ZNK9QSettings7allKeysEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QString QSettings::group(); fn C_ZNK9QSettings5groupEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; } // <= ext block end // body block begin => // class sizeof(QSettings)=1 #[derive(Default)] pub struct QSettings { qbase: QObject, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QSettings { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QSettings { return QSettings{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QSettings { type Target = QObject; fn deref(&self) -> &QObject { return & self.qbase; } } impl AsRef<QObject> for QSettings { fn as_ref(& self) -> & QObject { return & self.qbase; } } // proto: void QSettings::QSettings(QObject * parent); impl /*struct*/ QSettings { pub fn new<T: QSettings_new>(value: T) -> QSettings { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QSettings_new { fn new(self) -> QSettings; } // proto: void QSettings::QSettings(QObject * parent); impl<'a> /*trait*/ QSettings_new for (Option<&'a QObject>) { fn new(self) -> QSettings { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettingsC2EP7QObject()}; let ctysz: c_int = unsafe{QSettings_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN9QSettingsC2EP7QObject(arg0)}; let rsthis = QSettings{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: bool QSettings::isWritable(); impl /*struct*/ QSettings { pub fn isWritable<RetType, T: QSettings_isWritable<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isWritable(self); // return 1; } } pub trait QSettings_isWritable<RetType> { fn isWritable(self , rsthis: & QSettings) -> RetType; } // proto: bool QSettings::isWritable(); impl<'a> /*trait*/ QSettings_isWritable<i8> for () { fn isWritable(self , rsthis: & QSettings) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings10isWritableEv()}; let mut ret = unsafe {C_ZNK9QSettings10isWritableEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QString QSettings::fileName(); impl /*struct*/ QSettings { pub fn fileName<RetType, T: QSettings_fileName<RetType>>(& self, overload_args: T) -> RetType { return overload_args.fileName(self); // return 1; } } pub trait QSettings_fileName<RetType> { fn fileName(self , rsthis: & QSettings) -> RetType; } // proto: QString QSettings::fileName(); impl<'a> /*trait*/ QSettings_fileName<QString> for () { fn fileName(self , rsthis: & QSettings) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings8fileNameEv()}; let mut ret = unsafe {C_ZNK9QSettings8fileNameEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QSettings::fallbacksEnabled(); impl /*struct*/ QSettings { pub fn fallbacksEnabled<RetType, T: QSettings_fallbacksEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.fallbacksEnabled(self); // return 1; } } pub trait QSettings_fallbacksEnabled<RetType> { fn fallbacksEnabled(self , rsthis: & QSettings) -> RetType; } // proto: bool QSettings::fallbacksEnabled(); impl<'a> /*trait*/ QSettings_fallbacksEnabled<i8> for () { fn fallbacksEnabled(self , rsthis: & QSettings) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings16fallbacksEnabledEv()}; let mut ret = unsafe {C_ZNK9QSettings16fallbacksEnabledEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QString QSettings::applicationName(); impl /*struct*/ QSettings { pub fn applicationName<RetType, T: QSettings_applicationName<RetType>>(& self, overload_args: T) -> RetType { return overload_args.applicationName(self); // return 1; } } pub trait QSettings_applicationName<RetType> { fn applicationName(self , rsthis: & QSettings) -> RetType; } // proto: QString QSettings::applicationName(); impl<'a> /*trait*/ QSettings_applicationName<QString> for () { fn applicationName(self , rsthis: & QSettings) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings15applicationNameEv()}; let mut ret = unsafe {C_ZNK9QSettings15applicationNameEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QSettings::sync(); impl /*struct*/ QSettings { pub fn sync<RetType, T: QSettings_sync<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sync(self); // return 1; } } pub trait QSettings_sync<RetType> { fn sync(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::sync(); impl<'a> /*trait*/ QSettings_sync<()> for () { fn sync(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings4syncEv()}; unsafe {C_ZN9QSettings4syncEv(rsthis.qclsinst)}; // return 1; } } // proto: void QSettings::setValue(const QString & key, const QVariant & value); impl /*struct*/ QSettings { pub fn setValue<RetType, T: QSettings_setValue<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setValue(self); // return 1; } } pub trait QSettings_setValue<RetType> { fn setValue(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::setValue(const QString & key, const QVariant & value); impl<'a> /*trait*/ QSettings_setValue<()> for (&'a QString, &'a QVariant) { fn setValue(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings8setValueERK7QStringRK8QVariant()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN9QSettings8setValueERK7QStringRK8QVariant(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QSettings::setArrayIndex(int i); impl /*struct*/ QSettings { pub fn setArrayIndex<RetType, T: QSettings_setArrayIndex<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setArrayIndex(self); // return 1; } } pub trait QSettings_setArrayIndex<RetType> { fn setArrayIndex(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::setArrayIndex(int i); impl<'a> /*trait*/ QSettings_setArrayIndex<()> for (i32) { fn setArrayIndex(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings13setArrayIndexEi()}; let arg0 = self as c_int; unsafe {C_ZN9QSettings13setArrayIndexEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QSettings::QSettings(const QString & organization, const QString & application, QObject * parent); impl<'a> /*trait*/ QSettings_new for (&'a QString, Option<&'a QString>, Option<&'a QObject>) { fn new(self) -> QSettings { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettingsC2ERK7QStringS2_P7QObject()}; let ctysz: c_int = unsafe{QSettings_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {QString::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void; let arg2 = (if self.2.is_none() {0} else {self.2.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN9QSettingsC2ERK7QStringS2_P7QObject(arg0, arg1, arg2)}; let rsthis = QSettings{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QSettings::setIniCodec(QTextCodec * codec); impl /*struct*/ QSettings { pub fn setIniCodec<RetType, T: QSettings_setIniCodec<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setIniCodec(self); // return 1; } } pub trait QSettings_setIniCodec<RetType> { fn setIniCodec(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::setIniCodec(QTextCodec * codec); impl<'a> /*trait*/ QSettings_setIniCodec<()> for (&'a QTextCodec) { fn setIniCodec(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings11setIniCodecEP10QTextCodec()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QSettings11setIniCodecEP10QTextCodec(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QSettings::setIniCodec(const char * codecName); impl<'a> /*trait*/ QSettings_setIniCodec<()> for (&'a String) { fn setIniCodec(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings11setIniCodecEPKc()}; let arg0 = self.as_ptr() as *mut c_char; unsafe {C_ZN9QSettings11setIniCodecEPKc(rsthis.qclsinst, arg0)}; // return 1; } } // proto: int QSettings::beginReadArray(const QString & prefix); impl /*struct*/ QSettings { pub fn beginReadArray<RetType, T: QSettings_beginReadArray<RetType>>(& self, overload_args: T) -> RetType { return overload_args.beginReadArray(self); // return 1; } } pub trait QSettings_beginReadArray<RetType> { fn beginReadArray(self , rsthis: & QSettings) -> RetType; } // proto: int QSettings::beginReadArray(const QString & prefix); impl<'a> /*trait*/ QSettings_beginReadArray<i32> for (&'a QString) { fn beginReadArray(self , rsthis: & QSettings) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings14beginReadArrayERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN9QSettings14beginReadArrayERK7QString(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: void QSettings::clear(); impl /*struct*/ QSettings { pub fn clear<RetType, T: QSettings_clear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clear(self); // return 1; } } pub trait QSettings_clear<RetType> { fn clear(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::clear(); impl<'a> /*trait*/ QSettings_clear<()> for () { fn clear(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings5clearEv()}; unsafe {C_ZN9QSettings5clearEv(rsthis.qclsinst)}; // return 1; } } // proto: void QSettings::~QSettings(); impl /*struct*/ QSettings { pub fn free<RetType, T: QSettings_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QSettings_free<RetType> { fn free(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::~QSettings(); impl<'a> /*trait*/ QSettings_free<()> for () { fn free(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettingsD2Ev()}; unsafe {C_ZN9QSettingsD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: QTextCodec * QSettings::iniCodec(); impl /*struct*/ QSettings { pub fn iniCodec<RetType, T: QSettings_iniCodec<RetType>>(& self, overload_args: T) -> RetType { return overload_args.iniCodec(self); // return 1; } } pub trait QSettings_iniCodec<RetType> { fn iniCodec(self , rsthis: & QSettings) -> RetType; } // proto: QTextCodec * QSettings::iniCodec(); impl<'a> /*trait*/ QSettings_iniCodec<QTextCodec> for () { fn iniCodec(self , rsthis: & QSettings) -> QTextCodec { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings8iniCodecEv()}; let mut ret = unsafe {C_ZNK9QSettings8iniCodecEv(rsthis.qclsinst)}; let mut ret1 = QTextCodec::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: static void QSettings::setUserIniPath(const QString & dir); impl /*struct*/ QSettings { pub fn setUserIniPath_s<RetType, T: QSettings_setUserIniPath_s<RetType>>( overload_args: T) -> RetType { return overload_args.setUserIniPath_s(); // return 1; } } pub trait QSettings_setUserIniPath_s<RetType> { fn setUserIniPath_s(self ) -> RetType; } // proto: static void QSettings::setUserIniPath(const QString & dir); impl<'a> /*trait*/ QSettings_setUserIniPath_s<()> for (&'a QString) { fn setUserIniPath_s(self ) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings14setUserIniPathERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QSettings14setUserIniPathERK7QString(arg0)}; // return 1; } } // proto: QStringList QSettings::childGroups(); impl /*struct*/ QSettings { pub fn childGroups<RetType, T: QSettings_childGroups<RetType>>(& self, overload_args: T) -> RetType { return overload_args.childGroups(self); // return 1; } } pub trait QSettings_childGroups<RetType> { fn childGroups(self , rsthis: & QSettings) -> RetType; } // proto: QStringList QSettings::childGroups(); impl<'a> /*trait*/ QSettings_childGroups<QStringList> for () { fn childGroups(self , rsthis: & QSettings) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings11childGroupsEv()}; let mut ret = unsafe {C_ZNK9QSettings11childGroupsEv(rsthis.qclsinst)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QVariant QSettings::value(const QString & key, const QVariant & defaultValue); impl /*struct*/ QSettings { pub fn value<RetType, T: QSettings_value<RetType>>(& self, overload_args: T) -> RetType { return overload_args.value(self); // return 1; } } pub trait QSettings_value<RetType> { fn value(self , rsthis: & QSettings) -> RetType; } // proto: QVariant QSettings::value(const QString & key, const QVariant & defaultValue); impl<'a> /*trait*/ QSettings_value<QVariant> for (&'a QString, Option<&'a QVariant>) { fn value(self , rsthis: & QSettings) -> QVariant { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings5valueERK7QStringRK8QVariant()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {QVariant::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void; let mut ret = unsafe {C_ZNK9QSettings5valueERK7QStringRK8QVariant(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QVariant::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QSettings::organizationName(); impl /*struct*/ QSettings { pub fn organizationName<RetType, T: QSettings_organizationName<RetType>>(& self, overload_args: T) -> RetType { return overload_args.organizationName(self); // return 1; } } pub trait QSettings_organizationName<RetType> { fn organizationName(self , rsthis: & QSettings) -> RetType; } // proto: QString QSettings::organizationName(); impl<'a> /*trait*/ QSettings_organizationName<QString> for () { fn organizationName(self , rsthis: & QSettings) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings16organizationNameEv()}; let mut ret = unsafe {C_ZNK9QSettings16organizationNameEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QSettings::metaObject(); impl /*struct*/ QSettings { pub fn metaObject<RetType, T: QSettings_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QSettings_metaObject<RetType> { fn metaObject(self , rsthis: & QSettings) -> RetType; } // proto: const QMetaObject * QSettings::metaObject(); impl<'a> /*trait*/ QSettings_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QSettings) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings10metaObjectEv()}; let mut ret = unsafe {C_ZNK9QSettings10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QSettings::setFallbacksEnabled(bool b); impl /*struct*/ QSettings { pub fn setFallbacksEnabled<RetType, T: QSettings_setFallbacksEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setFallbacksEnabled(self); // return 1; } } pub trait QSettings_setFallbacksEnabled<RetType> { fn setFallbacksEnabled(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::setFallbacksEnabled(bool b); impl<'a> /*trait*/ QSettings_setFallbacksEnabled<()> for (i8) { fn setFallbacksEnabled(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings19setFallbacksEnabledEb()}; let arg0 = self as c_char; unsafe {C_ZN9QSettings19setFallbacksEnabledEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QSettings::contains(const QString & key); impl /*struct*/ QSettings { pub fn contains<RetType, T: QSettings_contains<RetType>>(& self, overload_args: T) -> RetType { return overload_args.contains(self); // return 1; } } pub trait QSettings_contains<RetType> { fn contains(self , rsthis: & QSettings) -> RetType; } // proto: bool QSettings::contains(const QString & key); impl<'a> /*trait*/ QSettings_contains<i8> for (&'a QString) { fn contains(self , rsthis: & QSettings) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings8containsERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK9QSettings8containsERK7QString(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: void QSettings::remove(const QString & key); impl /*struct*/ QSettings { pub fn remove<RetType, T: QSettings_remove<RetType>>(& self, overload_args: T) -> RetType { return overload_args.remove(self); // return 1; } } pub trait QSettings_remove<RetType> { fn remove(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::remove(const QString & key); impl<'a> /*trait*/ QSettings_remove<()> for (&'a QString) { fn remove(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings6removeERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QSettings6removeERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QSettings::endGroup(); impl /*struct*/ QSettings { pub fn endGroup<RetType, T: QSettings_endGroup<RetType>>(& self, overload_args: T) -> RetType { return overload_args.endGroup(self); // return 1; } } pub trait QSettings_endGroup<RetType> { fn endGroup(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::endGroup(); impl<'a> /*trait*/ QSettings_endGroup<()> for () { fn endGroup(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings8endGroupEv()}; unsafe {C_ZN9QSettings8endGroupEv(rsthis.qclsinst)}; // return 1; } } // proto: void QSettings::beginWriteArray(const QString & prefix, int size); impl /*struct*/ QSettings { pub fn beginWriteArray<RetType, T: QSettings_beginWriteArray<RetType>>(& self, overload_args: T) -> RetType { return overload_args.beginWriteArray(self); // return 1; } } pub trait QSettings_beginWriteArray<RetType> { fn beginWriteArray(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::beginWriteArray(const QString & prefix, int size); impl<'a> /*trait*/ QSettings_beginWriteArray<()> for (&'a QString, Option<i32>) { fn beginWriteArray(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings15beginWriteArrayERK7QStringi()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {-1} else {self.1.unwrap()}) as c_int; unsafe {C_ZN9QSettings15beginWriteArrayERK7QStringi(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QSettings::beginGroup(const QString & prefix); impl /*struct*/ QSettings { pub fn beginGroup<RetType, T: QSettings_beginGroup<RetType>>(& self, overload_args: T) -> RetType { return overload_args.beginGroup(self); // return 1; } } pub trait QSettings_beginGroup<RetType> { fn beginGroup(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::beginGroup(const QString & prefix); impl<'a> /*trait*/ QSettings_beginGroup<()> for (&'a QString) { fn beginGroup(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings10beginGroupERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QSettings10beginGroupERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QStringList QSettings::childKeys(); impl /*struct*/ QSettings { pub fn childKeys<RetType, T: QSettings_childKeys<RetType>>(& self, overload_args: T) -> RetType { return overload_args.childKeys(self); // return 1; } } pub trait QSettings_childKeys<RetType> { fn childKeys(self , rsthis: & QSettings) -> RetType; } // proto: QStringList QSettings::childKeys(); impl<'a> /*trait*/ QSettings_childKeys<QStringList> for () { fn childKeys(self , rsthis: & QSettings) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings9childKeysEv()}; let mut ret = unsafe {C_ZNK9QSettings9childKeysEv(rsthis.qclsinst)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QSettings::endArray(); impl /*struct*/ QSettings { pub fn endArray<RetType, T: QSettings_endArray<RetType>>(& self, overload_args: T) -> RetType { return overload_args.endArray(self); // return 1; } } pub trait QSettings_endArray<RetType> { fn endArray(self , rsthis: & QSettings) -> RetType; } // proto: void QSettings::endArray(); impl<'a> /*trait*/ QSettings_endArray<()> for () { fn endArray(self , rsthis: & QSettings) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings8endArrayEv()}; unsafe {C_ZN9QSettings8endArrayEv(rsthis.qclsinst)}; // return 1; } } // proto: static void QSettings::setSystemIniPath(const QString & dir); impl /*struct*/ QSettings { pub fn setSystemIniPath_s<RetType, T: QSettings_setSystemIniPath_s<RetType>>( overload_args: T) -> RetType { return overload_args.setSystemIniPath_s(); // return 1; } } pub trait QSettings_setSystemIniPath_s<RetType> { fn setSystemIniPath_s(self ) -> RetType; } // proto: static void QSettings::setSystemIniPath(const QString & dir); impl<'a> /*trait*/ QSettings_setSystemIniPath_s<()> for (&'a QString) { fn setSystemIniPath_s(self ) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QSettings16setSystemIniPathERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QSettings16setSystemIniPathERK7QString(arg0)}; // return 1; } } // proto: QStringList QSettings::allKeys(); impl /*struct*/ QSettings { pub fn allKeys<RetType, T: QSettings_allKeys<RetType>>(& self, overload_args: T) -> RetType { return overload_args.allKeys(self); // return 1; } } pub trait QSettings_allKeys<RetType> { fn allKeys(self , rsthis: & QSettings) -> RetType; } // proto: QStringList QSettings::allKeys(); impl<'a> /*trait*/ QSettings_allKeys<QStringList> for () { fn allKeys(self , rsthis: & QSettings) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings7allKeysEv()}; let mut ret = unsafe {C_ZNK9QSettings7allKeysEv(rsthis.qclsinst)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QSettings::group(); impl /*struct*/ QSettings { pub fn group<RetType, T: QSettings_group<RetType>>(& self, overload_args: T) -> RetType { return overload_args.group(self); // return 1; } } pub trait QSettings_group<RetType> { fn group(self , rsthis: & QSettings) -> RetType; } // proto: QString QSettings::group(); impl<'a> /*trait*/ QSettings_group<QString> for () { fn group(self , rsthis: & QSettings) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QSettings5groupEv()}; let mut ret = unsafe {C_ZNK9QSettings5groupEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // <= body block end
// 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 std::{cell::RefCell, rc::Rc}; use crate::{context::ContextInner, spinel_sys::*}; #[derive(Debug)] pub(crate) struct RasterInner { context: Rc<RefCell<ContextInner>>, pub(crate) spn_raster: SpnRaster, } impl RasterInner { fn new(context: &Rc<RefCell<ContextInner>>, spn_raster: SpnRaster) -> Self { Self { context: Rc::clone(context), spn_raster } } } impl Drop for RasterInner { fn drop(&mut self) { self.context.borrow_mut().discard_raster(self.spn_raster); } } /// Spinel raster created by a `RasterBuilder`. [spn_raster_t] /// /// [spn_raster_t]: https://fuchsia.googlesource.com/fuchsia/+/refs/heads/master/src/graphics/lib/compute/spinel/spinel.h#139 #[derive(Clone, Debug)] pub struct Raster { pub(crate) inner: Rc<RasterInner>, } impl Raster { pub(crate) fn new(context: &Rc<RefCell<ContextInner>>, spn_raster: SpnRaster) -> Self { Self { inner: Rc::new(RasterInner::new(context, spn_raster)) } } } impl Eq for Raster {} impl PartialEq for Raster { fn eq(&self, other: &Self) -> bool { Rc::ptr_eq(&self.inner, &other.inner) } }
macro_rules! shared_impls { (pointer mod=$mod_:ident new_type=$tconst:ident[$($lt:lifetime),*][$($ty:ident),*] $(extra[$($ex_ty:ident),* $(,)* ])? $(where [ $($where_:tt)* ])? , original_type=$original:ident, ) => { mod $mod_{ use super::*; use std::{ fmt::{self,Display, Pointer as PointerFmt}, ops::Deref, }; use serde::{Deserialize,Serialize,Deserializer,Serializer}; impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> Deref for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> { type Target=T; fn deref(&self)->&Self::Target{ unsafe{ &*self.data() } } } impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> Display for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where $($ty:Display,)* { fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ Display::fmt(&**self,f) } } impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> PointerFmt for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> { fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ let ptr: *const _ = &**self; PointerFmt::fmt(&ptr, f) } } impl<'de,$($lt,)* $($ty,)* $($($ex_ty,)*)?> Deserialize<'de> for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where T:Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { T::deserialize(deserializer) .map(Self::new) } } impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> Serialize for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where T:Serialize { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { (&**self).serialize(serializer) } } shared_impls!{ mod=$mod_ new_type=$tconst[$($lt),*][$($ty),*] $(extra[$($ex_ty),*])? $(where [ $($where_)* ])? , original_type=$original, } } }; ( mod=$mod_:ident new_type=$tconst:ident[$($lt:lifetime),*][$($ty:ident),*] $(extra[$($ex_ty:ident),* $(,)*])? $(constrained[$($c_ty:ty),* $(,)*])? $(where [ $($where_:tt)* ])? , original_type=$original:ident, $(deref_approach=$deref:tt,)? ) => { mod $mod_{ use std::{ cmp::{PartialEq,Eq,Ord,PartialOrd,Ordering}, fmt::{self,Debug}, hash::{Hash,Hasher}, }; use super::*; impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> Debug for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where $($ty:Debug,)* $($($c_ty:Debug,)*)? $($($where_)*)? { fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ Debug::fmt(si_deref!($($deref)? self),f) } } impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> Eq for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where $($ty:Eq,)* $($($c_ty:Eq,)*)? $($($where_)*)? {} impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> PartialEq for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where $($ty:PartialEq,)* $($($c_ty:PartialEq,)*)? $($($where_)*)? { fn eq(&self, other: &Self) -> bool{ ::std::ptr::eq(si_deref!($($deref)? self),si_deref!($($deref)? other))|| si_deref!($($deref)? self) == si_deref!($($deref)? other) } } impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> Ord for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where $($ty:Ord,)* $($($c_ty:Ord,)*)? $($($where_)*)? { fn cmp(&self, other: &Self) -> Ordering{ if ::std::ptr::eq(si_deref!($($deref)? self),si_deref!($($deref)? other)) { return Ordering::Equal; } si_deref!($($deref)? self).cmp(si_deref!($($deref)? other)) } } impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> PartialOrd for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where $($ty:PartialOrd,)* $($($c_ty:PartialOrd,)*)? $($($where_)*)? { fn partial_cmp(&self, other: &Self) -> Option<Ordering>{ if ::std::ptr::eq(si_deref!($($deref)? self),si_deref!($($deref)? other)) { return Some(Ordering::Equal); } si_deref!($($deref)? self).partial_cmp(si_deref!($($deref)? other)) } } impl<$($lt,)* $($ty,)* $($($ex_ty,)*)?> Hash for $tconst<$($lt,)* $($ty,)* $($($ex_ty,)*)?> where $($ty:Hash,)* $($($c_ty:Hash,)*)? $($($where_)*)? { fn hash<H>(&self, state: &mut H) where H: Hasher { si_deref!($($deref)? self).hash(state) } } } }; } macro_rules! si_deref { ($self:ident) => { &**$self }; (double_deref $self:ident) => { &**$self }; ((method = $method:ident) $self:ident) => { $self.$method() }; }
mod persistance; use std::env; use persistance::persistance; fn main() { let arg: u128 = env::args().nth(1).and_then(|x| x.parse().ok()).expect("Missing positive integer as argument."); println!("Persistance for {} is {}", arg, persistance(arg)) }
//! Linux `statx`. use crate::fd::AsFd; use crate::fs::AtFlags; use crate::{backend, io, path}; pub use backend::fs::types::{Statx, StatxFlags, StatxTimestamp}; #[cfg(feature = "linux_4_11")] use backend::fs::syscalls::statx as _statx; #[cfg(not(feature = "linux_4_11"))] use compat::statx as _statx; /// `statx(dirfd, path, flags, mask, statxbuf)` /// /// This function returns [`io::Errno::NOSYS`] if `statx` is not available on /// the platform, such as Linux before 4.11. This also includes older Docker /// versions where the actual syscall fails with different error codes; rustix /// handles this and translates them into `NOSYS`. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/statx.2.html #[inline] pub fn statx<P: path::Arg, Fd: AsFd>( dirfd: Fd, path: P, flags: AtFlags, mask: StatxFlags, ) -> io::Result<Statx> { path.into_with_c_str(|path| _statx(dirfd.as_fd(), path, flags, mask)) } #[cfg(not(feature = "linux_4_11"))] mod compat { use crate::fd::BorrowedFd; use crate::ffi::CStr; use crate::fs::AtFlags; use crate::{backend, io}; use core::sync::atomic::{AtomicU8, Ordering}; use backend::fs::types::{Statx, StatxFlags}; // Linux kernel prior to 4.11 old versions of Docker don't support `statx`. // We store the availability in a global to avoid unnecessary syscalls. // // 0: Unknown // 1: Not available // 2: Available static STATX_STATE: AtomicU8 = AtomicU8::new(0); #[inline] pub fn statx( dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags, mask: StatxFlags, ) -> io::Result<Statx> { match STATX_STATE.load(Ordering::Relaxed) { 0 => statx_init(dirfd, path, flags, mask), 1 => Err(io::Errno::NOSYS), _ => backend::fs::syscalls::statx(dirfd, path, flags, mask), } } /// The first `statx` call. We don't know if `statx` is available yet. fn statx_init( dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags, mask: StatxFlags, ) -> io::Result<Statx> { match backend::fs::syscalls::statx(dirfd, path, flags, mask) { Err(io::Errno::NOSYS) => statx_error_nosys(), Err(io::Errno::PERM) => statx_error_perm(), result => { STATX_STATE.store(2, Ordering::Relaxed); result } } } /// The first `statx` call failed with `NOSYS` (or something we're treating /// like `NOSYS`). #[cold] fn statx_error_nosys() -> io::Result<Statx> { STATX_STATE.store(1, Ordering::Relaxed); Err(io::Errno::NOSYS) } /// The first `statx` call failed with `PERM`. #[cold] fn statx_error_perm() -> io::Result<Statx> { // Some old versions of Docker have `statx` fail with `PERM` when it // isn't recognized. Check whether `statx` really is available, and if // so, fail with `PERM`, and if not, treat it like `NOSYS`. if backend::fs::syscalls::is_statx_available() { STATX_STATE.store(2, Ordering::Relaxed); Err(io::Errno::PERM) } else { statx_error_nosys() } } }
use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::render::BlendMode; use sdl2::pixels::Color; use setup; pub fn alpha_blend() { let basic_window_setup = setup::init("Alpha Blending", 640, 480); let mut events = basic_window_setup.sdl_context.event_pump().unwrap(); let mut renderer = basic_window_setup.window .renderer() .present_vsync() .accelerated() .build() .unwrap(); // unmodulated alpha - shows up only when the foreground texture goes transparent let bg_fade_in_texture = setup::load_image("resources/fadein.png", &renderer); // not a sprite (with a background color key), but will be alpha modulated let mut fg_fade_out_texture = setup::load_image("resources/fadeout.png", &renderer); fg_fade_out_texture.set_blend_mode(BlendMode::Blend); let mut alpha_modulation: u8 = 255; let mod_increment: u8 = 32; 'event: loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, // keycode: Option<KeyCode> // https://doc.rust-lang.org/book/patterns.html Event::KeyDown{keycode: Some(Keycode::Q), ..} => break 'event, Event::KeyDown{keycode: Some(key), ..} => { match key { Keycode::W => { if (alpha_modulation as u32) + (mod_increment as u32) > 255 { alpha_modulation = 255; } else { alpha_modulation += mod_increment; } } Keycode::S => { if (alpha_modulation as i32) - (mod_increment as i32) < 0 { alpha_modulation = 0; } else { alpha_modulation -= mod_increment; } } _ => continue, } } _ => continue, } } fg_fade_out_texture.set_alpha_mod(alpha_modulation); renderer.set_draw_color(Color::RGB(0xff, 0xff, 0xff)); renderer.clear(); renderer.copy(&bg_fade_in_texture, None, None).expect("Texture copy failed"); renderer.copy(&fg_fade_out_texture, None, None).expect("Texture copy failed"); renderer.present(); } }
//! Provides functionality related to computing the Levenshtein edit distance //! metric. /// Compute the Levenshtein distance between `str1` and `str2`. /// /// #Parameters /// /// * `str1` - first string /// * `str2` - second string pub fn distance(str1: &[char], str2: &[char]) -> usize { let mut cost = 0; if str1.len() == 0 { return str2.len(); } if str2.len() == 0 { return str1.len(); } cost = if str1.last() == str2.last() { 0 } else { 1 }; let options = vec![ distance(&str1[..str1.len() - 1], str2) + 1, distance(str1, &str2[..str2.len() - 1]) + 1, distance(&str1[..str1.len() - 1], &str2[..str2.len() - 1]) + cost, ]; *options.iter().min().unwrap() }
// ignore-compare-mode-nll // revisions: base nll // [nll]compile-flags: -Zborrowck=mir #![feature(generic_associated_types)] pub trait X { type Y<'a> where Self: 'a; fn m(&self) -> Self::Y<'_>; } impl X for () { type Y<'a> = &'a (); fn m(&self) -> Self::Y<'_> { self } } fn f(x: &impl for<'a> X<Y<'a> = &'a ()>) -> &'static () { x.m() //[base]~^ ERROR `x` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement [E0759] //[nll]~^^ ERROR lifetime may not live long enough } fn g<T: for<'a> X<Y<'a> = &'a ()>>(x: &T) -> &'static () { x.m() //[base]~^ ERROR `x` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement [E0759] //[nll]~^^ ERROR lifetime may not live long enough } fn h(x: &()) -> &'static () { x.m() //[base]~^ ERROR `x` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement [E0759] //[nll]~^^ ERROR lifetime may not live long enough } fn main() { f(&()); g(&()); h(&()); }
use std::io::Cursor; use std::sync::Mutex; use sourcerenderer_bsp::PakFile; use crate::asset::asset_manager::{ AssetContainer, AssetFile, }; pub struct PakFileContainer { pakfile: Mutex<PakFile>, } impl PakFileContainer { pub fn new(pakfile: PakFile) -> Self { Self { pakfile: Mutex::new(pakfile), } } } impl AssetContainer for PakFileContainer { fn contains(&self, path: &str) -> bool { let mut guard = self.pakfile.lock().unwrap(); guard.contains_entry(path) } fn load(&self, path: &str) -> Option<AssetFile> { let mut guard = self.pakfile.lock().unwrap(); let data = guard.read_entry(path)?; Some(AssetFile { path: path.to_string(), data: Cursor::new(data), }) } }
extern crate rust_decimal; extern crate wasm_bindgen; mod util; use rust_decimal::prelude::*; use wasm_bindgen::prelude::*; fn format_currency_str (amount_str: Box<str>, decimal: &usize) -> String { let formatted = Decimal::from_str(&*amount_str).unwrap(); format!("{:.1$}", formatted, decimal) } fn format_minimal_str (amount_str: Box<str>, decimal: &usize) -> String { let str = String::from(amount_str); // let formatted: String = str.chars().take(*decimal).collect(); str.to_string() } #[wasm_bindgen] pub fn from_minimal (amount: &str, decimal: usize) -> String { let formatted_amount = format_minimal_str(Box::from(amount), &decimal); let satoshis = 10_i64.pow(decimal.to_u32().unwrap()); (formatted_amount.parse::<f64>().unwrap() / satoshis as f64).to_string() } #[wasm_bindgen] pub fn to_minimal (amount: &str, decimal: usize) -> String { let formatted_amount = format_currency_str(Box::from(amount), &decimal); let satoshis = 10_i64.pow(decimal.to_u32().unwrap()); (formatted_amount.parse::<f64>().unwrap() * satoshis as f64).to_string() } #[cfg(test)] mod tests { use super::*; #[test] fn min_test() { assert_eq!(to_minimal("134.677452125", 18), "134677452125000000000"); } #[test] fn cur_test() { assert_eq!(from_minimal("134677452125000000000", 18), "134.677452125"); } }
use bintree::Tree; use std::fmt; pub fn hbal_trees<T: fmt::Display + Copy>(h: usize, v: T) -> Vec<Tree<T>> { if h == 0 { vec![Tree::end()] } else if h == 1 { vec![Tree::leaf(v)] } else { let subtree1 = hbal_trees(h - 1, v); let subtree2 = hbal_trees(h - 2, v); let mut res = vec![]; let trees1: Vec<Tree<T>> = subtree1 .iter() .flat_map(|s1| { subtree1 .iter() .map(move |s2| Tree::node(v, s1.clone(), s2.clone())) }) .collect(); res.extend_from_slice(&trees1); let trees2: Vec<Tree<T>> = subtree1 .iter() .flat_map(|s1| { subtree2.iter().flat_map(move |s2| { vec![ Tree::node(v, s1.clone(), s2.clone()), Tree::node(v, s2.clone(), s1.clone()), ] }) }) .collect(); res.extend_from_slice(&trees2); res } } #[cfg(test)] mod tests { use super::*; #[test] fn test_hbal_trees_0() { let trees = hbal_trees(0, '_'); assert_eq!(trees, vec![Tree::end()]); } #[test] fn test_hbal_trees_1() { let trees = hbal_trees(1, 'x'); assert_eq!(trees, vec![Tree::leaf('x')]); } #[test] fn test_hbal_trees_2() { let trees = hbal_trees(2, 'x'); assert_eq!( trees, vec![ Tree::node( 'x', Tree::node('x', Tree::end(), Tree::end()), Tree::node('x', Tree::end(), Tree::end()) ), Tree::node('x', Tree::node('x', Tree::end(), Tree::end()), Tree::end()), Tree::node('x', Tree::end(), Tree::node('x', Tree::end(), Tree::end())) ] ) } #[test] fn test_hbal_trees3() { let trees = hbal_trees(3, 'x'); assert_eq!(trees.len(), 15); } }
use std::fmt::Display; const TORQUE_START_THRESHOLD: u32 = 1000; #[derive(Debug)] pub enum Vehicle { Running, Stopped } fn move_vehicle<T, F>(rpm: T, torque_eq: F) -> Vehicle where F: Fn(T) -> u32, T: Display + Copy { let curr_torque = torque_eq(rpm); println!("Engine torque is: {}", rpm); let axles_rpm: f64 = curr_torque as f64 / 150.0; println!("Driven axles rpm: {}", axles_rpm); if curr_torque > TORQUE_START_THRESHOLD { Vehicle::Running } else { Vehicle::Stopped } } fn dump_state(v: &Vehicle) { println!("{:?}", v); println!("-------------------- dump_vehicle_state_end --------------------"); } fn make_movement_energy_operator_cps(clbk: Box<Fn(&Vehicle) -> ()>) -> Box<Fn(u32)> { Box::new(move |energy: u32| { let torque_eq = |rpm: u32| -> u32 { rpm * 1000 }; let v = move_vehicle(energy, torque_eq); clbk(&v); }) } fn move_over(energies: Vec<u32>, clbk: Box<Fn(&Vehicle) -> ()>) -> Box<Iterator<Item=Vehicle>> { Box::new( energies.into_iter().map(move |energy: u32| { let torque_eq = |rpm: u32| -> u32 { rpm * 1000 }; let v = move_vehicle(energy, torque_eq); clbk(&v); v }) ) } pub fn run_fn() { println!("-------------------- {} --------------------", file!()); let m_op = make_movement_energy_operator_cps(Box::new(dump_state)); m_op(12); m_op(12); m_op(0); let energies: Vec<u32> = vec![12, 12, 0]; let energy_states: Vec<Vehicle> = move_over(energies, Box::new(dump_state)).collect(); println!("{:?}", energy_states); let energies: Vec<u32> = vec![12, 12, 0]; let energy_ops = energies.into_iter().map(move |energy: u32| { let torque_eq = |rpm: u32| -> u32 { rpm * 1000 }; let v = move_vehicle(energy, torque_eq); dump_state(&v); }); println!("{:?}", energy_ops); for x in energy_ops { println!("{:?}", x); } let boxed_fn = Box::new(|i| i * 2); for n in (0..10).map(*boxed_fn) { println!("{}", n); } }
pub use VkFormatFeatureFlags::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkFormatFeatureFlags { VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x0000_0001, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x0000_0002, VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 0x0000_0004, VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT = 0x0000_0008, VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT = 0x0000_0010, VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT = 0x0000_0020, VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT = 0x0000_0040, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT = 0x0000_0080, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT = 0x0000_0100, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x0000_0200, VK_FORMAT_FEATURE_BLIT_SRC_BIT = 0x0000_0400, VK_FORMAT_FEATURE_BLIT_DST_BIT = 0x0000_0800, VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT = 0x0000_1000, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR = 0x0000_4000, VK_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR = 0x0000_8000, VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT = 0x0002_0000, VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT = 0x0004_0000, VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT = 0x0008_0000, } use crate::SetupVkFlags; #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq, Hash)] pub struct VkFormatFeatureFlagBits(u32); SetupVkFlags!(VkFormatFeatureFlags, VkFormatFeatureFlagBits);
#![feature(vec_remove_item)] use crate::objects::player::*; use crate::objects::exec::*; use crate::objects::node::*; use crate::objects::game_data::*; use crate::objects::action::*; use crate::objects::config::*; pub mod objects; pub mod game; mod generators { extern crate rand; extern crate heck; use rand::prelude::*; pub fn generate_name() -> String { use heck::CamelCase; let mut rng = thread_rng(); let mut name = String::from(""); for _ in 0..rng.gen_range(1,4) { name.push_str(add_syllable()); } if name.len() < 2 { name.push_str(add_syllable()); } name.to_camel_case() } fn add_syllable() -> &'static str { let mut rng = thread_rng(); let syls = vec!["al", "ham", "bra", "a", "chil", "les", "o", "din", "heim", "dal"]; let syl = rng.gen_range(0, syls.len()-1); syls[syl] } #[cfg(test)] mod tests { use super::*; #[test] fn namegeneration() { use crate::objects::player; let obj = player::Player::new(String::from("1"), generate_name(), 0); assert!(obj.name.len() > 1); } } }
use adder::*; use adder::common; #[test] fn it_add_works() { assert_eq!(4, add_two(2)) } #[test] fn it_add_works2() { // 函数执行 common::common_test(); println!("你好, 集合测试中..."); assert_eq!(4, add_two(2)) }
/* ZVM Disassembler ================ Copyright (c) 2020 Dannii Willis MIT licenced https://github.com/curiousdannii/ifvms.js */ use bytes::Buf; use super::*; use super::opcodes::*; use super::Operand::*; // Disassemble one Z-Code instruction pub fn disassemble_instruction(state: &mut ZVMState) -> Instruction { let image = &mut state.image; let opcode_definitions = &state.opcode_definitions; // Begin with an enum that will only be used within this function enum OperandEncoding {LargeConstant, SmallConstant, Variable} use OperandEncoding::*; // Helper function to decode operand codes into the enum fn get_operand_encodings(mut operand_codes: u8, operand_encodings: &mut Vec<OperandEncoding>) { let mut count = 0; while count < 4 { let code = operand_codes & 0xC0; if code == 0xC0 { break; } operand_encodings.push(match code { 0x00 => LargeConstant, 0x40 => SmallConstant, 0x80 => Variable, _ => unreachable!(), }); operand_codes <<= 2; count += 1; } } // Start decoding the instruction let addr = image.position() as u32; // Decode the operand byte let opcode_byte = image.get_u8() as u16; let opcode: u16; let mut operand_encodings = Vec::new(); // Get the opcode and operand_types match opcode_byte as u8 { // Long 2OP 0 ..= 127 => { opcode = opcode_byte & 0x1F; operand_encodings.push(if opcode_byte & 0x40 == 0 {SmallConstant} else {Variable}); operand_encodings.push(if opcode_byte & 0x20 == 0 {SmallConstant} else {Variable}); }, // Short 1OP 128 ..= 175 => { opcode = opcode_byte & 0x8F; get_operand_encodings((opcode_byte << 2) as u8 | 0x3F, &mut operand_encodings); }, // 0OP 176 ..= 189 | 191 => { opcode = opcode_byte; }, // EXT/VAR 190 | 192 ..= 255 => { opcode = match opcode_byte { 190 => 1000 + image.get_u8() as u16, 192 ..= 223 => opcode_byte & 0x1F, _ => opcode_byte, }; get_operand_encodings(image.get_u8(), &mut operand_encodings); if opcode == 236 || opcode == 250 { get_operand_encodings(image.get_u8(), &mut operand_encodings); } }, } // Opcode definition let opcode_definition = opcode_definitions.get(&opcode).unwrap_or(&OpcodeDefinition { stores: false, branches: false, ends_block: false, pauses_vm: false, operands: None, }); // Read the operands let mut operands = Vec::new(); if operand_encodings.len() > 0 { let default_operand_types = Vec::new(); let operand_types = opcode_definition.operands.as_ref().unwrap_or(&default_operand_types); for (operand_num, operand_encoding) in operand_encodings.iter().enumerate() { let operand_type = operand_types.get(operand_num).unwrap_or(&Unsigned); operands.push(match operand_type { Unsigned => match operand_encoding { LargeConstant => Constant(image.get_u16()), SmallConstant=> Constant(image.get_u8() as u16), Variable => { let var = image.get_u8(); match var { 0 => StackPointer, 1 ..= 15 => LocalVariable(var - 1), 16 ..= 255 => GlobalVariable(((var - 16) as u16 * 2) + state.globals_addr), } }, }, Signed => match operand_encoding { LargeConstant => SignedConstant(image.get_i16()), SmallConstant => SignedConstant(image.get_u8() as u16 as i16), Variable => { let var = image.get_u8(); match var { 0 => SignedStackPointer, 1 ..= 15 => SignedLocalVariable(var - 1), 16 ..= 255 => SignedGlobalVariable(((var - 16) as u16 * 2) + state.globals_addr), } }, } }); } } // Result variable let stores = opcode_definition.stores; let result = if stores { Some(image.get_u8()) // Call_*s, restore_undo } else if let 25 | 136 | 224 | 236 | 1010 = opcode { Some(image.get_u8()) } else { None }; // Branch offset let branch = if opcode_definition.branches { let first_branch_byte = image.get_u8(); let iftrue = first_branch_byte & 0x80 != 0; let twobytes = first_branch_byte & 0x40 == 0; let offset: i16 = if twobytes { (((((first_branch_byte & 0x3F) as u16) << 8) | image.get_u8() as u16) << 2) as i16 >> 2 } else { (first_branch_byte & 0x3F) as i16 }; Some(BranchTarget { iftrue, offset, }) } else { None }; let branches = opcode_definition.branches && !opcode_definition.pauses_vm; // Inline text data let text = if opcode == 178 || opcode == 179 { let addr = image.position() as u32; loop { if image.get_u16() & 0x8000 != 0 { break; } } Some(addr) } else { None }; // Next instruction, and time to stop? let next = image.position() as u32; let ends_block = opcode_definition.ends_block; let pauses_vm = opcode_definition.pauses_vm; Instruction { addr, opcode, operands, result, stores, branch, branches, text, next, ends_block, pauses_vm, } }
//! Compact binary representations of nucleic acid kmers pub type BitKmerSeq = u64; pub type BitKmer = (BitKmerSeq, u8); const NUC2BIT_LOOKUP: [Option<u8>; 256] = { let mut lookup = [None; 256]; lookup[b'A' as usize] = Some(0); lookup[b'C' as usize] = Some(1); lookup[b'G' as usize] = Some(2); lookup[b'T' as usize] = Some(3); lookup[b'a' as usize] = Some(0); lookup[b'c' as usize] = Some(1); lookup[b'g' as usize] = Some(2); lookup[b't' as usize] = Some(3); lookup }; fn nuc2bti_lookup_nocheck(nuc: u8) -> Option<u8> { unsafe { *NUC2BIT_LOOKUP.get_unchecked(nuc as usize) } } /// Takes a BitKmer and adds a new base on the end, optionally loping off the /// first base if the resulting kmer is too long. fn extend_kmer(kmer: &mut BitKmer, new_char: u8) -> bool { if let Some(new_char_int) = nuc2bti_lookup_nocheck(new_char) { let new_kmer = (kmer.0 << 2) + new_char_int as BitKmerSeq; // mask out any overflowed bits kmer.0 = new_kmer & (BitKmerSeq::pow(2, u32::from(2 * kmer.1)) - 1) as BitKmerSeq; true } else { false } } /// Used for the BitNuclKmer iterator to handle skipping invalid bases. fn update_position( start_pos: &mut usize, kmer: &mut BitKmer, buffer: &[u8], initial: bool, ) -> bool { // check if we have enough "physical" space for one more kmer if *start_pos + kmer.1 as usize > buffer.len() { return false; } let (mut kmer_len, stop_len) = if initial { (0, (kmer.1 - 1) as usize) } else { ((kmer.1 - 1) as usize, kmer.1 as usize) }; let cur_kmer = kmer; while kmer_len < stop_len { if extend_kmer(cur_kmer, buffer[*start_pos + kmer_len]) { kmer_len += 1; } else { kmer_len = 0; *cur_kmer = (0u64, cur_kmer.1); *start_pos += kmer_len + 1; if *start_pos + cur_kmer.1 as usize > buffer.len() { return false; } } } true } pub struct BitNuclKmer<'a> { start_pos: usize, cur_kmer: BitKmer, buffer: &'a [u8], canonical: bool, } impl<'a> BitNuclKmer<'a> { pub fn new(slice: &'a [u8], k: u8, canonical: bool) -> BitNuclKmer<'a> { let mut kmer = (0u64, k); let mut start_pos = 0; update_position(&mut start_pos, &mut kmer, slice, true); BitNuclKmer { start_pos, cur_kmer: kmer, buffer: slice, canonical, } } } impl<'a> Iterator for BitNuclKmer<'a> { type Item = (usize, BitKmer, bool); fn next(&mut self) -> Option<(usize, BitKmer, bool)> { if !update_position(&mut self.start_pos, &mut self.cur_kmer, self.buffer, false) { return None; } self.start_pos += 1; if self.canonical { let (kmer, was_rc) = canonical(self.cur_kmer); Some((self.start_pos - 1, kmer, was_rc)) } else { Some((self.start_pos - 1, self.cur_kmer, false)) } } } /// Reverse complement a BitKmer (reverses the sequence and swaps A<>T and G<>C) pub fn reverse_complement(kmer: BitKmer) -> BitKmer { // FIXME: this is not going to work with BitKmers of u128 or u32 // inspired from https://www.biostars.org/p/113640/ let mut new_kmer = kmer.0; // reverse it new_kmer = (new_kmer >> 2 & 0x3333_3333_3333_3333) | (new_kmer & 0x3333_3333_3333_3333) << 2; new_kmer = (new_kmer >> 4 & 0x0F0F_0F0F_0F0F_0F0F) | (new_kmer & 0x0F0F_0F0F_0F0F_0F0F) << 4; new_kmer = (new_kmer >> 8 & 0x00FF_00FF_00FF_00FF) | (new_kmer & 0x00FF_00FF_00FF_00FF) << 8; new_kmer = (new_kmer >> 16 & 0x0000_FFFF_0000_FFFF) | (new_kmer & 0x0000_FFFF_0000_FFFF) << 16; new_kmer = (new_kmer >> 32 & 0x0000_0000_FFFF_FFFF) | (new_kmer & 0x0000_0000_FFFF_FFFF) << 32; // complement it new_kmer ^= 0xFFFF_FFFF_FFFF_FFFF; // shift it to the right size new_kmer >>= 2 * (32 - kmer.1); (new_kmer, kmer.1) } /// Return the lexigraphically lowest of the BitKmer and its reverse complement and /// whether the returned kmer is the reverse_complement (true) or the original (false) pub fn canonical(kmer: BitKmer) -> (BitKmer, bool) { let rc = reverse_complement(kmer); if kmer.0 > rc.0 { (rc, true) } else { (kmer, false) } } /// Find the lexicographically lowest substring of a given length in the BitKmer pub fn minimizer(kmer: BitKmer, minmer_size: u8) -> BitKmer { let mut new_kmer = kmer.0; let mut lowest = !0; let bitmask = (BitKmerSeq::pow(2, u32::from(2 * minmer_size)) - 1) as BitKmerSeq; for _ in 0..=(kmer.1 - minmer_size) { let cur = bitmask & new_kmer; if cur < lowest { lowest = cur; } let cur_rev = reverse_complement((bitmask & new_kmer, kmer.1)); if cur_rev.0 < lowest { lowest = cur_rev.0; } new_kmer >>= 2; } (lowest, kmer.1) } pub fn bitmer_to_bytes(kmer: BitKmer) -> Vec<u8> { let mut new_kmer = kmer.0; let mut new_kmer_str = Vec::new(); // we're reading the bases off from the "high" end of the integer so we need to do some // math to figure out where they start (this helps us just pop the bases on the end // of the working buffer as we read them off "left to right") let offset = (kmer.1 - 1) * 2; let bitmask = BitKmerSeq::pow(2, u32::from(2 * kmer.1 - 1)) + BitKmerSeq::pow(2, u32::from(2 * kmer.1 - 2)); for _ in 0..kmer.1 { let new_char = (new_kmer & bitmask) >> offset; new_kmer <<= 2; new_kmer_str.push(match new_char { 0 => b'A', 1 => b'C', 2 => b'G', 3 => b'T', _ => panic!("Mathematical impossibility"), }); } new_kmer_str } #[cfg(test)] mod tests { use super::*; #[test] fn can_kmerize() { // test general function let mut i = 0; for (_, k, _) in BitNuclKmer::new(b"AGCT", 1, false) { match i { 0 => assert_eq!(k.0, 0b00 as BitKmerSeq), 1 => assert_eq!(k.0, 0b10 as BitKmerSeq), 2 => assert_eq!(k.0, 0b01 as BitKmerSeq), 3 => assert_eq!(k.0, 0b11 as BitKmerSeq), _ => unreachable!("Too many kmers"), } i += 1; } // test that we skip over N's i = 0; for (_, k, _) in BitNuclKmer::new(b"ACNGT", 2, false) { match i { 0 => assert_eq!(k.0, 0b0001 as BitKmerSeq), 1 => assert_eq!(k.0, 0b1011 as BitKmerSeq), _ => unreachable!("Too many kmers"), } i += 1; } // test that we skip over N's and handle short kmers i = 0; for (_, k, _) in BitNuclKmer::new(b"ACNG", 2, false) { match i { 0 => assert_eq!(k.0, 0x0001 as BitKmerSeq), _ => unreachable!("Too many kmers"), } i += 1; } // test that the minimum length works i = 0; for (_, k, _) in BitNuclKmer::new(b"AC", 2, false) { match i { 0 => assert_eq!(k.0, 0x0001 as BitKmerSeq), _ => unreachable!("Too many kmers"), } i += 1; } } #[test] fn test_iterator() { let seq = b"ACGTA"; let mut kmer_iter = BitNuclKmer::new(seq, 3, false); assert_eq!(kmer_iter.next(), Some((0, (6, 3), false))); assert_eq!(kmer_iter.next(), Some((1, (27, 3), false))); assert_eq!(kmer_iter.next(), Some((2, (44, 3), false))); assert_eq!(kmer_iter.next(), None); let seq = b"TA"; let mut kmer_iter = BitNuclKmer::new(seq, 3, false); assert_eq!(kmer_iter.next(), None); } #[test] fn test_reverse_complement() { assert_eq!(reverse_complement((0b00_0000, 3)).0, 0b11_1111); assert_eq!(reverse_complement((0b11_1111, 3)).0, 0b00_0000); assert_eq!(reverse_complement((0b0000_0000, 4)).0, 0b1111_1111); assert_eq!(reverse_complement((0b0001_1011, 4)).0, 0b0001_1011); } #[test] fn test_minimizer() { assert_eq!(minimizer((0b00_1011, 3), 2).0, 0b0010); assert_eq!(minimizer((0b00_1011, 3), 1).0, 0b00); assert_eq!(minimizer((0b1100_0011, 4), 2).0, 0b0000); assert_eq!(minimizer((0b11_0001, 3), 2).0, 0b0001); } #[test] fn test_bytes_to_bitkmer() { let mut ikmer: BitKmer = bytes_to_bitmer(b"C"); assert_eq!(ikmer.0, 1 as BitKmerSeq); ikmer = bytes_to_bitmer(b"TTA"); assert_eq!(ikmer.0, 60 as BitKmerSeq); ikmer = bytes_to_bitmer(b"AAA"); assert_eq!(ikmer.0, 0 as BitKmerSeq); } #[test] fn test_bitmer_to_bytes() { assert_eq!(bitmer_to_bytes((1 as BitKmerSeq, 1)), b"C".to_vec()); assert_eq!(bitmer_to_bytes((60 as BitKmerSeq, 3)), b"TTA".to_vec()); assert_eq!(bitmer_to_bytes((0 as BitKmerSeq, 3)), b"AAA".to_vec()); } pub fn bytes_to_bitmer(kmer: &[u8]) -> BitKmer { let k = kmer.len() as u8; let mut bit_kmer = (0u64, k); for i in 0..k { extend_kmer(&mut bit_kmer, kmer[i as usize]); } bit_kmer } }
use assembler::Token; use instruction::Opcode; use nom::{alpha, digit}; use nom::types::CompleteStr; named!(pub opcode<CompleteStr, Token>, ws!( do_parse!( str: alpha >> ( Token::Op{code: Opcode::from(str)} ) ) ) ); mod tests { use super::*; #[test] fn test_opcode() { let result = opcode(CompleteStr("load")); assert_eq!(result.is_ok(), true); let (rest, token) = result.unwrap(); assert_eq!(token, Token::Op { code: Opcode::LOAD }); assert_eq!(rest, CompleteStr("")); let result = opcode(CompleteStr("aold")); let (_, token) = result.unwrap(); assert_eq!(token, Token::Op { code: Opcode::IGL }); } }
use std::mem; #[derive(Clone, Debug)] pub struct UnionFind { root: Vec<usize>, size: Vec<usize>, } impl UnionFind { pub fn new(size: usize) -> Self { Self { root: (0..size).collect(), size: vec![0; size], } } // 指定した要素の根を返す(経路圧縮もする). pub fn root(&mut self, x: usize) -> usize { if self.root[x] == x { x } else { let parent = self.root[x]; let root = self.root(parent); self.root[x] = root; root } } // 二つの要素が同じ木にあるかを返す. pub fn same(&mut self, x: usize, y: usize) -> bool { self.root(x) == self.root(y) } // 二つの要素が含まれる木を併合する. pub fn unite(&mut self, x: usize, y: usize) -> bool { let mut x_root = self.root(x); let mut y_root = self.root(y); if x_root == y_root { return false; } if self.size(x_root) < self.size(y_root) { mem::swap(&mut x_root, &mut y_root); } self.root[y_root] = x_root; self.size[x_root] += self.size[y_root]; true } // 指定した要素が属する木の大きさを返す. pub fn size(&self, x: usize) -> usize { self.size[x] } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Edge { from: usize, to: usize, cost: usize, } impl Edge { pub fn new(from: usize, to: usize, cost: usize) -> Self { Self { from, to, cost } } } impl Ord for Edge { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.cost.cmp(&other.cost) } } impl PartialOrd for Edge { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } /// Find minimum spanning tree by kruskal method. /// Time complexity is `O(|E| log|E|) pub fn kruskal(edges: Vec<Edge>, num_vertex: usize) -> Vec<Edge> { let mut edges = edges; edges.sort(); let mut spanning = Vec::new(); let mut uf = UnionFind::new(num_vertex); for e in edges { if !uf.same(e.from, e.to) { uf.unite(e.from, e.to); spanning.push(e); } } spanning } #[cfg(test)] mod tests { use super::*; #[test] fn minimum_spanning_tree() { let edges = vec![ Edge::new(0, 1, 2), Edge::new(0, 2, 8), Edge::new(0, 3, 4), Edge::new(0, 4, 6), Edge::new(1, 2, 7), Edge::new(1, 3, 3), Edge::new(1, 4, 6), Edge::new(2, 3, 9), Edge::new(2, 4, 8), Edge::new(3, 4, 5), ]; assert_eq!( vec![ Edge::new(0, 1, 2), Edge::new(1, 3, 3), Edge::new(3, 4, 5), Edge::new(1, 2, 7), ], kruskal(edges, 5) ); } }
/* * __ __ _ _ _ * | \/ | ___ ___ __ _| | (_)_ __ | | __ * | |\/| |/ _ \/ __|/ _` | | | | '_ \| |/ / * | | | | __/\__ \ (_| | |___| | | | | < * |_| |_|\___||___/\__,_|_____|_|_| |_|_|\_\ * * Copyright (c) 2017-2018, The MesaLink Authors. * All rights reserved. * * This work is licensed under the terms of the BSD 3-Clause License. * For a copy, see the LICENSE file. * */ // Module imports use parking_lot::Mutex; use std::collections::HashMap; use std::sync::Arc; /// An implementor of `StoresClientSessions` that stores everything /// in memory. It enforces a limit on the number of entries /// to bound memory usage. pub struct ClientSessionMemoryCache { cache: Mutex<HashMap<Vec<u8>, Vec<u8>>>, max_entries: usize, } impl ClientSessionMemoryCache { /// Make a new ClientSessionMemoryCache. `size` is the /// maximum number of stored sessions. pub fn new(size: usize) -> Arc<ClientSessionMemoryCache> { debug_assert!(size > 0); Arc::new(ClientSessionMemoryCache { cache: Mutex::new(HashMap::new()), max_entries: size, }) } fn limit_size(&self) { let mut cache = self.cache.lock(); while cache.len() > self.max_entries { let k = cache.keys().next().unwrap().clone(); let _ = cache.remove(&k); } } } impl rustls::StoresClientSessions for ClientSessionMemoryCache { fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool { let _ = self.cache.lock().insert(key, value); self.limit_size(); true } fn get(&self, key: &[u8]) -> Option<Vec<u8>> { self.cache.lock().get(key).cloned() } } pub struct ServerSessionMemoryCache { cache: Mutex<HashMap<Vec<u8>, Vec<u8>>>, max_entries: usize, } impl ServerSessionMemoryCache { /// Make a new ServerSessionMemoryCache. `size` is the maximum /// number of stored sessions. pub fn new(size: usize) -> Arc<ServerSessionMemoryCache> { debug_assert!(size > 0); Arc::new(ServerSessionMemoryCache { cache: Mutex::new(HashMap::new()), max_entries: size, }) } fn limit_size(&self) { let mut cache = self.cache.lock(); while cache.len() > self.max_entries { let k = cache.keys().next().unwrap().clone(); let _ = cache.remove(&k); } } } impl rustls::StoresServerSessions for ServerSessionMemoryCache { fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool { let _ = self.cache.lock().insert(key, value); self.limit_size(); true } fn get(&self, key: &[u8]) -> Option<Vec<u8>> { self.cache.lock().get(key).cloned() } fn take(&self, key: &[u8]) -> Option<Vec<u8>> { self.cache.lock().remove(key) } }
// Copyright 2018 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. #![deny(warnings)] #![feature(async_await, await_macro, futures_api)] use std::borrow::Cow; use std::collections::HashMap; use std::fs; use std::os::unix::io::AsRawFd; use std::path; use std::sync::Arc; use failure::{self, ResultExt}; use fidl::endpoints::{RequestStream, ServiceMarker}; use fidl_fuchsia_net_dns::DnsPolicyMarker; use fidl_fuchsia_net_policy::{ObserverMarker, ObserverRequestStream}; use fuchsia_app::server::ServicesServer; use fuchsia_async as fasync; use fuchsia_syslog::{fx_log_err, fx_log_info}; use futures::lock::Mutex; use futures::{self, StreamExt, TryFutureExt, TryStreamExt}; use serde_derive::Deserialize; mod device_id; mod dns_policy_service; mod interface; mod matchers; mod observer_service; #[derive(Debug, Deserialize)] pub struct DnsConfig { pub servers: Vec<std::net::IpAddr>, } #[derive(Debug, Deserialize)] struct Config { pub device_name: Option<String>, pub dns_config: DnsConfig, #[serde(deserialize_with = "matchers::InterfaceSpec::parse_as_tuples")] pub rules: Vec<matchers::InterfaceSpec>, } impl Config { pub fn load<P: AsRef<path::Path>>(path: P) -> Result<Self, failure::Error> { let path = path.as_ref(); let file = fs::File::open(path) .with_context(|_| format!("could not open the config file {}", path.display()))?; let config = serde_json::from_reader(file).with_context(|_| { format!("could not deserialize the config file {}", path.display()) })?; Ok(config) } } fn derive_device_name(interfaces: Vec<fidl_fuchsia_netstack::NetInterface>) -> Option<String> { interfaces .iter() .filter(|iface| { fidl_fuchsia_hardware_ethernet_ext::EthernetFeatures::from_bits_truncate(iface.features) .is_physical() }) .min_by(|a, b| a.id.cmp(&b.id)) .map(|iface| device_id::device_id(&iface.hwaddr)) } static DEVICE_NAME_KEY: &str = "DeviceName"; fn main() -> Result<(), failure::Error> { fuchsia_syslog::init_with_tags(&["netcfg"])?; fx_log_info!("Started"); let Config { device_name, dns_config: DnsConfig { servers }, rules: default_config_rules } = Config::load("/pkg/data/default.json")?; let mut persisted_interface_config = interface::FileBackedConfig::load(&"/data/net_interfaces.cfg.json")?; let mut executor = fuchsia_async::Executor::new().context("could not create executor")?; let stack = fuchsia_app::client::connect_to_service::<fidl_fuchsia_net_stack::StackMarker>() .context("could not connect to stack")?; let netstack = fuchsia_app::client::connect_to_service::<fidl_fuchsia_netstack::NetstackMarker>() .context("could not connect to netstack")?; let device_settings_manager = fuchsia_app::client::connect_to_service::< fidl_fuchsia_devicesettings::DeviceSettingsManagerMarker, >() .context("could not connect to device settings manager")?; let mut servers = servers .into_iter() .map(fidl_fuchsia_net_ext::IpAddress) .map(Into::into) .collect::<Vec<fidl_fuchsia_net::IpAddress>>(); let () = netstack.set_name_servers(&mut servers.iter_mut()).context("could not set name servers")?; let default_device_name = device_name.as_ref().map(Cow::Borrowed).map(Ok); let mut device_name_stream = futures::stream::iter(default_device_name).chain( netstack.take_event_stream().try_filter_map( |fidl_fuchsia_netstack::NetstackEvent::OnInterfacesChanged { interfaces }| { futures::future::ok(derive_device_name(interfaces).map(Cow::Owned)) }, ), ); let device_name = async { match await!(device_name_stream.try_next()) .context("netstack event stream ended before providing interfaces")? { Some(device_name) => { let success = await!(device_settings_manager.set_string(DEVICE_NAME_KEY, &device_name))?; Ok(success) } None => { Err(failure::err_msg("netstack event stream ended before providing interfaces")) } } }; const ETHDIR: &str = "/dev/class/ethernet"; let mut interface_ids = HashMap::new(); // TODO(chunyingw): Add the loopback interfaces through netcfg // Remove the following hardcoded nic id 1. interface_ids.insert("lo".to_owned(), 1); let interface_ids = Arc::new(Mutex::new(interface_ids)); let ethdir = fs::File::open(ETHDIR).with_context(|_| format!("could not open {}", ETHDIR))?; let mut watcher = fuchsia_vfs_watcher::Watcher::new(&ethdir) .with_context(|_| format!("could not watch {}", ETHDIR))?; let ethernet_device = async { while let Some(fuchsia_vfs_watcher::WatchMessage { event, filename }) = await!(watcher.try_next()).with_context(|_| format!("watching {}", ETHDIR))? { match event { fuchsia_vfs_watcher::WatchEvent::ADD_FILE | fuchsia_vfs_watcher::WatchEvent::EXISTING => { let filename = path::Path::new(ETHDIR).join(filename); let device = fs::File::open(&filename) .with_context(|_| format!("could not open {}", filename.display()))?; let topological_path = fdio::device_get_topo_path(&device).with_context(|_| { format!("fdio::device_get_topo_path({})", filename.display()) })?; let device = device.as_raw_fd(); let mut client = 0; // Safe because we're passing a valid fd. let () = fuchsia_zircon::Status::ok(unsafe { fdio::fdio_sys::fdio_get_service_handle(device, &mut client) }) .with_context(|_| { format!( "fuchsia_zircon::sys::fdio_get_service_handle({})", filename.display() ) })?; // Safe because we checked the return status above. let client = fuchsia_zircon::Channel::from(unsafe { fuchsia_zircon::Handle::from_raw(client) }); let device = fidl::endpoints::ClientEnd::< fidl_fuchsia_hardware_ethernet::DeviceMarker, >::new(client) .into_proxy()?; let device_info = await!(device.get_info())?; let device_info: fidl_fuchsia_hardware_ethernet_ext::EthernetInfo = device_info.into(); if device_info.features.is_physical() { let client = device .into_channel() .map_err(|fidl_fuchsia_hardware_ethernet::DeviceProxy { .. }| { failure::err_msg("failed to convert device proxy into channel") })? .into_zx_channel(); let name = persisted_interface_config.get_stable_name( topological_path.clone(), /* TODO(tamird): we can probably do * better with std::borrow::Cow. */ device_info.mac, device_info.features.contains( fidl_fuchsia_hardware_ethernet_ext::EthernetFeatures::WLAN, ), )?; let mut derived_interface_config = matchers::config_for_device( &device_info, name.to_string(), &topological_path, &default_config_rules, ); let nic_id = await!(netstack.add_ethernet_device( &topological_path, &mut derived_interface_config, fidl::endpoints::ClientEnd::< fidl_fuchsia_hardware_ethernet::DeviceMarker, >::new(client), )) .with_context(|_| { format!( "fidl_netstack::Netstack::add_ethernet_device({})", filename.display() ) })?; await!(match derived_interface_config.ip_address_config { fidl_fuchsia_netstack::IpAddressConfig::Dhcp(_) => { netstack.set_dhcp_client_status(nic_id as u32, true) } fidl_fuchsia_netstack::IpAddressConfig::StaticIp( fidl_fuchsia_net::Subnet { addr: mut address, prefix_len }, ) => netstack.set_interface_address( nic_id as u32, &mut address, prefix_len ), })?; let () = netstack.set_interface_status(nic_id as u32, true)?; // TODO(chunyingw): when netcfg switches to stack.add_ethernet_interface, // remove casting nic_id to u64. await!(interface_ids.lock()) .insert(derived_interface_config.name, nic_id as u64); } } fuchsia_vfs_watcher::WatchEvent::IDLE | fuchsia_vfs_watcher::WatchEvent::REMOVE_FILE => {} event => { let () = Err(failure::format_err!("unknown WatchEvent {:?}", event))?; } } } Ok(()) }; let interface_ids = interface_ids.clone(); let netstack_service = netstack.clone(); let fidl_service_fut = ServicesServer::new() .add_service((DnsPolicyMarker::NAME, move |channel| { dns_policy_service::spawn_net_dns_fidl_server(netstack_service.clone(), channel); })) .add_service((ObserverMarker::NAME, move |channel| { fasync::spawn( observer_service::serve_fidl_requests( stack.clone(), ObserverRequestStream::from_channel(channel), interface_ids.clone(), ) .unwrap_or_else(|e| fx_log_err!("failed to serve_fidl_requests:{}", e)), ); })) .start() .context("error starting netcfg services server")?; let (_success, (), ()) = executor.run_singlethreaded(device_name.try_join3(ethernet_device, fidl_service_fut))?; Ok(()) }
#[macro_use] extern crate log; use actix_web::{ error::{BlockingError, ResponseError}, Error as ActixError, HttpResponse, }; use derive_more::Display; use diesel::result::{DatabaseErrorKind, Error as DBError}; use r2d2::Error as PoolError; use serde::{Deserialize, Serialize}; #[derive(Debug, Display, PartialEq)] #[allow(dead_code)] pub enum Error { BadRequest(String), CannotDecodeJwtToken(String), CannotEncodeJwtToken(String), InternalServerError(String), Unauthorized, Forbidden, NotFound(String), PoolError(String), #[display(fmt = "")] ValidationError(Vec<String>), UnprocessableEntity(String), BlockingError(String), } // User-friendly error messages #[derive(Debug, Deserialize, Serialize)] pub struct ErrorResponse { pub errors: Vec<String>, } impl ResponseError for Error { fn error_response(&self) -> HttpResponse { match self { Error::ValidationError(ref validation_errors) => { HttpResponse::UnprocessableEntity().json(validation_errors.to_vec()) } Error::BadRequest(message) => { let error: ErrorResponse = message.into(); HttpResponse::BadRequest().json(error) } Error::NotFound(message) => { let error: ErrorResponse = message.into(); HttpResponse::NotFound().json(error) } Error::UnprocessableEntity(message) => { let error: ErrorResponse = message.into(); HttpResponse::UnprocessableEntity().json(error) } Error::Forbidden => { let error: ErrorResponse = "Forbidden".into(); HttpResponse::Forbidden().json(error) } _ => { error!("Internal server error: {:?}", self); let error: ErrorResponse = "Internal Server Error".into(); HttpResponse::InternalServerError().json(error) } } } } impl From<&str> for ErrorResponse { fn from(error: &str) -> Self { ErrorResponse { errors: vec![error.into()], } } } impl From<&String> for ErrorResponse { fn from(error: &String) -> Self { ErrorResponse { errors: vec![error.into()], } } } impl From<Vec<String>> for ErrorResponse { fn from(error: Vec<String>) -> Self { ErrorResponse { errors: error } } } // Convert DBErrors to our Error type impl From<DBError> for Error { fn from(error: DBError) -> Error { // Right now we just care about UniqueViolation from diesel // But this would be helpful to easily map errors as our app grows match error { DBError::DatabaseError(kind, info) => { if let DatabaseErrorKind::UniqueViolation = kind { let message = info.details().unwrap_or_else(|| info.message()).to_string(); return Error::BadRequest(message); } Error::InternalServerError("Unknown database error".into()) } DBError::NotFound => Error::NotFound("Record not found".into()), _ => Error::InternalServerError("Unknown database error".into()), } } } // Convert PoolError to our Error type impl From<PoolError> for Error { fn from(error: PoolError) -> Error { Error::PoolError(error.to_string()) } } impl From<BlockingError> for Error { fn from(error: BlockingError) -> Error { error!("Thread blocking error {:?}", error); Error::BlockingError("Thread blocking error".into()) } } impl From<ActixError> for Error { fn from(error: ActixError) -> Error { Error::InternalServerError(error.to_string()) } }
use fileutil; use std::ascii::AsciiExt; use std::time::SystemTime; use std::collections::HashSet; fn reacts(c1: char, c2: char) -> bool { return c1.to_ascii_lowercase() == c2.to_ascii_lowercase() && c1 != c2; } fn react(chars: &Vec<char>) -> Vec<char> { let mut newchars: Vec<char> = Vec::with_capacity(chars.len()); let mut prev: Option<char> = Option::None; for (idx, c) in chars.iter().enumerate() { match prev { Some(prev_char) => { if reacts(prev_char, *c) { prev = Option::None; } else { newchars.push(prev_char); prev = Option::Some(*c); } } None => { prev = Option::Some(*c); } } } match prev { Some(prev_char) => { newchars.push(prev_char); } None => {} } return newchars; } fn react_fixedpoint(orig: &str) -> usize { let orig_initial_len = orig.len(); let mut orig_chars: Vec<char> = orig.chars().collect(); loop { let filtered: Vec<char> = react(&orig_chars); if (&filtered).len() == (&orig_chars).len() { break; } orig_chars = filtered; } return orig_chars.len(); } fn part1(orig: &str) -> () { println!("part 1"); println!("fully reacted length: {}", react_fixedpoint(orig)); } fn part2(orig: &str) -> () { println!("part 2"); let mut unitset: HashSet<char> = HashSet::new(); for c in orig.chars() { unitset.insert(c.to_ascii_lowercase()); } for unit in unitset.iter() { let filtered: String = orig.chars() .filter(|c| c.to_ascii_lowercase() != *unit) .collect(); let fully_reacted_len = react_fixedpoint(&filtered); println!("filtering unit {}, fully reacted length: {}", unit, fully_reacted_len); } } pub fn run() -> () { match fileutil::read_file("./data/2018/05.txt") { Ok(orig) => { part1(&orig); part2(&orig); } Err(e) => println!("oh no!") } } pub fn timed() -> () { let init = SystemTime::now(); run(); let fin = SystemTime::now(); let ttc = fin.duration_since(init).unwrap(); println!("time to complete: {} secs and {} millis", ttc.as_secs(), ttc.subsec_nanos() / 1000000); }
use super::Compositor; use super::System; use openvr_sys::EVRApplicationType; use openvr_sys::EVRInitError; pub struct Api { pub system: System, pub compositor: Compositor, } impl Api { pub fn new() -> Self { Api::init(EVRApplicationType::EVRApplicationType_VRApplication_Scene); Api { system: System::new(), compositor: Compositor::new(), } } pub fn function_table<T>(version: &'static str) -> *mut T { use std::ffi::CString; let name = CString::new(version).unwrap(); let error = &mut EVRInitError::EVRInitError_VRInitError_None; unsafe { ::openvr_sys::VR_GetGenericInterface(name.as_ptr(), error) as *mut T } } pub fn init(application_type: EVRApplicationType) { let error = &mut EVRInitError::EVRInitError_VRInitError_None; unsafe { ::openvr_sys::VR_InitInternal(error, application_type); } } pub fn shutdown() { unsafe { ::openvr_sys::VR_ShutdownInternal(); } } pub fn is_hmd_present() -> bool { unsafe { ::openvr_sys::VR_IsHmdPresent() != 0 } } pub fn is_runtime_installed() -> bool { unsafe { ::openvr_sys::VR_IsRuntimeInstalled() != 0 } } }
// 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. //! Process key prefix. use crate::kvapi::KeyError; /// Convert a `prefix` to a left-close-right-open range (start, end) that includes exactly all possible string that starts with `prefix`. /// /// It only supports ASCII characters. pub fn prefix_to_range(prefix: &str) -> Result<(String, String), KeyError> { Ok((prefix.to_string(), ascii_next(prefix)?)) } // TODO: the algo is not likely correct. /// Return a ascii string that bigger than all the string starts with the input `s`. /// /// It only supports ASCII char. /// /// "a" -> "b" /// "1" -> "2" /// [96,97,127] -> [96,98,127] /// [127] -> [127, 127] /// [127, 127, 127, 127] -> [127, 127, 127, 127, 127] fn ascii_next(s: &str) -> Result<String, KeyError> { for c in s.chars() { if !c.is_ascii() { return Err(KeyError::AsciiError { non_ascii: s.to_string(), }); } } let mut l = s.len(); while l > 0 { l -= 1; if let Some(c) = s.chars().nth(l) { if c == 127 as char { continue; } return Ok(replace_nth_char(s, l, (c as u8 + 1) as char)); } } Ok(format!("{}{}", s, 127 as char)) } /// Replace idx-th char as new char /// /// If `idx` is out of len(s) range, then no replacement is performed. /// replace_nth_char("a13", 1, '2') -> 'a23' /// replace_nth_char("a13", 10, '2') -> 'a13' pub fn replace_nth_char(s: &str, idx: usize, new_char: char) -> String { s.chars() .enumerate() .map(|(i, c)| if i == idx { new_char } else { c }) .collect() } #[cfg(test)] mod tests { use crate::kvapi::prefix::ascii_next; use crate::kvapi::prefix::replace_nth_char; use crate::kvapi::prefix_to_range; #[test] fn test_ascii_next() -> anyhow::Result<()> { assert_eq!("b".to_string(), ascii_next("a")?); assert_eq!("2".to_string(), ascii_next("1")?); assert_eq!( "__fd_table_by_ie".to_string(), ascii_next("__fd_table_by_id")? ); { let str = 127 as char; let s = str.to_string(); let ret = ascii_next(&s)?; for byte in ret.as_bytes() { assert_eq!(*byte, 127_u8); } } { let s = format!("ab{}", 127 as char); let ret = ascii_next(&s)?; assert_eq!(ret, format!("ac{}", 127 as char)); } { let s = "我".to_string(); let ret = ascii_next(&s); match ret { Err(e) => { assert_eq!("Non-ascii char are not supported: '我'", e.to_string(),); } Ok(_) => panic!("MUST return error "), } } Ok(()) } #[test] fn test_prefix_to_range() -> anyhow::Result<()> { assert_eq!(("aa".to_string(), "ab".to_string()), prefix_to_range("aa")?); assert_eq!(("a1".to_string(), "a2".to_string()), prefix_to_range("a1")?); { let str = 127 as char; let s = str.to_string(); let (_, end) = prefix_to_range(&s)?; for byte in end.as_bytes() { assert_eq!(*byte, 127_u8); } } { let ret = prefix_to_range("我"); match ret { Err(e) => { assert_eq!("Non-ascii char are not supported: '我'", e.to_string(),); } Ok(_) => panic!("MUST return error "), } } Ok(()) } #[test] fn test_replace_nth_char() { assert_eq!("a23".to_string(), replace_nth_char("a13", 1, '2')); assert_eq!("a13".to_string(), replace_nth_char("a13", 10, '2')); } }
use bevy::{ app::AppExit, prelude::{ debug, App, AssetServer, Camera2dBundle, Color, Commands, Component, DefaultPlugins, Entity, EventReader, EventWriter, HorizontalAlign, ParallelSystemDescriptorCoercion, ParamSet, Query, Res, ResMut, SpriteBundle, Text as BevyText, Text2dBundle, TextAlignment, TextStyle, Transform, Vec2, VerticalAlign, Windows, }, render::texture::ImageSettings, time::Time, utils::HashMap, window::close_on_esc, }; use bevy_prototype_lyon::prelude::*; use std::{ ops::{Deref, DerefMut}, path::PathBuf, time::Duration, }; use crate::{ audio::AudioManager, mouse::{CursorMoved, MouseButtonInput, MouseMotion, MousePlugin, MouseWheel}, prelude::{ AudioManagerPlugin, CollisionEvent, KeyboardInput, KeyboardPlugin, KeyboardState, MouseState, PhysicsPlugin, }, sprite::Sprite, text::Text, }; // Public re-export pub use bevy::window::{WindowDescriptor, WindowMode, WindowResizeConstraints}; /// Engine is the primary way that you will interact with Rusty Engine. Each frame this struct /// is provided to the "logic" functions (or closures) that you provided to [`Game::add_logic`]. The /// fields in this struct are divided into two groups: /// /// 1. `SYNCED` fields. /// /// These fields are marked with `SYNCED`. These fields are shared between you and the engine. Each /// frame Rusty Engine will populate these fields, then provide them to the user's game logic /// function, and then examine any changes the user made and sync those changes back to the engine. /// /// 2. `INFO` fields /// /// INFO fields are provided as fresh, readable information to you each frame. Since information in /// these fields are overwritten every frame, any changes to them are ignored. Thus, you can feel /// free to, e.g. consume all the events out of the `collision_events` vector. #[derive(Default, Debug)] pub struct Engine { /// SYNCED - The state of all sprites this frame. To add a sprite, use the /// [`add_sprite`](Engine::add_sprite) method. Modify & remove sprites as you like. pub sprites: HashMap<String, Sprite>, /// SYNCED - The state of all texts this frame. For convenience adding a text, use the /// [`add_text`](Engine::add_text) method. Modify & remove text as you like. pub texts: HashMap<String, Text>, /// SYNCED - If set to `true`, the game exits. Note: the current frame will run to completion first. pub should_exit: bool, /// SYNCED - If set to `true`, then debug lines are shown depicting sprite colliders pub show_colliders: bool, // so we can tell if the value changed this frame last_show_colliders: bool, /// INFO - All the collision events that occurred this frame. For collisions to be generated /// between sprites, both sprites must have [`Sprite.collision`] set to `true` and both sprites /// must have colliders (use the collider example to create a collider for your own images). /// Collision events are generated when two sprites' colliders begin or end overlapping in 2D /// space. pub collision_events: Vec<CollisionEvent>, /// INFO - The current state of mouse location and buttons. Useful for input handling that only /// cares about the final state of the mouse each frame, and not the intermediate states. pub mouse_state: MouseState, /// INFO - All the mouse button events that occurred this frame. pub mouse_button_events: Vec<MouseButtonInput>, /// INFO - All the mouse location events that occurred this frame. The events are Bevy /// [`CursorMoved`] structs, but despite the name they represent the _location_ of the mouse /// during this frame. pub mouse_location_events: Vec<CursorMoved>, /// INFO - All the mouse motion events that occurred this frame. These represent the relative /// movements of the mouse, not the location of the mouse. pub mouse_motion_events: Vec<MouseMotion>, /// INFO - All the mouse wheel events that occurred this frame. pub mouse_wheel_events: Vec<MouseWheel>, /// INFO - The current state of all the keys on the keyboard. Use this to control movement in /// your games! A [`KeyboardState`] has helper methods you should use to query the state of /// specific [`KeyCode`](crate::prelude::KeyCode)s. pub keyboard_state: KeyboardState, /// INFO - All the keyboard input events. These are text-processor-like events. If you are /// looking for keyboard events to control movement in a game character, you should use /// [`Engine::keyboard_state`] instead. For example, one pressed event will fire when you /// start holding down a key, and then after a short delay additional pressed events will occur /// at the same rate that additional letters would show up in a word processor. When the key is /// finally released, a single released event is emitted. pub keyboard_events: Vec<KeyboardInput>, /// INFO - The delta time (time between frames) for the current frame as a [`Duration`], perfect /// for use with [`Timer`](crate::prelude::Timer)s pub delta: Duration, /// INFO - The delta time (time between frames) for the current frame as an [`f32`], perfect for /// use in math with other `f32`'s. A cheap and quick way to approximate smooth movement /// (velocity, accelleration, etc.) is to multiply it by `delta_f32`. pub delta_f32: f32, /// INFO - The amount of time the game has been running since startup as a [`Duration`] pub time_since_startup: Duration, /// INFO - The amount of time the game has been running as an [`f64`]. This needs to be an f64, /// since it gets to be large enough that an f32 would lose precision. For best results, do your /// math on the `f64` and get it to a smaller value _before_ casting it to an `f32`. pub time_since_startup_f64: f64, /// A struct with methods to play sound effects and music pub audio_manager: AudioManager, /// INFO - Window dimensions in logical pixels. On high DPI screens, there will often be four /// physical pixels per logical pixel. On low DPI screens, one logical pixel is one physical /// pixel. pub window_dimensions: Vec2, } impl Engine { #[must_use] /// Create and add a [`Sprite`] to the game. Use the `&mut Sprite` that is returned to adjust /// the translation, rotation, etc. Use a *unique* label for each sprite. Attempting to add two /// sprites with the same label will cause a crash. pub fn add_sprite<T: Into<String>, P: Into<PathBuf>>( &mut self, label: T, file_or_preset: P, ) -> &mut Sprite { let label = label.into(); self.sprites .insert(label.clone(), Sprite::new(label.clone(), file_or_preset)); // Unwrap: Can't crash because we just inserted the sprite self.sprites.get_mut(&label).unwrap() } #[must_use] /// Create and add a [`Text`] to the game. Use the `&mut Text` that is returned to adjust the /// translation, rotation, etc. Use a *unique* label for each text. Attempting to add two texts /// with the same label will cause a crash. pub fn add_text<T, S>(&mut self, label: T, text: S) -> &mut Text where T: Into<String>, S: Into<String>, { let label = label.into(); let text = text.into(); let curr_text = Text { label: label.clone(), value: text, ..Default::default() }; self.texts.insert(label.clone(), curr_text); // Unwrap: Can't crash because we just inserted the text self.texts.get_mut(&label).unwrap() } } /// startup system - grab window settings, initialize all the starting sprites #[doc(hidden)] pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut engine: ResMut<Engine>) { add_sprites(&mut commands, &asset_server, &mut engine); add_texts(&mut commands, &asset_server, &mut engine); } /// Add visible lines representing a collider fn add_collider_lines(commands: &mut Commands, sprite: &mut Sprite) { // Add the collider lines, a visual representation of the sprite's collider let points = sprite.collider.points(); // will be empty vector if NoCollider if points.len() >= 2 { let mut path_builder = PathBuilder::new(); path_builder.move_to(points[0]); for point in &points[1..] { path_builder.line_to(*point); } path_builder.close(); // draws the line from the last point to the first point let line = path_builder.build(); let transform = sprite.bevy_transform(); commands .spawn_bundle(GeometryBuilder::build_as( &line, DrawMode::Stroke(StrokeMode::new(Color::WHITE, 1.0 / transform.scale.x)), transform, )) .insert(ColliderLines { sprite_label: sprite.label.clone(), }); } sprite.collider_dirty = false; } /// helper function: Add Bevy components for all the sprites in engine.sprites #[doc(hidden)] pub fn add_sprites(commands: &mut Commands, asset_server: &Res<AssetServer>, engine: &mut Engine) { for (_, sprite) in engine.sprites.drain() { // Create the sprite let transform = sprite.bevy_transform(); let texture_path = sprite.filepath.clone(); commands.spawn().insert(sprite).insert_bundle(SpriteBundle { texture: asset_server.load(texture_path), transform, ..Default::default() }); } } /// Bevy system which adds any needed Bevy components to correspond to the texts in /// `engine.texts` #[doc(hidden)] pub fn add_texts(commands: &mut Commands, asset_server: &Res<AssetServer>, engine: &mut Engine) { for (_, text) in engine.texts.drain() { let transform = text.bevy_transform(); let font_size = text.font_size; let text_string = text.value.clone(); let font_path = text.font.clone(); commands.spawn().insert(text).insert_bundle(Text2dBundle { text: BevyText::from_section( text_string, TextStyle { font: asset_server.load(font_path.as_str()), font_size, color: Color::WHITE, }, ) .with_alignment(TextAlignment { vertical: VerticalAlign::Center, horizontal: HorizontalAlign::Center, }), transform, ..Default::default() }); } } /// system - update current window dimensions in the engine, because people resize windows #[doc(hidden)] pub fn update_window_dimensions(windows: Res<Windows>, mut engine: ResMut<Engine>) { // It's possible to not have window dimensions for the first frame or two if let Some(window) = windows.get_primary() { let screen_dimensions = Vec2::new(window.width(), window.height()); if screen_dimensions != engine.window_dimensions { engine.window_dimensions = screen_dimensions; debug!("Set window dimensions: {}", engine.window_dimensions); } } } /// Component to add to the collider lines visualizations to link them to the sprite they represent #[derive(Component)] #[doc(hidden)] pub struct ColliderLines { sprite_label: String, } /// A [`Game`] represents the entire game and its data. /// By default the game will spawn an empty window, and exit upon Esc or closing of the window. /// Under the hood, Rusty Engine syncs the game data to [Bevy](https://bevyengine.org/) to power /// most of the underlying functionality. /// /// [`Game`] forwards method calls to [`Engine`] when it can, so you should be able to use all /// of the methods from [`Engine`] on [`Game`] during your game setup in your `main()` function. pub struct Game<S: Send + Sync + 'static> { app: App, engine: Engine, logic_functions: Vec<fn(&mut Engine, &mut S)>, window_descriptor: WindowDescriptor, } impl<S: Send + Sync + 'static> Default for Game<S> { fn default() -> Self { Self { app: App::new(), engine: Engine::default(), logic_functions: vec![], window_descriptor: WindowDescriptor { title: "Rusty Engine".into(), ..Default::default() }, } } } impl<S: Send + Sync + 'static> Game<S> { /// Create an new, empty [`Game`] with an empty [`Engine`] pub fn new() -> Self { if std::fs::read_dir("assets").is_err() { println!("FATAL: Could not find assets directory. Have you downloaded the assets?\nhttps://github.com/CleanCut/rusty_engine#you-must-download-the-assets-separately"); std::process::exit(1); } Default::default() } /// Use this to set properties of the native OS window before running the game. See the /// [window](https://github.com/CleanCut/rusty_engine/blob/main/examples/window.rs) example for /// more information. pub fn window_settings(&mut self, window_descriptor: WindowDescriptor) -> &mut Self { self.window_descriptor = window_descriptor; self } /// Start the game. pub fn run(&mut self, initial_game_state: S) { self.app .insert_resource::<WindowDescriptor>(self.window_descriptor.clone()) .insert_resource(ImageSettings::default_nearest()) .insert_resource::<S>(initial_game_state); self.app // Built-ins .add_plugins(DefaultPlugins) .add_system(close_on_esc) // External Plugins .add_plugin(ShapePlugin) // bevy_prototype_lyon, for displaying sprite colliders // Rusty Engine Plugins .add_plugin(AudioManagerPlugin) .add_plugin(KeyboardPlugin) .add_plugin(MousePlugin) .add_plugin(PhysicsPlugin) //.insert_resource(ReportExecutionOrderAmbiguities) // for debugging .add_system( update_window_dimensions .label("update_window_dimensions") .before("game_logic_sync"), ) .add_system(game_logic_sync::<S>.label("game_logic_sync")) .add_startup_system(setup); self.app .world .spawn() .insert_bundle(Camera2dBundle::default()); let engine = std::mem::take(&mut self.engine); self.app.insert_resource(engine); let logic_functions = std::mem::take(&mut self.logic_functions); self.app.insert_resource(logic_functions); self.app.run(); } /// `logic_function` is a function or closure that takes two parameters and returns nothing: /// /// - `engine: &mut Engine` /// - `game_state`, which is a mutable reference (`&mut`) to the game state struct you defined, /// or `&mut ()` if you didn't define one. pub fn add_logic(&mut self, logic_function: fn(&mut Engine, &mut S)) { self.logic_functions.push(logic_function); } } /// system - the magic that connects Rusty Engine to Bevy, frame by frame #[allow(clippy::type_complexity, clippy::too_many_arguments)] fn game_logic_sync<S: Send + Sync + 'static>( mut commands: Commands, asset_server: Res<AssetServer>, mut engine: ResMut<Engine>, mut game_state: ResMut<S>, logic_functions: Res<Vec<fn(&mut Engine, &mut S)>>, keyboard_state: Res<KeyboardState>, mouse_state: Res<MouseState>, time: Res<Time>, mut app_exit_events: EventWriter<AppExit>, mut collision_events: EventReader<CollisionEvent>, mut query_set: ParamSet<( Query<(Entity, &mut Sprite, &mut Transform)>, Query<(Entity, &mut Text, &mut Transform, &mut BevyText)>, Query<(Entity, &mut DrawMode, &mut Transform, &ColliderLines)>, )>, ) { // Update this frame's timing info engine.delta = time.delta(); engine.delta_f32 = time.delta_seconds(); engine.time_since_startup = time.time_since_startup(); engine.time_since_startup_f64 = time.seconds_since_startup(); // Copy keyboard state over to engine to give to users engine.keyboard_state = keyboard_state.clone(); // Copy mouse state over to engine to give to users engine.mouse_state = mouse_state.clone(); // Copy all collision events over to the engine to give to users engine.collision_events.clear(); for collision_event in collision_events.iter() { engine.collision_events.push(collision_event.clone()); } // Copy all sprites over to the engine to give to users engine.sprites.clear(); for (_, sprite, _) in query_set.p0().iter() { let _ = engine .sprites .insert(sprite.label.clone(), (*sprite).clone()); } // Copy all texts over to the engine to give to users engine.texts.clear(); for (_, text, _, _) in query_set.p1().iter() { let _ = engine.texts.insert(text.label.clone(), (*text).clone()); } // Perform all the user's game logic for this frame for func in logic_functions.iter() { func(&mut engine, &mut game_state); } if !engine.last_show_colliders && engine.show_colliders { // Just turned on show_colliders -- create collider lines for all sprites for sprite in engine.sprites.values_mut() { add_collider_lines(&mut commands, sprite); } } else if engine.last_show_colliders && !engine.show_colliders { // Just turned off show_colliders -- delete collider lines for all sprites for (entity, _, _, _) in query_set.p2().iter_mut() { commands.entity(entity).despawn(); } } // Update transform & line width of all collider lines if engine.show_colliders { // Delete collider lines for sprites which are missing, or whose colliders are dirty for (entity, _, _, collider_lines) in query_set.p2().iter_mut() { if let Some(sprite) = engine.sprites.get(&collider_lines.sprite_label) { if sprite.collider_dirty { commands.entity(entity).despawn(); } } else { commands.entity(entity).despawn(); } } // Add collider lines for sprites whose colliders are dirty for sprite in engine.sprites.values_mut() { if sprite.collider_dirty { add_collider_lines(&mut commands, sprite); } } // Update transform & line width for (_, mut draw_mode, mut transform, collider_lines) in query_set.p2().iter_mut() { if let Some(sprite) = engine.sprites.get(&collider_lines.sprite_label) { *transform = sprite.bevy_transform(); // We want collider lines to appear on top of the sprite they are for, so they need a // slightly higher z value. We tell users to only use up to 999.0. transform.translation.z = (transform.translation.z + 0.1).clamp(0.0, 999.1); } // Stroke line width gets scaled with the transform, but we want it to appear to be the same // regardless of scale, so we have to counter the scale. if let DrawMode::Stroke(ref mut stroke_mode) = *draw_mode { let line_width = 1.0 / transform.scale.x; *stroke_mode = StrokeMode::new(Color::WHITE, line_width); } } } engine.last_show_colliders = engine.show_colliders; // Transfer any changes in the user's Sprite copies to the Bevy Sprite and Transform components for (entity, mut sprite, mut transform) in query_set.p0().iter_mut() { if let Some(sprite_copy) = engine.sprites.remove(&sprite.label) { *sprite = sprite_copy; *transform = sprite.bevy_transform(); } else { commands.entity(entity).despawn(); } } // Add Bevy components for any new sprites remaining in engine.sprites add_sprites(&mut commands, &asset_server, &mut engine); // Transfer any changes in the user's Texts to the Bevy Text and Transform components for (entity, mut text, mut transform, mut bevy_text_component) in query_set.p1().iter_mut() { if let Some(text_copy) = engine.texts.remove(&text.label) { *text = text_copy; *transform = text.bevy_transform(); if text.value != bevy_text_component.sections[0].value { bevy_text_component.sections[0].value = text.value.clone(); } #[allow(clippy::float_cmp)] if text.font_size != bevy_text_component.sections[0].style.font_size { bevy_text_component.sections[0].style.font_size = text.font_size; } let font = asset_server.load(text.font.as_str()); if bevy_text_component.sections[0].style.font != font { bevy_text_component.sections[0].style.font = font; } } else { commands.entity(entity).despawn(); } } // Add Bevy components for any new texts remaining in engine.texts add_texts(&mut commands, &asset_server, &mut engine); if engine.should_exit { app_exit_events.send(AppExit); } } // The Deref and DerefMut implementations make it so that you can call all the `Engine` methods // on a `Game`, which is much more straightforward for game setup in `main()` impl<S: Send + Sync + 'static> Deref for Game<S> { type Target = Engine; fn deref(&self) -> &Self::Target { &self.engine } } impl<S: Send + Sync + 'static> DerefMut for Game<S> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.engine } }
use input::Input; use input::evaluator::InputEvaluatorRef; use parser::{ Evaluator, Node }; // Maximum accumulator // // Examines a bunch of inputs and takes the // highest value. pub struct Maximum { inputs : Vec<Box<Input>>, } impl Maximum { pub fn create(inputs_v: Vec<Box<Input>>) -> Box<Input> { Box::new(Maximum { inputs : inputs_v }) } fn max(a: f64, b: f64) -> f64 { match a > b { true => a, false => b, } } } impl Input for Maximum { fn compute(&mut self) -> f64 { let mut result : f64 = 0.0; for i in self.inputs.as_mut_slice() { result = Maximum::max(result, i.compute()); } result } } /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////// pub struct EvalMaximum { input : InputEvaluatorRef, } impl EvalMaximum { pub fn new(input_v : InputEvaluatorRef) -> EvalMaximum { EvalMaximum { input : input_v } } } impl Evaluator<Box<Input>> for EvalMaximum { fn parse_nodes(&self, nodes: &[Node]) -> Result<Box<Input>, String> { Ok(Maximum::create(try!(self.input.borrow().parse_nodes(nodes)))) } }
#![allow(unused_mut)] #![allow(incomplete_features)] #![feature(generic_associated_types)] /* class Functor f where fmap :: (a -> b) -> F a -> F b */ trait Functor { type Unwrapped; type Wrapped<B>: Functor; fn map<F, B>(self, f: F) -> Self::Wrapped<B> where F: FnMut(Self::Unwrapped) -> B; } impl<A> Functor for Option<A> { type Unwrapped = A; type Wrapped<B> = Option<B>; fn map<F: FnMut(A) -> B, B>(self, mut f: F) -> Option<B> { self.map(f) } } trait Semigroup { fn append(self, rhs: Self) -> Self; } impl Semigroup for String { fn append(mut self, rhs: Self) -> Self { self = self + &rhs; self } } fn main() { println!("Hello world!") }
use super::parse::{Command, Config}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::error::Error; use std::fmt::Display; use std::fs::File; use std::io::{Read, Write}; pub const LOGIN_API: &str = "/api/management/v1/useradm/auth/login"; pub const DEPLOY_API: &str = "/api/management/v1/deployments/deployments"; pub const GET_DEVICES_INVENTORY_API: &str = "/api/management/v1/inventory/devices"; pub const GET_DEVICES_AUTH_API: &str = "/api/management/v2/devauth/devices"; #[derive(Debug)] pub struct MenderError { err: String, } impl Display for MenderError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { write!(f, "{}", self.err) } } impl Error for MenderError {} impl MenderError { fn new(err: String) -> MenderError { MenderError { err } } } fn blocking_client( cert_file: &Option<String>, ) -> Result<reqwest::blocking::Client, Box<dyn Error>> { if let Some(cert_file) = cert_file { let mut buf = Vec::new(); File::open(cert_file)?.read_to_end(&mut buf)?; let cert = reqwest::Certificate::from_pem(&buf)?; Ok(reqwest::blocking::Client::builder() .add_root_certificate(cert) .build()?) } else { Ok(reqwest::blocking::Client::builder().build()?) } } macro_rules! check_success { ($response:expr, $cmd:expr) => { if !$response.status().is_success() { return Err(Box::new(MenderError::new(format!( "{} failed. Status code '{}' response '{}'", $cmd, $response.status(), $response.text().unwrap() )))); } }; } /// Request an auth token from mender server, it should be called /// with a Login command otherwise an error is returned. pub fn get_token(conf: &Config, pass: &str) -> Result<String, Box<dyn Error>> { if let Command::Login { email } = &conf.command { let client = blocking_client(&conf.cert_file)?; let url_login = conf.server_url.clone() + LOGIN_API; let get_token = client .post(&url_login) .basic_auth(&email, Some(pass)) .send()?; check_success!(get_token, "login"); Ok(get_token.text().unwrap()) } else { Err(Box::new(MenderError::new(String::from( "Command must be Login for get_token", )))) } } #[derive(Serialize)] struct DeployData<'a> { artifact_name: &'a str, name: &'a str, devices: Vec<String>, } /// Deploy an update to a device group or a single device, return the number of devices affected. /// An error can occur if communication with the server fails, if the group, device or the /// artifact is not found and if command is not Deploy or token is not present. pub fn deploy(conf: &Config) -> Result<usize, Box<dyn Error>> { if let ( Command::Deploy { group, device, artifact, name, }, Some(token), ) = (&conf.command, &conf.token) { if group.is_none() && device.is_none() { return Err(Box::new(MenderError::new(String::from( "A group or a device id must be provided for deployment", )))); } let name = name.as_ref().unwrap_or_else(|| { if group.is_some() { group.as_ref().unwrap() } else { device.as_ref().unwrap() } }); println!( "Posting deployment to {} {} using artifact {} and with name {}.", if group.is_some() { "group" } else { "device" }, if let Some(group) = group { &group } else { device.as_ref().unwrap() }, &artifact, &name ); let client = blocking_client(&conf.cert_file)?; // List devices in the group let mut page = Some(1); let mut devices: Vec<String> = vec![]; if let Some(group) = group { while let Some(page_idx) = page { let list_url = format!( "{}/api/management/v1/inventory/groups/{}/devices", conf.server_url, group ); let list_devices = client .get(&list_url) .bearer_auth(token) .query(&[("per_page", "500"), ("page", &page_idx.to_string())]) .send()?; check_success!(list_devices, "deployment"); let mut res = list_devices.json::<Vec<String>>()?; page = if res.len() == 0 { None } else { Some(page_idx + 1) }; devices.append(&mut res); } } else { devices.push(device.as_ref().unwrap().to_string()); } // Post deployment let nb_devices = devices.len(); let deploy_data = DeployData { artifact_name: artifact, name, devices, }; let url_deploy = conf.server_url.clone() + DEPLOY_API; let post_deploy = client .post(&url_deploy) .bearer_auth(token) .json(&deploy_data) .send()?; check_success!(post_deploy, "deployment"); Ok(nb_devices) } else { Err(Box::new(MenderError::new(String::from( "Command must be Deploy and token must be provided for deploy", )))) } } #[derive(Deserialize, Debug)] struct MenderId { id: String, } #[derive(Deserialize, Debug)] struct MenderIdentity { id: String, identity_data: MenderSn, } #[derive(Deserialize, Debug)] #[allow(non_snake_case)] struct MenderSn { SerialNumber: String, } /// Get mender id of a device based on its SerialNumber attribute. /// The command must be getid and a token must be provided. pub fn get_id(conf: &Config) -> Result<String, Box<dyn Error>> { if let (Command::GetId { serial_number }, Some(token)) = (&conf.command, &conf.token) { println!("Searching for device with SerialNumber {}", &serial_number); let client = blocking_client(&conf.cert_file)?; let get_device_inventory = client .get(&format!( "{}{}", &conf.server_url, GET_DEVICES_INVENTORY_API )) .bearer_auth(token) .query(&[("SerialNumber", serial_number)]) .send()?; check_success!(get_device_inventory, "searching device"); let mut res = get_device_inventory.json::<Vec<MenderId>>()?; if let Some(mender_id) = res.pop() { Ok(mender_id.id) } else { println!("SerialNumber not found in attributes, searching in identity data."); let mut page = Some(1); while let Some(page_idx) = page { print!("."); std::io::stdout().flush().unwrap(); let get_devices_auth = client .get(&format!("{}{}", &conf.server_url, GET_DEVICES_AUTH_API)) .bearer_auth(token) .query(&[ ("per_page", "500"), ("page", &page_idx.to_string()), ("status", "accepted"), ]) .send()?; check_success!(get_devices_auth, "device search"); let res = get_devices_auth.json::<Vec<MenderIdentity>>()?; let nb_results = res.len(); if let Some(mender_identity) = res .into_iter() .filter(|mender_identity| { mender_identity.identity_data.SerialNumber.as_str() == serial_number }) .next() { println!(""); return Ok(mender_identity.id); } else { page = if nb_results == 0 { None } else { Some(page_idx + 1) }; } } println!(""); Err(Box::new(MenderError::new(String::from( "SerialNumber not found", )))) } } else { Err(Box::new(MenderError::new(String::from( "Command must be getid and token must be provided in get_id call", )))) } } /// Get info of a device pub fn get_info(conf: &Config) -> Result<String, Box<dyn Error>> { if let (Command::GetInfo { id }, Some(token)) = (&conf.command, &conf.token) { let client = blocking_client(&conf.cert_file)?; let get_device_inventory = client .get(&format!( "{}{}/{}", &conf.server_url, GET_DEVICES_INVENTORY_API, id )) .bearer_auth(token) .send()?; check_success!(get_device_inventory, "get info"); let json: serde_json::Value = get_device_inventory.json()?; Ok(serde_json::to_string_pretty(&json)?) } else { Err(Box::new(MenderError::new(String::from( "Command must be getinfo and token must be provided in get_info call", )))) } } #[derive(Deserialize, Debug)] struct MenderAttribute { name: String, value: String, } #[derive(Deserialize, Debug)] struct MenderDevice { id: String, attributes: Option<Vec<MenderAttribute>>, } impl MenderDevice { fn artifact_name(&self) -> String { if let Some(attributes) = &self.attributes { for attribute in attributes { if attribute.name == "artifact_name" { return attribute.value.clone(); } } } return String::new(); } } /// Return the list of artifacts with a count of how much devices are using it. pub fn count_artifacts(conf: &Config) -> Result<String, Box<dyn Error>> { if let (Command::CountArtifacts, Some(token)) = (&conf.command, &conf.token) { print!("Inventoring artifact used by devices"); let client = blocking_client(&conf.cert_file)?; let mut artifacts_count = HashMap::new(); let mut page = Some(1); while let Some(page_idx) = page { print!("."); std::io::stdout().flush().unwrap(); let get_devices_inv = client .get(&format!( "{}{}", &conf.server_url, GET_DEVICES_INVENTORY_API )) .bearer_auth(token) .query(&[("per_page", "500"), ("page", &page_idx.to_string())]) .send()?; check_success!(get_devices_inv, "artifacts counting"); let res = get_devices_inv.json::<Vec<MenderDevice>>()?; let nb_devices = res.len(); let artifacts: Vec<String> = res .into_iter() .map(|device| device.artifact_name()) .collect(); for artifact in artifacts { let count = artifacts_count.entry(artifact).or_insert(0); *count += 1; } page = if nb_devices > 0 { Some(page_idx + 1) } else { None }; } println!(""); Ok(display_ordered(artifacts_count)) } else { Err(Box::new(MenderError::new(String::from( "Command must be countartifacts and token must be provided in count_artifacts call", )))) } } fn display_ordered(map: HashMap<String, i32>) -> String { let mut vec: Vec<(&String, &i32)> = map.iter().collect(); vec.sort_by(|a, b| b.1.cmp(a.1)); let mut disp = String::new(); for (key, value) in vec { disp.push_str(&format!("{}: {}\n", key, value)); } disp }
//! Edit a `DataBase`. mod component; mod residue; use error::GrafenCliError; use ui::utils::{MenuResult, print_description, select_command}; use grafen::database::{write_database, DataBase}; use std::error::Error; pub fn user_menu(database: &mut DataBase) -> MenuResult { let path_backup = database.path.clone(); let residues_backup = database.residue_defs.clone(); let components_backup = database.component_defs.clone(); create_menu![ @pre: { print_description(database); }; EditResidues, "Edit list of residues" => { residue::user_menu(&mut database.residue_defs).map(|msg| msg.into()) }, EditComponents, "Edit list of components" => { component::user_menu(&mut database.component_defs, &database.residue_defs) .map(|msg| msg.into()) }, WriteToDisk, "Write changes of database to disk" => { write_database(&database) .map(|_| String::from("Successfully wrote changes of database to disk.").into()) .map_err(|err| GrafenCliError::RunError( format!("Could not write database: {}", err.description()) )) }, QuitAndSave, "Finish editing database" => { return Ok("Finished editing database".to_string().into()); }, QuitWithoutSaving, "Abort editing and discard changes" => { database.path = path_backup; database.residue_defs = residues_backup; database.component_defs = components_backup; return Ok("Discarding changes to database".to_string().into()); } ]; }
use super::{HPAMap, Material}; pub type Materials = Vec<Vec<Material>>; pub type Visible = Vec<Vec<bool>>; #[derive(Debug)] pub struct Maze { pub width: usize, pub height: usize, pub data: Option<MazeData>, } impl Maze { pub fn new(width: usize, height: usize) -> Maze { Maze { width, height, data: Some(MazeData::new(width, height)), } } } #[derive(Debug)] pub struct MazeData { pub width: usize, pub height: usize, pub materials: Materials, pub visible: Visible, pub hpa_map: HPAMap, } impl MazeData { pub fn new(width: usize, height: usize) -> MazeData { use std::iter::repeat; let materials = repeat(repeat(Material::Bedrock).take(height).collect()) .take(width) .collect(); let visible = repeat(repeat(false).take(height).collect()) .take(width) .collect(); MazeData { width, height, materials, visible, hpa_map: HPAMap::empty(), } } pub fn gen_hpa_map(&mut self) { self.hpa_map = HPAMap::new(self.width, self.height, &mut self.materials); } } use std::ops::*; impl Deref for Maze { type Target = MazeData; fn deref(&self) -> &MazeData { self.data.as_ref().unwrap() } } impl DerefMut for Maze { fn deref_mut(&mut self) -> &mut MazeData { self.data.as_mut().unwrap() } }
use embedded_graphics::{ mono_font::{ascii::FONT_6X10, MonoFont}, pixelcolor::BinaryColor, }; use crate::themes::default::button::{ButtonStateColors, ButtonStyle}; pub struct PrimaryButtonInactive; pub struct PrimaryButtonIdle; pub struct PrimaryButtonHovered; pub struct PrimaryButtonPressed; impl ButtonStateColors<BinaryColor> for PrimaryButtonInactive { const LABEL_COLOR: BinaryColor = BinaryColor::Off; const BORDER_COLOR: BinaryColor = BinaryColor::On; const BACKGROUND_COLOR: BinaryColor = BinaryColor::On; } impl ButtonStateColors<BinaryColor> for PrimaryButtonIdle { const LABEL_COLOR: BinaryColor = BinaryColor::Off; const BORDER_COLOR: BinaryColor = BinaryColor::On; const BACKGROUND_COLOR: BinaryColor = BinaryColor::On; } impl ButtonStateColors<BinaryColor> for PrimaryButtonHovered { const LABEL_COLOR: BinaryColor = BinaryColor::On; const BORDER_COLOR: BinaryColor = BinaryColor::On; const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off; } impl ButtonStateColors<BinaryColor> for PrimaryButtonPressed { const LABEL_COLOR: BinaryColor = BinaryColor::Off; const BORDER_COLOR: BinaryColor = BinaryColor::On; const BACKGROUND_COLOR: BinaryColor = BinaryColor::On; } pub struct PrimaryButtonStyle; impl ButtonStyle<BinaryColor> for PrimaryButtonStyle { type Inactive = PrimaryButtonInactive; type Idle = PrimaryButtonIdle; type Hovered = PrimaryButtonHovered; type Pressed = PrimaryButtonPressed; const FONT: MonoFont<'static> = FONT_6X10; }
use super::Diagnostic; use crate::util::{ attribute_arg, def_to_name, meta_into_nesteds, optional_attribute_arg, path_eq, ItemIdent, ItemMeta, ItemType, }; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, quote_spanned, ToTokens}; use std::collections::HashMap; use syn::{ parse_quote, spanned::Spanned, Attribute, AttributeArgs, Ident, Index, Item, Lit, Meta, NestedMeta, }; #[derive(Default)] struct Class { // Unlike pymodule, meta variant is not supported items: HashMap<String, ClassItem>, } #[derive(PartialEq, Eq, Hash)] enum ClassItem { Method { item_ident: Ident, py_name: String, }, ClassMethod { item_ident: Ident, py_name: String, }, Property { item_ident: Ident, py_name: String, setter: bool, }, Slot { slot_ident: Ident, item_ident: Ident, }, } impl ClassItem { fn name(&self) -> String { use ClassItem::*; match self { Method { py_name, .. } => py_name.clone(), ClassMethod { py_name, .. } => py_name.clone(), Property { py_name, setter, .. } => { if *setter { format!("{}.setter", py_name) } else { py_name.clone() } } Slot { slot_ident, .. } => format!("#slot({})", slot_ident), } } } impl Class { fn add_item(&mut self, item: ClassItem, span: Span) -> Result<(), Diagnostic> { if let Some(existing) = self.items.insert(item.name(), item) { Err(Diagnostic::span_error( span, format!("Duplicate #[py*] attribute on pyimpl: {}", existing.name()), )) } else { Ok(()) } } fn extract_method(ident: &Ident, nesteds: Vec<NestedMeta>) -> Result<ClassItem, Diagnostic> { let item_meta = ItemMeta::from_nested_meta("pymethod", &ident, &nesteds, ItemMeta::ATTRIBUTE_NAMES)?; Ok(ClassItem::Method { item_ident: ident.clone(), py_name: item_meta.method_name()?, }) } fn extract_classmethod( ident: &Ident, nesteds: Vec<NestedMeta>, ) -> Result<ClassItem, Diagnostic> { let item_meta = ItemMeta::from_nested_meta( "pyclassmethod", &ident, &nesteds, ItemMeta::ATTRIBUTE_NAMES, )?; Ok(ClassItem::ClassMethod { item_ident: ident.clone(), py_name: item_meta.method_name()?, }) } fn extract_property(ident: &Ident, nesteds: Vec<NestedMeta>) -> Result<ClassItem, Diagnostic> { let item_meta = ItemMeta::from_nested_meta("pyproperty", &ident, &nesteds, ItemMeta::PROPERTY_NAMES)?; Ok(ClassItem::Property { py_name: item_meta.property_name()?, item_ident: ident.clone(), setter: item_meta.setter()?, }) } fn extract_slot(ident: &Ident, meta: Meta) -> Result<ClassItem, Diagnostic> { let pyslot_err = "#[pyslot] must be of the form #[pyslot] or #[pyslot(slotname)]"; let nesteds = meta_into_nesteds(meta).map_err(|meta| err_span!(meta, "{}", pyslot_err))?; if nesteds.len() > 1 { return Err(Diagnostic::spanned_error(&quote!(#(#nesteds)*), pyslot_err)); } let slot_ident = if nesteds.is_empty() { let ident_str = ident.to_string(); if let Some(stripped) = ident_str.strip_prefix("tp_") { proc_macro2::Ident::new(stripped, ident.span()) } else { ident.clone() } } else { match nesteds.into_iter().next().unwrap() { NestedMeta::Meta(Meta::Path(path)) => path .get_ident() .cloned() .ok_or_else(|| err_span!(path, "{}", pyslot_err))?, bad => bail_span!(bad, "{}", pyslot_err), } }; Ok(ClassItem::Slot { slot_ident, item_ident: ident.clone(), }) } fn extract_item_from_syn(&mut self, item: &mut ItemIdent) -> Result<(), Diagnostic> { let mut attr_idxs = Vec::new(); for (i, meta) in item .attrs .iter() .filter_map(|attr| attr.parse_meta().ok()) .enumerate() { let meta_span = meta.span(); let name = match meta.path().get_ident() { Some(name) => name, None => continue, }; assert!(item.typ == ItemType::Method); let into_nested = || { meta_into_nesteds(meta.clone()).map_err(|meta| { err_span!( meta, "#[{name} = \"...\"] cannot be a name/value, you probably meant \ #[{name}(name = \"...\")]", name = name.to_string(), ) }) }; let item = match name.to_string().as_str() { "pymethod" => Self::extract_method(item.ident, into_nested()?)?, "pyclassmethod" => Self::extract_classmethod(item.ident, into_nested()?)?, "pyproperty" => Self::extract_property(item.ident, into_nested()?)?, "pyslot" => Self::extract_slot(item.ident, meta)?, _ => { continue; } }; self.add_item(item, meta_span)?; attr_idxs.push(i); } let mut i = 0; let mut attr_idxs = &*attr_idxs; item.attrs.retain(|_| { let drop = attr_idxs.first().copied() == Some(i); if drop { attr_idxs = &attr_idxs[1..]; } i += 1; !drop }); for (i, idx) in attr_idxs.iter().enumerate() { item.attrs.remove(idx - i); } Ok(()) } } fn extract_impl_items(mut items: Vec<ItemIdent>) -> Result<TokenStream2, Diagnostic> { let mut diagnostics: Vec<Diagnostic> = Vec::new(); let mut class = Class::default(); for item in items.iter_mut() { push_diag_result!(diagnostics, class.extract_item_from_syn(item),); } let mut properties: HashMap<&str, (Option<&Ident>, Option<&Ident>)> = HashMap::new(); for item in class.items.values() { if let ClassItem::Property { ref item_ident, ref py_name, setter, } = item { let entry = properties.entry(py_name).or_default(); let func = if *setter { &mut entry.1 } else { &mut entry.0 }; if func.is_some() { bail_span!( item_ident, "Multiple property accessors with name {:?}", py_name ) } *func = Some(item_ident); } } let properties = properties .into_iter() .map(|(name, prop)| { let getter_func = match prop.0 { Some(func) => func, None => { push_err_span!( diagnostics, prop.1.unwrap(), "Property {:?} is missing a getter", name ); return TokenStream2::new(); } }; let (new, setter) = match prop.1 { Some(func) => (quote! { with_get_set }, quote! { , &Self::#func }), None => (quote! { with_get }, quote! { }), }; let str_name = name.to_string(); quote! { class.set_str_attr( #name, ::rustpython_vm::pyobject::PyObject::new( ::rustpython_vm::obj::objgetset::PyGetSet::#new(#str_name.into(), &Self::#getter_func #setter), ctx.getset_type(), None) ); } }) .collect::<Vec<_>>(); let methods = class.items.values().filter_map(|item| match item { ClassItem::Method { item_ident, py_name, } => { let new_meth = quote_spanned!(item_ident.span()=> .new_method(Self::#item_ident)); Some(quote! { class.set_str_attr(#py_name, ctx#new_meth); }) } ClassItem::ClassMethod { item_ident, py_name, } => { let new_meth = quote_spanned!(item_ident.span()=> .new_classmethod(Self::#item_ident)); Some(quote! { class.set_str_attr(#py_name, ctx#new_meth); }) } ClassItem::Slot { slot_ident, item_ident, } => { let transform = if vec!["new", "call"].contains(&slot_ident.to_string().as_str()) { quote! { ::rustpython_vm::function::IntoPyNativeFunc::into_func } } else { quote! { ::rustpython_vm::__exports::smallbox! } }; let into_func = quote_spanned! {item_ident.span()=> #transform(Self::#item_ident) }; Some(quote! { (*class.slots.write()).#slot_ident = Some(#into_func); }) } _ => None, }); Diagnostic::from_vec(diagnostics)?; Ok(quote! { #(#methods)* #(#properties)* }) } fn extract_impl_attrs(attr: AttributeArgs) -> Result<(TokenStream2, TokenStream2), Diagnostic> { let mut withs = Vec::new(); let mut flags = vec![quote! { ::rustpython_vm::slots::PyTpFlags::DEFAULT.bits() }]; for attr in attr { match attr { NestedMeta::Meta(Meta::List(syn::MetaList { path, nested, .. })) => { if path_eq(&path, "with") { for meta in nested { match meta { NestedMeta::Meta(Meta::Path(path)) => { withs.push(quote! { <Self as #path>::__extend_py_class(ctx, class); }); } meta => { bail_span!(meta, "#[pyimpl(with(...))] arguments should be paths") } } } } else if path_eq(&path, "flags") { for meta in nested { match meta { NestedMeta::Meta(Meta::Path(path)) => { if let Some(ident) = path.get_ident() { flags.push(quote! { | ::rustpython_vm::slots::PyTpFlags::#ident.bits() }); } else { bail_span!( path, "#[pyimpl(flags(...))] arguments should be ident" ) } } meta => { bail_span!(meta, "#[pyimpl(flags(...))] arguments should be ident") } } } } else { bail_span!(path, "Unknown pyimpl attribute") } } attr => bail_span!(attr, "Unknown pyimpl attribute"), } } Ok(( quote! { #(#withs)* }, quote! { #(#flags)* }, )) } pub fn impl_pyimpl(attr: AttributeArgs, item: Item) -> Result<TokenStream2, Diagnostic> { match item { Item::Impl(mut imp) => { let items = imp .items .iter_mut() .filter_map(|item| match item { syn::ImplItem::Method(syn::ImplItemMethod { attrs, sig, .. }) => { Some(ItemIdent { typ: ItemType::Method, attrs, ident: &sig.ident, }) } _ => None, }) .collect(); let extend_impl = extract_impl_items(items)?; let (with_impl, flags) = extract_impl_attrs(attr)?; let ty = &imp.self_ty; let ret = quote! { #imp impl ::rustpython_vm::pyobject::PyClassImpl for #ty { const TP_FLAGS: ::rustpython_vm::slots::PyTpFlags = ::rustpython_vm::slots::PyTpFlags::from_bits_truncate(#flags); fn impl_extend_class( ctx: &::rustpython_vm::pyobject::PyContext, class: &::rustpython_vm::obj::objtype::PyClassRef, ) { #extend_impl #with_impl } } }; Ok(ret) } Item::Trait(mut trai) => { let items = trai .items .iter_mut() .filter_map(|item| match item { syn::TraitItem::Method(syn::TraitItemMethod { attrs, sig, .. }) => { Some(ItemIdent { typ: ItemType::Method, attrs, ident: &sig.ident, }) } _ => None, }) .collect(); let extend_impl = extract_impl_items(items)?; let item = parse_quote! { fn __extend_py_class( ctx: &::rustpython_vm::pyobject::PyContext, class: &::rustpython_vm::obj::objtype::PyClassRef, ) { #extend_impl } }; trai.items.push(item); Ok(trai.into_token_stream()) } item => Ok(quote!(#item)), } } fn generate_class_def( ident: &Ident, name: &str, tp_name: &str, attrs: &[Attribute], ) -> Result<TokenStream2, Diagnostic> { let mut doc: Option<Vec<String>> = None; for attr in attrs.iter() { if attr.path.is_ident("doc") { let meta = attr.parse_meta().expect("expected doc attr to be a meta"); if let Meta::NameValue(name_value) = meta { if let Lit::Str(s) = name_value.lit { let val = s.value().trim().to_owned(); match doc { Some(ref mut doc) => doc.push(val), None => doc = Some(vec![val]), } } } } } let doc = match doc { Some(doc) => { let doc = doc.join("\n"); quote!(Some(#doc)) } None => quote!(None), }; let ret = quote! { impl ::rustpython_vm::pyobject::PyClassDef for #ident { const NAME: &'static str = #name; const TP_NAME: &'static str = #tp_name; const DOC: Option<&'static str> = #doc; } }; Ok(ret) } pub fn impl_pyclass(attr: AttributeArgs, item: Item) -> Result<TokenStream2, Diagnostic> { let (item, ident, attrs) = match item { Item::Struct(struc) => (quote!(#struc), struc.ident, struc.attrs), Item::Enum(enu) => (quote!(#enu), enu.ident, enu.attrs), other => bail_span!( other, "#[pyclass] can only be on a struct or enum declaration" ), }; let class_name = def_to_name("pyclass", &ident, &attr)?; let module_class_name = if let Some(module_name) = optional_attribute_arg("pystruct_sequence", "module", &attr)? { format!("{}.{}", module_name, class_name) } else { class_name.clone() }; let class_def = generate_class_def(&ident, &class_name, &module_class_name, &attrs)?; let ret = quote! { #item #class_def }; Ok(ret) } pub fn impl_pystruct_sequence(attr: AttributeArgs, item: Item) -> Result<TokenStream2, Diagnostic> { let struc = if let Item::Struct(struc) = item { struc } else { bail_span!( item, "#[pystruct_sequence] can only be on a struct declaration" ) }; let module_name = attribute_arg("pystruct_sequence", "module", &attr)?; let class_name = def_to_name("pystruct_sequence", &struc.ident, &attr)?; let module_class_name = format!("{}.{}", module_name, class_name); let class_def = generate_class_def(&struc.ident, &class_name, &module_class_name, &struc.attrs)?; let mut properties = Vec::new(); let mut field_names = Vec::new(); for (i, field) in struc.fields.iter().enumerate() { let idx = Index::from(i); if let Some(ref field_name) = field.ident { let field_name_str = field_name.to_string(); // TODO add doc to the generated property let property = quote! { class.set_str_attr( #field_name_str, ctx.new_readonly_getset( #field_name_str, |zelf: &::rustpython_vm::obj::objtuple::PyTuple, _vm: &::rustpython_vm::VirtualMachine| { zelf.fast_getitem(#idx) } ), ); }; properties.push(property); field_names.push(quote!(#field_name)); } else { field_names.push(quote!(#idx)); } } let ty = &struc.ident; let ret = quote! { #struc #class_def impl #ty { pub fn into_struct_sequence(&self, vm: &::rustpython_vm::VirtualMachine, cls: ::rustpython_vm::obj::objtype::PyClassRef, ) -> ::rustpython_vm::pyobject::PyResult<::rustpython_vm::obj::objtuple::PyTupleRef> { let tuple = ::rustpython_vm::obj::objtuple::PyTuple::from( vec![#(::rustpython_vm::pyobject::IntoPyObject::into_pyobject( ::std::clone::Clone::clone(&self.#field_names), vm, )),*], ); ::rustpython_vm::pyobject::PyValue::into_ref_with_type(tuple, vm, cls) } } impl ::rustpython_vm::pyobject::PyStructSequenceImpl for #ty { const FIELD_NAMES: &'static [&'static str] = &[#(stringify!(#field_names)),*]; } impl ::rustpython_vm::pyobject::PyClassImpl for #ty { fn impl_extend_class( ctx: &::rustpython_vm::pyobject::PyContext, class: &::rustpython_vm::obj::objtype::PyClassRef, ) { use ::rustpython_vm::pyobject::PyStructSequenceImpl; #(#properties)* class.set_str_attr("__repr__", ctx.new_method(Self::repr)); } fn make_class( ctx: &::rustpython_vm::pyobject::PyContext, ) -> ::rustpython_vm::obj::objtype::PyClassRef { let py_class = ctx.new_class(<Self as ::rustpython_vm::pyobject::PyClassDef>::NAME, ctx.tuple_type()); Self::extend_class(ctx, &py_class); py_class } } }; Ok(ret) }
//! Layout containers pub mod frame; pub mod linear;
use std::io; use std::io::Read; fn find_positions( tiles: &Vec<(Vec<Vec<char>>, Vec<Vec<u16>>)>, side_len: usize, used_orientations: &mut Vec<(usize, usize)>, ) -> bool { let row = used_orientations.len() / side_len; let col = used_orientations.len() % side_len; for (n, (_, tile)) in tiles.iter().enumerate() { if used_orientations.iter().any(|&(m, _)| n == m) { continue; } for orientation in 0..8 { let flipped = orientation / 4; if row > 0 { let (adjacent_index, adjacent_orientation) = used_orientations[(row - 1) * side_len + col]; let adjacent_flipped = adjacent_orientation / 4; let (_, adjacent_tile) = &tiles[adjacent_index]; if adjacent_tile[(adjacent_orientation + 2) % 4][1 - adjacent_flipped] != tile[orientation % 4][flipped] { continue; } } if col > 0 { let (adjacent_index, adjacent_orientation) = used_orientations[row * side_len + col - 1]; let adjacent_flipped = adjacent_orientation / 4; let (_, adjacent_tile) = &tiles[adjacent_index]; if adjacent_tile[(adjacent_orientation + 1 + adjacent_flipped * 2) % 4][1 - adjacent_flipped] != tile[(orientation + 3 + flipped * 2) % 4][flipped] { continue; } } used_orientations.push((n, orientation)); if used_orientations.len() == tiles.len() { return true; } else { if find_positions(tiles, side_len, used_orientations) { return true; } } used_orientations.pop(); } } false } fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let tiles: Vec<(Vec<Vec<char>>, Vec<Vec<u16>>)> = input.trim().split("\n\n").map(|text| { let side_len = text.lines().skip(1).count(); let image: Vec<Vec<u16>> = text.lines().skip(1).map(|line| { line.chars().map(|y| if y == '#' { 1 } else { 0 } ).collect() }).collect(); ( image.iter().skip(1).take(side_len - 2).map(|row| { row.iter().skip(1).take(side_len - 2).map(|&pix| if pix > 0 { '#' } else { '.' }).collect() }).collect(), (0..4).map(|side| { [false, true].iter().map(|&reverse| { (0..side_len).map(|mut i| { let mut col = i; let mut row = 0; for _ in 0..side { let new_row = col; col = side_len - row - 1; row = new_row; } if !reverse { i = side_len - i - 1; } image[row][col] << i }).sum() }).collect() }).collect(), ) }).collect(); let mut used_orientations = Vec::new(); let outer_side_len = (tiles.len() as f64).sqrt() as usize; let inner_side_len = tiles[0].0.len(); let full_side_len = outer_side_len * inner_side_len; if !find_positions(&tiles, outer_side_len, &mut used_orientations) { panic!(""); } let mut full_image: Vec<Vec<char>> = (0..full_side_len).map(|row| { let outer_row = row / inner_side_len; let inner_row = row % inner_side_len; (0..full_side_len).map(|col| { let outer_col = col / inner_side_len; let mut inner_col = col % inner_side_len; let mut inner_row = inner_row; let (index, orientation) = used_orientations[outer_row * outer_side_len + outer_col]; let flipped = orientation / 4 > 0; let tile = &tiles[index].0; if flipped { inner_col = inner_side_len - inner_col - 1; } for _ in 0..orientation % 4 { let new_inner_row = inner_col; inner_col = inner_side_len - inner_row - 1; inner_row = new_inner_row; } tile[inner_row][inner_col] }).collect() }).collect(); let sea_monster = [ " #", "# ## ## ###", " # # # # # #", ]; let sea_monster_height = sea_monster.len(); let sea_monster_width = sea_monster.iter().map(|line| line.len()).max().unwrap(); let sea_monster: Vec<_> = sea_monster.iter().enumerate().flat_map(|(row, &line)| { line.chars().enumerate().filter_map(move |(col, pix)| if pix == '#' { Some((row, col)) } else { None }) }).collect(); let mut monster_count = 0; for orientation in 0..8 { let size_wo_height = full_side_len - sea_monster_height + 1; let size_wo_width = full_side_len - sea_monster_width + 1; for row in 0..size_wo_height { for col in 0..size_wo_width { if sea_monster.iter().all(|(diff_row, diff_col)| { full_image[row + diff_row][col + diff_col] != '.' }) { for &(diff_row, diff_col) in sea_monster.iter() { full_image[row + diff_row][col + diff_col] = 'O' } monster_count += 1; } } } if monster_count > 0 { break; } full_image = (0..full_side_len).map(|row| { (0..full_side_len).map(|col| { full_image[col][if orientation % 4 == 3 { row } else { full_side_len - row - 1 }] }).collect() }).collect(); } // for row in &full_image { // for pix in row { // print!("{}", pix); // } // println!(""); // } println!("{}", full_image.iter().flat_map(|x| x.iter()).filter(|&&x| x == '#').count()); }
extern crate argparse; use std::process::Command; use std::os::unix::process::CommandExt; use argparse::{ArgumentParser, Store}; fn main() { let mut run = "".to_string(); let mut uid = "".to_string(); let mut gid = "".to_string(); { let mut ap = ArgumentParser::new(); ap.refer(&mut run) .add_option(&["--command"], Store, "Command to run") .required(); ap.refer(&mut uid) .add_option(&["--uid"], Store, "User ID"); ap.refer(&mut gid) .add_option(&["--gid"], Store, "Group ID"); ap.parse_args_or_exit(); } let mut args = run.split(" "); let mut command = Command::new(args.nth(0).unwrap()); command.args(&args.collect::<Vec<_>>()); let _ = uid.parse::<u32>() .and_then(|id| { command.uid(id); Ok(id) }); let _ = gid.parse::<u32>() .and_then(|id| { command.gid(id); Ok(id) }); let output = command.output() .unwrap_or_else(|e| { panic!("Failed to execute process: {}", e) }); println!("{}", String::from_utf8(output.stdout).unwrap()); }
// 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_exception::Result; use common_expression::types::StringType; use common_expression::DataBlock; use common_expression::DataSchemaRef; use common_expression::FromData; use common_meta_api::ShareApi; use common_meta_app::share::GetShareGrantObjectReq; use common_meta_app::share::ShareGrantObjectName; use common_meta_app::share::ShareNameIdent; use common_users::UserApiProvider; use crate::interpreters::Interpreter; use crate::pipelines::PipelineBuildResult; use crate::sessions::QueryContext; use crate::sessions::TableContext; use crate::sql::plans::share::DescSharePlan; pub struct DescShareInterpreter { ctx: Arc<QueryContext>, plan: DescSharePlan, } impl DescShareInterpreter { pub fn try_create(ctx: Arc<QueryContext>, plan: DescSharePlan) -> Result<Self> { Ok(DescShareInterpreter { ctx, plan }) } } #[async_trait::async_trait] impl Interpreter for DescShareInterpreter { fn name(&self) -> &str { "DescShareInterpreter" } fn schema(&self) -> DataSchemaRef { self.plan.schema() } async fn execute2(&self) -> Result<PipelineBuildResult> { let meta_api = UserApiProvider::instance().get_meta_store_client(); let req = GetShareGrantObjectReq { share_name: ShareNameIdent { tenant: self.ctx.get_tenant(), share_name: self.plan.share.clone(), }, }; let resp = meta_api.get_share_grant_objects(req).await?; if resp.objects.is_empty() { return Ok(PipelineBuildResult::create()); } let mut names: Vec<Vec<u8>> = vec![]; let mut kinds: Vec<Vec<u8>> = vec![]; let mut shared_owns: Vec<Vec<u8>> = vec![]; for entry in resp.objects.iter() { match &entry.object { ShareGrantObjectName::Database(db) => { kinds.push("DATABASE".to_string().as_bytes().to_vec()); names.push(db.clone().as_bytes().to_vec()); } ShareGrantObjectName::Table(db, table_name) => { kinds.push("TABLE".to_string().as_bytes().to_vec()); names.push(format!("{}.{}", db, table_name).as_bytes().to_vec()); } } shared_owns.push(entry.grant_on.to_string().as_bytes().to_vec()); } PipelineBuildResult::from_blocks(vec![DataBlock::new_from_columns(vec![ StringType::from_data(kinds), StringType::from_data(names), StringType::from_data(shared_owns), ])]) } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - control register"] pub cr: CR, #[doc = "0x04 - software trigger register"] pub swtrigr: SWTRIGR, #[doc = "0x08 - channel1 12-bit right-aligned data holding register"] pub dhr12r1: DHR12R1, #[doc = "0x0c - DAC channel1 12-bit left aligned data holding register"] pub dhr12l1: DHR12L1, #[doc = "0x10 - DAC channel1 8-bit right aligned data holding register"] pub dhr8r1: DHR8R1, _reserved5: [u8; 24usize], #[doc = "0x2c - DAC channel1 data output register"] pub dor1: DOR1, _reserved6: [u8; 4usize], #[doc = "0x34 - DAC status register"] pub sr: SR, } #[doc = "control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"] pub type CR = crate::Reg<u32, _CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CR; #[doc = "`read()` method returns [cr::R](cr::R) reader structure"] impl crate::Readable for CR {} #[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"] impl crate::Writable for CR {} #[doc = "control register"] pub mod cr; #[doc = "software trigger register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [swtrigr](swtrigr) module"] pub type SWTRIGR = crate::Reg<u32, _SWTRIGR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SWTRIGR; #[doc = "`write(|w| ..)` method takes [swtrigr::W](swtrigr::W) writer structure"] impl crate::Writable for SWTRIGR {} #[doc = "software trigger register"] pub mod swtrigr; #[doc = "channel1 12-bit right-aligned data holding register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dhr12r1](dhr12r1) module"] pub type DHR12R1 = crate::Reg<u32, _DHR12R1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DHR12R1; #[doc = "`read()` method returns [dhr12r1::R](dhr12r1::R) reader structure"] impl crate::Readable for DHR12R1 {} #[doc = "`write(|w| ..)` method takes [dhr12r1::W](dhr12r1::W) writer structure"] impl crate::Writable for DHR12R1 {} #[doc = "channel1 12-bit right-aligned data holding register"] pub mod dhr12r1; #[doc = "DAC channel1 12-bit left aligned data holding register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dhr12l1](dhr12l1) module"] pub type DHR12L1 = crate::Reg<u32, _DHR12L1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DHR12L1; #[doc = "`read()` method returns [dhr12l1::R](dhr12l1::R) reader structure"] impl crate::Readable for DHR12L1 {} #[doc = "`write(|w| ..)` method takes [dhr12l1::W](dhr12l1::W) writer structure"] impl crate::Writable for DHR12L1 {} #[doc = "DAC channel1 12-bit left aligned data holding register"] pub mod dhr12l1; #[doc = "DAC channel1 8-bit right aligned data holding register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dhr8r1](dhr8r1) module"] pub type DHR8R1 = crate::Reg<u32, _DHR8R1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DHR8R1; #[doc = "`read()` method returns [dhr8r1::R](dhr8r1::R) reader structure"] impl crate::Readable for DHR8R1 {} #[doc = "`write(|w| ..)` method takes [dhr8r1::W](dhr8r1::W) writer structure"] impl crate::Writable for DHR8R1 {} #[doc = "DAC channel1 8-bit right aligned data holding register"] pub mod dhr8r1; #[doc = "DAC channel1 data output register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dor1](dor1) module"] pub type DOR1 = crate::Reg<u32, _DOR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DOR1; #[doc = "`read()` method returns [dor1::R](dor1::R) reader structure"] impl crate::Readable for DOR1 {} #[doc = "DAC channel1 data output register"] pub mod dor1; #[doc = "DAC status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sr](sr) module"] pub type SR = crate::Reg<u32, _SR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SR; #[doc = "`read()` method returns [sr::R](sr::R) reader structure"] impl crate::Readable for SR {} #[doc = "`write(|w| ..)` method takes [sr::W](sr::W) writer structure"] impl crate::Writable for SR {} #[doc = "DAC status register"] pub mod sr;
//! Encoding related code. //! //! You'll find two stuctures for configuration: //! * `EncodingConfig<E>`: For sinks without a default `Encoding`. //! * `EncodingConfigWithDefault<E: Default>`: For sinks that have a default `Encoding`. //! //! Your sink should define some `Encoding` enum that is used as the `E` parameter. //! //! You can use either of these for a sink! They both implement `EncodingConfiguration`, which you //! will need to import as well. //! //! # Using a configuration //! //! To use an `EncodingConfig` involves three steps: //! //! 1. Choose between `EncodingConfig` and `EncodingConfigWithDefault`. //! 2. Call `apply_rules(&mut event)` on this config **on each event** just before it gets sent. //! //! # Implementation notes //! //! You may wonder why we have both of these types! **Great question.** `serde` works with the //! static `*SinkConfig` types when it deserializes our configuration. This means `serde` needs to //! statically be aware if there is a default for some given `E` of the config. Since //! We don't require `E: Default` we can't always assume that, so we need to create statically //! distinct types! Having `EncodingConfigWithDefault` is a relatively straightforward way to //! accomplish this without a bunch of magic. //! // TODO: To avoid users forgetting to apply the rules, the `E` param should require a trait // `Encoder` that defines some `encode` function which this config then calls internally as // part of it's own (yet to be written) `encode() -> Vec<u8>` function. mod config; pub use config::EncodingConfig; mod with_default; pub use with_default::EncodingConfigWithDefault; use crate::{ event::{PathComponent, PathIter, Value}, Event, Result, }; use serde::{Deserialize, Serialize}; use std::{collections::VecDeque, fmt::Debug}; use string_cache::DefaultAtom as Atom; /// The behavior of a encoding configuration. pub trait EncodingConfiguration<E> { // Required Accessors fn codec(&self) -> &E; // TODO(2410): Using PathComponents here is a hack for #2407, #2410 should fix this fully. fn only_fields(&self) -> &Option<Vec<Vec<PathComponent>>>; fn except_fields(&self) -> &Option<Vec<Atom>>; fn timestamp_format(&self) -> &Option<TimestampFormat>; fn apply_only_fields(&self, event: &mut Event) { if let Some(only_fields) = &self.only_fields() { match event { Event::Log(log_event) => { let to_remove = log_event .keys() .filter(|field| { let field_path = PathIter::new(field).collect::<Vec<_>>(); !only_fields.iter().any(|only| { // TODO(2410): Using PathComponents here is a hack for #2407, #2410 should fix this fully. field_path.starts_with(&only[..]) }) }) .collect::<VecDeque<_>>(); for removal in to_remove { log_event.remove(&Atom::from(removal)); } } Event::Metric(_) => { // Metrics don't get affected by this one! } } } } fn apply_except_fields(&self, event: &mut Event) { if let Some(except_fields) = &self.except_fields() { match event { Event::Log(log_event) => { for field in except_fields { log_event.remove(field); } } Event::Metric(_) => (), // Metrics don't get affected by this one! } } } fn apply_timestamp_format(&self, event: &mut Event) { if let Some(timestamp_format) = &self.timestamp_format() { match event { Event::Log(log_event) => { match timestamp_format { TimestampFormat::Unix => { let mut unix_timestamps = Vec::new(); for (k, v) in log_event.all_fields() { if let Value::Timestamp(ts) = v { unix_timestamps .push((k.clone(), Value::Integer(ts.timestamp()))); } } for (k, v) in unix_timestamps { log_event.insert(k, v); } } // RFC3339 is the default serialization of a timestamp. TimestampFormat::RFC3339 => (), } } Event::Metric(_) => (), // Metrics don't get affected by this one! } } } /// Check that the configuration is valid. /// /// If an error is returned, the entire encoding configuration should be considered inoperable. /// /// For example, this checks if `except_fields` and `only_fields` items are mutually exclusive. fn validate(&self) -> Result<()> { if let (Some(only_fields), Some(except_fields)) = (&self.only_fields(), &self.except_fields()) { if except_fields.iter().any(|f| { let path_iter = PathIter::new(f).collect::<Vec<_>>(); only_fields.iter().any(|v| v == &path_iter) }) { return Err( "`except_fields` and `only_fields` should be mutually exclusive.".into(), ); } } Ok(()) } /// Apply the EncodingConfig rules to the provided event. /// /// Currently, this is idempotent. fn apply_rules(&self, event: &mut Event) { // Ordering in here should not matter. self.apply_except_fields(event); self.apply_only_fields(event); self.apply_timestamp_format(event); } } #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum TimestampFormat { Unix, RFC3339, } #[cfg(test)] mod tests { use super::*; use crate::event; #[derive(Deserialize, Serialize, Debug, Eq, PartialEq, Clone)] enum TestEncoding { Snoot, Boop, } #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] struct TestConfig { encoding: EncodingConfig<TestEncoding>, } // TODO(2410): Using PathComponents here is a hack for #2407, #2410 should fix this fully. fn as_path_components(a: &str) -> Vec<PathComponent> { PathIter::new(a).collect() } const TOML_SIMPLE_STRING: &str = r#" encoding = "Snoot" "#; #[test] fn config_string() { let config: TestConfig = toml::from_str(TOML_SIMPLE_STRING).unwrap(); config.encoding.validate().unwrap(); assert_eq!(config.encoding.codec(), &TestEncoding::Snoot); } const TOML_SIMPLE_STRUCT: &str = r#" encoding.codec = "Snoot" encoding.except_fields = ["Doop"] encoding.only_fields = ["Boop"] "#; #[test] fn config_struct() { let config: TestConfig = toml::from_str(TOML_SIMPLE_STRUCT).unwrap(); config.encoding.validate().unwrap(); assert_eq!(config.encoding.codec, TestEncoding::Snoot); assert_eq!(config.encoding.except_fields, Some(vec!["Doop".into()])); assert_eq!( config.encoding.only_fields, Some(vec![as_path_components("Boop")]) ); } const TOML_EXCLUSIVITY_VIOLATION: &str = r#" encoding.codec = "Snoot" encoding.except_fields = ["Doop"] encoding.only_fields = ["Doop"] "#; #[test] fn exclusivity_violation() { let config: std::result::Result<TestConfig, _> = toml::from_str(TOML_EXCLUSIVITY_VIOLATION); assert!(config.is_err()) } const TOML_EXCEPT_FIELD: &str = r#" encoding.codec = "Snoot" encoding.except_fields = ["a.b.c", "b", "c[0].y"] "#; #[test] fn test_except() { let config: TestConfig = toml::from_str(TOML_EXCEPT_FIELD).unwrap(); config.encoding.validate().unwrap(); let mut event = Event::new_empty_log(); { let log = event.as_mut_log(); log.insert("a", 1); log.insert("a.b", 1); log.insert("a.b.c", 1); log.insert("a.b.d", 1); log.insert("b[0]", 1); log.insert("b[1].x", 1); log.insert("c[0].x", 1); log.insert("c[0].y", 1); } config.encoding.apply_rules(&mut event); assert!(!event.as_mut_log().contains(&Atom::from("a.b.c"))); assert!(!event.as_mut_log().contains(&Atom::from("b"))); assert!(!event.as_mut_log().contains(&Atom::from("b[1].x"))); assert!(!event.as_mut_log().contains(&Atom::from("c[0].y"))); assert!(event.as_mut_log().contains(&Atom::from("a.b.d"))); assert!(event.as_mut_log().contains(&Atom::from("c[0].x"))); } const TOML_ONLY_FIELD: &str = r#" encoding.codec = "Snoot" encoding.only_fields = ["a.b.c", "b", "c[0].y"] "#; #[test] fn test_only() { let config: TestConfig = toml::from_str(TOML_ONLY_FIELD).unwrap(); config.encoding.validate().unwrap(); let mut event = Event::new_empty_log(); { let log = event.as_mut_log(); log.insert("a", 1); log.insert("a.b", 1); log.insert("a.b.c", 1); log.insert("a.b.d", 1); log.insert("b[0]", 1); log.insert("b[1].x", 1); log.insert("c[0].x", 1); log.insert("c[0].y", 1); } config.encoding.apply_rules(&mut event); assert!(event.as_mut_log().contains(&Atom::from("a.b.c"))); assert!(event.as_mut_log().contains(&Atom::from("b"))); assert!(event.as_mut_log().contains(&Atom::from("b[1].x"))); assert!(event.as_mut_log().contains(&Atom::from("c[0].y"))); assert!(!event.as_mut_log().contains(&Atom::from("a.b.d"))); assert!(!event.as_mut_log().contains(&Atom::from("c[0].x"))); } const TOML_TIMESTAMP_FORMAT: &str = r#" encoding.codec = "Snoot" encoding.timestamp_format = "unix" "#; #[test] fn test_timestamp() { let config: TestConfig = toml::from_str(TOML_TIMESTAMP_FORMAT).unwrap(); config.encoding.validate().unwrap(); let mut event = Event::from("Demo"); let timestamp = event .as_mut_log() .get(&event::log_schema().timestamp_key()) .unwrap() .clone(); let timestamp = timestamp.as_timestamp().unwrap(); event .as_mut_log() .insert("another", Value::Timestamp(*timestamp)); config.encoding.apply_rules(&mut event); match event .as_mut_log() .get(&event::log_schema().timestamp_key()) .unwrap() { Value::Integer(_) => {} e => panic!( "Timestamp was not transformed into a Unix timestamp. Was {:?}", e ), } match event.as_mut_log().get(&Atom::from("another")).unwrap() { Value::Integer(_) => {} e => panic!( "Timestamp was not transformed into a Unix timestamp. Was {:?}", e ), } } }
use std::error; use std::fmt; #[derive(Debug)] pub struct ErrorType1; impl error::Error for ErrorType1 { fn description(&self) -> &str { "Error 1!" } fn cause(&self) -> Option<&error::Error> { None } } impl fmt::Display for ErrorType1 { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", error::Error::description(self)) } } #[derive(Debug)] pub struct ErrorType2; impl error::Error for ErrorType2 { fn description(&self) -> &str { "Error 2!" } fn cause(&self) -> Option<&error::Error> { None } } impl fmt::Display for ErrorType2 { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", error::Error::description(self)) } }
use winapi::shared::windef::{HFONT, HBITMAP}; use winapi::ctypes::c_int; use winapi::um::winnt::HANDLE; use crate::resources::OemImage; use super::base_helper::{get_system_error, to_utf16}; #[allow(unused_imports)] use std::{ptr, mem}; #[allow(unused_imports)] use crate::NwgError; #[cfg(feature = "file-dialog")] use winapi::Interface; #[cfg(feature = "file-dialog")] use winapi::um::shobjidl_core::IShellItem; #[cfg(feature = "file-dialog")] use crate::resources::FileDialogAction; #[cfg(feature = "file-dialog")] use winapi::um::shobjidl::{IFileDialog, IFileOpenDialog}; #[cfg(feature = "file-dialog")] use std::ffi::OsString; pub fn is_bitmap(handle: HBITMAP) -> bool { use winapi::um::wingdi::GetBitmapBits; use winapi::shared::minwindef::LPVOID; let mut bits: [u8; 1] = [0; 1]; unsafe { GetBitmapBits(handle, 1, &mut bits as *mut [u8; 1] as LPVOID) != 0 } } pub fn destroy_icon(icon: HANDLE) { unsafe { winapi::um::winuser::DestroyIcon(icon as _); } } pub fn destroy_cursor(cursor: HANDLE) { unsafe { winapi::um::winuser::DestroyCursor(cursor as _); } } pub fn destroy_obj(obj: HANDLE) { unsafe { winapi::um::wingdi::DeleteObject(obj as _); } } pub unsafe fn build_font( size: i32, weight: u32, style: [bool; 3], family_name: Option<&str>, ) -> Result<HFONT, NwgError> { use winapi::um::wingdi::{DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH}; use winapi::um::wingdi::CreateFontW; let [use_italic, use_underline, use_strikeout] = style; let fam; let family_name_ptr; if family_name.is_some() { fam = to_utf16(&family_name.unwrap()); family_name_ptr = fam.as_ptr(); } else { fam = Vec::new(); family_name_ptr = ptr::null(); } let (size, _) = super::high_dpi::logical_to_physical(size as i32, 0); let handle = CreateFontW( size as c_int, // nHeight 0, 0, 0, // nWidth, nEscapement, nOrientation weight as c_int, // fnWeight use_italic as u32, // fdwItalic use_underline as u32, // fdwUnderline use_strikeout as u32, // fdwStrikeOut DEFAULT_CHARSET, // fdwCharSet OUT_DEFAULT_PRECIS, // fdwOutputPrecision CLIP_DEFAULT_PRECIS, // fdwClipPrecision CLEARTYPE_QUALITY, // fdwQuality VARIABLE_PITCH, // fdwPitchAndFamily family_name_ptr, // lpszFace ); drop(fam); if handle.is_null() { Err( NwgError::resource_create("Failed to create font") ) } else { Ok( handle ) } } pub unsafe fn build_image<'a>( source: &'a str, size: Option<(u32, u32)>, strict: bool, image_type: u32 ) -> Result<HANDLE, NwgError> { use winapi::um::winuser::{LR_LOADFROMFILE, LR_CREATEDIBSECTION, LR_DEFAULTSIZE, LR_SHARED, IMAGE_ICON, IDC_ARROW, IDI_ERROR, IMAGE_CURSOR, IMAGE_BITMAP}; use winapi::um::winuser::LoadImageW; let filepath = to_utf16(source); let (width, height) = size.unwrap_or((0,0)); let mut handle = LoadImageW(ptr::null_mut(), filepath.as_ptr(), image_type, width as i32, height as i32, LR_LOADFROMFILE); if handle.is_null() { let (code, _) = get_system_error(); if code == 2 && !strict { // If the file was not found (err code: 2) and the loading is not strict, replace the image by the system error icon handle = match image_type { IMAGE_ICON => { let dr = (IDI_ERROR as usize) as *const u16; LoadImageW(ptr::null_mut(), dr, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE|LR_SHARED) }, IMAGE_CURSOR => { let dr = (IDC_ARROW as usize) as *const u16; LoadImageW(ptr::null_mut(), dr, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE|LR_SHARED) }, IMAGE_BITMAP => { let dr = (32754 as usize) as *const u16; LoadImageW(ptr::null_mut(), dr, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION|LR_DEFAULTSIZE|LR_SHARED) }, _ => { unreachable!() } }; } } if handle.is_null() { Err( NwgError::resource_create(format!("Failed to create image from source '{}' ", source))) } else { Ok(handle) } } #[cfg(feature="image-decoder")] pub unsafe fn build_image_decoder<'a>( source: &'a str, size: Option<(u32, u32)>, _strict: bool, _image_type: u32 ) -> Result<HANDLE, NwgError> { use crate::ImageDecoder; let decoder = ImageDecoder::new()?; let mut image_frame = decoder .from_filename(source)? .frame(0)?; if let Some((width, height)) = size { image_frame = decoder.resize_image(&image_frame, [width, height])?; } let mut bitmap = image_frame.as_bitmap()?; bitmap.owned = false; Ok(bitmap.handle) } #[cfg(feature="image-decoder")] pub unsafe fn build_image_decoder_from_memory<'a>( src: &'a [u8], size: Option<(u32, u32)>, ) -> Result<HANDLE, NwgError> { use crate::ImageDecoder; let decoder = ImageDecoder::new()?; let mut image_frame = decoder .from_stream(src)? .frame(0)?; if let Some((width, height)) = size { image_frame = decoder.resize_image(&image_frame, [width, height])?; } let mut bitmap = image_frame.as_bitmap()?; bitmap.owned = false; Ok(bitmap.handle) } pub unsafe fn build_oem_image( source: OemImage, size: Option<(u32, u32)>, ) -> Result<HANDLE, NwgError> { use winapi::um::winuser::{LR_DEFAULTSIZE, LR_SHARED, IMAGE_ICON, IMAGE_CURSOR, IMAGE_BITMAP}; use winapi::um::winuser::LoadImageW; use winapi::shared::ntdef::LPCWSTR; let (width, height) = size.unwrap_or((0,0)); let (c_res_type, res_identifier) = match source { OemImage::Bitmap(b) => { (IMAGE_BITMAP, (b as usize) as LPCWSTR) }, OemImage::Cursor(c) => { (IMAGE_CURSOR, (c as usize) as LPCWSTR) }, OemImage::Icon(i) => { (IMAGE_ICON, (i as usize) as LPCWSTR) } }; let flags = if (width, height) == (0, 0) { LR_DEFAULTSIZE|LR_SHARED } else { LR_SHARED }; let handle = LoadImageW(ptr::null_mut(), res_identifier, c_res_type, width as i32, height as i32, flags); if handle.is_null() { Err( NwgError::resource_create("Failed to create image from system resource") ) } else { Ok(handle) } } /** Create a bitmap from memory. Only supports bitmap. Enable the `image-decoder` to load more image type from memory The memory must contain the whole file (including the bitmap header). */ #[cfg(not(feature="image-decoder"))] pub unsafe fn bitmap_from_memory(source: &[u8]) -> Result<HANDLE, NwgError> { use winapi::um::wingdi::{CreateCompatibleBitmap, CreateCompatibleDC, SetDIBits, BITMAPFILEHEADER, BITMAPINFO, BITMAPINFOHEADER, DIB_RGB_COLORS, BI_RGB, RGBQUAD}; use winapi::shared::{ntdef::LONG, minwindef::DWORD}; use winapi::um::winuser::{GetDC, ReleaseDC}; use winapi::ctypes::c_void; // Check the header size requirement let fheader_size = mem::size_of::<BITMAPFILEHEADER>(); let iheader_size = mem::size_of::<BITMAPINFOHEADER>(); let header_size = fheader_size + iheader_size; if source.len() < header_size { let msg = format!("Invalid source. The source size ({} bytes) is smaller than the required headers size ({} bytes).", source.len(), header_size); return Err(NwgError::ResourceCreationError(msg)); } // Read the bitmap file header let src: *const u8 = source.as_ptr(); let fheader_ptr = src as *const BITMAPFILEHEADER; let fheader: BITMAPFILEHEADER = ptr::read( fheader_ptr ); // Read the bitmap info header let iheader_ptr = src.offset(fheader_size as isize) as *const BITMAPINFOHEADER; let iheader: BITMAPINFOHEADER = ptr::read( iheader_ptr ); let (w, h) = (iheader.biWidth, iheader.biHeight); let screen_dc = GetDC(ptr::null_mut()); let hdc = CreateCompatibleDC(screen_dc); let bitmap = CreateCompatibleBitmap(screen_dc, w, h); ReleaseDC(ptr::null_mut(), screen_dc); let header = BITMAPINFOHEADER { biSize: mem::size_of::<BITMAPINFOHEADER>() as DWORD, biWidth: w as LONG, biHeight: h as LONG, biPlanes: 1, biBitCount: 24, biCompression: BI_RGB, biSizeImage: (w * h * 3) as u32, biXPelsPerMeter: 0, biYPelsPerMeter: 0, biClrUsed: 0, biClrImportant: 0 }; let quad = RGBQUAD { rgbBlue: 0, rgbGreen: 0, rgbRed: 0, rgbReserved: 0 }; let info = BITMAPINFO { bmiHeader: header, bmiColors: [quad], }; let data_ptr = source.as_ptr().offset(fheader.bfOffBits as isize) as *const c_void; if 0 == SetDIBits(hdc, bitmap, 0, h as u32, data_ptr, &info, DIB_RGB_COLORS) { let msg = "SetDIBits failed.".to_string(); return Err(NwgError::ResourceCreationError(msg)); } return Ok(bitmap as HANDLE); } /** Create a bitmap from memory. The source can be any image type supported by the windows imaging component. The memory must contain the whole file (including the file header). */ #[cfg(feature="image-decoder")] pub unsafe fn bitmap_from_memory(src: &[u8]) -> Result<HANDLE, NwgError> { build_image_decoder_from_memory(src, None) } #[cfg(feature="image-decoder")] pub unsafe fn icon_from_memory(src: &[u8], strict: bool, size: Option<(u32, u32)>) -> Result<HANDLE, NwgError> { use winapi::um::wingdi::DeleteObject; use winapi::um::winuser::{LoadImageW, CreateIconIndirect}; use winapi::um::winuser::{ICONINFO, IDI_ERROR, IMAGE_ICON, LR_DEFAULTSIZE, LR_SHARED}; let color_bmp = build_image_decoder_from_memory(src, size); if color_bmp.is_err() { if strict { return color_bmp; } else { let dr = (IDI_ERROR as usize) as *const u16; return Ok(LoadImageW(ptr::null_mut(), dr, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE|LR_SHARED)); } } let color_bmp = color_bmp?; let mut icon_info = ICONINFO { fIcon: 1, xHotspot: 0, yHotspot: 0, hbmMask: color_bmp as _, hbmColor: color_bmp as _ }; let icon = CreateIconIndirect(&mut icon_info); match icon.is_null() { true => match strict { true => Err(NwgError::resource_create("Failed to create icon from source")), false => { let dr = (IDI_ERROR as usize) as *const u16; Ok(LoadImageW(ptr::null_mut(), dr, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE|LR_SHARED)) } }, false => { DeleteObject(color_bmp); Ok(icon as _) } } } #[cfg(not(feature="image-decoder"))] pub unsafe fn icon_from_memory(_src: &[u8], _strict: bool, _size: Option<(u32, u32)>) -> Result<HANDLE, NwgError> { unimplemented!("Loading icons from memory require the \"image-decoder\" feature"); } // // File dialog low level methods // #[cfg(feature = "file-dialog")] pub unsafe fn create_file_dialog<'a, 'b>( action: FileDialogAction, multiselect: bool, default_folder: Option<String>, filters: Option<String> ) -> Result<*mut IFileDialog, NwgError> { use winapi::um::shobjidl_core::{CLSID_FileSaveDialog, CLSID_FileOpenDialog}; use winapi::um::shobjidl::{FOS_PICKFOLDERS, FOS_ALLOWMULTISELECT, FOS_FORCEFILESYSTEM}; use winapi::um::combaseapi::CoCreateInstance; use winapi::shared::{wtypesbase::CLSCTX_INPROC_SERVER, winerror::S_OK}; let (clsid, uuid) = match action { FileDialogAction::Save => (CLSID_FileSaveDialog, IFileDialog::uuidof()), _ => (CLSID_FileOpenDialog, IFileOpenDialog::uuidof()) }; let mut handle: *mut IFileDialog = ptr::null_mut(); let r = CoCreateInstance(&clsid, ptr::null_mut(), CLSCTX_INPROC_SERVER, &uuid, mem::transmute(&mut handle) ); if r != S_OK { return Err(NwgError::file_dialog("Filedialog creation failed")); } let file_dialog = &mut *handle; let mut flags = 0; // Set dialog options if file_dialog.GetOptions(&mut flags) != S_OK { file_dialog.Release(); return Err(NwgError::file_dialog("Filedialog creation failed")); } let use_dir = if action == FileDialogAction::OpenDirectory { FOS_PICKFOLDERS } else { 0 }; let multiselect = if multiselect { FOS_ALLOWMULTISELECT } else { 0 }; if file_dialog.SetOptions(flags | FOS_FORCEFILESYSTEM | use_dir | multiselect) != S_OK { file_dialog.Release(); return Err(NwgError::file_dialog("Filedialog creation failed")); } // Set the default folder match &default_folder { &Some(ref f) => match file_dialog_set_default_folder(file_dialog, f) { Ok(_) => (), Err(e) => { file_dialog.Release(); return Err(e); } }, &None => () } // Set the default filters match &filters { &Some(ref f) => match file_dialog_set_filters(file_dialog, f) { Ok(_) => (), Err(e) => { println!("set filters"); file_dialog.Release(); return Err(e); } }, &None => () } Ok(handle) } #[cfg(feature = "file-dialog")] pub unsafe fn file_dialog_set_default_folder<'a>(dialog: &mut IFileDialog, folder_name: &'a str) -> Result<(), NwgError> { use winapi::um::shobjidl_core::{SFGAOF}; use winapi::um::objidl::IBindCtx; use winapi::shared::{winerror::{S_OK, S_FALSE}, guiddef::REFIID, ntdef::{HRESULT, PCWSTR}}; use winapi::ctypes::c_void; const SFGAO_FOLDER: u32 = 0x20000000; extern "system" { pub fn SHCreateItemFromParsingName(pszPath: PCWSTR, pbc: *mut IBindCtx, riid: REFIID, ppv: *mut *mut c_void) -> HRESULT; } // Code starts here :) let mut shellitem: *mut IShellItem = ptr::null_mut(); let path = to_utf16(&folder_name); if SHCreateItemFromParsingName(path.as_ptr(), ptr::null_mut(), &IShellItem::uuidof(), mem::transmute(&mut shellitem) ) != S_OK { return Err(NwgError::file_dialog("Failed to set default folder")); } let shellitem = &mut *shellitem; let mut file_properties: SFGAOF = 0; let results = shellitem.GetAttributes(SFGAO_FOLDER, &mut file_properties); if results != S_OK && results != S_FALSE { shellitem.Release(); return Err(NwgError::file_dialog("Failed to set default folder")); } if file_properties & SFGAO_FOLDER != SFGAO_FOLDER { shellitem.Release(); return Err(NwgError::file_dialog("Failed to set default folder")); } if dialog.SetDefaultFolder(shellitem) != S_OK { shellitem.Release(); return Err(NwgError::file_dialog("Failed to set default folder")); } shellitem.Release(); Ok(()) } #[cfg(feature = "file-dialog")] pub unsafe fn file_dialog_set_filters<'a>(dialog: &mut IFileDialog, filters: &'a str) -> Result<(), NwgError> { use winapi::shared::minwindef::UINT; use winapi::um::shtypes::COMDLG_FILTERSPEC; use winapi::shared::winerror::S_OK; let mut raw_filters: Vec<COMDLG_FILTERSPEC> = Vec::with_capacity(3); let mut keep_alive: Vec<(Vec<u16>, Vec<u16>)> = Vec::with_capacity(3); for f in filters.split('|') { let end = f.rfind('('); if end.is_none() { let err = format!("Bad extension filter format: {:?}", filters); return Err(NwgError::file_dialog(&err)); } let (_name, _filter) = f.split_at(end.unwrap()); let (name, filter) = (to_utf16(_name), to_utf16(&_filter[1.._filter.len()-1])); raw_filters.push(COMDLG_FILTERSPEC{ pszName: name.as_ptr(), pszSpec: filter.as_ptr() }); keep_alive.push( (name, filter) ); } let filters_count = raw_filters.len() as UINT; if dialog.SetFileTypes(filters_count, raw_filters.as_ptr()) == S_OK { Ok(()) } else { let err = format!("Failed to set the filters using {:?}", filters); return Err(NwgError::file_dialog(&err)); } } #[cfg(feature = "file-dialog")] pub unsafe fn filedialog_get_item(dialog: &mut IFileDialog) -> Result<OsString, NwgError> { use winapi::shared::winerror::S_OK; let mut _item: *mut IShellItem = ptr::null_mut(); if dialog.GetResult(&mut _item) != S_OK { return Err(NwgError::file_dialog("Failed to get dialog item")); } let text = get_ishellitem_path(&mut *_item); (&mut *_item).Release(); text } #[cfg(feature = "file-dialog")] pub unsafe fn filedialog_get_items(dialog: &mut IFileOpenDialog) -> Result<Vec<OsString>, NwgError> { use winapi::um::shobjidl::IShellItemArray; use winapi::shared::{winerror::S_OK, minwindef::DWORD}; let mut _item: *mut IShellItem = ptr::null_mut(); let mut _items: *mut IShellItemArray = ptr::null_mut(); if dialog.GetResults( mem::transmute(&mut _items) ) != S_OK { return Err(NwgError::file_dialog("Failed to get dialog items")); } let items = &mut *_items; let mut count: DWORD = 0; items.GetCount(&mut count); let mut item_names: Vec<OsString> = Vec::with_capacity(count as usize); for i in 0..count { items.GetItemAt(i, &mut _item); match get_ishellitem_path(&mut *_item) { Ok(s) => item_names.push(s), Err(_) => {} } } items.Release(); Ok(item_names) } #[cfg(feature = "file-dialog")] unsafe fn get_ishellitem_path(item: &mut IShellItem) -> Result<OsString, NwgError> { use winapi::um::shobjidl_core::SIGDN_FILESYSPATH; use winapi::shared::{ntdef::PWSTR, winerror::S_OK}; use winapi::um::combaseapi::CoTaskMemFree; use super::base_helper::os_string_from_wide_ptr; let mut item_path: PWSTR = ptr::null_mut(); if item.GetDisplayName(SIGDN_FILESYSPATH, &mut item_path) != S_OK { return Err(NwgError::file_dialog("Failed to get file name")); } let text = os_string_from_wide_ptr(item_path, None); CoTaskMemFree(mem::transmute(item_path)); Ok(text) } #[cfg(feature = "file-dialog")] pub unsafe fn file_dialog_options(dialog: &mut IFileDialog) -> Result<u32, NwgError> { use winapi::shared::winerror::S_OK; let mut flags = 0; if dialog.GetOptions(&mut flags) != S_OK { return Err(NwgError::file_dialog("Failed to get the file dialog options")); } Ok(flags) } #[cfg(feature = "file-dialog")] pub unsafe fn toggle_dialog_flags(dialog: &mut IFileDialog, flag: u32, enabled: bool) -> Result<(), NwgError> { use winapi::shared::winerror::S_OK; let mut flags = file_dialog_options(dialog)?; flags = match enabled { true => flags | flag, false => flags & (!flag) }; if dialog.SetOptions(flags) != S_OK { return Err(NwgError::file_dialog("Failed to set the file dialog options")); } else { Ok(()) } }
use scanner_proc_macro::insert_scanner; use std::collections::VecDeque; #[insert_scanner] fn main() { let n = scan!(usize); let (sy, sx) = scan!((usize, usize)); let (gy, gx) = scan!((usize, usize)); let a: Vec<Vec<char>> = (0..n) .map(|_| { let s = scan!(String); s.chars().collect() }) .collect(); let dirs = [(1, 1), (1, -1), (-1, 1), (-1, -1)]; let inf = std::u64::MAX; let mut d = vec![vec![vec![inf; 5]; n]; n]; let mut que = VecDeque::new(); d[sy - 1][sx - 1][4] = 0; que.push_back(((sy - 1, sx - 1), 4)); while let Some(((y, x), dir)) = que.pop_front() { for (i, &(dy, dx)) in dirs.iter().enumerate() { let ny = y as isize + dy; let nx = x as isize + dx; if ny < 0 || ny >= n as isize || nx < 0 || nx >= n as isize { continue; } let ny = ny as usize; let nx = nx as usize; if a[ny][nx] == '#' { continue; } if dir == i { if d[ny][nx][dir] > d[y][x][dir] { d[ny][nx][dir] = d[y][x][dir]; que.push_front(((ny, nx), dir)); } } else { if d[ny][nx][i] > d[y][x][dir] + 1 { d[ny][nx][i] = d[y][x][dir] + 1; que.push_back(((ny, nx), i)); } } } } let mut ans = inf; for dir in 0..4 { ans = ans.min(d[gy - 1][gx - 1][dir]); } if ans == inf { println!("-1"); } else { println!("{}", ans); } }
use structopt::StructOpt; use crate::auth_access_cmd::AuthAccessCmd; use crate::config_cmd::ConfigCmd; use crate::domain_cmd::DomainCmd; use crate::occurrence_cmd::OccurrenceCmd; use crate::stream_cmd::StreamCmd; use crate::stream_square_cmd::StreamSquareCmd; #[derive(Debug, StructOpt)] #[structopt(name = "Sidemash Cli", about = "Official Cli to interact with Sidemash Cloud Platform", author = "Sidemash Cloud <opensource@sidemash.com>", bin_name="sdm")] pub enum Sdm { Config(ConfigCmd), AuthAccess(AuthAccessCmd), Domain(DomainCmd), Occurrence(OccurrenceCmd), Stream(StreamCmd), #[structopt(alias = "s2")] StreamSquare(StreamSquareCmd) }
#![allow(clippy::all)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(deref_nullptr)] #![allow(unaligned_references)] include!(concat!(env!("OUT_DIR"), "/msfs-sys.rs")); // https://github.com/rustwasm/team/issues/291 extern "C" { pub fn nvgStrokeColor(ctx: *mut NVGcontext, color: *const NVGcolor); pub fn nvgStrokePaint(ctx: *mut NVGcontext, paint: *const NVGpaint); pub fn nvgFillColor(ctx: *mut NVGcontext, color: *const NVGcolor); pub fn nvgFillPaint(ctx: *mut NVGcontext, paint: *const NVGpaint); }
use super::{exception::Exception, value::Value, DynType}; pub enum ListItem { Middle(Value), Last(Value), End, } impl ListItem { pub fn to_middle(self) -> Result<Value, Exception> { match self { ListItem::Middle(value) => Ok(value), ListItem::Last(value) => Err(Exception { thrown_object: Value::new( DynType::Str(format!( "Unexpected part of list. Most be Pair, found {}", value.content )), None, ), traceback: vec![], previous_exception: None, }), ListItem::End => Err(Exception { thrown_object: Value::new(DynType::Str(format!("Unexpected end of list")), None), traceback: vec![], previous_exception: None, }), } } pub fn to_end(self) -> Result<(), Exception> { match self { ListItem::End => Ok(()), ListItem::Middle(value) | ListItem::Last(value) => Err(Exception { thrown_object: Value::new( DynType::Str(format!("Expected end of list, found {}", value.content)), None, ), traceback: vec![], previous_exception: None, }), } } } pub struct List { pub current_value: Value, } impl List { pub fn new(start_value: Value) -> List { List { current_value: start_value, } } pub fn next(&mut self) -> ListItem { let current_value = self.current_value.clone(); match &*current_value.content { DynType::Nil => ListItem::End, DynType::Pair(dot_pair) => { self.current_value = dot_pair.right.clone(); ListItem::Middle(dot_pair.left.clone()) } _ => ListItem::Last(current_value), } } pub fn peek(&self) -> ListItem { let current_value = self.current_value.clone(); match &*current_value.content { DynType::Nil => ListItem::End, DynType::Pair(dot_pair) => ListItem::Middle(dot_pair.left.clone()), _ => ListItem::Last(current_value), } } }
use super::ifaces::LockIface; use std::fmt; use std::{ cell::UnsafeCell, sync::atomic::{spin_loop_hint, AtomicBool, Ordering}, }; use std::{ marker::PhantomData as marker, ops::{Deref, DerefMut}, thread::ThreadId, time::{Duration, Instant}, }; pub struct TTasGuard<'a, T: ?Sized> { mutex: &'a TTas<T>, marker: marker<&'a mut T>, } impl<'a, T: ?Sized + 'a> Deref for TTasGuard<'a, T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &*self.mutex.data.get() } } } impl<'a, T: ?Sized + 'a> DerefMut for TTasGuard<'a, T> { #[inline] fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.mutex.data.get() } } } impl<'a, T: ?Sized + 'a> Drop for TTasGuard<'a, T> { #[inline] fn drop(&mut self) { self.mutex.unlock(); } } impl<'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for TTasGuard<'a, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } impl<'a, T: fmt::Display + ?Sized + 'a> fmt::Display for TTasGuard<'a, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (**self).fmt(f) } } pub struct TTas<T> where T: ?Sized, { tid: ThreadId, acquired: AtomicBool, data: UnsafeCell<T>, } impl<T> TTas<T> { #[inline] pub fn new(data: T) -> Self { Self { tid: std::thread::current().id(), acquired: AtomicBool::default(), data: UnsafeCell::new(data), } } #[inline] pub fn into_inner(self) -> T { self.data.into_inner() } #[inline] pub fn get_mut(&mut self) -> &mut T { unsafe { &mut *self.data.get() } } #[inline] unsafe fn guard(&self) -> TTasGuard<'_, T> { TTasGuard { mutex: self, marker, } } #[inline] pub fn lock(&self) -> TTasGuard<'_, T> { // TODO: dispatch directly <Self as LockIface>::lock(self); // SAFETY: The lock is held, as required. unsafe { self.guard() } } #[inline] pub fn try_lock(&self) -> Option<TTasGuard<'_, T>> { if <Self as LockIface>::try_lock(self) { // SAFETY: The lock is held, as required. Some(unsafe { self.guard() }) } else { None } } #[inline] pub unsafe fn force_unlock(&self) { <Self as LockIface>::unlock(&self); } #[inline] pub fn try_write_lock_for(&self, timeout: Duration) -> Option<TTasGuard<'_, T>> { let deadline = Instant::now() .checked_add(timeout) .expect("Deadline can't fit in"); loop { if Instant::now() < deadline { match self.try_lock() { Some(guard) => { break Some(guard); } _ => { std::thread::sleep(timeout / 10); std::thread::yield_now() } }; } else { break None; } } } #[inline] pub fn is_current(&self) -> bool { std::thread::current().id() == self.tid } } unsafe impl<T: ?Sized + Send> Send for TTas<T> {} unsafe impl<T: ?Sized + Send> Sync for TTas<T> {} unsafe impl<T> LockIface for TTas<T> where T: ?Sized, { #[inline] fn lock(&self) { 'lock: loop { while let Some(true) = Some(self.acquired.load(Ordering::SeqCst)) { spin_loop_hint(); } if !self.acquired.swap(true, Ordering::SeqCst) { break 'lock; } } } #[inline] fn try_lock(&self) -> bool { self.acquired .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) .is_ok() } #[inline] fn is_locked(&self) -> bool { self.acquired.load(Ordering::Acquire) } #[inline] fn unlock(&self) { self.acquired.store(false, Ordering::Release); } #[inline] fn try_unlock(&self) -> bool { self.acquired .compare_exchange_weak(true, false, Ordering::Acquire, Ordering::Relaxed) .is_ok() } } #[cfg(test)] mod test_ttas { use super::*; #[test] fn ttas_create_and_lock() { let ttas = TTas::new(42); let data = ttas.try_lock(); assert!(data.is_some()); assert_eq!(*data.unwrap(), 42); } #[test] fn mutual_exclusion() { let ttas = TTas::new(1); let data = ttas.try_lock(); assert!(data.is_some()); assert!(ttas.try_lock().is_none()); assert!(ttas.try_lock().is_none()); core::mem::drop(data); assert!(ttas.try_lock().is_some()); } #[test] fn three_locks() { let ttas1 = TTas::new(1); let ttas2 = TTas::new(2); let ttas3 = TTas::new(3); let data1 = ttas1.try_lock(); let data2 = ttas2.try_lock(); let data3 = ttas3.try_lock(); assert!(data1.is_some()); assert!(data2.is_some()); assert!(data3.is_some()); assert!(ttas1.try_lock().is_none()); assert!(ttas1.try_lock().is_none()); assert!(ttas2.try_lock().is_none()); assert!(ttas2.try_lock().is_none()); assert!(ttas3.try_lock().is_none()); assert!(ttas3.try_lock().is_none()); core::mem::drop(data3); assert!(ttas3.try_lock().is_some()); } }
use std::time::Duration; use libsystemd::daemon::{notify, NotifyState, watchdog_enabled}; use futures::prelude::*; #[cfg(feature = "tokio-core")] use tokio_core::reactor::{PollEvented, Handle}; #[cfg(feature = "tokio")] use tokio::reactor::{PollEvented2, Handle}; #[cfg(feature = "tokio")] use mio::Ready; use std::{io, mem}; use super::timer::LinuxTimer; use super::error::Error; #[cfg(feature = "tokio-core")] #[derive(Debug)] struct Timer(PollEvented<LinuxTimer>); #[cfg(feature = "tokio-core")] impl Timer { fn start(tick: Duration, reactor_data: &ReactorData) -> io::Result<Timer> { Ok(Timer(PollEvented::new(LinuxTimer::new(tick)?, &reactor_data.0)?)) } fn poll(&mut self) -> io::Result<bool> { match self.0.poll_read() { Async::Ready(()) => { let ret = self.0.get_mut().read() > 0; self.0.need_read(); Ok(ret) }, Async::NotReady => Ok(false), } } } #[cfg(feature = "tokio-core")] #[derive(Debug)] struct ReactorData(Handle); #[cfg(feature = "tokio")] #[derive(Debug)] struct Timer(PollEvented2<LinuxTimer>); #[cfg(feature = "tokio")] impl Timer { fn start(tick: Duration, reactor_data: &ReactorData) -> io::Result<Timer> { let timer = LinuxTimer::new(tick)?; match reactor_data.0 { Some(ref handle) => Ok(Timer(PollEvented2::new_with_handle(timer, handle)?)), None => Ok(Timer(PollEvented2::new(timer))), } } fn poll(&mut self) -> io::Result<bool> { match self.0.poll_read_ready(Ready::readable()) { Ok(Async::Ready(ready)) => { if ready.is_readable() { let ret = self.0.get_mut().read() > 0; self.0.clear_read_ready(Ready::readable())?; Ok(ret) } else { Ok(false) } }, Ok(Async::NotReady) => Ok(false), Err(err) => Err(err), } } } #[cfg(feature = "tokio")] #[derive(Debug)] struct ReactorData(Option<Handle>); #[derive(Debug)] enum SystemdNotifierInner { Starting { reactor_data: ReactorData }, Running { watchdog_timer: Timer }, } /// A future for notifying systemd about daemon startup and pinging the watchdog. /// /// When first polled, this future will notify systemd that daemon startup has completed. /// If the systemd watchdog is disabled for this service, the future will then complete /// successfully. Otherwise, it will ping the watchdog until the main loop shuts down. /// /// If the application was not started with systemd or notify access was not enabled, /// this future will complete with [`Error::NotRunningWithSystemd`](enum.Error.html#variant.NotRunningWithSystemd). /// To ensure that the daemon works properly with or without systemd, this error should be silently ignored. #[derive(Debug)] pub struct SystemdNotifier(SystemdNotifierInner); impl SystemdNotifier { /// Creates a new SystemdNotifier. #[cfg(feature = "tokio-core")] pub fn new(handle: &Handle) -> SystemdNotifier { SystemdNotifier(SystemdNotifierInner::Starting { reactor_data: ReactorData(handle.clone()), }) } /// Creates a new SystemdNotifier using the default reactor. #[cfg(feature = "tokio")] pub fn new() -> SystemdNotifier { SystemdNotifier(SystemdNotifierInner::Starting { reactor_data: ReactorData(None), }) } /// Creates a new SystemdNotifier. #[cfg(feature = "tokio")] pub fn new_with_handle(handle: &Handle) -> SystemdNotifier { SystemdNotifier(SystemdNotifierInner::Starting { reactor_data: ReactorData(Some(handle.clone())), }) } fn notify_ready() -> bool { notify(false, &[NotifyState::Ready]).unwrap_or(false) } fn ping_watchdog(timer: &mut Timer) -> io::Result<()> { if timer.poll()? { let _ = notify(false, &[NotifyState::Watchdog]); } Ok(()) } } impl Future for SystemdNotifier { type Item = (); type Error = Error; fn poll(&mut self) -> Poll<(), Error> { let mut watchdog_timer = { let (watchdog_tick, reactor_data) = match self.0 { SystemdNotifierInner::Starting{ ref reactor_data } => { if Self::notify_ready() { if let Some(watchdog_tick) = watchdog_enabled(false) { (watchdog_tick, reactor_data) } else { // Watchdog timer is not enabled return Ok(Async::Ready(())); } } else { // We are not running with systemd, or our service // has NotifyAccess disabled. return Err(Error::NotRunningWithSystemd) } }, SystemdNotifierInner::Running { ref mut watchdog_timer } => { Self::ping_watchdog(watchdog_timer)?; return Ok(Async::NotReady); }, }; Timer::start(watchdog_tick / 2, &reactor_data)? }; Self::ping_watchdog(&mut watchdog_timer)?; mem::replace(&mut self.0, SystemdNotifierInner::Running { watchdog_timer }); Ok(Async::NotReady) } }
use crate::errors::ServiceError; use crate::models::msg::Msg; use crate::schema::order; use crate::utils::validator::Validate; use actix::Message; use actix_web::error; use actix_web::Error; use diesel; use uuid::Uuid; #[derive(Deserialize, Serialize, Debug, Message, Identifiable, AsChangeset)] #[rtype(result = "Result<Msg, ServiceError>")] #[table_name = "order"] pub struct Update { pub id: i32, pub shop_id: Uuid, pub state: i32, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InpUpdate { pub id: i32, pub shop_id: Uuid, pub state: i32, } impl Validate for InpUpdate { fn validate(&self) -> Result<(), Error> { let check_name = true; if check_name { Ok(()) } else { Err(error::ErrorBadRequest("option name")) } } } impl InpUpdate { pub fn new(&self, shop_id: Uuid) -> Update { Update { id: self.id, shop_id: shop_id, state: self.state.clone(), } } } #[derive(Deserialize, Serialize, Debug, Message, Identifiable)] #[rtype(result = "Result<Msg, ServiceError>")] #[table_name = "order"] pub struct Get { pub id: i32, pub shop_id: Uuid, } #[derive(Deserialize, Serialize, Debug, Message)] #[rtype(result = "Result<Msg, ServiceError>")] pub struct GetList { pub shop_id: Uuid, } use diesel::sql_types::{Integer, Json, Text, Uuid as uu}; #[derive(Clone, Debug, Serialize, Deserialize, QueryableByName)] pub struct Simple { #[sql_type = "Integer"] pub id: i32, #[sql_type = "uu"] pub shop_id: Uuid, #[sql_type = "Text"] pub name: String, #[sql_type = "Integer"] pub default: i32, #[sql_type = "Json"] pub option_list: serde_json::Value, } #[derive(Deserialize, Serialize, Debug, Message)] #[rtype(result = "Result<Msg, ServiceError>")] pub struct NowList { pub shop_id: Uuid, }
use serde::{Deserialize, Serialize}; #[repr(C)] #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CodeImport { pub name: String, pub import: String, pub source: String, }