blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
140
path
stringlengths
5
183
src_encoding
stringclasses
6 values
length_bytes
int64
12
5.32M
score
float64
2.52
4.94
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
12
5.32M
download_success
bool
1 class
8f52291035a654c2f0ae187dc1dd00fd2ac241d5
Rust
rfaulhaber/pluv
/src/client/client.rs
UTF-8
1,016
3.0625
3
[ "MIT" ]
permissive
use super::darksky::DarkSkyClient; use std::error; use std::fmt; pub enum ClientType { DarkSky { api_key: String }, } pub enum ForecastClient { DarkSkyClient(DarkSkyClient), } impl ForecastClient { pub fn get_current_weather(&mut self, latitude: f64, longitude: f64) -> Forecast { match self { ForecastClient::DarkSkyClient(ds) => ds.get_current_weather(latitude, longitude), } } } #[derive(Debug)] pub struct Forecast { pub current_temp: String, } pub struct Currently {} pub struct Weekly {} pub struct Hourly {} pub struct Daily {} // TODO implement better display! impl std::fmt::Display for Forecast { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "current temperature: {}", self.current_temp) } } pub fn new_client(clientType: ClientType) -> ForecastClient { match clientType { ClientType::DarkSky { api_key: key } => { ForecastClient::DarkSkyClient(DarkSkyClient::new(key)) } } }
true
3b09f48960952a66626c2e76e36030bec4f60658
Rust
jkbstrmen/snark-tool
/src/service/component_analysis/vertex_pairs.rs
UTF-8
1,877
3.234375
3
[ "Apache-2.0", "MIT" ]
permissive
use crate::graph::graph::Graph; use crate::graph::vertex::Vertex; /// /// de-facto list of edges for simple graph with undirected edges /// pub struct PairsOfAdjacentVertices<'a, V: Vertex, G: Graph> { first_vertex_iterator: Box<dyn Iterator<Item = &'a V> + 'a>, second_vertex_iterator: Box<dyn Iterator<Item = &'a V> + 'a>, first_vertex_current: Option<&'a V>, graph: &'a G, } impl<'a, V: Vertex, G: Graph<V = V>> Iterator for PairsOfAdjacentVertices<'a, V, G> { type Item = (&'a V, &'a V); fn next(&mut self) -> Option<Self::Item> { if self.first_vertex_current.is_none() { self.first_vertex_current = self.first_vertex_iterator.next(); } while let Some(first_vertex) = self.first_vertex_current { while let Some(second_vertex) = self.second_vertex_iterator.next() { if first_vertex.index().eq(&second_vertex.index()) { continue; } if first_vertex.index() > second_vertex.index() { continue; } if self .graph .has_edge(first_vertex.index(), second_vertex.index()) { return Some((first_vertex, second_vertex)); } } // renew second edge iterator to original value self.second_vertex_iterator = self.graph.vertices(); self.first_vertex_current = self.first_vertex_iterator.next(); } None } } impl<'a, V: Vertex, G: Graph<V = V>> PairsOfAdjacentVertices<'a, V, G> { pub fn new(graph: &'a G) -> Self { PairsOfAdjacentVertices { first_vertex_iterator: graph.vertices(), second_vertex_iterator: graph.vertices(), first_vertex_current: None, graph, } } }
true
191f32d7f58094276529e2668f7c98a76fe22239
Rust
zoosky/rust-yew-realworld-example-app
/crates/conduit-wasm/src/routes/editor.rs
UTF-8
10,942
2.765625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use yew::services::fetch::FetchTask; use yew::{ agent::Bridged, html, Bridge, Callback, Component, ComponentLink, FocusEvent, Html, InputData, KeyboardEvent, Properties, ShouldRender, }; use yew_router::{agent::RouteRequest::ChangeRoute, prelude::*}; use crate::components::list_errors::ListErrors; use crate::error::Error; use crate::routes::AppRoute; use crate::services::Articles; use crate::types::{ArticleCreateUpdateInfo, ArticleCreateUpdateInfoWrapper, ArticleInfoWrapper}; /// Create or update an article pub struct Editor { articles: Articles, error: Option<Error>, request: ArticleCreateUpdateInfo, tag_input: String, response: Callback<Result<ArticleInfoWrapper, Error>>, loaded: Callback<Result<ArticleInfoWrapper, Error>>, task: Option<FetchTask>, props: Props, router_agent: Box<dyn Bridge<RouteAgent>>, link: ComponentLink<Self>, } #[derive(Properties, Clone)] pub struct Props { #[prop_or_default] pub slug: Option<String>, } pub enum Msg { Request, Response(Result<ArticleInfoWrapper, Error>), Loaded(Result<ArticleInfoWrapper, Error>), Ignore, UpdateTitle(String), UpdateDescription(String), UpdateBody(String), UpdateTagInput(String), AddTag, RemoveTag(String), } impl Component for Editor { type Message = Msg; type Properties = Props; fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self { Editor { articles: Articles::new(), error: None, request: ArticleCreateUpdateInfo::default(), tag_input: String::default(), response: link.callback(Msg::Response), loaded: link.callback(Msg::Loaded), task: None, props, router_agent: RouteAgent::bridge(link.callback(|_| Msg::Ignore)), link, } } fn rendered(&mut self, first_render: bool) { if first_render { if let Some(slug) = &self.props.slug { self.task = Some(self.articles.get(slug.clone(), self.loaded.clone())); } } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::AddTag => { // Add a new tag if let Some(tag_list) = &mut self.request.tag_list { if !tag_list.contains(&self.tag_input) { tag_list.push(self.tag_input.clone()); } } else { self.request.tag_list = Some(vec![self.tag_input.clone()]); } // Clear tag input self.tag_input = String::default(); } Msg::Ignore => {} Msg::RemoveTag(tag) => { // Remove a tag if let Some(tag_list) = &mut self.request.tag_list { tag_list.retain(|t| t != &tag); } } Msg::Request => { let request = ArticleCreateUpdateInfoWrapper { article: self.request.clone(), }; // Update or create an article if let Some(slug) = &self.props.slug { self.task = Some(self.articles.update( slug.clone(), request, self.response.clone(), )); } else { self.task = Some(self.articles.create(request, self.response.clone())); } } Msg::Response(Ok(article_info)) => { self.error = None; self.task = None; self.router_agent.send(ChangeRoute( AppRoute::Article(article_info.article.slug).into(), )); } Msg::Response(Err(err)) => { self.error = Some(err); self.task = None; } Msg::Loaded(Ok(article_info)) => { self.error = None; self.task = None; // Load the article to editor form self.request = ArticleCreateUpdateInfo { title: article_info.article.title, description: article_info.article.description, body: article_info.article.body, tag_list: Some(article_info.article.tag_list), }; } Msg::Loaded(Err(err)) => { self.error = Some(err); self.task = None; } Msg::UpdateBody(body) => { self.request.body = body; } Msg::UpdateDescription(description) => { self.request.description = description; } Msg::UpdateTagInput(tag_input) => { self.tag_input = tag_input; } Msg::UpdateTitle(title) => { self.request.title = title; } } true } fn change(&mut self, props: Self::Properties) -> ShouldRender { self.props = props; true } fn view(&self) -> Html { let onsubmit = self.link.callback(|ev: FocusEvent| { ev.prevent_default(); Msg::Request }); let oninput_title = self .link .callback(|ev: InputData| Msg::UpdateTitle(ev.value)); let oninput_description = self .link .callback(|ev: InputData| Msg::UpdateDescription(ev.value)); let oninput_body = self .link .callback(|ev: InputData| Msg::UpdateBody(ev.value)); let oninput_tag = self .link .callback(|ev: InputData| Msg::UpdateTagInput(ev.value)); let onkeypress = self.link.callback(|ev: KeyboardEvent| { // Prevent submit the form when press Enter if ev.code() == "Enter" { ev.prevent_default(); } Msg::Ignore }); let onkeyup = self.link.callback(|ev: KeyboardEvent| { // Add a new tag when press Enter if ev.code() == "Enter" { ev.prevent_default(); Msg::AddTag } else { Msg::Ignore } }); html! { <div class="editor-page"> <div class="container page"> <div class="row"> <div class="col-md-10 offset-md-1 col-xs-12"> <ListErrors error=&self.error /> <form onsubmit=onsubmit> <fieldset> <fieldset class="form-group"> <input class="form-control form-control-lg" type="text" placeholder="Article Title" value={ &self.request.title } oninput=oninput_title /> </fieldset> <fieldset class="form-group"> <input class="form-control" type="text" placeholder="What's this article about?" value={ &self.request.description } oninput=oninput_description /> </fieldset> <fieldset class="form-group"> <textarea class="form-control" rows="8" placeholder="Write your article (in markdown)" value={ &self.request.body} oninput=oninput_body > </textarea> </fieldset> <fieldset class="form-group"> <input class="form-control" type="text" placeholder="Enter tags" value={ &self.tag_input } oninput=oninput_tag onkeypress=onkeypress onkeyup=onkeyup /> <div class="tag-list"> { if let Some(tag_list) = &self.request.tag_list { html! {for tag_list.iter().map(|tag| { let tag_to_remove = tag.clone(); let onclick_remove = self.link.callback(move |ev| Msg::RemoveTag(tag_to_remove.to_string())); html! { <span class="tag-default tag-pill"> <i class="ion-close-round" onclick=onclick_remove> </i> { &tag } </span> } })} } else { html! {} } } </div> </fieldset> <button class="btn btn-lg pull-xs-right btn-primary" type="submit" disabled=false> { "Publish Article" } </button> </fieldset> </form> </div> </div> </div> </div> } } }
true
bbe7165cdffa742a7ded7f59623a6bfb5c38e092
Rust
cowboy8625/ggezLife
/src/main.rs
UTF-8
5,199
2.515625
3
[]
no_license
mod game; mod grid; mod commands; mod game_event; use ggez::{input::mouse::MouseButton, GameResult, Context, event, event::KeyCode, graphics}; use game::Game; use commands::{key_mapper, Mapper}; use grid::Grid; const WINDOW: CellPoint<i32> = CellPoint { x:1400, y:800 }; const GRID: i32 = 2; const CELL: CellPoint<i32> = CellPoint { x: WINDOW.x / GRID, y: WINDOW.y / GRID, }; const LIMITS: CellPoint<i32> = CellPoint { x: 2, y: 100 }; const STEP: i32 = 2; #[derive(Clone)] struct CellPoint<T> { x: T, y: T, } struct Mouse { left: bool, middle: bool, } struct GameState { game: Game, key: Mapper, mouse: Mouse, } impl GameState { pub fn new() -> Self { Self { game: Game::new(), key: key_mapper(), mouse: Mouse { left: false, middle: false }, } } } impl event::EventHandler for GameState { fn update(&mut self, ctx: &mut Context) -> GameResult { self.game.make_screen(); if self.mouse.left { let pos = ggez::input::mouse::position(ctx); self.game.place_cell(pos.x as i32, pos.y as i32); // TODO: make line pattern. self.game.add_point((pos.x, pos.y)); } if self.mouse.middle { let pos = ggez::input::mouse::position(ctx); dbg!(pos); } self.game.update(); Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult { graphics::clear(ctx, [1.0, 1.0, 1.0, 1.0].into()); display_board(ctx, &self.game.screen, self.game.grid)?; graphics::present(ctx)?; ggez::timer::yield_now(); Ok(()) } fn key_down_event(&mut self, ctx: &mut Context, keycode: KeyCode, _keymod: ggez::input::keyboard::KeyMods, _repeat: bool) { if let Some(event) = self.key.get(keycode) { self.game.key_event(event); } if let KeyCode::Escape = keycode { event::quit(ctx); } } fn mouse_button_down_event( &mut self, _ctx: &mut Context, button: MouseButton, _x: f32, _y: f32 ) { if let MouseButton::Left = button { self.mouse.left = true; } if let MouseButton::Middle = button { self.mouse.middle = true; } } fn mouse_button_up_event( &mut self, _ctx: &mut Context, button: MouseButton, _x: f32, _y: f32 ) { if let MouseButton::Left = button { self.mouse.left = false; } if let MouseButton::Middle = button { self.mouse.middle = false; } } fn mouse_wheel_event(&mut self, _ctx: &mut Context, _x: f32, y: f32) { use game_event::GameEvent::{ZoomIn, ZoomOut}; if y > 0.0 { self.game.key_event(ZoomOut); } else if y < 0.0 { self.game.key_event(ZoomIn); } } } fn main() -> GameResult { let (mut ctx, mut event_loop) = ggez::ContextBuilder::new("life", "Cowboy8625") .window_setup(ggez::conf::WindowSetup::default().title("Game Of Life")) .window_mode(ggez::conf::WindowMode::default().dimensions(WINDOW.x as f32, WINDOW.y as f32)) .build().expect("Failed to build ggez context"); let state = &mut GameState::new(); event::run(&mut ctx, &mut event_loop, state)?; // game.place_cell(mouse.x(), mouse.y(), mouse.left()); Ok(()) } fn display_board(ctx: &mut Context, cells: &Grid, grid: i32) -> GameResult { let mut meshbuilder = graphics::MeshBuilder::new(); let mut count = 0; for y in 0..cells.height { for x in 0..cells.width { if cells[y][x] { meshbuilder.rectangle( graphics::DrawMode::fill(), graphics::Rect::new_i32(x as i32 * grid, y as i32 * grid, grid, grid), [0.0, 0.0, 0.0, 1.0].into(), ); count += 1; } } } if count > 0 { let mesh = meshbuilder.build(ctx)?; graphics::draw(ctx, &mesh, graphics::DrawParam::default())?; } Ok(()) } fn alive(x: i32, y: i32, v: &Grid) -> bool { let n = cell_count(x as usize, y as usize, v); let curr = v[y as usize][x as usize] as i32; match (curr, n) { (1, 0..=1) => false, (1, 4..=8) => false, (1, 2..=3) => true, (0, 3) => true, (0, 0..=2) => false, (0, 4..=8) => false, _ => panic!("alive: error in match"), } } fn inc_x(n: usize) -> usize { (n + 1) % CELL.x as usize } fn dec_x(n: usize) -> usize { if n == 0 { CELL.x as usize - 1 } else { (n - 1) as usize } } fn inc_y(n: usize) -> usize { (n + 1) % CELL.y as usize } fn dec_y(n: usize) -> usize { if n == 0 { CELL.y as usize - 1 } else { n - 1 } } fn cell_count(x: usize, y: usize, v: &Grid) -> i32 { v[dec_y(y)][x] as i32 + v[inc_y(y)][x] as i32 + v[y][dec_x(x)] as i32 + v[y][inc_x(x)] as i32 + v[dec_y(y)][dec_x(x)] as i32 + v[dec_y(y)][inc_x(x)] as i32 + v[inc_y(y)][inc_x(x)] as i32 + v[inc_y(y)][dec_x(x)] as i32 }
true
451bf20341229e1ab0451b902b036f86a38346c2
Rust
wookievx/advent-of-code-2020
/rust/src/day2.rs
UTF-8
1,837
3.09375
3
[]
no_license
extern crate nom; use nom::{ IResult, bytes::complete::tag, combinator::map_res}; use nom::sequence::separated_pair; use nom::bytes::complete::take_while; use nom::sequence::preceded; use nom::bytes::complete::take; use nom::AsChar; pub struct Password { min_req: u16, max_req: u16, character: char, content: String } pub fn solve(input: &Vec<Password>) -> usize { input .iter() .filter(|p| { let count = p.content.as_str().matches(|c: char| c == p.character).count(); let res = usize::from(p.min_req) <= count && count <= usize::from(p.max_req); res }) .count() } pub fn solve_adv(input: &Vec<Password>) -> usize { input .iter() .filter(|p| { let chars: Vec<char> = p.content.chars().collect(); let res = (chars[usize::from(p.min_req) - 1] == p.character) ^ (chars[usize::from(p.max_req) - 1] == p.character); res }) .count() } pub fn parse_input(input: Vec<String>) -> Vec<Password> { input .iter() .map(|contents| parse_line(contents.as_str()).unwrap().1) .collect() } fn parse_line(input: &str) -> IResult<&str, Password> { let (input, (min_req, max_req)) = separated_pair(parse_number, tag("-"), parse_number)(input)?; let (_, (character, content)) = preceded(take_while(|c: char| c.is_whitespace()), separated_pair(take(1usize), tag(": "), take_rest))(input)?; IResult::Ok(("", Password { min_req, max_req, character: character.chars().next().unwrap(), content: content.to_string() })) } fn parse_number(input: &str) -> IResult<&str, u16> { map_res(take_while(|c: char| c.is_dec_digit()), |s: &str| s.parse::<u16>())(input) } fn take_rest(input: &str) -> IResult<&str, &str> { IResult::Ok(("", input)) }
true
3a70d0024e940942d8ead84f8364222306c34b77
Rust
javiercode/gb
/src/cpu.rs
UTF-8
55,647
2.703125
3
[]
no_license
use crate::bus::Bus; use anyhow::{bail, Result}; use bitfield::bitfield; use bitmatch::bitmatch; use rustyline::Editor; bitfield! { #[derive(Default)] struct F(u8); impl Debug; c, set_c: 4; h, set_h: 5; n, set_n: 6; z, set_z: 7; } pub struct Cpu { a: u8, f: F, bc: u16, de: u16, hl: u16, sp: u16, pc: u16, stalls: u8, ime: bool, halt: bool, stepping: bool, pub breakpoints: Vec<u16>, rl: Editor<()>, trace_left: u64, pub bus: Bus, } impl Cpu { pub fn new(bus: Bus, rl: Editor<()>) -> Self { Cpu { a: 0, f: Default::default(), bc: 0, de: 0, hl: 0, sp: 0, pc: 0, stalls: 0, ime: false, halt: false, stepping: true, breakpoints: Vec::new(), rl, // trace_left: 300000, trace_left: 0, bus, } } pub fn reset(&mut self) -> Result<()> { self.a = 0x01; self.f = F(0xB0); self.bc = 0x0013; self.de = 0x00D8; self.hl = 0x014D; self.sp = 0xFFFE; self.pc = 0x0100; self.stalls = 0; Ok(()) } pub fn tick(&mut self) -> Result<()> { if self.stalls > 0 { self.stalls -= 1; return Ok(()); } self.stalls += 4; if self.ime { if let Some(mnemonic) = self.interrupt()? { // println!("{}: IE={:?}", mnemonic, self.bus.ie); self.ime = false; self.halt = false; } } if self.halt { return Ok(()); } let opecode = self.bus.read(self.pc)?; let step = self.stepping || self.breakpoints.contains(&self.pc); let trace = self.trace_left > 0; if step { println!( "PC: {:#04X}, OPECODE: {:#02X}, A: {:#02X}, BC: {:#04X}, DE: {:#04X}, HL: {:#04X}, SP: {:#04X} FLAGS: {:?}, IE: {:?}, IRQ: {}", self.pc, opecode, self.a, self.bc, self.de, self.hl, self.sp, self.f, self.bus.ie, self.bus.read_irq().map_or("ERR".to_string(), |v| format!("{:#02X}", v)), ); } if self.trace_left > 0 { self.trace_left -= 1; if self.trace_left == 0 { self.debug_break(); } } if step { self.debug_break(); } self.pc = self.pc.wrapping_add(1); let mnemonic = self.do_mnemonic(opecode)?; if step { println!("{}", mnemonic); } if trace { println!("A: {:02X} F: {:02X} B: {:02X} C: {:02X} D: {:02X} E: {:02X} H: {:02X} L: {:02X} SP: {:04X} PC: {:04X} | {:04X}: {}", self.a, self.f.0, self.b(), self.c(), self.d(), self.e(), self.h(), self.l(), self.sp, self.pc, opecode, mnemonic ); } Ok(()) } pub fn b(&self) -> u8 { ((self.bc & 0xFF00) >> 8) as u8 } pub fn c(&self) -> u8 { (self.bc & 0x00FF) as u8 } pub fn d(&self) -> u8 { ((self.de & 0xFF00) >> 8) as u8 } pub fn e(&self) -> u8 { (self.de & 0x00FF) as u8 } pub fn h(&self) -> u8 { ((self.hl & 0xFF00) >> 8) as u8 } pub fn l(&self) -> u8 { (self.hl & 0x00FF) as u8 } fn af(&self) -> u16 { ((self.a as u16) << 8) | (self.f.0 as u16) } fn set_b(&mut self, val: u8) { self.bc &= 0x00FF; self.bc |= ((val as u16) << 8) as u16; } fn set_c(&mut self, val: u8) { self.bc &= 0xFF00; self.bc |= val as u16; } fn set_d(&mut self, val: u8) { self.de &= 0x00FF; self.de |= ((val as u16) << 8) as u16; } fn set_e(&mut self, val: u8) { self.de &= 0xFF00; self.de |= val as u16; } fn set_h(&mut self, val: u8) { self.hl &= 0x00FF; self.hl |= ((val as u16) << 8) as u16; } fn set_l(&mut self, val: u8) { self.hl &= 0xFF00; self.hl |= val as u16; } fn set_af(&mut self, val: u16) { self.a = (val >> 8) as u8; self.f.0 = (val & 0x00F0) as u8; } fn r8(&mut self, index: u8) -> Result<u8> { match index { 0 => Ok(self.b()), 1 => Ok(self.c()), 2 => Ok(self.d()), 3 => Ok(self.e()), 4 => Ok(self.h()), 5 => Ok(self.l()), 6 => self.bus.read(self.hl), 7 => Ok(self.a), _ => bail!("unknown r8 {}", index), } } fn r8_str(&self, index: u8) -> String { match index { 0 => "B".to_string(), 1 => "C".to_string(), 2 => "D".to_string(), 3 => "E".to_string(), 4 => "H".to_string(), 5 => "L".to_string(), 6 => format!("{:#04X}", self.hl), 7 => "A".to_string(), _ => "?".to_string(), } } fn set_r8(&mut self, index: u8, val: u8) -> Result<()> { match index { 0 => { self.set_b(val); Ok(()) } 1 => { self.set_c(val); Ok(()) } 2 => { self.set_d(val); Ok(()) } 3 => { self.set_e(val); Ok(()) } 4 => { self.set_h(val); Ok(()) } 5 => { self.set_l(val); Ok(()) } 6 => self.bus.write(self.hl, val), 7 => { self.a = val; Ok(()) } _ => bail!("unknown r8 {}", index), } } fn r16(&self, index: u8, high: bool) -> Result<u16> { match index { 0 => Ok(self.bc), 1 => Ok(self.de), 2 => Ok(self.hl), 3 if high => Ok(self.af()), 3 if !high => Ok(self.sp), _ => bail!("unknown r16 {}", index), } } fn r16_str(&self, index: u8, high: bool) -> String { match index { 0 => "BC".to_string(), 1 => "DE".to_string(), 2 => "HL".to_string(), 3 if high => "AF".to_string(), 3 if !high => "SP".to_string(), _ => "??".to_string(), } } fn set_r16(&mut self, index: u8, val: u16, high: bool) -> Result<()> { match index { 0 => { self.bc = val; Ok(()) } 1 => { self.de = val; Ok(()) } 2 => { self.hl = val; Ok(()) } 3 if high => { self.set_af(val); Ok(()) } 3 if !high => { self.sp = val; Ok(()) } _ => bail!("unknown r16 {}", index), } } fn carry_positive(&self, left: u8, right: u8) -> bool { left.overflowing_add(right).1 } fn carry_negative(&self, left: u8, right: u8) -> bool { left.overflowing_sub(right).1 } fn half_carry_positive(&self, left: u8, right: u8) -> bool { (left & 0x0F) + (right & 0x0F) > 0x0F } fn half_carry_negative(&self, left: u8, right: u8) -> bool { (left & 0x0F) < (right & 0x0F) } fn carry_positive_16(&self, left: u16, right: u16) -> bool { left.overflowing_add(right).1 } fn half_carry_positive_16(&self, left: u16, right: u16) -> bool { (left & 0x00FF) + (right & 0x00FF) > 0x00FF } fn half_carry_positive_16_12(&self, left: u16, right: u16) -> bool { (left & 0x0FFF) + (right & 0x0FFF) > 0x0FFF } fn interrupt(&mut self) -> Result<Option<String>> { let mut int = 0x0040; if self.bus.ie.v_blank() && self.bus.irq_v_blank() { self.bus.set_irq_v_blank(false); self.call(int)?; return Ok(Some(format!("INT {:02X}h", int))); } int += 0x0008; if self.bus.ie.lcd_stat() && self.bus.irq_lcd_stat() { self.bus.set_irq_lcd_stat(false); self.call(int)?; return Ok(Some(format!("INT {:02X}h", int))); } int += 0x0008; if self.bus.ie.timer() && self.bus.irq_timer() { self.bus.set_irq_timer(false); self.call(int)?; return Ok(Some(format!("INT {:02X}h", int))); } int += 0x0008; if self.bus.ie.serial() && self.bus.irq_serial() { self.bus.set_irq_serial(false); self.call(int)?; return Ok(Some(format!("INT {:02X}h", int))); } int += 0x0008; if self.bus.ie.joypad() && self.bus.irq_joypad() { self.bus.set_irq_joypad(false); self.call(int)?; return Ok(Some(format!("INT {:02X}h", int))); } Ok(None) } #[bitmatch] fn do_mnemonic(&mut self, opecode: u8) -> Result<String> { #[bitmatch] match &opecode { // NOP "00000000" => self.nop(), // HALT "01110110" => self.halt(), // STOP "00010000" => self.stop(), // DI "11110011" => self.di(), // EI "11111011" => self.ei(), // LD r, r' // LD r, (HL) // LD (HL), r "01xxxyyy" => self.load_8_r_r(x, y), // LD r, n // LD (HL), n "00xxx110" => self.load_8_r_im8(x), // LD A, (BC) "00001010" => self.load_8_a_addr_bc(), // LD A, (DE) "00011010" => self.load_8_a_addr_de(), // LD (BC), A "00000010" => self.load_8_addr_bc_a(), // LD (DE), A "00010010" => self.load_8_addr_de_a(), // LD A, (nn) "11111010" => self.load_8_a_addr_im16(), // LD (nn), A "11101010" => self.load_8_addr_im16_a(), // LDH A, (C) "11110010" => self.load_8_a_addr_index_c(), // LDH (C), A "11100010" => self.load_8_addr_index_c_a(), // LDH A, (n) "11110000" => self.load_8_a_addr_index_im8(), // LDH (n), A "11100000" => self.load_8_addr_index_im8_a(), // LD A, (HL-) "00111010" => self.load_dec_8_a_addr_hl(), // LD (HL-), A "00110010" => self.load_dec_8_addr_hl_a(), // LD A, (HL+) "00101010" => self.load_inc_8_a_addr_hl(), // LD (HL+), A "00100010" => self.load_inc_8_addr_hl_a(), // LD rr, nn "00xx0001" => self.load_16_rr_im16(x), // LD (nn), SP "00001000" => self.load_16_addr_im16_sp(), // LD HL, SP+n "11111000" => self.load_16_hl_index_im8_sp(), // LD SP, HL "11111001" => self.load_16_sp_hl(), // PUSH rr "11xx0101" => self.push_16_rr(x), // POP rr "11xx0001" => self.pop_16_rr(x), // ADD A, r "10000xxx" => self.add_8_a_r(x), // ADD A, n "11000110" => self.add_8_a_im8(), // ADC A, r "10001xxx" => self.add_carry_8_a_r(x), // ADC A, n "11001110" => self.add_carry_8_a_im8(), // SUB A, r "10010xxx" => self.sub_8_a_r(x), // SUB n "11010110" => self.sub_8_a_im8(), // SBC A, r "10011xxx" => self.sub_carry_8_a_r(x), // SBC A, n "11011110" => self.sub_carry_8_a_im8(), // AND A, r "10100xxx" => self.and_8_a_r(x), // AND A, n "11100110" => self.and_8_a_im8(), // OR A, r "10110xxx" => self.or_8_a_r(x), // OR A, n "11110110" => self.or_8_a_im8(), // XOR A, r "10101xxx" => self.xor_8_a_r(x), // XOR A, n "11101110" => self.xor_8_a_im8(), // CP A, r "10111xxx" => self.cp_8_a_r(x), // CP A, n "11111110" => self.cp_8_a_im8(), // INC r "00xxx100" => self.inc_8_r(x), // DEC r "00xxx101" => self.dec_8_r(x), // ADD HL, rr "00xx1001" => self.add_16_hl_rr(x), // ADD SP, n "11101000" => self.add_16_sp_im8(), // INC rr "00xx0011" => self.inc_16_rr(x), // DEC rr "00xx1011" => self.dec_16_rr(x), // RLCA "00000111" => self.rlca_8(), // RLA "00010111" => self.rla_8(), // RRCA "00001111" => self.rrca_8(), // RRA "00011111" => self.rra_8(), // DAA "00100111" => self.decimal_adjust_8_a(), // CPL "00101111" => self.complement_8_a(), // CCF "00111111" => self.complement_carry(), // SCF "00110111" => self.set_carry_flag(), // JP nn "11000011" => self.jp_16(), // JP NZ, nn "11000010" => self.jp_16_nz(), // JP Z, nn "11001010" => self.jp_16_z(), // JP NC, nn "11010010" => self.jp_16_nc(), // JP C, nn "11011010" => self.jp_16_c(), // JP (HL) "11101001" => self.jp_16_hl(), // JR "00011000" => self.jr_8_im_8(), // JR NZ, nn "00100000" => self.jr_8_nz(), // JR Z, nn "00101000" => self.jr_8_z(), // JR NC, nn "00110000" => self.jr_8_nc(), // JR C, nn "00111000" => self.jr_8_c(), // CALL nn "11001101" => self.call_16(), // CALL NZ, nn "11000100" => self.call_16_nz(), // CALL Z, nn "11001100" => self.call_16_z(), // CALL NC, nn "11010100" => self.call_16_nc(), // CALL C, nn "11011100" => self.call_16_c(), // RST 00H~38H "11xxx111" => self.restart(x), // RET "11001001" => self.ret(), // RET NZ "11000000" => self.ret_nz(), // RET Z "11001000" => self.ret_z(), // RET NC "11010000" => self.ret_nc(), // RET C "11011000" => self.ret_c(), // RETI "11011001" => self.reti(), // CB Prefixed Instructions "11001011" => { let prefixed = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); self.do_mnemonic_prefixed(prefixed) } _ => { eprintln!("unimplemented opecode {:#02X}", opecode); Ok("UNIMPLEMENTED".to_string()) } } } #[bitmatch] fn do_mnemonic_prefixed(&mut self, opecode: u8) -> Result<String> { #[bitmatch] match &opecode { // SWAP r "00110xxx" => self.swap_8_r(x), // RLC r "00000xxx" => self.rlc_8_r(x), // RL r "00010xxx" => self.rl_8_r(x), // RRC r "00001xxx" => self.rrc_8_r(x), // RR r "00011xxx" => self.rr_8_r(x), // SLA r "00100xxx" => self.sla_8_r(x), // SRA r "00101xxx" => self.sra_8_r(x), // SRL r "00111xxx" => self.srl_8_r(x), // BIT b, r "01bbbxxx" => self.bit_8_bit_r(x, b), // SET b, r "11bbbxxx" => self.set_8_bit_r(x, b), // RES b, r "10bbbxxx" => self.reset_8_bit_r(x, b), _ => { eprintln!("unimplemented prefixed opecode {:#02X}", opecode); Ok("UNIMPLEMENTED".to_string()) } } } pub fn nop(&self) -> Result<String> { Ok("NOP".to_string()) } pub fn halt(&mut self) -> Result<String> { self.halt = true; Ok("HALT".to_string()) } pub fn stop(&mut self) -> Result<String> { // unimplemented!("停止して、LCDそのまま"); Ok("STOP".to_string()) } pub fn di(&mut self) -> Result<String> { self.ime = false; Ok("DI".to_string()) } pub fn ei(&mut self) -> Result<String> { self.ime = true; Ok("EI".to_string()) } pub fn load_8_r_im8(&mut self, index: u8) -> Result<String> { let val = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); self.set_r8(index, val)?; Ok(format!("LD {}, n: n={:02X}", self.r8_str(index), val)) } pub fn load_8_r_r(&mut self, left: u8, right: u8) -> Result<String> { let val = self.r8(right)?; self.set_r8(left, val)?; Ok(format!( "LD {}, {}: {}={:02X}", self.r8_str(left), self.r8_str(right), self.r8_str(left), val )) } pub fn load_8_a_addr_bc(&mut self) -> Result<String> { let val = self.bus.read(self.bc)?; self.a = val; Ok(format!("LD A, (BC): (BC)=({:04X})={:02X}", self.bc, val)) } pub fn load_8_a_addr_de(&mut self) -> Result<String> { let val = self.bus.read(self.de)?; self.a = val; Ok(format!("LD A, (DE): (DE)=({:04X})={:04X}", self.de, val)) } pub fn load_8_addr_bc_a(&mut self) -> Result<String> { self.bus.write(self.bc, self.a)?; Ok(format!( "LD (BC), A: (BC)=({:04X}), A={:02X}", self.bc, self.a )) } pub fn load_8_addr_de_a(&mut self) -> Result<String> { self.bus.write(self.de, self.a)?; Ok(format!( "LD (DE), A: (DE)=({:04X}), A={:02X}", self.de, self.a )) } pub fn load_8_a_addr_im16(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); let val = self.bus.read(addr)?; self.a = val; Ok(format!("LD A, (nn): (nn)=({:04X})={:02X}", addr, val,)) } pub fn load_8_addr_im16_a(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); let val = self.a; self.bus.write(addr, val)?; Ok(format!("LD (nn), A: (nn)=({:04X}), A={:02X}", addr, val)) } pub fn load_8_a_addr_index_c(&mut self) -> Result<String> { let index = self.c(); let addr = 0xFF00 + index as u16; let val = self.bus.read(addr)?; self.a = val; Ok(format!( "LDH A, (C): (C)=({:02X})=({:04X})={:02X}", index, addr, val )) } pub fn load_8_addr_index_c_a(&mut self) -> Result<String> { let index = self.c(); let addr = 0xFF00 + index as u16; self.bus.write(addr, self.a)?; Ok(format!( "LDH (C), A: (C)=({:02X})=({:04X})={:02X}", index, addr, self.a )) } pub fn load_8_a_addr_index_im8(&mut self) -> Result<String> { let index = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let addr = 0xFF00 + index as u16; let val = self.bus.read(addr)?; self.a = val; Ok(format!( "LDH A, (n): (n)=({:02X})=({:04X})={:02X}", index, addr, val )) } pub fn load_8_addr_index_im8_a(&mut self) -> Result<String> { let index = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let addr = 0xFF00 + index as u16; self.bus.write(addr, self.a)?; Ok(format!( "LDH (n), A: (n)=({:02X})=({:04X}), A={:02X}", index, addr, self.a, )) } pub fn load_dec_8_a_addr_hl(&mut self) -> Result<String> { let val = self.bus.read(self.hl)?; self.hl = self.hl.wrapping_sub(1); self.a = val; Ok(format!( "LD A, (HL-): (HL)=({:04X})={:02X}, (HL-)=({:04X})", self.hl.wrapping_add(1), val, self.hl )) } pub fn load_dec_8_addr_hl_a(&mut self) -> Result<String> { self.bus.write(self.hl, self.a)?; self.hl = self.hl.wrapping_sub(1); Ok(format!( "LD (HL-), A: (HL)=({:04X}), (HL-)=({:04X}), A={:02X}", self.hl.wrapping_add(1), self.hl, self.a, )) } pub fn load_inc_8_a_addr_hl(&mut self) -> Result<String> { let val = self.bus.read(self.hl)?; self.hl = self.hl.wrapping_add(1); self.a = val; Ok(format!( "LD A, (HL+): (HL)=({:04X})={:02X}, (HL+)=({:04X})", self.hl.wrapping_sub(1), val, self.hl, )) } pub fn load_inc_8_addr_hl_a(&mut self) -> Result<String> { self.bus.write(self.hl, self.a)?; self.hl = self.hl.wrapping_add(1); Ok(format!( "LD (HL+), A: (HL)=({:04X}), (HL+)=({:04X}), A={:02X}", self.hl.wrapping_sub(1), self.hl, self.a )) } pub fn load_16_rr_im16(&mut self, index: u8) -> Result<String> { let val = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); self.set_r16(index, val, false)?; Ok(format!( "LD {}, nn: nn={:04X}", self.r16_str(index, false), val, )) } pub fn load_16_addr_im16_sp(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); let val = self.sp; self.bus.write_word(addr, val)?; Ok(format!("LD (nn), sp: (nn)=({:04X}), SP={:04X}", addr, val)) } pub fn load_16_hl_index_im8_sp(&mut self) -> Result<String> { let base_addr = self.sp; let index_addr = self.bus.read(self.pc)? as i8 as u16; self.pc = self.pc.wrapping_add(1); self.hl = base_addr.wrapping_add(index_addr); self.f.set_z(false); self.f.set_n(false); self.f .set_h(self.half_carry_positive(base_addr as u8, index_addr as u8)); self.f .set_c(self.carry_positive(base_addr as u8, index_addr as u8)); Ok(format!( "LD HL, SP+n: SP={:04X}, n={:02X}, SP+n={:04X}", self.sp, index_addr, self.hl )) } pub fn load_16_sp_hl(&mut self) -> Result<String> { self.sp = self.hl; self.stalls += 8; Ok(format!("LD SP, HL: HL={:04X}", self.hl)) } pub fn push_16_rr(&mut self, index: u8) -> Result<String> { let val = self.r16(index, true)?; self.sp = self.sp.wrapping_sub(2); self.bus.write_word(self.sp, val)?; self.stalls += 16; Ok(format!( "PUSH {}: {0}={:04X}", self.r16_str(index, true), val )) } pub fn pop_16_rr(&mut self, index: u8) -> Result<String> { let val = self.bus.read_word(self.sp)?; self.sp = self.sp.wrapping_add(2); self.set_r16(index, val, true)?; self.stalls += 12; Ok(format!( "POP {}: data={:04X}", self.r16_str(index, true), val )) } pub fn add_8_a_r(&mut self, index: u8) -> Result<String> { let left = self.a; let right = self.r8(index)?; let result = left.wrapping_add(right); self.a = result; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(self.half_carry_positive(left, right)); self.f.set_c(self.carry_positive(left, right)); self.stalls += 4; Ok(format!( "ADD A, {}: A={:02X}, {0}={:02X}", self.r8_str(index), left, right )) } pub fn add_8_a_im8(&mut self) -> Result<String> { let right = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let left = self.a; let result = left.wrapping_add(right); self.a = result; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(self.half_carry_positive(left, right)); self.f.set_c(self.carry_positive(left, right)); self.stalls += 8; Ok(format!("ADD A, n: A={:02X}, n={:02X}", left, right)) } pub fn add_carry_8_a_r(&mut self, index: u8) -> Result<String> { let c = self.f.c() as u8; let right = self.r8(index)?; let left = self.a; let result1 = left.wrapping_add(right); let result2 = result1.wrapping_add(c); let c1 = self.carry_positive(left, right); let h1 = self.half_carry_positive(left, right); let c2 = self.carry_positive(result1, c); let h2 = self.half_carry_positive(result1, c); self.a = result2; self.f.set_z(result2 == 0); self.f.set_n(false); self.f.set_h(h1 || h2); self.f.set_c(c1 || c2); self.stalls += 4; Ok(format!( "ADC A, {}: A={:02X}, {0}={:02X}", self.r8_str(index), left, right, )) } pub fn add_carry_8_a_im8(&mut self) -> Result<String> { let c = self.f.c() as u8; let right = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let left = self.a; let result1 = left.wrapping_add(right); let result2 = result1.wrapping_add(c); let c1 = self.carry_positive(left, right); let h1 = self.half_carry_positive(left, right); let c2 = self.carry_positive(result1, c); let h2 = self.half_carry_positive(result1, c); self.a = result2; self.f.set_z(result2 == 0); self.f.set_n(false); self.f.set_h(h1 || h2); self.f.set_c(c1 || c2); self.stalls += 8; Ok(format!("ADC A, n: A={:02X}, n={:02X}", left, right,)) } pub fn sub_8_a_r(&mut self, index: u8) -> Result<String> { let left = self.a; let right = self.r8(index)?; let result = left.wrapping_sub(right); self.a = result; self.f.set_z(result == 0); self.f.set_n(true); self.f.set_h(self.half_carry_negative(left, right)); self.f.set_c(self.carry_negative(left, right)); self.stalls += 4; Ok(format!( "SUB A, {}: A={:02X}, {0}={:02X}", self.r8_str(index), left, right )) } pub fn sub_8_a_im8(&mut self) -> Result<String> { let left = self.a; let right = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let result = left.wrapping_sub(right); self.a = result; self.f.set_z(result == 0); self.f.set_n(true); self.f.set_h(self.half_carry_negative(left, right)); self.f.set_c(self.carry_negative(left, right)); self.stalls += 8; Ok(format!("SUB A, n: A={:02X}, n={:02X}", left, right)) } pub fn sub_carry_8_a_r(&mut self, index: u8) -> Result<String> { let c = self.f.c() as u8; let left = self.a; let right = self.r8(index)?; let result1 = left.wrapping_sub(right); let result2 = result1.wrapping_sub(c); self.a = result2; let c1 = self.carry_negative(left, right); let h1 = self.half_carry_negative(left, right); let c2 = self.carry_negative(result1, c); let h2 = self.half_carry_negative(result1, c); self.f.set_z(result2 == 0); self.f.set_n(true); self.f.set_h(h1 || h2); self.f.set_c(c1 || c2); self.stalls += 4; Ok(format!( "SBC A, {}: A={:02X}, {0}={:02X}", self.r8_str(index), left, right )) } pub fn sub_carry_8_a_im8(&mut self) -> Result<String> { let c = self.f.c() as u8; let left = self.a; let right = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let result1 = left.wrapping_sub(right); let result2 = result1.wrapping_sub(c); self.a = result2; let c1 = self.carry_negative(left, right); let h1 = self.half_carry_negative(left, right); let c2 = self.carry_negative(result1, c); let h2 = self.half_carry_negative(result1, c); self.f.set_z(result2 == 0); self.f.set_n(true); self.f.set_h(h1 || h2); self.f.set_c(c1 || c2); self.stalls += 8; Ok(format!("SBC A, n: A={:02X}, n={:02X}", left, right)) } pub fn and_8_a_r(&mut self, index: u8) -> Result<String> { let left = self.a; let right = self.r8(index)?; let result = left & right; self.a = result; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(true); self.f.set_c(false); self.stalls += 4; Ok(format!( "AND A, {}: A={:02X}, {0}={:02X}", self.r8_str(index), left, right )) } pub fn and_8_a_im8(&mut self) -> Result<String> { let left = self.a; let right = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let result = left & right; self.a = result; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(true); self.f.set_c(false); self.stalls += 8; Ok(format!("AND A, n: A={:02X}, n={:02X}", left, right)) } pub fn or_8_a_r(&mut self, index: u8) -> Result<String> { let left = self.a; let right = self.r8(index)?; let result = left | right; self.a = result; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(false); self.stalls += 4; Ok(format!( "OR A, {}: A={:02X}, {0}={:02X}", self.r8_str(index), left, right )) } pub fn or_8_a_im8(&mut self) -> Result<String> { let left = self.a; let right = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let result = left | right; self.a = result; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(false); self.stalls += 8; Ok(format!("OR A, n: A={:02X}, n={:02X}", left, right)) } pub fn xor_8_a_r(&mut self, index: u8) -> Result<String> { let left = self.a; let right = self.r8(index)?; let result = left ^ right; self.a = result; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(false); self.stalls += 4; Ok(format!( "XOR A, {}: A={:02X}, {0}={:02X}", self.r8_str(index), left, right )) } pub fn xor_8_a_im8(&mut self) -> Result<String> { let left = self.a; let right = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let result = left ^ right; self.a = result; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(false); self.stalls += 8; Ok(format!("XOR A, n: A={:02X}, n={:02X}", left, right)) } pub fn cp_8_a_r(&mut self, index: u8) -> Result<String> { let left = self.a; let right = self.r8(index)?; let result = left.wrapping_sub(right); self.f.set_z(result == 0); self.f.set_n(true); self.f.set_h(self.half_carry_negative(left, right)); self.f.set_c(self.carry_negative(left, right)); self.stalls += 4; Ok(format!( "CP A, {}: A={:02X}, {0}={:02X}", self.r8_str(index), left, right )) } pub fn cp_8_a_im8(&mut self) -> Result<String> { let left = self.a; let right = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); let result = left.wrapping_sub(right); self.f.set_z(result == 0); self.f.set_n(true); self.f.set_h(self.half_carry_negative(left, right)); self.f.set_c(self.carry_negative(left, right)); self.stalls += 8; Ok(format!("CP A, n: A={:02X}, n={:02X}", left, right)) } pub fn inc_8_r(&mut self, index: u8) -> Result<String> { let left = self.r8(index)?; let right = 1; let result = left.wrapping_add(right); self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(self.half_carry_positive(left, right)); self.stalls += 4; Ok(format!("INC {}: {0}={:02X}", self.r8_str(index), left)) } pub fn dec_8_r(&mut self, index: u8) -> Result<String> { let left = self.r8(index)?; let right = 1; let result = left.wrapping_sub(right); self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(true); self.f.set_h(self.half_carry_negative(left, right)); self.stalls += 4; Ok(format!("DEC {}: {0}={:02X}", self.r8_str(index), left)) } pub fn add_16_hl_rr(&mut self, index: u8) -> Result<String> { let left = self.hl; let right = self.r16(index, false)?; let result = left.wrapping_add(right); self.hl = result; self.f.set_n(false); self.f.set_h(self.half_carry_positive_16_12(left, right)); self.f.set_c(self.carry_positive_16(left, right)); self.stalls += 8; Ok(format!( "ADD HL, {}: HL={:04X}, {0}={:04X}", self.r16_str(index, false), left, right )) } pub fn add_16_sp_im8(&mut self) -> Result<String> { let left = self.sp; let right = self.bus.read(self.pc)? as i8 as u16; self.pc = self.pc.wrapping_add(1); let result = left.wrapping_add(right); self.sp = result; self.f.set_z(false); self.f.set_n(false); self.f .set_h(self.half_carry_positive(left as u8, right as u8)); self.f.set_c(self.carry_positive(left as u8, right as u8)); self.stalls += 16; Ok(format!("ADD SP, n: SP={:04X}, n={:02X}", left, right)) } pub fn inc_16_rr(&mut self, index: u8) -> Result<String> { let left = self.r16(index, false)?; let right = 1; let result = left.wrapping_add(right); self.set_r16(index, result, false)?; self.stalls += 8; Ok(format!( "INC {}: {0}={:04X}", self.r16_str(index, false), left )) } pub fn dec_16_rr(&mut self, index: u8) -> Result<String> { let left = self.r16(index, false)?; let right = 1; let result = left.wrapping_sub(right); self.set_r16(index, result, false)?; self.stalls += 8; Ok(format!( "DEC {}: {0}={:04X}", self.r16_str(index, false), left )) } pub fn rlca_8(&mut self) -> Result<String> { let val = self.a; let c = (val >> 7) & 1; let result = val.rotate_left(1); self.a = result; self.f.set_z(false); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 4; Ok(format!("RLCA: A={:02X}, #={:02X}", val, result)) } pub fn rla_8(&mut self) -> Result<String> { let val = self.a; let c = (val >> 7) & 1; let result = val << 1 | self.f.c() as u8; self.a = result; self.f.set_z(false); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 4; Ok(format!("RLA: A={:02X}, #={:02X}", val, result)) } pub fn rrca_8(&mut self) -> Result<String> { let val = self.a; let c = val & 1; let result = val.rotate_right(1); self.a = result; self.f.set_z(false); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 4; Ok(format!("RRCA: A={:02X}, #={:02X}", val, result)) } pub fn rra_8(&mut self) -> Result<String> { let val = self.a; let c = val & 1; let result = val >> 1 | ((self.f.c() as u8) << 7); self.a = result; self.f.set_z(false); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 4; Ok(format!("RRA: A={:02X}, #={:02X}", val, result)) } pub fn rlc_8_r(&mut self, index: u8) -> Result<String> { let val = self.r8(index)?; let c = (val >> 7) & 1; let result = val.rotate_left(1); self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 8; Ok(format!( "RLC {}: {0}={:02X}, #={:02X}", self.r8_str(index), val, result )) } pub fn rl_8_r(&mut self, index: u8) -> Result<String> { let val = self.r8(index)?; let c = (val >> 7) & 1; let result = val << 1 | self.f.c() as u8; self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 8; Ok(format!( "RL {}: {0}={:02X}, #={:02X}", self.r8_str(index), val, result )) } pub fn rrc_8_r(&mut self, index: u8) -> Result<String> { let val = self.r8(index)?; let c = val & 1; let result = val.rotate_right(1); self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 8; Ok(format!( "RRC {}: {0}={:02X}, #={:02X}", self.r8_str(index), val, result )) } pub fn rr_8_r(&mut self, index: u8) -> Result<String> { let val = self.r8(index)?; let c = val & 1; let result = val >> 1 | ((self.f.c() as u8) << 7); self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 8; Ok(format!( "RR {}: {0}={:02X}, #={:02X}", self.r8_str(index), val, result )) } pub fn sla_8_r(&mut self, index: u8) -> Result<String> { let val = self.r8(index)?; let c = (val >> 7) & 1; let result = val << 1; self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 8; Ok(format!( "SLA {}: {0}={:02X}, #={:02X}", self.r8_str(index), val, result )) } pub fn sra_8_r(&mut self, index: u8) -> Result<String> { let val = self.r8(index)?; let c = val & 1; let result = val >> 1 | (val & 0b10000000); self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 8; Ok(format!( "SRA {}: {0}={:02X}, #={:02X}", self.r8_str(index), val, result )) } pub fn srl_8_r(&mut self, index: u8) -> Result<String> { let val = self.r8(index)?; let c = val & 1; let result = val >> 1; self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(c == 1); self.stalls += 8; Ok(format!( "SRL {}: {0}={:02X}, #={:02X}", self.r8_str(index), val, result )) } pub fn bit_8_bit_r(&mut self, index: u8, bit: u8) -> Result<String> { let left = self.r8(index)?; let right = bit; let result = (left >> right) & 1; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(true); self.stalls += 8; Ok(format!( "BIT b, {}: b={}, {0}={:02X}, #={:02X}", self.r8_str(index), right, left, result )) } pub fn set_8_bit_r(&mut self, index: u8, bit: u8) -> Result<String> { let left = self.r8(index)?; let right = bit; let result = left | (1 << right); self.set_r8(index, result)?; self.stalls += 8; Ok(format!( "SET b, {}: b={}, {0}={:02X}, #={:02X}", self.r8_str(index), right, left, result )) } pub fn reset_8_bit_r(&mut self, index: u8, bit: u8) -> Result<String> { let left = self.r8(index)?; let right = bit; let result = left & !(1 << right); self.set_r8(index, result)?; self.stalls += 8; Ok(format!( "RES b, {}: b={}, {0}={:02X}, #={:02X}", self.r8_str(index), right, left, result )) } pub fn jp_16(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = addr; self.stalls += 16; Ok(format!("JP nn: nn={:04X}", addr)) } pub fn jp_16_nz(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); if !self.f.z() { self.pc = addr; } self.stalls += 16; Ok(format!("JP NZ, nn: NZ={}, nn={:04X}", !self.f.z(), addr)) } pub fn jp_16_z(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); if self.f.z() { self.pc = addr; } self.stalls += 16; Ok(format!("JP Z, nn: Z={}, nn={:04X}", self.f.z(), addr)) } pub fn jp_16_nc(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); if !self.f.c() { self.pc = addr; } self.stalls += 16; Ok(format!("JP NC, nn: NC={}, nn={:04X}", !self.f.c(), addr)) } pub fn jp_16_c(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); if self.f.c() { self.pc = addr; } self.stalls += 16; Ok(format!("JP C, nn: C={}, nn={:04X}", self.f.c(), addr)) } pub fn jp_16_hl(&mut self) -> Result<String> { self.pc = self.hl; self.stalls += 4; Ok(format!("JP (HL): (HL)=({:04X})", self.hl)) } pub fn jr_8_im_8(&mut self) -> Result<String> { let index = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); self.pc = self.pc.wrapping_add(index as i8 as u16); self.stalls += 12; Ok(format!("JR n: n={}", index)) } pub fn jr_8_nz(&mut self) -> Result<String> { let index = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); if !self.f.z() { self.pc = self.pc.wrapping_add(index as i8 as u16); } self.stalls += 12; Ok(format!("JR NZ, n: NZ={}, n={}", !self.f.z(), index)) } pub fn jr_8_z(&mut self) -> Result<String> { let index = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); if self.f.z() { self.pc = self.pc.wrapping_add(index as i8 as u16); } self.stalls += 12; Ok(format!("JR Z, n: Z={}, n={}", self.f.z(), index)) } pub fn jr_8_nc(&mut self) -> Result<String> { let index = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); if !self.f.c() { self.pc = self.pc.wrapping_add(index as i8 as u16); } self.stalls += 12; Ok(format!("JR NC, n: NC={}, n={}", !self.f.c(), index)) } pub fn jr_8_c(&mut self) -> Result<String> { let index = self.bus.read(self.pc)?; self.pc = self.pc.wrapping_add(1); if self.f.c() { self.pc = self.pc.wrapping_add(index as i8 as u16); } self.stalls += 12; Ok(format!("JR C, n: C={}, n={}", self.f.c(), index)) } pub fn call(&mut self, addr: u16) -> Result<()> { self.sp = self.sp.wrapping_sub(2); self.bus.write_word(self.sp, self.pc)?; self.pc = addr; self.stalls += 24; Ok(()) } pub fn call_16(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); self.call(addr)?; Ok(format!("CALL nn: nn={:04X}", addr)) } pub fn call_16_nz(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); if !self.f.z() { self.call(addr)?; } Ok(format!("CALL NZ, nn: NZ={}, nn={:04X}", !self.f.z(), addr)) } pub fn call_16_z(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); if self.f.z() { self.call(addr)?; } Ok(format!("CALL Z, nn: Z={}, nn={:04X}", self.f.z(), addr)) } pub fn call_16_nc(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); if !self.f.c() { self.call(addr)?; } Ok(format!("CALL NC, nn: NC={}, nn={:04X}", !self.f.c(), addr)) } pub fn call_16_c(&mut self) -> Result<String> { let addr = self.bus.read_word(self.pc)?; self.pc = self.pc.wrapping_add(2); if self.f.c() { self.call(addr)?; } Ok(format!("CALL C, nn: C={}, nn={:04X}", self.f.c(), addr)) } pub fn restart(&mut self, param: u8) -> Result<String> { let addr = param as u16 * 0x08; self.sp = self.sp.wrapping_sub(2); self.bus.write_word(self.sp, self.pc)?; self.pc = addr; self.stalls += 16; Ok(format!("RST nn: nn={:04X}", addr)) } pub fn ret(&mut self) -> Result<String> { let addr = self.bus.read_word(self.sp)?; self.sp = self.sp.wrapping_add(2); self.pc = addr; self.stalls += 16; Ok(format!( "RET: (SP)=({:04X})={:04X}", self.sp.wrapping_sub(2), addr )) } pub fn ret_nz(&mut self) -> Result<String> { let addr = self.bus.read_word(self.sp)?; if !self.f.z() { self.sp = self.sp.wrapping_add(2); self.pc = addr; } self.stalls += 20; Ok(format!( "RET NZ: NZ={}, (SP)=({:04X})={:04X}", !self.f.z(), self.sp.wrapping_sub(2), addr )) } pub fn ret_z(&mut self) -> Result<String> { let addr = self.bus.read_word(self.sp)?; if self.f.z() { self.sp = self.sp.wrapping_add(2); self.pc = addr; } self.stalls += 20; Ok(format!( "RET Z: Z={}, (SP)=({:04X})={:04X}", self.f.z(), self.sp.wrapping_sub(2), addr )) } pub fn ret_nc(&mut self) -> Result<String> { let addr = self.bus.read_word(self.sp)?; if !self.f.c() { self.sp = self.sp.wrapping_add(2); self.pc = addr; } self.stalls += 20; Ok(format!( "RET NC: NC={}, (SP)=({:04X})={:04X}", !self.f.c(), self.sp.wrapping_sub(2), addr )) } pub fn ret_c(&mut self) -> Result<String> { let addr = self.bus.read_word(self.sp)?; if self.f.c() { self.sp = self.sp.wrapping_add(2); self.pc = addr; } self.stalls += 20; Ok(format!( "RET C: C={}, (SP)=({:04X})={:04X}", self.f.c(), self.sp.wrapping_sub(2), addr )) } pub fn reti(&mut self) -> Result<String> { let addr = self.bus.read_word(self.sp)?; self.sp = self.sp.wrapping_add(2); self.pc = addr; self.ime = true; self.stalls += 16; Ok(format!( "RETI: (SP)=({:04X})={:04X}", self.sp.wrapping_sub(2), addr )) } pub fn swap_8_r(&mut self, index: u8) -> Result<String> { let val = self.r8(index)?; let high = val & 0xF0; let low = val & 0x0F; let result = (high >> 4) | (low << 4); self.set_r8(index, result)?; self.f.set_z(result == 0); self.f.set_n(false); self.f.set_h(false); self.f.set_c(false); self.stalls += 8; Ok(format!( "SWAP {}: {0}={:02X}, #={:02X}", self.r8_str(index), val, result )) } pub fn decimal_adjust_8_a(&mut self) -> Result<String> { let val = self.a; // @see https://forums.nesdev.com/viewtopic.php?t=15944 if !self.f.n() { if self.f.c() || self.a > 0x99 { self.a = self.a.wrapping_add(0x60); self.f.set_c(true); } if self.f.h() || (self.a & 0x0F) > 0x09 { self.a = self.a.wrapping_add(0x06); } } else { if self.f.c() { self.a = self.a.wrapping_sub(0x60); } if self.f.h() { self.a = self.a.wrapping_sub(0x06); } } self.f.set_z(self.a == 0); self.f.set_h(false); self.stalls += 4; Ok(format!("DAA: A={:02X}, #={:02X}", val, self.a)) } pub fn complement_8_a(&mut self) -> Result<String> { let val = self.a; let result = !val; self.a = result; self.f.set_n(true); self.f.set_h(true); self.stalls += 4; Ok(format!("CPL: A={:02X}, #={:02X}", val, result)) } pub fn complement_carry(&mut self) -> Result<String> { let c = self.f.c(); let result = !c; self.f.set_n(false); self.f.set_h(false); self.f.set_c(result); self.stalls += 4; Ok(format!("CCF: C={}, #={}", c, result)) } pub fn set_carry_flag(&mut self) -> Result<String> { self.f.set_n(false); self.f.set_h(false); self.f.set_c(true); self.stalls += 4; Ok("SCF".to_string()) } pub fn debug_break(&mut self) { loop { let readline = self.rl.readline(">>> "); match readline { Ok(line) if line.starts_with("continue") || line == "c" => { self.rl.add_history_entry(line.as_str()); self.stepping = false; break; } Ok(line) if line.starts_with("step") || line == "s" => { self.rl.add_history_entry(line.as_str()); self.stepping = true; break; } Ok(line) if line.starts_with("break ") || line.starts_with("b ") => { if let Some(addr_str) = line.split_ascii_whitespace().nth(1) { if let Ok(addr) = u16::from_str_radix(addr_str.trim_start_matches("0x"), 16) { self.rl.add_history_entry(line.as_str()); self.breakpoints.push(addr); println!("add breakpoint: {:#04X}", addr); continue; } } println!("break command parse failed"); } Ok(line) if line.starts_with("print ") || line.starts_with("p ") => { if let Some(addr_str) = line.split_ascii_whitespace().nth(1) { if let Ok(addr) = u16::from_str_radix(addr_str.trim_start_matches("0x"), 16) { if let Ok(val) = self.bus.read(addr) { self.rl.add_history_entry(line.as_str()); println!("({:#04X})={:#02X}", addr, val); continue; } } } println!("print command failed"); } Ok(line) if line.starts_with("printw ") || line.starts_with("pw ") => { if let Some(addr_str) = line.split_ascii_whitespace().nth(1) { if let Ok(addr) = u16::from_str_radix(addr_str.trim_start_matches("0x"), 16) { if let Ok(val) = self.bus.read_word(addr) { self.rl.add_history_entry(line.as_str()); println!("({:#04X})={:#04X}", addr, val); continue; } } } println!("printw command parse failed"); } Ok(line) if line.starts_with("reset") || line == "r" => { self.rl.add_history_entry(line.as_str()); if let Err(err) = self.reset() { println!("failed to reset {}", err); } break; } Ok(line) if line.starts_with("trace ") || line.starts_with("t ") => { self.rl.add_history_entry(line.as_str()); if let Some(num_str) = line.split_ascii_whitespace().nth(1) { if let Ok(num) = num_str.parse() { self.trace_left = num; self.stepping = false; break; } } println!("print command failed"); } Ok(line) => { println!("unknown command {}", line); } Err(_) => { println!("aborted"); std::process::exit(0); } } } } }
true
d5a3f15c382c6226f8ffa55e735a03d5818ea559
Rust
qqq-tech/braiins
/open/bosminer/bosminer-config/src/group.rs
UTF-8
3,219
2.578125
3
[]
no_license
// Copyright (C) 2020 Braiins Systems s.r.o. // // This file is part of Braiins Open-Source Initiative (BOSI). // // BOSI is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // // Please, keep in mind that we may also license BOSI or any part thereof // under a proprietary license. For more information on the terms and conditions // of such proprietary license or if you have any other questions, please // contact us at opensource@braiins.com. use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub enum LoadBalanceStrategy { #[serde(rename = "quota")] Quota(usize), /// Fixed share ratio is value between 0.0 to 1.0 where 1.0 represents that all work is /// generated from the group #[serde(rename = "fixed_share_ratio")] FixedShareRatio(f64), } impl LoadBalanceStrategy { pub fn get_quota(&self) -> Option<usize> { match self { Self::Quota(value) => Some(*value), _ => None, } } pub fn get_fixed_share_ratio(&self) -> Option<f64> { match self { Self::FixedShareRatio(value) => Some(*value), _ => None, } } } /// Contains basic information about group #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct Descriptor { pub name: String, #[serde(skip)] pub private: bool, #[serde(flatten)] #[serde(skip_serializing_if = "Option::is_none")] strategy: Option<LoadBalanceStrategy>, } impl Descriptor { pub const DEFAULT_NAME: &'static str = "Default"; pub const DEFAULT_INDEX: usize = 0; pub const DEFAULT_QUOTA: usize = 1; pub fn new<T>(name: String, private: bool, strategy: T) -> Self where T: Into<Option<LoadBalanceStrategy>>, { Self { name, private, strategy: strategy.into(), } } pub fn strategy(&self) -> LoadBalanceStrategy { self.strategy .clone() .unwrap_or(LoadBalanceStrategy::Quota(Self::DEFAULT_QUOTA)) } pub fn get_quota(&self) -> Option<usize> { match self.strategy() { LoadBalanceStrategy::Quota(value) => Some(value), _ => None, } } pub fn get_fixed_share_ratio(&self) -> Option<f64> { self.strategy .as_ref() .and_then(|strategy| strategy.get_fixed_share_ratio()) } } impl Default for Descriptor { fn default() -> Self { Self { name: Self::DEFAULT_NAME.to_string(), private: false, strategy: None, } } }
true
be9000d0372156fcb6818a1a375039441f2f8bba
Rust
mucompilers/project
/pa2/tests/11-arr1.rs
UTF-8
147
2.71875
3
[]
no_license
fn main() { let a : [bool; 3] = [true, false, false]; let x = a[0]; a[0]; a[1 - 1]; a[if (a[0]) { 0 } else { 1 }]; }
true
90849c7e645d9b315d91f8149bd602624f8f993a
Rust
timokoesters/ruma-client-api
/src/r0/directory/get_public_rooms_filtered.rs
UTF-8
2,023
2.734375
3
[ "MIT" ]
permissive
//! [POST /_matrix/client/r0/publicRooms](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-publicrooms) use js_int::UInt; use ruma_api::ruma_api; use serde::{Deserialize, Serialize}; use super::PublicRoomsChunk; ruma_api! { metadata { description: "Get the list of rooms in this homeserver's public directory.", method: POST, name: "get_public_rooms_filtered", path: "/_matrix/client/r0/publicRooms", rate_limited: false, requires_authentication: true, } request { /// The server to fetch the public room lists from. /// /// `None` means the server this request is sent to. #[serde(skip_serializing_if = "Option::is_none")] #[ruma_api(query)] pub server: Option<String>, /// Limit for the number of results to return. #[serde(skip_serializing_if = "Option::is_none")] pub limit: Option<UInt>, /// Pagination token from a previous request. #[serde(skip_serializing_if = "Option::is_none")] pub since: Option<String>, /// Filter to apply to the results. #[serde(skip_serializing_if = "Option::is_none")] pub filter: Option<Filter>, } response { /// A paginated chunk of public rooms. pub chunk: Vec<PublicRoomsChunk>, /// A pagination token for the response. pub next_batch: Option<String>, /// A pagination token that allows fetching previous results. pub prev_batch: Option<String>, /// An estimate on the total number of public rooms, if the server has an estimate. pub total_room_count_estimate: Option<UInt>, } error: crate::Error } /// A filter for public rooms lists #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Filter { /// A string to search for in the room metadata, e.g. name, topic, canonical alias etc. #[serde(skip_serializing_if = "Option::is_none")] pub generic_search_term: Option<String>, }
true
e8cd23f733925eb9029725a7760ff351fd7e699d
Rust
SINHASantos/configure_me
/configure_me_codegen/tests/custom_args.rs
UTF-8
2,246
2.59375
3
[ "MITNFA" ]
permissive
macro_rules! test_name { () => { "single_optional_param" } } include!("glue/boilerplate.rs"); use std::iter; use std::path::PathBuf; #[test] fn custom_args() { let (config, mut remaining, _metadata) = config::Config::custom_args_and_optional_files(&["custom_args", "--foo", "42"], iter::empty::<PathBuf>()).unwrap(); assert_eq!(config.foo, Some(42)); assert_eq!(remaining.next(), None); } #[test] fn custom_args_with_one_remaining() { let (config, mut remaining, _metadata) = config::Config::custom_args_and_optional_files(&["custom_args", "--foo", "42", "remaining_arg"], iter::empty::<PathBuf>()).unwrap(); assert_eq!(config.foo, Some(42)); assert_eq!(remaining.next(), Some("remaining_arg".into())); assert_eq!(remaining.next(), None); } #[test] fn custom_args_with_two_remaining() { let (config, mut remaining, _metadata) = config::Config::custom_args_and_optional_files(&["custom_args", "--foo", "42", "remaining_arg", "another_arg"], iter::empty::<PathBuf>()).unwrap(); assert_eq!(config.foo, Some(42)); assert_eq!(remaining.next(), Some("remaining_arg".into())); assert_eq!(remaining.next(), Some("another_arg".into())); assert_eq!(remaining.next(), None); } #[test] fn custom_args_with_two_dashes() { let (config, mut remaining, _metadata) = config::Config::custom_args_and_optional_files(&["custom_args", "--", "--foo", "42"], iter::empty::<PathBuf>()).unwrap(); assert_eq!(config.foo, None); assert_eq!(remaining.next(), Some("--foo".into())); assert_eq!(remaining.next(), Some("42".into())); assert_eq!(remaining.next(), None); } #[test] fn custom_args_with_two_dashes_foo_equals_val() { let (config, mut remaining, _metadata) = config::Config::custom_args_and_optional_files(&["custom_args", "--", "--foo=42"], iter::empty::<PathBuf>()).unwrap(); assert_eq!(config.foo, None); assert_eq!(remaining.next(), Some("--foo=42".into())); assert_eq!(remaining.next(), None); } #[test] fn param_equals_value() { let (config, mut remaining, _metadata) = config::Config::custom_args_and_optional_files(&["custom_args", "--foo=42"], iter::empty::<PathBuf>()).unwrap(); assert_eq!(config.foo, Some(42)); assert_eq!(remaining.next(), None); }
true
f6f90824662c014c336129ee6677a60cec401fc1
Rust
hextal/dolysis
/skipframe/src/cli.rs
UTF-8
5,343
2.953125
3
[ "Apache-2.0" ]
permissive
#![allow(deprecated)] use { clap::{crate_authors, crate_version, App, Arg, SubCommand}, std::{ net::{IpAddr, SocketAddr}, path::{Path, PathBuf}, str::FromStr, }, }; #[cfg(unix)] pub fn generate_cli<'a, 'b>() -> App<'a, 'b> { __generate_cli().subcommand( SubCommand::with_name("socket") .about("Use a unix socket for output") .arg( Arg::with_name("socket_connect") .takes_value(false) .value_name("PATH") .required(true) .validator(|val| match PathBuf::from(&val).exists() { true => Ok(()), false => Err(format!("'{}' does not exist or is an invalid path", &val)), }) .help("Connect to socket at PATH"), ), ) } #[cfg(not(unix))] pub fn generate_cli<'a, 'b>() -> App<'a, 'b> { __generate_cli() } /// Generates base CLI without architecture specific options fn __generate_cli<'a, 'b>() -> App<'a, 'b> { App::new("skipframe") .about("Reads and executes files from a given directory") .author(crate_authors!("\n")) .version(crate_version!()) .arg( Arg::with_name("exec_root") .takes_value(false) .value_name("PATH") .default_value(".") .help("Point at directory root of files to execute"), ) .subcommand( SubCommand::with_name("tcp") .about("Use a tcp socket for output") .arg( Arg::with_name("tcp_addr") .takes_value(false) .value_names(&["IPV4", "IPV6"]) .default_value("127.0.0.1") .validator(|val| { IpAddr::from_str(val.as_str()) .map(|_| ()) .map_err(|e| format!("'{}' is an {}", val, e)) }) .help("Connect to the given IP"), ) .arg( Arg::with_name("tcp_port") .takes_value(false) .value_name("PORT") .default_value("50000") .validator(|val| { val.parse::<u16>() .map(|_| ()) .map_err(|_| format!("'{}' is not a valid port", &val)) }) .help("On the given port"), ), ) } pub(crate) struct ProgramArgs { exec_root: PathBuf, con_type: ConOpts, } impl ProgramArgs { /// Retains relevant user defined config settings gathered from the CLI pub(crate) fn init(cli: App<'_, '_>) -> Self { let store = cli.get_matches(); let exec_root = PathBuf::from(store.value_of("exec_root").unwrap().to_string()); let con_type; match store.subcommand() { ("socket", Some(sub)) => { con_type = ConOpts::UnixSocket(PathBuf::from(sub.value_of("socket_connect").unwrap())) } ("tcp", Some(sub)) => { let ip = IpAddr::from_str(sub.value_of("tcp_addr").unwrap()).unwrap(); let port = sub .value_of("tcp_port") .map(|s| s.parse::<u16>().unwrap()) .unwrap(); con_type = ConOpts::Tcp(SocketAddr::new(ip, port)) } _ => con_type = ConOpts::default(), } Self { exec_root, con_type, } } /// Return user's specified path root pub(crate) fn exec_root(&self) -> &Path { &self.exec_root } /// If the user selected a TCP stream, returns the address. /// Guaranteed to be Some if con_socket() and con_stdout() are None pub(crate) fn con_tcp(&self) -> Option<SocketAddr> { match self.con_type { ConOpts::Tcp(addr) => Some(addr), _ => None, } } /// If the user selected a unix stream, returns the path. /// Guaranteed to be Some if con_tcp() and con_stdout() are None. /// NOTE: always returns None on unsupported architecture pub(crate) fn con_socket(&self) -> Option<&Path> { if cfg!(target_family = "unix") { match self.con_type { ConOpts::UnixSocket(ref path) => Some(path.as_ref()), _ => None, } } else { None } } /// If the user did not select an output stream, returns Some. /// Guaranteed to be Some if con_tcp() and con_socket() are None pub(crate) fn con_stdout(&self) -> Option<()> { match self.con_type { ConOpts::Stdout => Some(()), _ => None, } } } #[derive(Debug, Clone)] #[cfg(unix)] /// Possible output streams enum ConOpts { Stdout, Tcp(SocketAddr), UnixSocket(PathBuf), } #[derive(Debug, Clone)] #[cfg(not(unix))] /// Possible output streams enum ConOpts { Stdout, Tcp(SocketAddr), } impl Default for ConOpts { fn default() -> Self { Self::Stdout } }
true
5a5cc97d9f206326b8cffccc3bb7c71e51d0775d
Rust
ceigey/textgame-rs-prototype
/cellexp/src/main.rs
UTF-8
1,151
3.546875
4
[]
no_license
use std::cell::Cell; use std::vec::Vec; use std::fmt::Debug; use std::clone::Clone; use std::marker::Copy; use std::rc::Rc; use std::cell::RefCell; #[derive(Debug, Clone)] struct Room { name: String, doors: Vec<String>, } impl Room { fn new(name: String) -> Room { let doors = Vec::new(); Room { name, doors } } fn add_door(&self, room: &Room) -> Room { let mut new_room = self.clone(); new_room.doors.push(room.name.clone()); new_room } fn add_door_mut(&mut self, room: &Room) -> &mut Room { self.doors.push(room.name.clone()); self } } fn main() { let r1 = Room::new(String::from("r1")); let r2 = Room::new(String::from("r2")); let r1 = r1 .add_door(&r2) .add_door(&r2); let r1m = Rc::new(RefCell::new(r1.clone())); let r2m = Rc::new(RefCell::new(r2.clone())); r1m.borrow_mut() .add_door_mut(&r2m.borrow()) .add_door_mut(&r2m.borrow()); r2m.borrow_mut() .add_door_mut(&r1m.borrow()); println!("Immut: {:?}", r1); println!("RcRef: {:?}", r1m); println!("Hello, world!"); }
true
68a2ba263b50738191e70a82f2e702eb4688a14b
Rust
Lokathor/bytemuck
/tests/doc_tests.rs
UTF-8
3,155
3.125
3
[ "Zlib", "Apache-2.0", "MIT" ]
permissive
#![allow(clippy::disallowed_names)] //! Cargo miri doesn't run doctests yet, so we duplicate these here. It's //! probably not that important to sweat keeping these perfectly up to date, but //! we should try to catch the cases where the primary tests are doctests. use bytemuck::*; // Miri doesn't run on doctests, so... copypaste to the rescue. #[test] fn test_transparent_slice() { #[repr(transparent)] struct Slice<T>([T]); unsafe impl<T> TransparentWrapper<[T]> for Slice<T> {} let s = Slice::wrap_ref(&[1u32, 2, 3]); assert_eq!(&s.0, &[1, 2, 3]); let mut buf = [1, 2, 3u8]; let _sm = Slice::wrap_mut(&mut buf); } #[test] fn test_transparent_basic() { #[derive(Default)] struct SomeStruct(u32); #[repr(transparent)] struct MyWrapper(SomeStruct); unsafe impl TransparentWrapper<SomeStruct> for MyWrapper {} // interpret a reference to &SomeStruct as a &MyWrapper let thing = SomeStruct::default(); let wrapped_ref: &MyWrapper = MyWrapper::wrap_ref(&thing); // Works with &mut too. let mut mut_thing = SomeStruct::default(); let wrapped_mut: &mut MyWrapper = MyWrapper::wrap_mut(&mut mut_thing); let _ = (wrapped_ref, wrapped_mut); } // Work around miri not running doctests #[test] fn test_contiguous_doc() { #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq)] enum Foo { A = 0, B = 1, C = 2, D = 3, E = 4, } unsafe impl Contiguous for Foo { type Int = u8; const MIN_VALUE: u8 = Foo::A as u8; const MAX_VALUE: u8 = Foo::E as u8; } assert_eq!(Foo::from_integer(3).unwrap(), Foo::D); assert_eq!(Foo::from_integer(8), None); assert_eq!(Foo::C.into_integer(), 2); assert_eq!(Foo::B.into_integer(), Foo::B as u8); } #[test] fn test_offsetof_vertex() { #[repr(C)] struct Vertex { pos: [f32; 2], uv: [u16; 2], color: [u8; 4], } unsafe impl Zeroable for Vertex {} let pos = offset_of!(Zeroable::zeroed(), Vertex, pos); let uv = offset_of!(Zeroable::zeroed(), Vertex, uv); let color = offset_of!(Zeroable::zeroed(), Vertex, color); assert_eq!(pos, 0); assert_eq!(uv, 8); assert_eq!(color, 12); } #[test] fn test_offsetof_nonpod() { #[derive(Default)] struct Foo { a: u8, b: &'static str, c: i32, } let a_offset = offset_of!(Default::default(), Foo, a); let b_offset = offset_of!(Default::default(), Foo, b); let c_offset = offset_of!(Default::default(), Foo, c); assert_ne!(a_offset, b_offset); assert_ne!(b_offset, c_offset); // We can't check against hardcoded values for a repr(Rust) type, // but prove to ourself this way. let foo = Foo::default(); // Note: offsets are in bytes. let as_bytes = &foo as *const _ as *const u8; // We're using wrapping_offset here because it's not worth // the unsafe block, but it would be valid to use `add` instead, // as it cannot overflow. assert_eq!( &foo.a as *const _ as usize, as_bytes.wrapping_add(a_offset) as usize ); assert_eq!( &foo.b as *const _ as usize, as_bytes.wrapping_add(b_offset) as usize ); assert_eq!( &foo.c as *const _ as usize, as_bytes.wrapping_add(c_offset) as usize ); }
true
7cdc92d974da35120590486f6e1770fc35eca318
Rust
ftxqxd/anagrams
/src/main.rs
UTF-8
6,578
3.25
3
[]
no_license
extern crate argparse; use std::collections::{HashMap, hash_map::DefaultHasher}; use std::hash::BuildHasherDefault; use std::fs::File; use std::path::Path; use std::io::{self, prelude::*}; /// `Identifier` is used to denote a normalized (i.e., lowercased) and sorted string. type Identifier = str; type Dictionary = HashMap<Box<Identifier>, Vec<Box<Identifier>>, BuildHasherDefault<DefaultHasher>>; type Iter<'a> = std::collections::hash_map::Iter<'a, Box<Identifier>, Vec<Box<Identifier>>>; fn subtract(word: &Identifier, pool: &Identifier) -> Option<Box<Identifier>> { let mut result = String::new(); let mut word_chars = word.chars().peekable(); for c in pool.chars() { let next = word_chars.peek(); if next.is_some() && *next.unwrap() == c { word_chars.next(); } else { result.push(c); } } if word_chars.peek().is_none() { return Some(result.into()) } None } fn make_key(word: &str) -> Box<Identifier> { let mut bs: Vec<char> = vec![]; // Take only the alphabetic characters for c in word.chars() { if c.is_alphanumeric() { for lc in c.to_lowercase() { bs.push(lc); } } } bs.sort(); let mut string = String::with_capacity(bs.len()); // lower bound on UTF-8 len for c in bs { string.push(c); } string.into() } pub struct Anagrammer { dictionary: Dictionary, } impl Anagrammer { pub fn from_dictionary_path<P: AsRef<Path>>(path: P) -> io::Result<Self> { let mut file = File::open(path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let mut dictionary = Dictionary::default(); for line in contents.split('\n') { let word = line.trim(); if word.len() == 0 { continue } let bs = make_key(&word); dictionary.entry(bs).or_insert_with(|| vec![]).push(word.into()); } Ok(Anagrammer { dictionary, }) } pub fn from_default_list() -> Self { let mut dictionary = Dictionary::default(); for line in include_str!("english-words").split('\n') { let word = line.trim(); if word.len() == 0 { continue } let bs = make_key(&word); dictionary.entry(bs).or_insert_with(|| vec![]).push(word.into()); } Anagrammer { dictionary, } } fn restrict(&mut self, pool: &Identifier) { self.dictionary.retain(|key, _| { subtract(key, pool).is_some() }); } pub fn restrict_letters(&mut self, minletters: usize, maxletters: usize) { self.dictionary.retain(|key, _| { key.len() >= minletters && key.len() <= maxletters }); } pub fn find_anagrams<F: FnMut(Vec<&str>)>(mut self, pool: &Identifier, minwords: usize, maxwords: usize, mut f: F) { self.restrict(pool); self.anagrams_recur(self.dictionary.iter(), pool, minwords, maxwords, &mut f); } fn anagrams_recur(&self, mut dictionary_iter: Iter, pool: &Identifier, minwords: usize, maxwords: usize, f: &mut dyn FnMut(Vec<&str>)) { if minwords > maxwords { return } if pool.len() == 0 && minwords == 0 { f(vec![]); return } if maxwords == 0 { return } if maxwords == 1 { if let Some((key, words)) = self.dictionary.get_key_value(pool) { let opt = dictionary_iter.next(); if opt.is_none() { return } let (next_key, _) = opt.unwrap(); // Make sure to skip any words that we've already searched // to avoid permutations of the same anagram if next_key as *const _ > key as *const _ { return } for word in words { f(vec![word]); } } return } while let Some((key, words)) = dictionary_iter.next() { if let Some(new_pool) = subtract(key, pool) { let new_minwords = if minwords == 0 { 0 } else { minwords - 1 }; self.anagrams_recur(dictionary_iter.clone(), &new_pool, new_minwords, maxwords - 1, &mut |set| { for word in words { let mut new_set = set.clone(); new_set.push(word); f(new_set); } }) } } } } fn print_set(set: Vec<&str>) { let mut first = true; for item in set.iter().rev() { if !first { print!(" "); } print!("{}", item); first = false; } println!(""); } fn main() -> std::io::Result<()> { use argparse::{ArgumentParser, Store}; let (mut minwords, mut maxwords) = (0, std::usize::MAX); let (mut minletters, mut maxletters) = (0, std::usize::MAX); let mut dictionary_path = String::new(); let mut string = String::new(); { let mut ap = ArgumentParser::new(); ap.set_description("Find anagrams of the given string"); ap.refer(&mut string) .required() .add_argument("string", Store, "String to generate anagrams of"); ap.refer(&mut minwords) .add_option(&["-w", "--min-words"], Store, "The minimum number of words in the generated anagrams"); ap.refer(&mut maxwords) .add_option(&["-W", "--max-words"], Store, "The maximum number of words in the generated anagrams"); ap.refer(&mut minletters) .add_option(&["-l", "--min-words"], Store, "The minimum number of letters per word in the generated anagrams"); ap.refer(&mut maxletters) .add_option(&["-L", "--max-words"], Store, "The maximum number of letters per word in the generated anagrams"); ap.refer(&mut dictionary_path) .add_option(&["-f", "--dictionary"], Store, "The path of the word list"); ap.parse_args_or_exit(); } let mut anagrammer = if dictionary_path.len() == 0 { Anagrammer::from_default_list() } else { Anagrammer::from_dictionary_path(&dictionary_path)? }; if (minletters, maxletters) != (0, std::usize::MAX) { anagrammer.restrict_letters(minletters, maxletters); } let bytes = make_key(&string); anagrammer.find_anagrams(&bytes, minwords, maxwords, &mut print_set); Ok(()) }
true
c2ec02fa579009d4feb89c49de89d2b5edab510f
Rust
Sherif-Abdou/basic-algebra
/src/main.rs
UTF-8
3,952
3.265625
3
[]
no_license
extern crate regex; mod equation; mod equation_solver; mod expression; use crate::equation::*; use crate::equation_solver::*; use crate::expression::*; use regex::Regex; use std::env; fn tokenize(argument: &str) -> Vec<String> { let re = Regex::new(r"[0-9]+|\+|-|\*|/|=|[A-Za-z]").unwrap(); let mut values: Vec<String> = re .find_iter(argument) .map(|val| String::from(val.as_str())) .collect(); let mut insert_indexes: Vec<usize> = vec![]; for (i, value) in values.iter().enumerate() { if i + 1 < values.len() { if let Ok(_) = value.parse::<f64>() { if values[i + 1].chars().all(char::is_alphanumeric) { insert_indexes.push(i + 1); } } } } for index in insert_indexes.iter() { values.insert(*index, String::from("*")); } values } fn recursive_solve(mut solver: EquationSolver) -> EquationSolver { let mut new_eq_result = solver.solve_step(); let new_eq = new_eq_result.unwrap(); return if let ExpressionType::Variable(_) = new_eq.left_side { new_eq } else { recursive_solve(new_eq) }; } fn simplify_side(expression: ExpressionType) -> ExpressionType { match &expression { ExpressionType::Addition(box_tuple) => { let values = (*box_tuple.clone()); if let (ExpressionType::Constant(a), ExpressionType::Constant(b)) = (simplify_side(values.0), simplify_side(values.1)) { return ExpressionType::Constant(a + b); } } ExpressionType::Subtraction(box_tuple) => { let values = (*box_tuple.clone()); if let (ExpressionType::Constant(a), ExpressionType::Constant(b)) = (simplify_side(values.0), simplify_side(values.1)) { return ExpressionType::Constant(a - b); } } ExpressionType::Multiplication(box_tuple) => { let values = (*box_tuple.clone()); if let (ExpressionType::Constant(a), ExpressionType::Constant(b)) = (simplify_side(values.0), simplify_side(values.1)) { return ExpressionType::Constant(a * b); } } ExpressionType::Division(box_tuple) => { let values = (*box_tuple.clone()); if let (ExpressionType::Constant(a), ExpressionType::Constant(b)) = (simplify_side(values.0), simplify_side(values.1)) { return ExpressionType::Constant(a / b); } } _ => { return expression.clone(); } } return expression.clone(); } fn eqsolver_to_string(solver: EquationSolver) -> String { if let (ExpressionType::Variable(letter), ExpressionType::Constant(value)) = (&solver.left_side, &solver.right_side) { return format!("{} = {}", letter, value); } return String::from(format!("Unable to create a string from {:?}", solver)); } fn main() { let args: Vec<String> = env::args().collect(); if let Some(raw_tokens) = args.get(1) { let tokens = tokenize(raw_tokens); let mut equation = equation::Equation::from_tokens(tokens); let parsed_values = equation.parse().expect("Couldn't find equal sign"); let expressions = ( expression::ExpressionType::parse_tokens(parsed_values.0), expression::ExpressionType::parse_tokens(parsed_values.1), ); let mut solver = equation_solver::EquationSolver::from(expressions.0.unwrap(), expressions.1.unwrap()); let solved = recursive_solve(solver); let simplfied_side = EquationSolver::from(solved.left_side, simplify_side(solved.right_side)); println!("{}", eqsolver_to_string(simplfied_side)); } else { println!("Missing input"); } }
true
95d73efbb6a1fe1fe4f03f9cb7d24ff531dd29ed
Rust
dgodd/adventofcode
/2022/src/day5.rs
UTF-8
2,714
3.359375
3
[]
no_license
use regex::Regex; #[derive(Debug)] pub struct Input { crates: Vec<Vec<char>>, instructions: Vec<(u32, u8, u8)>, } #[aoc_generator(day5)] pub fn input_generator(input: &str) -> Input { let pos = input.find("\n\n").unwrap(); let (inp1, inp2) = input.split_at(pos); let num: usize = ((inp1.lines().next().unwrap().len() as f64) / 4.0).ceil() as usize; let crates = (0..num).map(|i| { let mut arr = vec![]; for l in inp1.lines() { let line = l.as_bytes(); let c = line[(i * 4) + 1] as char; if c != ' ' { arr.push(c); } } arr }).collect::<Vec<Vec<char>>>(); let re = Regex::new(r"move ([0-9]+) from ([0-9]+) to ([0-9]+)").unwrap(); let instructions = inp2.lines().filter(|l| l.len() > 0).map(|l| { let caps = re.captures(l).unwrap(); ( caps.get(1).unwrap().as_str().parse().unwrap(), caps.get(2).unwrap().as_str().parse::<u8>().unwrap() - 1, caps.get(3).unwrap().as_str().parse::<u8>().unwrap() - 1, ) }).collect::<Vec<(u32, u8, u8)>>(); Input{ crates: crates, instructions: instructions } } #[aoc(day5, part1)] pub fn solve_part1(input: &Input) -> String { // let mut crates: Vec<&[char]> = input.crates.iter().map(|c| c.as_slice()).collect(); let mut crates: Vec<Vec<char>> = input.crates.clone(); for inst in &input.instructions { // println!("INST: {:?}", inst); for _ in 0..inst.0 { let c = crates[inst.1 as usize].remove(0); crates[inst.2 as usize].insert(0, c); } // println!("CS: {:?}", &cs); // println!("CRATES: {:?}", &crates); } crates.iter().map(|c| c[0]).collect() } #[aoc(day5, part2)] pub fn solve_part2(input: &Input) -> String { let mut crates: Vec<Vec<char>> = input.crates.clone(); for inst in &input.instructions { // println!("INST: {:?}", inst); let cs: Vec<char> = crates[inst.1 as usize].splice(0..inst.0 as usize, vec![]).collect(); crates[inst.2 as usize].splice(0..0, cs); // println!("CRATES: {:?}", &crates); } crates.iter().map(|c| c[0]).collect() } #[cfg(test)] mod tests { use super::{input_generator as gen, solve_part1 as part1, solve_part2 as part2}; const SAMPLE: &str = " [D] \n[N] [C] \n[Z] [M] [P]\n1 2 3 \n\nmove 1 from 2 to 1\nmove 3 from 1 to 3\nmove 2 from 2 to 1\nmove 1 from 1 to 2\n"; #[test] fn sample1() { let data = gen(SAMPLE); assert_eq!(part1(&data), "CMZ"); } #[test] fn sample2() { let data = gen(SAMPLE); assert_eq!(part2(&data), "MCD"); } }
true
2bb21fe7bae774174c23130347a3f75c315058ee
Rust
mvanbem/oot-explorer
/oot-explorer-vrom/src/borrowed.rs
UTF-8
1,427
2.90625
3
[ "MIT" ]
permissive
use std::fmt::{self, Debug, Formatter}; use std::ops::{Deref, Range}; use crate::{VromAddr, VromError}; /// A slice representing all of VROM. #[derive(Clone, Copy)] pub struct Vrom<'a>(pub &'a [u8]); impl<'a> Vrom<'a> { pub fn slice_from(self, from: VromAddr) -> Result<&'a [u8], VromError> { self.0 .get(from.0 as usize..) .ok_or_else(|| VromError::OutOfRange { from: Some(from), to: None, vrom_size: self.0.len() as u32, }) } pub fn slice_to(self, to: VromAddr) -> Result<&'a [u8], VromError> { self.0 .get(..to.0 as usize) .ok_or_else(|| VromError::OutOfRange { from: None, to: Some(to), vrom_size: self.0.len() as u32, }) } pub fn slice(self, range: Range<VromAddr>) -> Result<&'a [u8], VromError> { self.0 .get(range.start.0 as usize..range.end.0 as usize) .ok_or_else(|| VromError::OutOfRange { from: Some(range.start), to: Some(range.end), vrom_size: self.0.len() as u32, }) } } impl<'a> Debug for Vrom<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "Vrom(_)") } } impl<'a> Deref for Vrom<'a> { type Target = [u8]; fn deref(&self) -> &[u8] { self.0 } }
true
b61b4863dc4a0358fd34be9151cb6567790cbed4
Rust
aonorin/immi
/src/animations/mod.rs
UTF-8
3,798
3.828125
4
[]
no_license
//! Contains everything related to the animations that are supported by this library. use Matrix; /// Describes a way to modify an element during an animation. pub trait Animation { /// Takes an animation percentage between `0.0` and `1.0`. Returns the most-inner matrix to /// multiply the element with. fn animate(&self, percent: f32) -> Matrix; } /// Relative movement of the element from `initial_offset` to `[0.0, 0.0]`. pub struct Translation { /// The initial position of the element at the start of the animation. /// /// A value of `1.0` corresponds to half of the size of the element. pub initial_offset: [f32; 2], } impl Translation { /// Builds a `Translation` object. #[inline] pub fn new(initial_offset: [f32; 2]) -> Translation { Translation { initial_offset: initial_offset, } } } impl Animation for Translation { #[inline] fn animate(&self, percent: f32) -> Matrix { let x = (1.0 - percent) * self.initial_offset[0]; let y = (1.0 - percent) * self.initial_offset[1]; Matrix::translate(x, y) } } /// Zooms the element from `initial_zoom` to `1.0`. pub struct Zoom { /// The initial zoom of the element at the start of the animation. /// /// `1.0` is the normal size. `2.0` means twice bigger. `0.5` means twice smaller. pub initial_zoom: f32, } impl Zoom { /// Builds a `Zoom` object. #[inline] pub fn new(initial_zoom: f32) -> Zoom { Zoom { initial_zoom: initial_zoom, } } } impl Animation for Zoom { #[inline] fn animate(&self, percent: f32) -> Matrix { let s = (1.0 - percent) * (self.initial_zoom - 1.0) + 1.0; Matrix::scale(s) } } /// Describes how an animation should be interpolated. pub trait Interpolation { /// Takes a number of ticks (in nanoseconds) representing the current point in time, a number /// of ticks representing the point in time when the animation has started or will start, the /// duration in nanoseconds, and returns a value between 0.0 and 1.0 representing the progress /// of the animation. /// /// Implementations typically return `0.0` when `now < start` and `1.0` when /// `now > start + duration_ns`. fn calculate(&self, now: u64, start: u64, duration_ns: u64) -> f32; } /// A linear animation. The animation progresses at a constant rate. #[derive(Copy, Clone, Default, Debug)] pub struct Linear; impl Interpolation for Linear { #[inline] fn calculate(&self, now: u64, start: u64, duration_ns: u64) -> f32 { let anim_progress = (now - start) as f32 / duration_ns as f32; if anim_progress >= 1.0 { 1.0 } else if anim_progress <= 0.0 { 0.0 } else { anim_progress } } } /// An ease-out animation. The animation progresses quickly and then slows down before reaching its /// final position. #[derive(Copy, Clone, Debug)] pub struct EaseOut { /// The formula is `1.0 - exp(-linear_progress * factor)`. /// /// The higher the factor, the quicker the element will reach its destination. pub factor: f32, } impl EaseOut { /// Builds a `EaseOut` object. #[inline] pub fn new(factor: f32) -> EaseOut { EaseOut { factor: factor, } } } impl Default for EaseOut { #[inline] fn default() -> EaseOut { EaseOut { factor: 10.0 } } } impl Interpolation for EaseOut { #[inline] fn calculate(&self, now: u64, start: u64, duration_ns: u64) -> f32 { if now < start { return 0.0; } let anim_progress = (now - start) as f32 / duration_ns as f32; 1.0 - (-anim_progress * self.factor).exp() } }
true
8e28f0da86e9c205afb09e5468057c75215992b1
Rust
zayenz/advent-of-code-2018
/day18/src/main.rs
UTF-8
5,334
2.65625
3
[ "MIT" ]
permissive
#![allow( dead_code, unused_imports, clippy::needless_range_loop, clippy::ptr_arg, clippy::char_lit_as_u8 )] use std::char; use std::cmp::{max, min}; use std::fmt; use std::io::BufRead; use std::iter::*; use std::ops::*; use std::str; use std::str::FromStr; use std::{io, process}; use enum_map::*; use failure::bail; use failure::err_msg; use failure::Error; use hashbrown::{HashMap, HashSet}; use itertools::Itertools; use rayon::prelude::*; use stats::Frequencies; use structopt::StructOpt; use strum_macros::EnumString; use tap::{TapOps, TapOptionOps, TapResultOps}; use aoc2018::dense_grid::Grid; use aoc2018::dense_grid::*; use aoc2018::input::*; use aoc2018::matrix::*; use aoc2018::position::*; use std::collections::BTreeSet; use std::fmt::Display; use std::fmt::Formatter; type Input = Grid<Tile>; type Output = String; #[derive(EnumString, Enum, Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] enum Tile { Empty, Open, Trees, Lumberyard, } use crate::Tile::*; impl Default for Tile { fn default() -> Self { Empty } } impl Display for Tile { fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> { write!( f, "{}", match *self { Empty => ' ', Open => '.', Trees => '|', Lumberyard => '#', } ) } } fn read_input() -> Result<Input, Error> { let stdin = io::stdin(); let lines = stdin .lock() .lines() .map(|s| s.unwrap().trim().to_owned()) .filter(|s| !s.is_empty()) .map(|s| s.chars().collect_vec()) .collect_vec(); let height = lines.len(); let width = lines[0].len(); assert!(lines.iter().map(|v| v.len()).all_equal()); let mut grid = Grid::from_origo(width + 2, height + 2); for x in 0..width { for y in 0..height { let pos = (x + 1, y + 1); match lines[y][x] { '.' => { grid[pos] = Open; } '#' => { grid[pos] = Lumberyard; } '|' => { grid[pos] = Trees; } ch => { bail!(format!( "Unrecognized input charachter '{}' at {},{}", ch, x, y )); } } } } // println!("Read initial map:"); // println!("{}", grid); Ok(grid) } fn count(it: &mut impl Iterator<Item = Tile>) -> EnumMap<Tile, usize> { let mut counts = EnumMap::new(); for value in it { counts[value] += 1; } counts } fn checksum(grid: &Grid<Tile>) -> usize { let frequencies = count(&mut grid.values.iter().cloned()); frequencies[Trees] * frequencies[Lumberyard] } fn evolve(input: &Grid<Tile>, iterations: usize) -> Grid<Tile> { let mut current = input.clone(); for _ in 0..iterations { let mut next = current.clone(); for x in 1..(input.width - 1) { for y in 1..(input.height - 1) { let pos: Position = (x, y).into(); let tile = current[pos]; let neighbours = count(&mut connect8(pos).map(|n| current[n])); next[pos] = match tile { Empty => Empty, Open => { if neighbours[Trees] >= 3 { Trees } else { Open } } Trees => { if neighbours[Lumberyard] >= 3 { Lumberyard } else { Trees } } Lumberyard => { if neighbours[Lumberyard] >= 1 && neighbours[Trees] >= 1 { Lumberyard } else { Open } } } } } current = next; } current } fn solve1(input: &mut Input) -> Result<Output, Error> { let result = evolve(input, 10); Ok(format!("{}", checksum(&result))) } fn solve2(input: &mut Input) -> Result<Output, Error> { let result = evolve(input, 1000); Ok(format!("{}", checksum(&result))) } #[derive(StructOpt, Debug)] #[structopt(name = "day6")] struct Opt { /// Part to solve, either 1 or 2 #[structopt(short = "-p", long = "--part", default_value = "1")] part: u8, } fn run() -> Result<(), Error> { let mut input = read_input()?; let options: Opt = Opt::from_args(); let output = if options.part == 1 { solve1(&mut input)? } else { solve2(&mut input)? }; println!("{}", output); Ok(()) } fn main() { match run() { Ok(()) => process::exit(0), Err(error) => { eprintln!("Error while solving problem: {}", error); for cause in error.iter_causes() { eprintln!("{}", cause) } process::exit(1) } } } #[cfg(test)] mod test { use super::*; }
true
21eba04f0540bf545afe15c821faf897cb944533
Rust
mnts26/aws-sdk-rust
/sdk/smithy-types/src/lib.rs
UTF-8
6,226
2.84375
3
[ "Apache-2.0" ]
permissive
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ pub mod base64; pub mod instant; pub mod primitive; pub mod retry; use std::collections::HashMap; pub use crate::instant::Instant; #[derive(Debug, PartialEq, Clone)] pub struct Blob { inner: Vec<u8>, } impl Blob { pub fn new<T: Into<Vec<u8>>>(input: T) -> Self { Blob { inner: input.into(), } } pub fn into_inner(self) -> Vec<u8> { self.inner } } impl AsRef<[u8]> for Blob { fn as_ref(&self) -> &[u8] { &self.inner } } /* ANCHOR: document */ /// Document Type /// /// Document types represents protocol-agnostic open content that is accessed like JSON data. /// Open content is useful for modeling unstructured data that has no schema, data that can't be /// modeled using rigid types, or data that has a schema that evolves outside of the purview of a model. /// The serialization format of a document is an implementation detail of a protocol. #[derive(Debug, Clone, PartialEq)] pub enum Document { Object(HashMap<String, Document>), Array(Vec<Document>), Number(Number), String(String), Bool(bool), Null, } /// A number type that implements Javascript / JSON semantics, modeled on serde_json: /// https://docs.serde.rs/src/serde_json/number.rs.html#20-22 #[derive(Debug, Clone, Copy, PartialEq)] pub enum Number { PosInt(u64), NegInt(i64), Float(f64), } macro_rules! to_num_fn { ($name:ident, $typ:ident) => { /// Converts to a `$typ`. This conversion may be lossy. pub fn $name(&self) -> $typ { match self { Number::PosInt(val) => *val as $typ, Number::NegInt(val) => *val as $typ, Number::Float(val) => *val as $typ, } } }; } impl Number { to_num_fn!(to_f32, f32); to_num_fn!(to_f64, f64); to_num_fn!(to_i8, i8); to_num_fn!(to_i16, i16); to_num_fn!(to_i32, i32); to_num_fn!(to_i64, i64); to_num_fn!(to_u8, u8); to_num_fn!(to_u16, u16); to_num_fn!(to_u32, u32); to_num_fn!(to_u64, u64); } /* ANCHOR_END: document */ pub use error::Error; pub mod error { use crate::retry::{ErrorKind, ProvideErrorKind}; use std::collections::HashMap; use std::fmt; use std::fmt::{Display, Formatter}; /// Generic Error type /// /// For many services, Errors are modeled. However, many services only partially model errors or don't /// model errors at all. In these cases, the SDK will return this generic error type to expose the /// `code`, `message` and `request_id`. #[derive(Debug, Eq, PartialEq, Default, Clone)] pub struct Error { code: Option<String>, message: Option<String>, request_id: Option<String>, extras: HashMap<&'static str, String>, } #[derive(Default)] pub struct Builder { inner: Error, } impl Builder { pub fn message(&mut self, message: impl Into<String>) -> &mut Self { self.inner.message = Some(message.into()); self } pub fn code(&mut self, code: impl Into<String>) -> &mut Self { self.inner.code = Some(code.into()); self } pub fn request_id(&mut self, request_id: impl Into<String>) -> &mut Self { self.inner.request_id = Some(request_id.into()); self } /// Set a custom field on the error metadata /// /// Typically, these will be accessed with an extension trait: /// ```rust /// use smithy_types::Error; /// const HOST_ID: &str = "host_id"; /// trait S3ErrorExt { /// fn extended_request_id(&self) -> Option<&str>; /// } /// /// impl S3ErrorExt for Error { /// fn extended_request_id(&self) -> Option<&str> { /// self.extra(HOST_ID) /// } /// } /// /// fn main() { /// // Extension trait must be brought into scope /// use S3ErrorExt; /// let sdk_response: Result<(), Error> = Err(Error::builder().custom(HOST_ID, "x-1234").build()); /// if let Err(err) = sdk_response { /// println!("request id: {:?}, extended request id: {:?}", err.request_id(), err.extended_request_id()); /// } /// } /// ``` pub fn custom(&mut self, key: &'static str, value: impl Into<String>) -> &mut Self { self.inner.extras.insert(key, value.into()); self } pub fn build(&mut self) -> Error { std::mem::take(&mut self.inner) } } impl Error { pub fn code(&self) -> Option<&str> { self.code.as_deref() } pub fn message(&self) -> Option<&str> { self.message.as_deref() } pub fn request_id(&self) -> Option<&str> { self.request_id.as_deref() } pub fn extra(&self, key: &'static str) -> Option<&str> { self.extras.get(key).map(|k| k.as_str()) } pub fn builder() -> Builder { Builder::default() } pub fn into_builder(self) -> Builder { Builder { inner: self } } } impl ProvideErrorKind for Error { fn retryable_error_kind(&self) -> Option<ErrorKind> { None } fn code(&self) -> Option<&str> { Error::code(self) } } impl Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut fmt = f.debug_struct("Error"); if let Some(code) = &self.code { fmt.field("code", code); } if let Some(message) = &self.message { fmt.field("message", message); } if let Some(req_id) = &self.request_id { fmt.field("request_id", req_id); } for (k, v) in &self.extras { fmt.field(k, &v); } fmt.finish() } } impl std::error::Error for Error {} }
true
ffed375083eded69ddb77547ad8070a37fd06536
Rust
TGElder/rust
/frontier/src/simulation/settlement/extensions/update_current_population.rs
UTF-8
7,833
3.015625
3
[ "CC-BY-4.0" ]
permissive
use crate::settlement::{Settlement, SettlementClass}; use crate::simulation::settlement::SettlementSimulation; use crate::simulation::MaxAbsPopulationChange; use crate::traits::has::HasParameters; use crate::traits::Micros; impl<T, D> SettlementSimulation<T, D> where T: HasParameters + Micros, { pub async fn update_current_population(&self, settlement: Settlement) -> Settlement { self.try_update_settlement(settlement).await } async fn try_update_settlement(&self, settlement: Settlement) -> Settlement { let game_micros = self.cx.micros().await; if settlement.last_population_update_micros >= game_micros { return settlement; } let change = clamp_population_change( get_population_change(&settlement, &game_micros), self.max_abs_population_change(&settlement.class).await, ); let current_population = settlement.current_population + change; Settlement { current_population, last_population_update_micros: game_micros, ..settlement } } async fn max_abs_population_change(&self, settlement_class: &SettlementClass) -> f64 { let MaxAbsPopulationChange { homeland, town } = self.cx.parameters().simulation.max_abs_population_change; match settlement_class { SettlementClass::Homeland => homeland, SettlementClass::Town => town, } } } fn get_population_change(settlement: &Settlement, game_micros: &u128) -> f64 { let half_life = settlement.gap_half_life.as_micros() as f64; if half_life == 0.0 { settlement.target_population - settlement.current_population } else { let last_update_micros = settlement.last_population_update_micros; let elapsed = (game_micros - last_update_micros) as f64; let exponent = elapsed / half_life; let gap_decay = 1.0 - 0.5f64.powf(exponent); (settlement.target_population - settlement.current_population) * gap_decay } } fn clamp_population_change(population_change: f64, max_abs_change: f64) -> f64 { population_change.max(-max_abs_change).min(max_abs_change) } #[cfg(test)] mod tests { use crate::parameters::Parameters; use crate::settlement::SettlementClass::Town; use super::*; use commons::almost::Almost; use commons::async_trait::async_trait; use commons::v2; use futures::executor::block_on; use std::sync::Arc; use std::time::Duration; struct Cx { micros: u128, parameters: Parameters, } impl HasParameters for Cx { fn parameters(&self) -> &Parameters { &self.parameters } } #[async_trait] impl Micros for Cx { async fn micros(&self) -> u128 { self.micros } } fn cx() -> Cx { let mut parameters = Parameters::default(); parameters.simulation.max_abs_population_change = MaxAbsPopulationChange { town: 100.0, homeland: 0.0, }; Cx { micros: 33, parameters, } } #[test] fn should_move_current_population_towards_target_population_when_target_more() { // Given let settlement = Settlement { position: v2(1, 2), current_population: 1.0, target_population: 100.0, gap_half_life: Duration::from_micros(10), last_population_update_micros: 11, class: Town, ..Settlement::default() }; let sim = SettlementSimulation::new(cx(), Arc::new(())); // When let settlement = block_on(sim.update_current_population(settlement)); // Then assert!(settlement.current_population.almost(&78.45387355842092)); assert_eq!(settlement.last_population_update_micros, 33); } #[test] fn should_move_current_population_towards_target_population_when_target_less() { // Given let settlement = Settlement { position: v2(1, 2), current_population: 100.0, target_population: 1.0, gap_half_life: Duration::from_micros(10), last_population_update_micros: 11, class: Town, ..Settlement::default() }; let sim = SettlementSimulation::new(cx(), Arc::new(())); // When let settlement = block_on(sim.update_current_population(settlement)); // Then assert!(settlement.current_population.almost(&22.54612644157907)); assert_eq!(settlement.last_population_update_micros, 33); } #[test] fn should_set_current_population_to_target_population_if_half_life_zero() { // Given let settlement = Settlement { position: v2(1, 2), current_population: 100.0, target_population: 1.0, gap_half_life: Duration::from_micros(0), last_population_update_micros: 11, class: Town, ..Settlement::default() }; let sim = SettlementSimulation::new(cx(), Arc::new(())); // When let settlement = block_on(sim.update_current_population(settlement)); // Then assert!(settlement .current_population .almost(&settlement.target_population)); assert_eq!(settlement.last_population_update_micros, 33); } #[test] fn should_not_change_settlement_if_last_population_update_after_game_micros() { // Given let settlement = Settlement { position: v2(1, 2), current_population: 100.0, target_population: 1.0, gap_half_life: Duration::from_micros(10), last_population_update_micros: 33, class: Town, ..Settlement::default() }; let cx = Cx { micros: 11, ..cx() }; let sim = SettlementSimulation::new(cx, Arc::new(())); // When let result = block_on(sim.update_current_population(settlement.clone())); // Then assert_eq!(result, settlement); } #[test] fn should_clamp_population_change_to_max_abs_population_change_when_increasing() { // Given let settlement = Settlement { position: v2(1, 2), current_population: 1.0, target_population: 100.0, gap_half_life: Duration::from_micros(10), last_population_update_micros: 11, class: Town, ..Settlement::default() }; let mut cx = cx(); cx.parameters.simulation.max_abs_population_change.town = 1.0; let sim = SettlementSimulation::new(cx, Arc::new(())); // When let settlement = block_on(sim.update_current_population(settlement)); // Then assert!(settlement.current_population.almost(&2.0)); assert_eq!(settlement.last_population_update_micros, 33); } #[test] fn should_clamp_population_change_to_max_abs_population_change_when_decreasing() { // Given let settlement = Settlement { position: v2(1, 2), current_population: 100.0, target_population: 1.0, gap_half_life: Duration::from_micros(10), last_population_update_micros: 11, class: Town, ..Settlement::default() }; let mut cx = cx(); cx.parameters.simulation.max_abs_population_change.town = 1.0; let sim = SettlementSimulation::new(cx, Arc::new(())); // When let settlement = block_on(sim.update_current_population(settlement)); // Then assert!(settlement.current_population.almost(&99.0)); assert_eq!(settlement.last_population_update_micros, 33); } }
true
22d690ee781fb5010868263ac774a7bbe68e5f2f
Rust
martinrlilja/foodtech-quiz
/src/main.rs
UTF-8
9,092
2.578125
3
[]
no_license
use anyhow::{Error, Result}; use rand::prelude::*; use ring::{digest, hmac}; use serde::{Deserialize, Serialize}; use std::{env, net::SocketAddr}; use tokio::fs; use warp::{ http::{self, Response}, reject, reply::{self, Reply}, Filter, }; use controllers::{QuizController, UserWriter}; use models::{Config, UserState}; mod controllers; mod filters; mod models; #[derive(Clone, Debug, Deserialize, Serialize)] struct QuizQuestionReply<'a> { question: &'a str, choices: Vec<&'a str>, token: &'a str, } #[derive(Clone, Debug, Deserialize, Serialize)] struct QuizAnswerRequest { answer: String, } #[derive(Clone, Debug, Deserialize, Serialize)] struct QuizAnswerReply<'a> { is_correct: bool, correct: Vec<&'a str>, token: &'a str, } #[derive(Clone, Debug, Deserialize, Serialize)] struct WheelSpinReply<'a> { points: u32, token: &'a str, } #[derive(Clone, Debug, Deserialize, Serialize)] struct CheckoutRequest { codes: Vec<String>, email: String, consent: bool, } #[derive(Clone, Debug, Deserialize, Serialize)] struct CheckoutReply { points: u32, } #[derive(Clone, Debug, Deserialize, Serialize)] struct StatsReply { total_points: u32, } #[derive(Clone, Debug, Deserialize, Serialize)] struct ErrorReply { error: ErrorCode, } #[derive(Clone, Debug, Deserialize, Serialize)] enum ErrorCode { NotFound, } #[tokio::main] async fn main() -> Result<()> { let bind_addr = env::var("BIND").unwrap_or_else(|_err| "127.0.0.1:3030".into()); let bind_addr: SocketAddr = bind_addr.parse()?; let cors_origin = env::var("CORS_ORIGIN").unwrap_or_else(|_err| "http://localhost:1313".into()); let secret_key = env::var("SECRET_KEY") .map_err(|err| Error::new(err)) .and_then(|env| { let mut secret_key = [0u8; digest::SHA256_OUTPUT_LEN]; hex::decode_to_slice(env, &mut secret_key)?; Ok(secret_key) }) .or_else(|_err| -> Result<_> { let mut secret_key = [0u8; digest::SHA256_OUTPUT_LEN]; rand::rngs::OsRng.fill(&mut secret_key); println!("No secret key was specified, generated a new secret key."); println!("Rerun with SECRET_KEY={}", hex::encode(secret_key)); Ok(secret_key) })?; let secret_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_ref()); let config = fs::read_to_string("quiz.toml").await?; let config: Config = toml::de::from_str(&config)?; let user_writer = UserWriter::new("users.csv")?; let quiz_controller = QuizController::new( secret_key, config.quiz.iter(), config.code.iter(), config.wheel.iter(), user_writer, ); let get_quiz = warp::path!("quiz" / String) .and(warp::get()) .and(filters::user_state(quiz_controller.clone())) .and(filters::with_quiz_controller(quiz_controller.clone())) .map( |quiz_name: String, user_state: UserState, quiz_controller: QuizController| { let question = quiz_controller.next_question(&quiz_name, &user_state); match question { None => reply::with_status( reply::json(&ErrorReply { error: ErrorCode::NotFound, }), http::StatusCode::NOT_FOUND, ) .into_response(), Some(question) => { let mut choices = question .correct .iter() .chain(question.incorrect.iter()) .map(|choice| choice.as_str()) .collect::<Vec<_>>(); let mut rng = thread_rng(); choices.shuffle(&mut rng); let token = quiz_controller.encode_user(&user_state).unwrap(); let reply = QuizQuestionReply { question: &question.question, choices, token: &token, }; reply::json(&reply).into_response() } } }, ); let post_quiz = warp::path!("quiz" / String) .and(warp::post()) .and(warp::filters::body::json()) .and(filters::user_state(quiz_controller.clone())) .and(filters::with_quiz_controller(quiz_controller.clone())) .map( |quiz_name: String, body: QuizAnswerRequest, mut user_state: UserState, quiz_controller: QuizController| { let answer = quiz_controller.answer_question(&quiz_name, &mut user_state, &body.answer); match answer { None => reply::with_status( reply::json(&ErrorReply { error: ErrorCode::NotFound, }), http::StatusCode::NOT_FOUND, ) .into_response(), Some((is_correct, question)) => { let correct = question.correct.iter().map(|c| c.as_str()).collect(); let token = quiz_controller.encode_user(&user_state).unwrap(); let reply = QuizAnswerReply { is_correct, correct, token: &token, }; reply::json(&reply).into_response() } } }, ); let post_wheel = warp::path!("wheel" / String) .and(warp::post()) .and(filters::user_state(quiz_controller.clone())) .and(filters::with_quiz_controller(quiz_controller.clone())) .map( |wheel_name: String, mut user_state: UserState, quiz_controller: QuizController| { let wheel = quiz_controller.spin_wheel(&wheel_name, &mut user_state); match wheel { None => reply::with_status( reply::json(&ErrorReply { error: ErrorCode::NotFound, }), http::StatusCode::NOT_FOUND, ) .into_response(), Some(points) => { let token = quiz_controller.encode_user(&user_state).unwrap(); let reply = WheelSpinReply { points, token: &token, }; reply::json(&reply).into_response() } } }, ); let stats = warp::path!("stats") .and(warp::get()) .and(filters::user_state(quiz_controller.clone())) .and(filters::with_quiz_controller(quiz_controller.clone())) .map(|user_state: UserState, quiz_controller: QuizController| { let points = quiz_controller.points(&user_state); let reply = StatsReply { total_points: points, }; reply::json(&reply).into_response() }); let checkout = warp::path!("checkout") .and(warp::post()) .and(warp::filters::body::json()) .and(filters::user_state(quiz_controller.clone())) .and(filters::with_quiz_controller(quiz_controller.clone())) .and_then(|body: CheckoutRequest, user_state: UserState, quiz_controller: QuizController| async move { if !body.email.contains('@') || body.email.len() < 3 { let reply = ErrorReply { error: ErrorCode::NotFound }; Ok(reply::with_status( reply::json(&reply), http::StatusCode::NOT_FOUND, ).into_response()) } else { let points = quiz_controller.register_user(&body.codes, &body.email, body.consent, &user_state).await; let reply = CheckoutReply { points }; Ok::<_, reject::Rejection>(reply::json(&reply).into_response()) } }); let script = warp::path!("static" / "script.js") .and(warp::get()) .map(|| { const SCRIPT: &str = include_str!("script.js"); Response::builder() .header("Content-Type", "application/javascript") .body(SCRIPT) }) .with(warp::compression::gzip()); let cors = warp::cors() .allow_origin(cors_origin.as_str()) .allow_methods(vec!["GET", "POST"]) .allow_headers(vec!["Authorization", "Content-Type"]); let server = get_quiz .or(post_quiz) .or(post_wheel) .or(stats) .or(checkout) .or(script) .with(cors); warp::serve(server).run(bind_addr).await; Ok(()) }
true
3a1c0f63b68ce54c3aa252e6c78eb6e8ac0f17c1
Rust
julesartd/Exercices-Kattis
/nastyhacks/src/main.rs
UTF-8
708
3.046875
3
[]
no_license
use std::io::{self, prelude::*}; fn main() { let mut entree = String::new(); io::stdin().read_to_string(&mut entree).expect("lecture données"); let mut line = entree.lines(); line.next(); for l in line { let mut mot = l.split_whitespace(); let i = mot.next().expect("i").parse::<i32>().expect("Entier"); let e = mot.next().expect("e").parse::<i32>().expect("Entier"); let c = mot.next().expect("c").parse::<i32>().expect("Entier"); decide(i,e,c); } } fn decide(r:i32,e:i32,c:i32) { if e -c > r { println!("advertise"); } else if e -c < r { println!("do not advertise"); } else { println!("does not matter"); } }
true
858dc55d3e027a927ec2b981fb08af990c06cf7f
Rust
AndrewGaspar/fortknight
/fortknight/src/parser/classify/types.rs
UTF-8
14,506
2.5625
3
[ "MIT" ]
permissive
use crate::parser::lex::{KeywordTokenKind, Token, TokenKind}; use super::statements::{ DeclarationTypeSpec, DerivedTypeSpec, IntegerTypeSpec, IntrinsicTypeSpec, KindSelector, Spanned, TypeParamSpec, TypeParamValue, }; use super::{Classifier, TakeUntil}; impl<'input, 'arena> Classifier<'input, 'arena> { /// R701: type-param-value /// /// Parse a type-param-value form start fn type_param_value(&mut self) -> Option<Spanned<TypeParamValue<'arena>>> { if self.check(TokenKind::Star) { Some(Spanned::new( TypeParamValue::Star, self.tokenizer.bump().unwrap().span, )) } else if self.check(TokenKind::Colon) { Some(Spanned::new( TypeParamValue::Colon, self.tokenizer.bump().unwrap().span, )) } else { // TODO: Check for expression start and emit an "unexpected token" error if it // couldn't possibly be an expression. let expr = self.expr()?; Some(Spanned::new( TypeParamValue::ScalarIntExpr(self.arena.expressions.alloc(expr.val)), expr.span, )) } } /// R703: declaration-type-spec /// /// Parses a declaration-type-spec from the start of the type. Returns None if the parse fails - /// does not consume the failure token. pub(super) fn declaration_type_spec(&mut self) -> Option<Spanned<DeclarationTypeSpec<'arena>>> { if self.check_intrinsic_type() { let spec = self.intrinsic_type_spec()?; Some(Spanned::new( DeclarationTypeSpec::Intrinsic(spec.val), spec.span, )) } else if self.check(TokenKind::Keyword(KeywordTokenKind::Type)) { let start_span = self.tokenizer.bump().unwrap().span; if self.check(TokenKind::LeftParen) { self.tokenizer.bump().unwrap(); } else { self.emit_unexpected_token(); return None; } enum Either<'a> { Intrinsic(Spanned<IntrinsicTypeSpec<'a>>), Derived(DerivedTypeSpec<'a>), Wildcard, }; let type_spec = if self.check_intrinsic_type() { Either::Intrinsic(self.intrinsic_type_spec()?) } else if self.check_name() { Either::Derived(self.derived_type_spec()?.val) } else if self.check(TokenKind::Star) { self.tokenizer.bump(); Either::Wildcard } else { self.emit_unexpected_token(); return None; }; let end_span = if self.check(TokenKind::RightParen) { self.tokenizer.bump().unwrap().span } else { self.emit_unexpected_token(); return None; }; let span = start_span.concat(end_span); match type_spec { Either::Intrinsic(intrinsic) => Some(Spanned::new( DeclarationTypeSpec::TypeIntrinsic(intrinsic.val), span, )), Either::Derived(derived) => Some(Spanned::new( DeclarationTypeSpec::TypeDerived(derived), span, )), Either::Wildcard => Some(Spanned::new(DeclarationTypeSpec::TypeWildcard, span)), } } else if self.check(TokenKind::Keyword(KeywordTokenKind::Class)) { let start_span = self.tokenizer.bump().unwrap().span; if self.check(TokenKind::LeftParen) { self.tokenizer.bump().unwrap(); } else { self.emit_unexpected_token(); return None; } enum Either<'a> { Derived(DerivedTypeSpec<'a>), Wildcard, }; let type_spec = if self.check_name() { Either::Derived(self.derived_type_spec()?.val) } else if self.check(TokenKind::Star) { self.tokenizer.bump(); Either::Wildcard } else { self.emit_unexpected_token(); return None; }; let end_span = if self.check(TokenKind::RightParen) { self.tokenizer.bump().unwrap().span } else { self.emit_unexpected_token(); return None; }; let span = start_span.concat(end_span); match type_spec { Either::Derived(derived) => Some(Spanned::new( DeclarationTypeSpec::ClassDerived(derived), span, )), Either::Wildcard => Some(Spanned::new(DeclarationTypeSpec::ClassWildcard, span)), } } else { self.emit_unexpected_token(); return None; } } /// R704: intrinsic-type-spec /// /// Parses an intrinsic type spec from its start. Returns None if the parse fails and does not /// consume the failing token. fn intrinsic_type_spec(&mut self) -> Option<Spanned<IntrinsicTypeSpec<'arena>>> { if self.check(TokenKind::Keyword(KeywordTokenKind::Integer)) { self.type_spec(KeywordTokenKind::Integer) } else if self.check(TokenKind::Keyword(KeywordTokenKind::Real)) { self.type_spec(KeywordTokenKind::Real) } else if self.check(TokenKind::Keyword(KeywordTokenKind::Complex)) { self.type_spec(KeywordTokenKind::Complex) } else if self.check(TokenKind::Keyword(KeywordTokenKind::Character)) { self.type_spec(KeywordTokenKind::Character) } else if self.check(TokenKind::Keyword(KeywordTokenKind::Logical)) { self.type_spec(KeywordTokenKind::Logical) } else if self.check(TokenKind::Keyword(KeywordTokenKind::Double)) { match self.tokenizer.peek_nth_kind(1) { Some(TokenKind::Keyword(KeywordTokenKind::Precision)) => { let start_span = self.tokenizer.bump().unwrap().span; let end_span = self.tokenizer.bump().unwrap().span; Some(Spanned::new( IntrinsicTypeSpec::DoublePrecision, start_span.concat(end_span), )) } _ => { self.emit_unexpected_token(); return None; } } } else if self.check(TokenKind::Keyword(KeywordTokenKind::DoublePrecision)) { Some(Spanned::new( IntrinsicTypeSpec::DoublePrecision, self.tokenizer.bump().unwrap().span, )) } else { self.emit_unexpected_token(); return None; } } /// R704: intrinsic-type-spec for types with kind-selector fn type_spec( &mut self, expected_keyword: KeywordTokenKind, ) -> Option<Spanned<IntrinsicTypeSpec<'arena>>> { let span = match self.tokenizer.peek_kind() { Some(TokenKind::Keyword(k)) if k == expected_keyword => { self.tokenizer.bump().unwrap().span } _ => { self.tokenizer .push_expected(TokenKind::Keyword(expected_keyword)); self.emit_unexpected_token(); return None; } }; let kind = match self.tokenizer.peek_kind() { Some(TokenKind::LeftParen) => Some(self.kind_selector()?), _ => None, }; let span = kind.map_or(span, |k| span.concat(k.span)); let kind = kind.map(|k| k.val); match expected_keyword { KeywordTokenKind::Integer => Some(Spanned::new( IntrinsicTypeSpec::Integer(IntegerTypeSpec(kind)), span, )), KeywordTokenKind::Real => Some(Spanned::new(IntrinsicTypeSpec::Real(kind), span)), KeywordTokenKind::Complex => Some(Spanned::new(IntrinsicTypeSpec::Complex(kind), span)), KeywordTokenKind::Character => { Some(Spanned::new(IntrinsicTypeSpec::Character(kind), span)) } KeywordTokenKind::Logical => Some(Spanned::new(IntrinsicTypeSpec::Logical(kind), span)), k => panic!( "Internal compiler error: `{:?}` is not a intrinsic type with a kind selector", k ), } } /// R705: integer-type-spec /// /// Parses from INTEGER fn integer_type_spec(&mut self) -> Option<Spanned<IntegerTypeSpec<'arena>>> { let spec = self.type_spec(KeywordTokenKind::Integer)?; let (spec, span) = match spec { Spanned { val: IntrinsicTypeSpec::Integer(spec), span, } => (spec, span), _ => { panic!("Internal compiler error - integer type spec was not an integer type spec!") } }; Some(Spanned::new(spec, span)) } /// R706: kind-selector /// /// Parses the kind-selector of a type from the parentheses fn kind_selector(&mut self) -> Option<Spanned<KindSelector<'arena>>> { let begin_span = if self.check(TokenKind::LeftParen) { self.tokenizer.bump().unwrap().span } else { self.emit_unexpected_token(); return None; }; if self.check(TokenKind::Keyword(KeywordTokenKind::Kind)) { match self.tokenizer.peek_nth(1).map(|t| t.kind) { Some(TokenKind::Equals) => { self.tokenizer.bump(); // consume KIND self.tokenizer.bump(); // consume = } Some(TokenKind::LeftParen) => { // assume we're in an expression and let the expression parsing take over } _ => { self.emit_expected_token(&[TokenKind::Equals, TokenKind::LeftParen]); return None; } } } else { // try parsing as an expression }; let expr = self.expr()?; let end_span = if self.check(TokenKind::RightParen) { self.tokenizer.bump().unwrap().span } else { self.emit_unexpected_token(); return None; }; // parse scalar-int-constant-expr Some(Spanned::new( KindSelector(self.arena.expressions.alloc(expr.val)), begin_span.concat(end_span), )) } /// R754: derived-type-spec /// /// Parses from the `type-name` fn derived_type_spec(&mut self) -> Option<Spanned<DerivedTypeSpec<'arena>>> { let (name, start_span) = if self.check_name() { let t = self.tokenizer.bump().unwrap(); ( t.try_intern_contents(&mut self.interner, &self.text) .unwrap(), t.span, ) } else { self.emit_unexpected_token(); return None; }; if self.check(TokenKind::LeftParen) { self.tokenizer.bump(); } else { return Some(Spanned::new( DerivedTypeSpec { name, spec_list: &[], }, start_span, )); }; let mut error_encountered = false; let spec_list = self.arena.type_param_specs.alloc_extend( std::iter::once(self.type_param_spec()?.val).chain(std::iter::from_fn(|| { if self.check(TokenKind::Comma) { self.tokenizer.bump(); } else if self.check(TokenKind::RightParen) { // End of list - return none return None; } else { error_encountered = true; self.emit_unexpected_token(); return None; } match self.type_param_spec() { Some(spec) => Some(spec.val), None => { error_encountered = true; return None; } } })), ); if error_encountered { // skip to the closing ), EOS, or EOF self.take_until(|lookahead| match lookahead { Some(Token { kind: TokenKind::RightParen, .. }) | None => TakeUntil::Stop, Some(t) if Self::is_eos(t) => TakeUntil::Stop, _ => TakeUntil::Continue, }) .unwrap(); } let end_span = if self.check(TokenKind::RightParen) { self.tokenizer.bump().unwrap().span } else { self.emit_unexpected_token(); return None; }; Some(Spanned::new( DerivedTypeSpec { name, spec_list }, start_span.concat(end_span), )) } /// R755: type-param-spec /// /// Parses a type-param-spec fn type_param_spec(&mut self) -> Option<Spanned<TypeParamSpec<'arena>>> { let keyword_and_span = if self.check_name() { // Might be a keyword, check for = match self.tokenizer.peek_nth_kind(1) { Some(TokenKind::Equals) => { let keyword = self.tokenizer.bump().unwrap(); // keyword self.tokenizer.bump(); // = Some(( keyword .try_intern_contents(&mut self.interner, &self.text) .unwrap(), keyword.span, )) } _ => { // Might be an expression, back off None } } } else { None }; let value = self.type_param_value()?; let span = keyword_and_span.map_or(value.span, |(_, span)| span.concat(value.span)); Some(Spanned::new( TypeParamSpec { keyword: keyword_and_span.map(|(k, _)| k), value: value.val, }, span, )) } }
true
c8934e48e8c23ce1cfb902717be7a5202a071b05
Rust
carrotflakes/kantera
/src/lerp.rs
UTF-8
239
2.921875
3
[ "MIT" ]
permissive
use std::ops::{Add, Mul}; pub trait Lerp: Copy + Add<Output = Self> + Mul<f64, Output = Self> { #[inline(always)] fn lerp(&self, other: &Self, v: f64) -> Self { *self * (1.0 - v) + *other * v } } impl Lerp for f64 {}
true
7b740592a56d90bacc7d1d6a89e4a1443086f3be
Rust
atuinsh/atuin
/atuin-common/src/utils.rs
UTF-8
5,899
2.8125
3
[ "MIT" ]
permissive
use std::env; use std::path::PathBuf; use chrono::{Months, NaiveDate}; use rand::RngCore; use uuid::Uuid; pub fn random_bytes<const N: usize>() -> [u8; N] { let mut ret = [0u8; N]; rand::thread_rng().fill_bytes(&mut ret); ret } // basically just ripped from the uuid crate. they have it as unstable, but we can use it fine. const fn encode_unix_timestamp_millis(millis: u64, random_bytes: &[u8; 10]) -> Uuid { let millis_high = ((millis >> 16) & 0xFFFF_FFFF) as u32; let millis_low = (millis & 0xFFFF) as u16; let random_and_version = (random_bytes[0] as u16 | ((random_bytes[1] as u16) << 8) & 0x0FFF) | (0x7 << 12); let mut d4 = [0; 8]; d4[0] = (random_bytes[2] & 0x3F) | 0x80; d4[1] = random_bytes[3]; d4[2] = random_bytes[4]; d4[3] = random_bytes[5]; d4[4] = random_bytes[6]; d4[5] = random_bytes[7]; d4[6] = random_bytes[8]; d4[7] = random_bytes[9]; Uuid::from_fields(millis_high, millis_low, random_and_version, &d4) } pub fn uuid_v7() -> Uuid { let bytes = random_bytes(); let now: u64 = chrono::Utc::now().timestamp_millis() as u64; encode_unix_timestamp_millis(now, &bytes) } pub fn uuid_v4() -> String { Uuid::new_v4().as_simple().to_string() } pub fn has_git_dir(path: &str) -> bool { let mut gitdir = PathBuf::from(path); gitdir.push(".git"); gitdir.exists() } // detect if any parent dir has a git repo in it // I really don't want to bring in libgit for something simple like this // If we start to do anything more advanced, then perhaps pub fn in_git_repo(path: &str) -> Option<PathBuf> { let mut gitdir = PathBuf::from(path); while gitdir.parent().is_some() && !has_git_dir(gitdir.to_str().unwrap()) { gitdir.pop(); } // No parent? then we hit root, finding no git if gitdir.parent().is_some() { return Some(gitdir); } None } // TODO: more reliable, more tested // I don't want to use ProjectDirs, it puts config in awkward places on // mac. Data too. Seems to be more intended for GUI apps. #[cfg(not(target_os = "windows"))] pub fn home_dir() -> PathBuf { let home = std::env::var("HOME").expect("$HOME not found"); PathBuf::from(home) } #[cfg(target_os = "windows")] pub fn home_dir() -> PathBuf { let home = std::env::var("USERPROFILE").expect("%userprofile% not found"); PathBuf::from(home) } pub fn config_dir() -> PathBuf { let config_dir = std::env::var("XDG_CONFIG_HOME").map_or_else(|_| home_dir().join(".config"), PathBuf::from); config_dir.join("atuin") } pub fn data_dir() -> PathBuf { let data_dir = std::env::var("XDG_DATA_HOME") .map_or_else(|_| home_dir().join(".local").join("share"), PathBuf::from); data_dir.join("atuin") } pub fn get_current_dir() -> String { // Prefer PWD environment variable over cwd if available to better support symbolic links match env::var("PWD") { Ok(v) => v, Err(_) => match env::current_dir() { Ok(dir) => dir.display().to_string(), Err(_) => String::from(""), }, } } pub fn get_days_from_month(year: i32, month: u32) -> i64 { let Some(start) = NaiveDate::from_ymd_opt(year, month, 1) else { return 30 }; let Some(end) = start.checked_add_months(Months::new(1)) else { return 30 }; end.signed_duration_since(start).num_days() } #[cfg(test)] mod tests { use super::*; use std::env; use std::collections::HashSet; #[test] fn test_dirs() { // these tests need to be run sequentially to prevent race condition test_config_dir_xdg(); test_config_dir(); test_data_dir_xdg(); test_data_dir(); } fn test_config_dir_xdg() { env::remove_var("HOME"); env::set_var("XDG_CONFIG_HOME", "/home/user/custom_config"); assert_eq!( config_dir(), PathBuf::from("/home/user/custom_config/atuin") ); env::remove_var("XDG_CONFIG_HOME"); } fn test_config_dir() { env::set_var("HOME", "/home/user"); env::remove_var("XDG_CONFIG_HOME"); assert_eq!(config_dir(), PathBuf::from("/home/user/.config/atuin")); env::remove_var("HOME"); } fn test_data_dir_xdg() { env::remove_var("HOME"); env::set_var("XDG_DATA_HOME", "/home/user/custom_data"); assert_eq!(data_dir(), PathBuf::from("/home/user/custom_data/atuin")); env::remove_var("XDG_DATA_HOME"); } fn test_data_dir() { env::set_var("HOME", "/home/user"); env::remove_var("XDG_DATA_HOME"); assert_eq!(data_dir(), PathBuf::from("/home/user/.local/share/atuin")); env::remove_var("HOME"); } #[test] fn days_from_month() { assert_eq!(get_days_from_month(2023, 1), 31); assert_eq!(get_days_from_month(2023, 2), 28); assert_eq!(get_days_from_month(2023, 3), 31); assert_eq!(get_days_from_month(2023, 4), 30); assert_eq!(get_days_from_month(2023, 5), 31); assert_eq!(get_days_from_month(2023, 6), 30); assert_eq!(get_days_from_month(2023, 7), 31); assert_eq!(get_days_from_month(2023, 8), 31); assert_eq!(get_days_from_month(2023, 9), 30); assert_eq!(get_days_from_month(2023, 10), 31); assert_eq!(get_days_from_month(2023, 11), 30); assert_eq!(get_days_from_month(2023, 12), 31); // leap years assert_eq!(get_days_from_month(2024, 2), 29); } #[test] fn uuid_is_unique() { let how_many: usize = 1000000; // for peace of mind let mut uuids: HashSet<Uuid> = HashSet::with_capacity(how_many); // there will be many in the same millisecond for _ in 0..how_many { let uuid = uuid_v7(); uuids.insert(uuid); } assert_eq!(uuids.len(), how_many); } }
true
f4d73e0cd363e5687b334485e696c188c8904e6a
Rust
Txuritan/stry
/stry-frontend-user/src/controllers/edit.rs
UTF-8
4,068
2.75
3
[ "MIT" ]
permissive
use { crate::{ models::ChapterForm, pages, utils::{self, wrap}, }, chrono::Utc, std::borrow::Cow, stry_backend::DataBackend, warp::{ http::{ header::{HeaderValue, LOCATION}, Response, StatusCode, }, hyper::Body, reply, Rejection, Reply, }, }; #[stry_macros::get("/story/{_story_id}")] pub async fn story( #[data] _backend: DataBackend, #[header("Accept-Language")] _languages: String, _story_id: String, ) -> Result<impl Reply, Rejection> { Ok(reply::html("story")) } #[stry_macros::get("/story/{story_id}/{chapter_page}")] pub async fn chapter_get( #[data] backend: DataBackend, #[header("Accept-Language")] languages: String, story_id: String, chapter_page: u32, ) -> Result<impl Reply, Rejection> { wrap(move || async move { let time = Utc::now(); let mut chapter_page = chapter_page as i32; if chapter_page == 0 { chapter_page = 1; } let user_lang = utils::get_languages(&languages); match backend.get_story(story_id.clone().into()).await? { Some(story) => { if chapter_page <= story.chapters && chapter_page != 0 { match backend .get_chapter(story.id.clone().into(), chapter_page) .await? { Some(chapter) => { let rendered: String = pages::edit::Chapter::new( format!( "edit | chapter {}: {} | {}", chapter_page, chapter.name, story.name ), time, story, chapter, user_lang, ) .into_string()?; Ok(rendered.into_response()) } None => { let rendered = pages::ErrorPage::server_error( format!("503 server error | {}", story.name), time, user_lang, ) .into_string()?; Ok(rendered.into_response()) } } } else { let mut res = Response::new(Body::empty()); res.headers_mut().insert( LOCATION, HeaderValue::from_str(&format!("/edit/story/{}", story_id)).unwrap(), ); *res.status_mut() = StatusCode::MOVED_PERMANENTLY; Ok(res) } } None => { let rendered = pages::ErrorPage::server_error("404 not found", time, user_lang) .into_string()?; Ok(rendered.into_response()) } } }) .await } #[stry_macros::post("/story/{story_id}/{chapter_page}")] pub async fn chapter_post( #[data] backend: DataBackend, story_id: String, chapter_page: u32, #[form] body: ChapterForm, ) -> Result<impl Reply, Rejection> { wrap(move || async move { let story_id: Cow<'static, str> = story_id.into(); backend .update_chapter( story_id.clone(), chapter_page as i32, body.pre.into(), body.main.into(), body.post.into(), ) .await?; let mut res = Response::new(Body::empty()); res.headers_mut().insert( LOCATION, HeaderValue::from_str(&format!("/edit/story/{}", story_id)).unwrap(), ); *res.status_mut() = StatusCode::MOVED_PERMANENTLY; Ok(res) }) .await }
true
6ef5b7e00a85ca50511ced48d6d6201a0e323602
Rust
TLmaK0/rustneat
/src/organism.rs
UTF-8
7,422
2.90625
3
[ "MIT" ]
permissive
use ctrnn::{Ctrnn, CtrnnNeuralNetwork}; use genome::Genome; use std::cmp; use std::cmp::Ordering; /// An organism is a Genome with fitness. /// Also maitain a fitenss measure of the organism #[allow(missing_docs)] #[derive(Debug, Clone)] pub struct Organism { pub genome: Genome, pub fitness: f64, } impl Ord for Organism { fn cmp(&self, other: &Self) -> Ordering { other.fitness.partial_cmp(&self.fitness).unwrap() } } impl Eq for Organism {} impl PartialEq for Organism { fn eq(&self, other: &Self) -> bool { self.fitness == other.fitness } } impl PartialOrd for Organism { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Organism { /// Create a new organmism form a single genome. pub fn new(genome: Genome) -> Organism { Organism { genome: genome, fitness: 0f64, } } /// Return a new Orgnaism by mutating this Genome and fitness of zero pub fn mutate(&self) -> Organism { let mut new_genome = self.genome.clone(); new_genome.mutate(); Organism::new(new_genome) } /// Mate this organism with another pub fn mate(&self, other: &Organism) -> Organism { Organism::new( self.genome .mate(&other.genome, self.fitness < other.fitness), ) } /// Activate this organism in the NN pub fn activate(&mut self, sensors: Vec<f64>, outputs: &mut Vec<f64>) { let neurons_len = self.genome.len(); let sensors_len = sensors.len(); let tau = vec![0.01; neurons_len]; let theta = self.get_bias(); let mut i = sensors.clone(); if neurons_len < sensors_len { i.truncate(neurons_len); } else { i = [i, vec![0.0; neurons_len - sensors_len]].concat(); } let wji = self.get_weights(); let activations = Ctrnn::default().activate_nn( 0.1, 0.01, &CtrnnNeuralNetwork { y: &vec![0.0; neurons_len], tau: &tau, wji: &wji, theta: &theta, i: &i, }, ); if sensors_len < neurons_len { let outputs_activations = activations.split_at(sensors_len).1.to_vec(); for n in 0..cmp::min(outputs_activations.len(), outputs.len()) { outputs[n] = outputs_activations[n]; } } } fn get_weights(&self) -> Vec<f64> { let neurons_len = self.genome.len(); let mut matrix = vec![0.0; neurons_len * neurons_len]; for gene in self.genome.get_genes() { if gene.enabled() { matrix[(gene.out_neuron_id() * neurons_len) + gene.in_neuron_id()] = gene.weight() } } matrix } fn get_bias(&self) -> Vec<f64> { let neurons_len = self.genome.len(); let mut matrix = vec![0.0; neurons_len]; for gene in self.genome.get_genes() { if gene.is_bias() { matrix[gene.in_neuron_id()] += 1f64; } } matrix } } #[cfg(test)] use gene::Gene; #[cfg(test)] mod tests { use super::*; use genome::Genome; #[test] fn should_propagate_signal_without_hidden_layers() { let mut organism = Organism::new(Genome::default()); organism.genome.add_gene(Gene::new(0, 1, 1f64, true, false)); let sensors = vec![1.0]; let mut output = vec![0f64]; organism.activate(sensors, &mut output); assert!(output[0] > 0.5f64, "{:?} is not bigger than 0.9", output[0]); let mut organism = Organism::new(Genome::default()); organism .genome .add_gene(Gene::new(0, 1, -2f64, true, false)); let sensors = vec![1f64]; let mut output = vec![0f64]; organism.activate(sensors, &mut output); assert!( output[0] < 0.1f64, "{:?} is not smaller than 0.1", output[0] ); } #[test] fn should_propagate_signal_over_hidden_layers() { let mut organism = Organism::new(Genome::default()); organism.genome.add_gene(Gene::new(0, 1, 0f64, true, false)); organism.genome.add_gene(Gene::new(0, 2, 5f64, true, false)); organism.genome.add_gene(Gene::new(2, 1, 5f64, true, false)); let sensors = vec![0f64]; let mut output = vec![0f64]; organism.activate(sensors, &mut output); assert!(output[0] > 0.9f64, "{:?} is not bigger than 0.9", output[0]); } #[test] fn should_work_with_cyclic_networks() { let mut organism = Organism::new(Genome::default()); organism.genome.add_gene(Gene::new(0, 1, 2f64, true, false)); organism.genome.add_gene(Gene::new(1, 2, 2f64, true, false)); organism.genome.add_gene(Gene::new(2, 1, 2f64, true, false)); let mut output = vec![0f64]; organism.activate(vec![10f64], &mut output); assert!(output[0] > 0.9, "{:#?} is not bigger than 0.9", output[0]); let mut organism = Organism::new(Genome::default()); organism .genome .add_gene(Gene::new(0, 1, -2f64, true, false)); organism .genome .add_gene(Gene::new(1, 2, -2f64, true, false)); organism .genome .add_gene(Gene::new(2, 1, -2f64, true, false)); let mut output = vec![0f64]; organism.activate(vec![1f64], &mut output); assert!(output[0] < 0.1, "{:?} is not smaller than 0.1", output[0]); } #[test] fn activate_organims_sensor_without_enough_neurons_should_ignore_it() { let mut organism = Organism::new(Genome::default()); organism.genome.add_gene(Gene::new(0, 1, 1f64, true, false)); let sensors = vec![0f64, 0f64, 0f64]; let mut output = vec![0f64]; organism.activate(sensors, &mut output); } #[test] fn should_allow_multiple_output() { let mut organism = Organism::new(Genome::default()); organism.genome.add_gene(Gene::new(0, 1, 1f64, true, false)); let sensors = vec![0f64]; let mut output = vec![0f64, 0f64]; organism.activate(sensors, &mut output); } #[test] fn should_be_able_to_get_matrix_representation_of_the_neuron_connections() { let mut organism = Organism::new(Genome::default()); organism.genome.add_gene(Gene::new(0, 1, 1f64, true, false)); organism .genome .add_gene(Gene::new(1, 2, 0.5f64, true, false)); organism .genome .add_gene(Gene::new(2, 1, 0.5f64, true, false)); organism .genome .add_gene(Gene::new(2, 2, 0.75f64, true, false)); organism.genome.add_gene(Gene::new(1, 0, 1f64, true, false)); assert_eq!( organism.get_weights(), vec![0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.0, 0.5, 0.75] ); } #[test] fn should_not_raise_exception_if_less_neurons_than_required() { let mut organism = Organism::new(Genome::default()); organism.genome.add_gene(Gene::new(0, 1, 1f64, true, false)); let sensors = vec![0f64, 0f64, 0f64]; let mut output = vec![0f64, 0f64, 0f64]; organism.activate(sensors, &mut output); } }
true
c50851b5f1d207b2fba4d7d9ab7306efb3da975e
Rust
fstiffo/scale-rust-old
/src/scale.rs
UTF-8
4,697
2.609375
3
[]
no_license
#![warn(clippy::all)] extern crate chrono; use chrono::NaiveDate; extern crate serde; use serde::{Deserialize, Serialize}; // use serde::Serialize; extern crate serde_json; use serde_json::Result; use std::io::prelude::*; use std::fs::{File, OpenOptions}; use std::path::Path; #[derive(Serialize, Deserialize)] pub enum Condomino { Michela, Gerardo, Elena, Giulia, } use Condomino as Co; #[derive(Serialize, Deserialize)] pub enum Operazione { VersamentoQuote(Condomino, u32), PagamentoScale, AltraSpesa(String, u32), AltroVersamento(String, u32), Prestito(u32), Restituzione(u32), } use Operazione as Op; pub type Movimento = (NaiveDate, Operazione); #[derive(Serialize, Deserialize)] pub struct Param { costo_scale: u32, num_pulize_mese: u32, quota_mensile: u32, } pub type Attuale = (NaiveDate, Param); #[macro_export] macro_rules! from_ymd { ($y:expr, $m:expr, $d:expr) => { <NaiveDate>::from_ymd($y, $m, $d); }; } macro_rules! since { ($d1:expr, $d2:expr) => { <NaiveDate>::signed_duration_since($d1, $d2); }; } const ANNO_ZERO: i32 = 2019; const MESE_ZERO: u32 = 7; const GIORNO_ZERO: u32 = 1; #[derive(Serialize, Deserialize)] pub struct Scale { tempo_zero: NaiveDate, attuale: Attuale, condomini: [Condomino; 4], movimenti: Vec<Movimento>, } fn setup_zero() -> Scale { let tempo_zero = from_ymd!(ANNO_ZERO, MESE_ZERO, GIORNO_ZERO); let attuale: Attuale = ( tempo_zero, Param { costo_scale: 20, num_pulize_mese: 2, quota_mensile: 12, }, ); let condomini = [Co::Michela, Co::Gerardo, Co::Elena, Co::Giulia]; let movimenti: Vec<Movimento> = vec![ ( tempo_zero, Op::AltroVersamento("Appianamento".to_string(), 333), ), (tempo_zero, Op::VersamentoQuote(Co::Michela, 74)), (tempo_zero, Op::VersamentoQuote(Co::Gerardo, 78)), (tempo_zero, Op::VersamentoQuote(Co::Elena, 48)), (from_ymd!(2019, 7, 22), Op::Prestito(500)), (from_ymd!(2019, 7, 11), Op::PagamentoScale), ]; Scale { tempo_zero, attuale, condomini, movimenti, } } impl Scale { pub fn new() -> Scale { let json_file_path = Path::new("scale.json"); if let Ok(json_file) = File::open(json_file_path) { if let Ok(deserialized_scala) = serde_json::from_reader(json_file) as Result<Scale> { deserialized_scala } else { setup_zero() } } else { setup_zero() } } fn contabile(&self, op: &Operazione) -> i32 { match *op { Op::VersamentoQuote(_, u) => u as i32, Op::PagamentoScale => -(self.attuale.1.costo_scale as i32), Op::AltraSpesa(_, u) => -(u as i32), Op::AltroVersamento(_, u) => u as i32, Op::Prestito(u) => -(u as i32), Op::Restituzione(u) => u as i32, } } pub fn cassa(&self) -> i32 { let mut somma = 0; for i in self.movimenti.iter().map(|(_, op)| self.contabile(op)) { somma += i } somma } fn altro_contabile(&self, op: &Operazione) -> i32 { match *op { Op::AltraSpesa(_, u) => -(u as i32), Op::AltroVersamento(_, u) => u as i32, _ => 0, } } pub fn tesoretto(&self, oggi: NaiveDate) -> i32 { let mut altro = 0; for i in self .movimenti .iter() .map(|(_, op)| self.altro_contabile(op)) { altro += i } let mut pagamenti = 0; for i in self.movimenti.iter().map(|(_, op)| { if let Op::PagamentoScale = op { self.attuale.1.costo_scale as i32 } else { 0 } }) { pagamenti += i } let mesi = since!(oggi, self.tempo_zero).num_days() as i32 / 30; let num_condomini = self.condomini.len() as i32; mesi * num_condomini * self.attuale.1.quota_mensile as i32 + altro - pagamenti } pub fn print_serialize(&self) -> Result<()> { let j = serde_json::to_string(&self)?; println!("{}", j); Ok(()) } pub fn save_json(&self) -> std::io::Result<()> { let json_file_path = Path::new("scale.json"); let mut json_file = OpenOptions::new().write(true).create(true).open(json_file_path)?; if let Ok(j) = serde_json::to_string(&self) { write!(json_file, "{}", j)?; } Ok(()) } }
true
ab27d207e116acf7fb1eb7347752b901a7395af5
Rust
marco-c/gecko-dev-comments-removed
/third_party/rust/idna/src/punycode.rs
UTF-8
7,801
2.84375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
use std::char; use std::u32; static BASE: u32 = 36; static T_MIN: u32 = 1; static T_MAX: u32 = 26; static SKEW: u32 = 38; static DAMP: u32 = 700; static INITIAL_BIAS: u32 = 72; static INITIAL_N: u32 = 0x80; static DELIMITER: char = '-'; #[inline] fn adapt(mut delta: u32, num_points: u32, first_time: bool) -> u32 { delta /= if first_time { DAMP } else { 2 }; delta += delta / num_points; let mut k = 0; while delta > ((BASE - T_MIN) * T_MAX) / 2 { delta /= BASE - T_MIN; k += BASE; } k + (((BASE - T_MIN + 1) * delta) / (delta + SKEW)) } #[inline] pub fn decode_to_string(input: &str) -> Option<String> { decode(input).map(|chars| chars.into_iter().collect()) } pub fn decode(input: &str) -> Option<Vec<char>> { Some(Decoder::default().decode(input).ok()?.collect()) } #[derive(Default)] pub(crate) struct Decoder { insertions: Vec<(usize, char)>, } impl Decoder { pub(crate) fn decode<'a>(&'a mut self, input: &'a str) -> Result<Decode<'a>, ()> { self.insertions.clear(); let (base, input) = match input.rfind(DELIMITER) { None => ("", input), Some(position) => ( &input[..position], if position > 0 { &input[position + 1..] } else { input }, ), }; if !base.is_ascii() { return Err(()); } let base_len = base.len(); let mut length = base_len as u32; let mut code_point = INITIAL_N; let mut bias = INITIAL_BIAS; let mut i = 0; let mut iter = input.bytes(); loop { let previous_i = i; let mut weight = 1; let mut k = BASE; let mut byte = match iter.next() { None => break, Some(byte) => byte, }; loop { let digit = match byte { byte @ b'0'..=b'9' => byte - b'0' + 26, byte @ b'A'..=b'Z' => byte - b'A', byte @ b'a'..=b'z' => byte - b'a', _ => return Err(()), } as u32; if digit > (u32::MAX - i) / weight { return Err(()); } i += digit * weight; let t = if k <= bias { T_MIN } else if k >= bias + T_MAX { T_MAX } else { k - bias }; if digit < t { break; } if weight > u32::MAX / (BASE - t) { return Err(()); } weight *= BASE - t; k += BASE; byte = match iter.next() { None => return Err(()), Some(byte) => byte, }; } bias = adapt(i - previous_i, length + 1, previous_i == 0); if i / (length + 1) > u32::MAX - code_point { return Err(()); } code_point += i / (length + 1); i %= length + 1; let c = match char::from_u32(code_point) { Some(c) => c, None => return Err(()), }; for (idx, _) in &mut self.insertions { if *idx >= i as usize { *idx += 1; } } self.insertions.push((i as usize, c)); length += 1; i += 1; } self.insertions.sort_by_key(|(i, _)| *i); Ok(Decode { base: base.chars(), insertions: &self.insertions, inserted: 0, position: 0, len: base_len + self.insertions.len(), }) } } pub(crate) struct Decode<'a> { base: std::str::Chars<'a>, pub(crate) insertions: &'a [(usize, char)], inserted: usize, position: usize, len: usize, } impl<'a> Iterator for Decode<'a> { type Item = char; fn next(&mut self) -> Option<Self::Item> { loop { match self.insertions.get(self.inserted) { Some((pos, c)) if *pos == self.position => { self.inserted += 1; self.position += 1; return Some(*c); } _ => {} } if let Some(c) = self.base.next() { self.position += 1; return Some(c); } else if self.inserted >= self.insertions.len() { return None; } } } fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len - self.position; (len, Some(len)) } } impl<'a> ExactSizeIterator for Decode<'a> { fn len(&self) -> usize { self.len - self.position } } #[inline] pub fn encode_str(input: &str) -> Option<String> { let mut buf = String::with_capacity(input.len()); encode_into(input.chars(), &mut buf).ok().map(|()| buf) } pub fn encode(input: &[char]) -> Option<String> { let mut buf = String::with_capacity(input.len()); encode_into(input.iter().copied(), &mut buf) .ok() .map(|()| buf) } pub(crate) fn encode_into<I>(input: I, output: &mut String) -> Result<(), ()> where I: Iterator<Item = char> + Clone, { let (mut input_length, mut basic_length) = (0, 0); for c in input.clone() { input_length += 1; if c.is_ascii() { output.push(c); basic_length += 1; } } if basic_length > 0 { output.push('-') } let mut code_point = INITIAL_N; let mut delta = 0; let mut bias = INITIAL_BIAS; let mut processed = basic_length; while processed < input_length { let min_code_point = input .clone() .map(|c| c as u32) .filter(|&c| c >= code_point) .min() .unwrap(); if min_code_point - code_point > (u32::MAX - delta) / (processed + 1) { return Err(()); } delta += (min_code_point - code_point) * (processed + 1); code_point = min_code_point; for c in input.clone() { let c = c as u32; if c < code_point { delta += 1; if delta == 0 { return Err(()); } } if c == code_point { let mut q = delta; let mut k = BASE; loop { let t = if k <= bias { T_MIN } else if k >= bias + T_MAX { T_MAX } else { k - bias }; if q < t { break; } let value = t + ((q - t) % (BASE - t)); output.push(value_to_digit(value)); q = (q - t) / (BASE - t); k += BASE; } output.push(value_to_digit(q)); bias = adapt(delta, processed + 1, processed == basic_length); delta = 0; processed += 1; } } delta += 1; code_point += 1; } Ok(()) } #[inline] fn value_to_digit(value: u32) -> char { match value { 0..=25 => (value as u8 + b'a') as char, 26..=35 => (value as u8 - 26 + b'0') as char, _ => panic!(), } }
true
57da01c94bd7722078f773045cbfd6fcfe437a67
Rust
KanoczTomas/bitcoin_playground
/src/types/points.rs
UTF-8
590
3.421875
3
[]
no_license
use crate::types::{Point, ECpoint}; #[derive(Debug, PartialEq,Clone,Copy)] /// Represents all possible points (even those not on curve!). pub enum Points{ /// Infinity. Infinity, /// A point with a coordinate. FinitePoint(Point) } impl std::convert::From<ECpoint> for Points { fn from(p: ECpoint)-> Self { match p { ECpoint::Infinity => Points::Infinity, ECpoint::OnCurve(p) => Points::FinitePoint(p) } } } impl std::convert::From<Point> for Points { fn from(p: Point) -> Self { Points::FinitePoint(p) } }
true
40bb350022275dd29ccd0685d13fa13fb3ba2dd6
Rust
jimblandy/fxsnapshot
/src/query/stream.rs
UTF-8
1,430
3.390625
3
[ "MIT", "Apache-2.0" ]
permissive
use fallible_iterator::FallibleIterator; use std::rc::Rc; #[derive(Clone)] pub struct Stream<'a, T, E>(Rc<dyn CloneableStream<'a, T, E> + 'a>); impl<'a, T: 'a, E> Stream<'a, T, E> { pub fn new<I>(iter: I) -> Stream<'a, I::Item, I::Error> where I: 'a + FallibleIterator<Item=T, Error=E> + Clone { Stream(Rc::new(iter)) } } trait CloneableStream<'a, T, E> { fn rc_clone(&self) -> Rc<dyn CloneableStream<'a, T, E> + 'a>; fn cs_next(&mut self) -> Result<Option<T>, E>; } impl<'a, I> CloneableStream<'a, I::Item, I::Error> for I where I: 'a + FallibleIterator + Clone, I::Item: 'a { fn rc_clone(&self) -> Rc<dyn CloneableStream<'a, I::Item, I::Error> + 'a> { Rc::new(self.clone()) } fn cs_next(&mut self) -> Result<Option<I::Item>, I::Error> { self.next() } } impl<'a, T, E> FallibleIterator for Stream<'a, T, E> { type Item = T; type Error = E; fn next(&mut self) -> Result<Option<T>, E> { // If we're sharing the underlying iterator tree with anyone, we need // exclusive access to it before we draw values from it, since `next` // has side effects. if Rc::strong_count(&self.0) > 1 { self.0 = self.0.rc_clone(); } // We ensured that we are the sole owner of `self.0`, so this unwrap // should always succeed. Rc::get_mut(&mut self.0).unwrap().cs_next() } }
true
cc544cc120513f4f1cbf4afdd4b3e72754553b8d
Rust
heyacherry/Team4
/projects/lesson-2/runtime/src/substrateKitties.rs
UTF-8
7,232
2.78125
3
[ "Unlicense" ]
permissive
/// A runtime module template with necessary imports /// Feel free to remove or edit this file as needed. /// If you change the name of this file, make sure to update its references in runtime/src/lib.rs /// If you remove this file, you can remove those references /// For more guidance on Substrate modules, see the example module /// https://github.com/paritytech/substrate/blob/master/srml/example/src/lib.rs /// /// requirements: /// - 链上存储加密猫数据 /// - 遍历所有加密猫 /// - 每只猫都有⾃己的dna,为 128bit的数据, 伪代码算法 /// - 每个用户可以拥有零到多只猫 /// - 遍历用户拥有的所有猫 use support::{decl_module, decl_storage, decl_event, StorageValue, dispatch::Result}; use system::ensure_signed; use sr_primitives::traits::{Hash}; use codec::{Encode, Decode}; pub struct Kitty<Hash, U64> { id: Hash, dna: Hash, price: U64, generation: U64, } pub trait Trait: system::Trait { type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>; } decl_storage! { trait Store for Module<T: Trait> as KittiesModule { // Here we are declaring a StorageValue, `Something` as a Option<u32> // `get(something)` is the default getter which returns either the stored `u32` or `None` if nothing stored // Something get(something): Option<u32>; Kitties get(kitty): map T::Hash => Kitty<T::Hash, u64>; KittyOwner get(owner): map T::Hash => Option<T::AccountId>; KittiesArrayByOwner get(kitty_by_owner_index): map (T::AccountId, u64) => T::Hash; KittiesCountByOwner get(all_kitty_count_by_onwer): map T::AccountId => u64; KittiesIndexByOwner: map T::Hash => u64; AllKittiesArray get(kitty_with_indexes): map u64 => T::Hash; AllKittiesCount get(all_kitty_count): u64; AllKittiesIndex: map T::Hash => u64; } } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { // Initializing events // this is needed only if you are using events in your module fn deposit_event() = default; // function that can be called by the external world as an extrinsics call // takes a parameter of the type `AccountId`, stores it and emits an event pub fn create_kitty(origin, ) -> Result { let who = ensure_signed(origin)?; // TODO: u128 let ramdom_hash = (<system::Module<T>>::random_seed(), &who, nonce) .using_encoded(<T as system::Trait>::Hashing::hash); ensure!(!<KittyOwner<T>>::exists(random_hash), "Kitty exists already!!"); let counted_kitty_by_owner = Self::all_kitty_count_by_onwer(&who); let new_all_kitty_count_by_owner = counted_kitty_by_owner.checked_add(1) .ok_or("Overflow adding a new kitty !!")?; let all_kitty_count = Self::all_kitty_count(); let new_all_kitty_count = all_kitty_count.checked_add(1) .ok_or("Overflow adding a new kitty to total supply!!!")?; let new_kitty = Kitty { id: random_hash, dna: random_hash, price: 0, generation: 0, }; <Kitties<T>>::insert(ramdom_hash, new_kitty); <KittyOwner<T>>::insert(ramdom_hash, &who); <KittiesArrayByOwner<T>>::insert((who.clone(), counted_kitty_by_owner), ramdom_hash); <KittiesCountByOwner<T>>::insert(&who, new_all_kitty_count_by_owner); <KittiesIndexByOwner<T>>::insert(random_hash, counted_kitty_by_owner); <AllKittiesArray<T>>::insert(all_kitty_count, random_hash); <AllKittiesCount>::put(new_all_kitty_count); <AllKittiesIndex<T>>::insert(kitty_id, all_kitty_count); // TODO: Code to execute when something calls this. // For example: the following line stores the passed in u32 in the storage // Something::put(something); // here we are raising the Something event Self::deposit_event(RawEvent::KittyStored(who,random_hash)); Ok(()) } // Iterate all kitties fn get_all_kittys(origin) -> Result { let who = ensure_signed(origin)?; for n in 0..Self::all_kitty_count() { let kitty_id = Self::kitty_by_owner_index(n); let kitty =Self::kitty(kitty_id); println!("kitty"); } Ok(()) } // Interate all kitties by owner fn get_kitties_accountId(origin) -> Result { let who = ensure_signed(origin)?; let owned_count = Self::all_kitty_count_by_onwer(&who); for n in 0..owned_count { let kitty_id = Self::kitty_by_owner_index((who.clone(), n)); let kitty =Self::kitty(kitty_id); } Ok(()) } } } decl_event!( pub enum Event<T> where AccountId = <T as system::Trait>::AccountId { // TODO: to sort out the event. // Event `Something` is declared with a parameter of the type `u32` and `AccountId` // To emit this event, we call the deposit funtion, from our runtime funtions KittyStored(AccountId, Hash), } ); decl_error!(); /// TODO: Add test /// tests for this module // #[cfg(test)] // mod tests { // use super::*; // use runtime_io::with_externalities; // use primitives::{H256, Blake2Hasher}; // use support::{impl_outer_origin, assert_ok, parameter_types}; // use sr_primitives::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; // use sr_primitives::weights::Weight; // use sr_primitives::Perbill; // impl_outer_origin! { // pub enum Origin for Test {} // } // // For testing the module, we construct most of a mock runtime. This means // // first constructing a configuration type (`Test`) which `impl`s each of the // // configuration traits of modules we want to use. // #[derive(Clone, Eq, PartialEq)] // pub struct Test; // parameter_types! { // pub const BlockHashCount: u64 = 250; // pub const MaximumBlockWeight: Weight = 1024; // pub const MaximumBlockLength: u32 = 2 * 1024; // pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); // } // impl system::Trait for Test { // type Origin = Origin; // type Call = (); // type Index = u64; // type BlockNumber = u64; // type Hash = H256; // type Hashing = BlakeTwo256; // type AccountId = u64; // type Lookup = IdentityLookup<Self::AccountId>; // type Header = Header; // type WeightMultiplierUpdate = (); // type Event = (); // type BlockHashCount = BlockHashCount; // type MaximumBlockWeight = MaximumBlockWeight; // type MaximumBlockLength = MaximumBlockLength; // type AvailableBlockRatio = AvailableBlockRatio; // type Version = (); // } // impl Trait for Test { // type Event = (); // } // type TemplateModule = Module<Test>; // // This function basically just builds a genesis storage key/value store according to // // our desired mockup. // fn new_test_ext() -> runtime_io::TestExternalities<Blake2Hasher> { // system::GenesisConfig::default().build_storage::<Test>().unwrap().into() // } // #[test] // fn it_works_for_default_value() { // with_externalities(&mut new_test_ext(), || { // // Just a dummy test for the dummy funtion `do_something` // // calling the `do_something` function with a value 42 // assert_ok!(TemplateModule::do_something(Origin::signed(1), 42)); // // asserting that the stored value is equal to what we stored // assert_eq!(TemplateModule::something(), Some(42)); // }); // } // }
true
bd29949b8dd7485b7069f9bf03a2cb7aaa44b066
Rust
alibaba/GraphScope
/interactive_engine/executor/store/groot/src/db/graph/bench/data.rs
UTF-8
1,125
3.109375
3
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "FSFAP", "BSD-3-Clause-Clear", "GPL-1.0-or-later", "BSD-2-Clause-Views", "Bitstream-Vera", "MPL-2.0", "LicenseRef-scancode-warranty-disclaimer", "OFL-1.1", "BSD-3-Clause", "APAFML", "0BSD", "LicenseRef-scancode-free-unknown", "CC-BY-4.0", "GPL-3.0-or-later", "LicenseRef-scancode-python-cwi", "Zlib", "Qhull", "u-boot-exception-2.0", "MIT", "ISC", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain", "CC0-1.0", "GPL-2.0-or-later", "BSD-2-Clause", "GCC-exception-3.1", "ZPL-1.1", "CC-BY-SA-4.0", "GPL-3.0-only", "LicenseRef-scancode-other-permissive", "Python-2.0", "X11", "TCL" ]
permissive
use std::collections::HashMap; use crate::db::api::*; pub fn gen_properties(type_def: &TypeDef) -> HashMap<PropertyId, Value> { let mut ret = HashMap::new(); for prop_def in type_def.get_prop_defs() { let v = gen_property(prop_def.r#type); ret.insert(prop_def.id, v); } ret } fn gen_property(r#type: ValueType) -> Value { match r#type { ValueType::Int => Value::int(100), ValueType::Long => Value::long(101), ValueType::Float => Value::float(10.1), ValueType::Double => Value::double(123.4), ValueType::String => Value::string(&String::from_utf8(vec!['a' as u8; 128]).unwrap()), _ => unimplemented!(), } } pub fn gen_one_string_properties(type_def: &TypeDef, len: usize) -> HashMap<PropertyId, Value> { let prop_def = type_def.get_prop_defs().next().unwrap(); assert_eq!(prop_def.r#type, ValueType::String); let mut ret = HashMap::new(); ret.insert(prop_def.id, gen_string_property(len)); ret } fn gen_string_property(len: usize) -> Value { Value::string(&String::from_utf8(vec!['a' as u8; len]).unwrap()) }
true
b7ea20408e26d99bc93be4e86561f0d33f51e57a
Rust
cszczepaniak/cribbage-scorer
/impl-rust/src/cards.rs
UTF-8
5,795
3.609375
4
[]
no_license
use core::fmt::Display; use std::error::Error; #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] pub enum Suit { Clubs, Diamonds, Hearts, Spades, Unknown, } impl From<usize> for Suit { fn from(n: usize) -> Self { match n { 0 => Suit::Clubs, 1 => Suit::Diamonds, 2 => Suit::Hearts, 3 => Suit::Spades, _ => Suit::Unknown, } } } impl From<Suit> for usize { fn from(n: Suit) -> Self { match n { Suit::Clubs => 0, Suit::Diamonds => 1, Suit::Hearts => 2, Suit::Spades => 3, Suit::Unknown => usize::MAX, } } } pub fn new_deck() -> Vec<Card> { let mut cards = Vec::new(); for i in 0..52 { cards.push(Card::from_index(i)) } cards } #[derive(Clone, Copy, Debug)] pub struct Card { pub suit: Suit, pub value: usize, pub rank: usize, } impl Card { fn from_index(i: usize) -> Card { let value = match i % 13 { n if n >= 10 => 10, n => n + 1, }; Card { value, suit: (i / 13).into(), rank: (i % 13) + 1, } } pub fn from_str(s: &str) -> Result<Card, Box<dyn Error>> { let lower_s = &s.to_lowercase(); let mut c = Card { rank: 0, value: 0, suit: Suit::Unknown, }; match &lower_s[lower_s.len() - 1..] { "c" => { c.suit = Suit::Clubs; } "d" => { c.suit = Suit::Diamonds; } "h" => { c.suit = Suit::Hearts; } "s" => { c.suit = Suit::Spades; } _ => Err("invalid suit!")?, }; match &lower_s[..lower_s.len() - 1] { "j" => { c.rank = 11; c.value = 10; } "q" => { c.rank = 12; c.value = 10; } "k" => { c.rank = 13; c.value = 10; } "a" => { c.rank = 1; c.value = 1; } v => { let val = v.parse::<usize>()?; c.rank = val; c.value = val; } }; Ok(c) } } impl Display for Card { fn fmt( &self, formatter: &mut std::fmt::Formatter<'_>, ) -> std::result::Result<(), std::fmt::Error> { match self.rank { 0 => formatter.write_str("A")?, 10 => formatter.write_str("J")?, 11 => formatter.write_str("Q")?, 12 => formatter.write_str("K")?, _ => formatter.write_str(&format!("{}", self.value))?, } match self.suit { Suit::Clubs => formatter.write_str("C"), Suit::Diamonds => formatter.write_str("D"), Suit::Hearts => formatter.write_str("H"), Suit::Spades => formatter.write_str("S"), Suit::Unknown => formatter.write_str("?"), } } } #[cfg(test)] mod tests { use super::*; use claim::*; use std::collections::HashSet; #[test] fn test_new_deck() { let d = new_deck(); assert_eq!(d.len(), 52); let mut unique: HashSet<(usize, usize, Suit)> = HashSet::new(); for c in d.iter() { let tup = (c.value, c.rank, c.suit); assert!(!unique.contains(&tup)); unique.insert(tup); } } #[test] fn test_from_index_equality() { let tests = vec![ ( 0, Card { rank: 0, value: 1, suit: Suit::Clubs, }, ), ( 1, Card { rank: 1, value: 2, suit: Suit::Clubs, }, ), ( 2, Card { rank: 2, value: 3, suit: Suit::Clubs, }, ), ( 10, Card { rank: 10, value: 10, suit: Suit::Clubs, }, ), ( 11, Card { rank: 11, value: 10, suit: Suit::Clubs, }, ), ( 12, Card { rank: 12, value: 10, suit: Suit::Clubs, }, ), ( 51, Card { rank: 12, value: 10, suit: Suit::Spades, }, ), ]; for (index, c) in tests { let actual_card = Card::from_index(index); assert_eq!(c.rank, actual_card.rank); assert_eq!(c.value, actual_card.value); assert_eq!(c.suit, actual_card.suit); } } #[test] fn test_from_index_full_range() { for i in 0..52 { let card = Card::from_index(i); assert_ge!(card.value, 1); assert_le!(card.value, 10); match i { 0..=12 => assert_eq!(card.suit, Suit::Clubs), 13..=25 => assert_eq!(card.suit, Suit::Diamonds), 26..=38 => assert_eq!(card.suit, Suit::Hearts), _ => assert_eq!(card.suit, Suit::Spades), } } } }
true
aeae4a31d395ac21ca140a4751f86cfd0cac77a6
Rust
Patryk27/avr-tester
/avr-tester/tests/tests/timeout.rs
UTF-8
846
3.328125
3
[ "MIT" ]
permissive
//! # Scenario //! //! We're given an AVR that does nothing, while we think it should toggle a pin //! on-and-off. //! //! By carefully constructing the test, using timeout, we prevent it from //! running forever, waiting for a toggle that will never happen. //! //! # Firmware //! //! See: [../../../avr-tester-tests/timeout/src/main.rs]. use crate::prelude::*; #[test] #[should_panic(expected = "Test timed-out")] fn test() { let mut avr = avr_with("timeout", |avr| { // We think our AVR should complete in 100ms, so: avr.with_timeout_of_ms(100) }); avr.pins().pd0().pulse_in(); // Without the timeout, `.pulse_in()` would get stuck forever (well, until // someone Ctrl+C'd and stopped `cargo test`), since it couldn't possibly // know whether the AVR would have eventually toggled the pin or not. }
true
806b640130d2b9034f736694300e43b657abab7f
Rust
emmanuelantony2000/deta-rust
/src/update.rs
UTF-8
2,982
3.5625
4
[ "MIT", "Apache-2.0" ]
permissive
use std::collections::HashMap; use std::string; use serde::{Deserialize, Serialize}; /// Only used for update requests. /// /// # Examples /// /// ``` /// use deta::Update; /// /// let update = Update::new() /// .set("profile.age", 33) /// .set("profile.active", true) /// .set("profile.email", "jimmy@deta.sh") /// .increment("purchases", 2) /// .append("likes", "ramen") /// .prepend("likes", "noodles") /// .delete("profile.hometown") /// .delete("on_mobile"); /// ``` #[derive(Serialize, Deserialize, Debug, Default, PartialEq, Eq)] pub struct Update { set: HashMap<String, String>, increment: HashMap<String, String>, append: HashMap<String, Vec<String>>, prepend: HashMap<String, Vec<String>>, delete: Vec<String>, } impl Update { /// To initialize a new empty `Update` struct. /// /// # Examples /// /// ``` /// use deta::Update; /// let update = Update::new(); /// ``` pub fn new() -> Self { Self::default() } /// To set a new value for an attribute. /// /// # Examples /// /// ``` /// use deta::Update; /// let update = Update::new().set("name", "Jimmy"); /// ``` pub fn set(mut self, key: impl string::ToString, value: impl string::ToString) -> Self { self.set.insert(key.to_string(), value.to_string()); self } /// To increment a value for an attribute. /// /// # Examples /// /// ``` /// use deta::Update; /// let update = Update::new().increment("age", 1); /// ``` pub fn increment(mut self, key: impl string::ToString, value: impl string::ToString) -> Self { self.increment.insert(key.to_string(), value.to_string()); self } /// To append a value to the existing value of an attribute. /// /// # Examples /// /// ``` /// use deta::Update; /// let update = Update::new().append("likes", "ramen"); /// ``` pub fn append(mut self, key: impl string::ToString, value: impl string::ToString) -> Self { self.append .entry(key.to_string()) .or_insert_with(Vec::new) .push(value.to_string()); self } /// To prepend a value to the existing value of an attribute. /// /// # Examples /// /// ``` /// use deta::Update; /// let update = Update::new().append("likes", "noodles"); /// ``` pub fn prepend(mut self, key: impl string::ToString, value: impl string::ToString) -> Self { self.prepend .entry(key.to_string()) .or_insert_with(Vec::new) .push(value.to_string()); self } /// To delete an attribute. /// /// # Examples /// /// ``` /// use deta::Update; /// let update = Update::new().append("likes", "ramen"); /// ``` pub fn delete(mut self, key: impl string::ToString) -> Self { self.delete.push(key.to_string()); self } }
true
02ea0022aed030f22d38c1becc62fada79891e71
Rust
mattclement/nanoblog
/nanoblog/src/posts.rs
UTF-8
3,058
2.65625
3
[ "MIT" ]
permissive
use tera::Tera; use tide::http; use tide::{Context, EndpointResult, Error, error::ResultExt}; use crate::db; use http::status::StatusCode; use pulldown_cmark::{Parser, Options, html}; const INDEX: &str = "index.html"; const POST: &str = "post.html"; const NOT_FOUND: &str = "404.html"; lazy_static! { pub static ref TERA: Tera = { compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*.html")) }; } pub fn res_404() -> EndpointResult { let tera_ctx: tera::Context = tera::Context::new(); let body = TERA.render(NOT_FOUND, &tera_ctx).unwrap(); let resp = http::Response::builder() .status(StatusCode::NOT_FOUND) .header(http::header::CONTENT_TYPE, "text/html; charset=UTF-8") .body(body.into()) .unwrap(); Ok(resp) } /// Render will apply the tera template context to the template and wrap it in a /// EndpointResult fn render(template: &str, tera_ctx: tera::Context) -> EndpointResult { let body = TERA.render(template, &tera_ctx) .map_err(|e| { let resp = http::Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .header(http::header::CONTENT_TYPE, "text/html; charset=UTF-8") .body(format!("<html><body>{:?}</body></html>", e).into()) .expect("Failed to build failure response"); Error::from(resp) })?; let resp = http::Response::builder() .status(StatusCode::OK) .header(http::header::CONTENT_TYPE, "text/html; charset=UTF-8") .body(body.into()) .expect("Error building response"); Ok(resp) } /// Render markdown contents fn render_markdown(contents: &str) -> String { let mut options = Options::empty(); options.insert(Options::ENABLE_STRIKETHROUGH); options.insert(Options::ENABLE_TABLES); let parser = Parser::new_ext(contents, options); let mut html_output = String::new(); html::push_html(&mut html_output, parser); html_output } pub async fn list_posts(cx: Context<db::Database>) -> EndpointResult { let client = cx.app_data().to_owned(); let mut tera_ctx: tera::Context = tera::Context::new(); let contents = client.list_posts().await; let mut contents: Vec<(String, db::PostMetadata)> = contents .into_iter() .collect(); contents.sort_by_key(|k| k.1.date_created.clone()); tera_ctx.insert("post_links", &contents); render(INDEX, tera_ctx) } pub async fn get_post(cx: Context<db::Database>) -> EndpointResult { let client = cx.app_data().to_owned(); let mut tera_ctx: tera::Context = tera::Context::new(); let title: String = cx.param("post").client_err()?; let contents = client.get_post(title.clone()).await; if contents.is_err() { return res_404(); } let contents = contents.unwrap(); tera_ctx.insert("title", &contents.title); tera_ctx.insert("date_created", &contents.date_created); tera_ctx.insert("body", &render_markdown(&contents.body)); render(POST, tera_ctx) }
true
4cd1bc26c00f4652b1eef574b062877f98d18e61
Rust
potatosalad/exercism
/rust/palindrome-products/src/lib.rs
UTF-8
1,933
3.21875
3
[]
no_license
extern crate num_cpus; use std::collections::HashSet; use std::sync::mpsc; use std::thread; pub type Palindrome = u64; pub fn get_palindrome_products(min: u64, max: u64) -> Vec<Palindrome> { let cpus = num_cpus::get(); if cpus == 1 { let mut products: HashSet<Palindrome> = HashSet::new(); palindrome_products(min, max, 1, |product| { products.insert(product); }); products.into_iter().collect() } else { let mut pool = Vec::new(); let (tx, rx) = mpsc::channel::<Palindrome>(); for n in 0..cpus { let tx = tx.clone(); pool.push(Some(thread::spawn(move || { palindrome_products(min + n as u64, max, cpus, |product| { tx.send(product).unwrap(); }); }))); } for handle in &mut pool { if let Some(thread) = handle.take() { thread.join().unwrap(); } } drop(tx); rx.into_iter() .collect::<HashSet<Palindrome>>() .into_iter() .collect() } } fn palindrome_products<F>(min: u64, max: u64, step: usize, mut cb: F) where F: FnMut(Palindrome), { for i in (min..=max).step_by(step) { for j in i..=max { let product = i * j; let digits = product.to_string(); if digits.chars().eq(digits.chars().rev()) { cb(product); } } } } pub fn min(palindromes: &[Palindrome]) -> Option<Palindrome> { palindromes.iter().fold(None, |min, &p| match min { None => Some(p), Some(q) if p < q => Some(p), Some(q) => Some(q), }) } pub fn max(palindromes: &[Palindrome]) -> Option<Palindrome> { palindromes.iter().fold(None, |max, &p| match max { None => Some(p), Some(q) if p > q => Some(p), Some(q) => Some(q), }) }
true
cb7d3d9270e2d93014a85492397cee825681aa3d
Rust
extrawurst/gitui
/src/components/cred.rs
UTF-8
3,714
2.625
3
[ "MIT" ]
permissive
use anyhow::Result; use crossterm::event::Event; use ratatui::{backend::Backend, layout::Rect, Frame}; use asyncgit::sync::cred::BasicAuthCredential; use crate::components::{EventState, InputType, TextInputComponent}; use crate::keys::key_match; use crate::{ components::{ visibility_blocking, CommandBlocking, CommandInfo, Component, DrawableComponent, }, keys::SharedKeyConfig, strings, ui::style::SharedTheme, }; /// pub struct CredComponent { visible: bool, key_config: SharedKeyConfig, input_username: TextInputComponent, input_password: TextInputComponent, cred: BasicAuthCredential, } impl CredComponent { /// pub fn new( theme: SharedTheme, key_config: SharedKeyConfig, ) -> Self { Self { visible: false, input_username: TextInputComponent::new( theme.clone(), key_config.clone(), &strings::username_popup_title(&key_config), &strings::username_popup_msg(&key_config), false, ) .with_input_type(InputType::Singleline), input_password: TextInputComponent::new( theme, key_config.clone(), &strings::password_popup_title(&key_config), &strings::password_popup_msg(&key_config), false, ) .with_input_type(InputType::Password), key_config, cred: BasicAuthCredential::new(None, None), } } pub fn set_cred(&mut self, cred: BasicAuthCredential) { self.cred = cred; } pub const fn get_cred(&self) -> &BasicAuthCredential { &self.cred } } impl DrawableComponent for CredComponent { fn draw<B: Backend>( &self, f: &mut Frame<B>, rect: Rect, ) -> Result<()> { if self.visible { self.input_username.draw(f, rect)?; self.input_password.draw(f, rect)?; } Ok(()) } } impl Component for CredComponent { fn commands( &self, out: &mut Vec<CommandInfo>, force_all: bool, ) -> CommandBlocking { if self.is_visible() || force_all { if !force_all { out.clear(); } out.push(CommandInfo::new( strings::commands::validate_msg(&self.key_config), true, true, )); out.push(CommandInfo::new( strings::commands::close_popup(&self.key_config), true, true, )); } visibility_blocking(self) } fn event(&mut self, ev: &Event) -> Result<EventState> { if self.visible { if let Event::Key(e) = ev { if key_match(e, self.key_config.keys.exit_popup) { self.hide(); return Ok(EventState::Consumed); } if self.input_username.event(ev)?.is_consumed() || self.input_password.event(ev)?.is_consumed() { return Ok(EventState::Consumed); } else if key_match(e, self.key_config.keys.enter) { if self.input_username.is_visible() { self.cred = BasicAuthCredential::new( Some( self.input_username .get_text() .to_string(), ), None, ); self.input_username.hide(); self.input_password.show()?; } else if self.input_password.is_visible() { self.cred = BasicAuthCredential::new( self.cred.username.clone(), Some( self.input_password .get_text() .to_string(), ), ); self.input_password.hide(); self.input_password.clear(); return Ok(EventState::NotConsumed); } else { self.hide(); } } } return Ok(EventState::Consumed); } Ok(EventState::NotConsumed) } fn is_visible(&self) -> bool { self.visible } fn hide(&mut self) { self.cred = BasicAuthCredential::new(None, None); self.visible = false; } fn show(&mut self) -> Result<()> { self.visible = true; if self.cred.username.is_none() { self.input_username.show() } else if self.cred.password.is_none() { self.input_password.show() } else { Ok(()) } } }
true
4b3635f2e8796d9695bc7c45819d5e173086aa58
Rust
Dipendra-creator/RustyChef
/Easy Problem to Get Started/Add Natural Numbers/main.rs
UTF-8
333
3.28125
3
[]
no_license
fn int_input() -> i64 { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let n: i64 = line.trim().parse().expect("invalid input"); return n; } fn main() { let num = int_input(); let mut sum: i64 = 0; for i in 1..num+1 { sum = sum + i; } println!("{}", sum); }
true
0fd015990658c9204fafca68f432f0d6351d50df
Rust
Devolutions/IronRDP
/crates/ironrdp-pdu/src/input/mouse.rs
UTF-8
2,295
3.140625
3
[ "Apache-2.0", "MIT" ]
permissive
use std::io; use bitflags::bitflags; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use super::InputEventError; use crate::PduParsing; #[derive(Debug, Clone, PartialEq, Eq)] pub struct MousePdu { pub flags: PointerFlags, pub number_of_wheel_rotation_units: i16, pub x_position: u16, pub y_position: u16, } impl PduParsing for MousePdu { type Error = InputEventError; fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> { let flags_raw = stream.read_u16::<LittleEndian>()?; let flags = PointerFlags::from_bits_truncate(flags_raw); let wheel_rotations_bits = flags_raw as u8; // truncate let number_of_wheel_rotation_units = if flags.contains(PointerFlags::WHEEL_NEGATIVE) { -i16::from(wheel_rotations_bits) } else { i16::from(wheel_rotations_bits) }; let x_position = stream.read_u16::<LittleEndian>()?; let y_position = stream.read_u16::<LittleEndian>()?; Ok(Self { flags, number_of_wheel_rotation_units, x_position, y_position, }) } fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> { let wheel_negative_bit = if self.number_of_wheel_rotation_units < 0 { PointerFlags::WHEEL_NEGATIVE.bits() } else { PointerFlags::empty().bits() }; let wheel_rotations_bits = u16::from(self.number_of_wheel_rotation_units as u8); // truncate let flags = self.flags.bits() | wheel_negative_bit | wheel_rotations_bits; stream.write_u16::<LittleEndian>(flags)?; stream.write_u16::<LittleEndian>(self.x_position)?; stream.write_u16::<LittleEndian>(self.y_position)?; Ok(()) } fn buffer_length(&self) -> usize { 6 } } bitflags! { #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PointerFlags: u16 { const WHEEL_NEGATIVE = 0x0100; const VERTICAL_WHEEL = 0x0200; const HORIZONTAL_WHEEL = 0x0400; const MOVE = 0x0800; const LEFT_BUTTON = 0x1000; const RIGHT_BUTTON = 0x2000; const MIDDLE_BUTTON_OR_WHEEL = 0x4000; const DOWN = 0x8000; } }
true
9b875c28998412ac06b03d27bfedbc8575deb5e2
Rust
mewhhaha/wasm-example
/wasm/src/lib.rs
UTF-8
43,581
3.0625
3
[]
no_license
#![feature(or_patterns)] #![feature(str_split_once)] #![feature(iterator_fold_self)] #![feature(array_map)] extern crate wasm_bindgen; use std::{ collections::{HashMap, HashSet}, hash::Hash, ops::{Add, Mul}, }; use fxhash::{FxHashMap, FxHashSet}; use parse_display::{Display, FromStr}; use wasm_bindgen::prelude::*; #[wasm_bindgen(js_name = "arrayTransferSingleTest")] pub fn array_transfer_single_test(_array: Box<[f64]>) {} #[wasm_bindgen(js_name = "arrayTransferDoubleTest")] pub fn array_transfer_double_test(array: Box<[f64]>) -> Box<[f64]> { array } #[wasm_bindgen(js_name = "stringTransferSingleTest")] pub fn string_transfer_single_test(_input: String) {} #[wasm_bindgen(js_name = "arrayMapFilterTest")] pub fn array_map_filter_test(array: Box<[f64]>) -> Box<[f64]> { array .into_iter() .filter_map(|x| { if x.sin() > 0.0 { Option::Some(*x) } else { Option::None } }) .collect::<Vec<f64>>() .into_boxed_slice() } fn is_prime(primes: &Vec<u32>, x: u32) -> bool { for p in primes.iter() { if p * p > x { return true; } if x % p == 0 { return false; } } return true; } #[wasm_bindgen(js_name = "primesTest")] pub fn primes_test(prime_n: u32) -> u32 { let mut primes: Vec<u32> = vec![2]; let mut n = primes.len() as u32; let mut i = 3; while n != prime_n { if is_prime(&primes, i) { primes.push(i); n += 1; } i += 2; } *primes.last().unwrap() } #[wasm_bindgen(js_name = "arrayReduceTest")] pub fn array_reduce_test(array: Box<[f64]>) -> f64 { array.into_iter().fold(0.0, |sum, x| sum + x) } #[wasm_bindgen(js_name = "advent1Part1")] pub fn advent_1_part_1(array: Box<[u32]>) -> u32 { let year = 2020; for i in 0..array.len() { let x = array[i]; for j in (i + 1)..array.len() { let y = array[j]; if (x + y) == year { return x * y; } } } 1 } #[wasm_bindgen(js_name = "advent1Part2")] pub fn advent_1_part_2(array: Box<[u32]>) -> u32 { let year = 2020; for i in 0..array.len() { let x = array[i]; for j in (i + 1)..array.len() { let y = array[j]; for k in (j + 1)..array.len() { let z = array[k]; if (x + y + z) == year { return x * y * z; } } } } 1 } #[derive(Display, FromStr)] #[display("{low}-{high} {letter}:{password}")] struct PasswordLine { low: usize, high: usize, letter: char, password: String, } fn is_valid_password1( PasswordLine { low, high, letter, password, }: PasswordLine, ) -> bool { let n = password.chars().filter(|c| *c == letter).count(); return n >= low && n <= high; } #[wasm_bindgen(js_name = "advent2Part1")] pub fn advent_2_part_1(input: String) -> usize { input .lines() .filter(|line| { let password_line = line.parse::<PasswordLine>().expect("!"); is_valid_password1(password_line) }) .count() } fn is_valid_password2( PasswordLine { low, high, letter, password, }: PasswordLine, ) -> bool { let chars = password.chars().collect::<Vec<_>>(); let first = chars[low]; let second = chars[high]; (first == letter || second == letter) && first != second } #[wasm_bindgen(js_name = "advent2Part2")] pub fn advent_2_part_2(input: String) -> usize { input .lines() .filter(|line| { let password_line = line.parse::<PasswordLine>().expect("!"); is_valid_password2(password_line) }) .count() } fn count_trees_on_slope(carta: &Vec<Vec<char>>, slope: (usize, usize)) -> u32 { let height = carta.len(); let width = carta[0].len(); let mut coordinates = (0, 0); let mut trees = 0; while coordinates.1 < height { if carta[coordinates.1][coordinates.0 % width] == '#' { trees += 1 } coordinates.0 += slope.0; coordinates.1 += slope.1; } trees } #[wasm_bindgen(js_name = "advent3Part1")] pub fn advent_3_part_1(input: String) -> u32 { let carta = input .lines() .map(|line| line.chars().collect()) .collect::<Vec<Vec<_>>>(); let slope = (3, 1); count_trees_on_slope(&carta, slope) } #[wasm_bindgen(js_name = "advent3Part2")] pub fn advent_3_part_2(input: String) -> u32 { let carta = input .lines() .map(|line| line.chars().collect()) .collect::<Vec<Vec<_>>>(); let slopes = vec![(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]; slopes.into_iter().fold(1, |product, slope| { product * count_trees_on_slope(&carta, slope) }) } fn has_required_passport_fields(passport: &&str) -> bool { let number_of_required_fields = 7; let number_of_fields = passport .split_whitespace() .filter(|item| match item.split_once(':') { Some(("byr" | "iyr" | "eyr" | "hgt" | "hcl" | "ecl" | "pid", _)) => true, _ => false, }) .count(); number_of_fields == number_of_required_fields } #[wasm_bindgen(js_name = "advent4Part1")] pub fn advent_4_part_1(input: String) -> usize { let passports = input.split("\n\n"); passports.filter(has_required_passport_fields).count() } fn valid_height(hgt: &str) -> bool { let (number, unit) = hgt.split_at(hgt.len() - 2); match (number.parse::<i32>(), unit) { (Ok(150..=193), "cm") => true, (Ok(59..=76), "in") => true, _ => false, } } fn valid_hair_color(hcl: &str) -> bool { let (hash, number) = hcl.split_at(1); match (hash, i32::from_str_radix(number, 16)) { ("#", Ok(_)) => hcl.len() == 7, _ => false, } } fn valid_eye_color(ecl: &str) -> bool { match ecl { "amb" | "blu" | "brn" | "gry" | "grn" | "hzl" | "oth" => true, _ => false, } } fn valid_pid(pid: &str) -> bool { match pid.parse::<i32>() { Ok(_) => pid.len() == 9, _ => false, } } fn is_valid_passport(passport: &&str) -> bool { let number_of_required_fields = 7; let number_of_valid_fields = passport .split_whitespace() .filter(|item| match item.split_once(':') { Some(("byr", value)) => match value.parse::<i32>() { Ok(1920..=2002) => true, _ => false, }, Some(("iyr", value)) => match value.parse::<i32>() { Ok(2010..=2020) => true, _ => false, }, Some(("eyr", value)) => match value.parse::<i32>() { Ok(2020..=2030) => true, _ => false, }, Some(("hgt", value)) => valid_height(value), Some(("hcl", value)) => valid_hair_color(value), Some(("ecl", value)) => valid_eye_color(value), Some(("pid", value)) => valid_pid(value), _ => false, }) .count(); number_of_valid_fields == number_of_required_fields } #[wasm_bindgen(js_name = "advent4Part2")] pub fn advent_4_part_2(input: String) -> usize { let passports = input.split("\n\n"); passports.filter(is_valid_passport).count() } fn calculate_seat_id(binary_seat: u16) -> u16 { let row_mask = 0b1111111000; let column_mask = 0b0000000111; let row = (binary_seat & row_mask) >> 3; let column = binary_seat & column_mask; row * 8 + column } #[wasm_bindgen(js_name = "advent5Part1")] pub fn advent_5_part_1(input: String) -> u16 { let boarding_passes = input.lines(); boarding_passes .map(to_binary) .map(calculate_seat_id) .max() .expect("!") } fn to_binary(boarding_pass: &str) -> u16 { boarding_pass.chars().fold(0, |binary, c| { (binary << 1) + match c { 'B' | 'R' => 1, _ => 0, } }) } fn estimate_full_sum((min, max): (u16, u16)) -> u16 { let below = (min - 1) * min / 2; let range = max * (max + 1) / 2; range - below } #[wasm_bindgen(js_name = "advent5Part2")] pub fn advent_5_part_2(input: String) -> u16 { let boarding_passes = input.lines(); let mut range = (u16::MAX, 0); let missing_one_sum: u16 = boarding_passes .map(to_binary) .map(|binary| { let seat_id = calculate_seat_id(binary); range.0 = range.0.min(seat_id); range.1 = range.1.max(seat_id); seat_id }) .sum(); estimate_full_sum(range) - missing_one_sum } fn count_group(group: &str) -> usize { group .chars() .filter(|c| c.is_alphabetic()) .collect::<HashSet<_>>() .len() } fn count_unanimous(group: &str) -> usize { group .lines() .map(|line| line.chars().collect::<HashSet<_>>()) .fold_first(|a, b| &a & &b) .expect("!") .len() } #[wasm_bindgen(js_name = "advent6Part1")] pub fn advent_6_part_1(input: String) -> usize { input.split("\n\n").map(count_group).sum() } #[wasm_bindgen(js_name = "advent6Part2")] pub fn advent_6_part_2(input: String) -> usize { input.split("\n\n").map(count_unanimous).sum() } #[wasm_bindgen(js_name = "advent6Part2Bits")] pub fn advent_6_part_2_bits(mut input: String) -> i32 { input.push('\n'); let mut sum = 0_i32; let mut group = -1_i32; let mut person = 0_i32; input.bytes().fold(b'\n', |prev, b| { match (prev, b) { (b'\n', b'\n') => { sum += group.count_ones() as i32; group = -1; person = 0 } (_, b'\n') => { group = match group { -1 => person, _ => group & person, }; person = 0; } _ => person |= 1 << (b - b'a'), }; b }); sum } #[derive(FromStr, PartialEq)] #[from_str(regex = "\\d+ (?P<0>\\w+ \\w+) .+")] struct Name(String); #[wasm_bindgen(js_name = "advent7Part1")] pub fn advent_7_part_1(input: String) -> usize { let mut lookup: HashMap<String, Vec<&str>> = HashMap::new(); input.lines().for_each(|line| { let (container, contains) = line.split_once(" bags contain ").expect("!"); contains.split(", ").for_each(|bags| { if let Ok(Name(name)) = bags.parse::<Name>() { lookup .entry(name) .or_insert(Vec::with_capacity(8)) .push(container); } }); }); let mut todo = vec!["shiny gold"]; let mut colors: HashSet<&str> = HashSet::with_capacity(lookup.len()); while let Some(color) = todo.pop() { if let Some(parents) = lookup.get(color) { for parent in parents { if !colors.insert(parent) { continue; } todo.push(parent); } }; } colors.len() } #[derive(FromStr, PartialEq)] #[from_str(regex = "(?P<n>\\d+) (?P<name>\\w+ \\w+) .+")] struct Bags { n: u32, name: String, } fn traverse(tree: &HashMap<&str, Vec<Bags>>, node: &str) -> u32 { let mut sum = 1; if let Some(children) = tree.get(node) { for Bags { n, name } in children { sum += n * traverse(tree, name); } } sum } #[wasm_bindgen(js_name = "advent7Part2")] pub fn advent_7_part_2(input: String) -> u32 { let lookup = input .lines() .map(|line| { let (container, contains) = line.split_once(" bags contain ").expect("!"); let children: Vec<_> = contains .split(", ") .filter_map(|bags| bags.parse::<Bags>().ok()) .collect(); (container, children) }) .collect(); traverse(&lookup, "shiny gold") - 1 } #[derive(FromStr, PartialEq, Clone)] enum Op { #[from_str(regex = "acc \\+?(?P<0>(\\d+|(-\\d+)))")] Acc(i32), #[from_str(regex = "jmp \\+?(?P<0>(\\d+|(-\\d+)))")] Jmp(i32), #[from_str(regex = "nop \\+?(?P<0>(\\d+|(-\\d+)))")] Nop(i32), } enum Finish { Loop(i32), Exit(i32), } fn machine(mut code: Vec<Option<Op>>) -> Finish { let mut i: i32 = 0; let mut acc = 0; while let Some(op) = &code[i as usize] { let mv: i32 = match op { Op::Acc(x) => { acc += x; 1 } Op::Nop(_) => 1, Op::Jmp(n) => *n, }; code[i as usize] = None; i += mv; if i as usize == code.len() { return Finish::Exit(acc); } } Finish::Loop(acc) } #[wasm_bindgen(js_name = "advent8Part1")] pub fn advent_8_part_1(input: String) -> i32 { let code: Vec<Option<Op>> = input.lines().map(|line| line.parse::<Op>().ok()).collect(); match machine(code) { Finish::Loop(res) => res, _ => panic!("Unexpected finish"), } } #[wasm_bindgen(js_name = "advent8Part2")] pub fn advent_8_part_2(input: String) -> i32 { let code: Vec<Option<Op>> = input.lines().map(|line| line.parse::<Op>().ok()).collect(); for i in 0..code.len() { let hack = match code[i] { Some(Op::Jmp(n)) => Some(Op::Nop(n)), Some(Op::Nop(n)) => Some(Op::Jmp(n)), _ => continue, }; let mut code_copy = code.clone(); code_copy[i] = hack; if let Finish::Exit(res) = machine(code_copy) { return res; } } panic!("Didn't quite work, did it?") } fn find_invalid_number(numbers: &Vec<u64>) -> u64 { let lookup = numbers.iter().collect::<HashSet<_>>(); for (i, n) in numbers[25..].iter().enumerate() { if numbers[i..i + 25] .iter() .filter(|m| m < &n) .all(|m| !lookup.contains(&(n - m))) { return *n; } } panic!("You should've found the number by now!") } #[wasm_bindgen(js_name = "advent9Part1")] pub fn advent_9_part_1(input: String) -> u64 { let numbers: Vec<u64> = input .lines() .map(|line| line.parse::<u64>().expect("!")) .collect(); find_invalid_number(&numbers) } #[wasm_bindgen(js_name = "advent9Part2")] pub fn advent_9_part_2(input: String) -> u64 { let numbers: Vec<u64> = input .lines() .map(|line| line.parse::<u64>().expect("!")) .collect(); let invalid_number = find_invalid_number(&numbers); for i in 0..numbers.len() { let mut acc = 0; for j in i..numbers.len() { acc += numbers[j]; if acc == invalid_number { let (minimum, maximum) = numbers[i..=j] .into_iter() .fold((u64::MAX, 0_u64), |(minimum, maximum), n| { (minimum.min(*n), maximum.max(*n)) }); return minimum + maximum; } if acc > invalid_number { break; } } } panic!("You should've found the range by now!") } #[wasm_bindgen(js_name = "advent10Part1")] pub fn advent_10_part_1(input: String) -> u32 { let mut numbers: Vec<u32> = input .lines() .map(|line| line.parse::<u32>().expect("!")) .collect(); numbers.push(0); numbers.sort(); let mut one_diffs = 0; let mut three_diffs = 0; numbers .iter() .skip(1) .zip(numbers.iter()) .for_each(|(x, y)| match x - y { 1 => one_diffs += 1, 3 => three_diffs += 1, _ => (), }); one_diffs * (three_diffs + 1) } fn count_possibilities(i: usize, numbers: &Vec<u64>, memo: &mut Vec<Option<u64>>) -> u64 { match memo[i] { Some(computed) => computed, _ if i == numbers.len() - 1 => 1, _ => { let curr = &numbers[i]; let mut acc = 0; for j in i + 1..numbers.len().min(i + 4) { let next = &numbers[j]; println!("{} - {} - {}", next, curr, next - curr); if next - curr > 3 { break; } acc += count_possibilities(j, numbers, memo); } memo[i] = Some(acc); acc } } } #[wasm_bindgen(js_name = "advent10Part2")] pub fn advent_10_part_2(input: String) -> u64 { let mut numbers: Vec<u64> = input .lines() .map(|line| line.parse::<u64>().expect("!")) .collect(); numbers.push(0); numbers.sort(); let mut memo = vec![None; numbers.len()]; count_possibilities(0, &numbers, &mut memo) } #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)] enum Seat { Vacant, Occupied, } fn is_seat_occupied(seat: &Option<Seat>) -> bool { match seat { Some(Seat::Occupied) => true, _ => false, } } const KERNEL_2D: [(isize, isize); 8] = [ (-1, -1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (1, 0), (0, 1), ]; fn num_adjacent_seats(width: usize, placements: &Vec<Option<Seat>>, i: usize) -> usize { KERNEL_2D .iter() .filter(|(oy, ox)| { let j = i as isize + oy * width as isize + ox; match (i % width) as isize + ox { x if x < 0 || x >= width as isize || j < 0 || j >= placements.len() as isize => { false } _ => is_seat_occupied(&placements[j as usize]), } }) .count() } fn num_seen_seats(width: usize, placements: &Vec<Option<Seat>>, i: usize) -> usize { KERNEL_2D .iter() .filter(|(oy, ox)| { let mut cy = *oy; let mut cx = *ox; loop { let j = i as isize + cy * width as isize + cx; match (i % width) as isize + cx { x if x < 0 || x >= width as isize || j < 0 || j >= placements.len() as isize => { return false } _ => match &placements[j as usize] { None => { cy += oy; cx += ox; } s => return is_seat_occupied(s), }, } } }) .count() } fn stabilize_seat_generations<F>(input: String, tolerance: usize, look_at_seats: F) -> u32 where F: Fn(usize, &Vec<Option<Seat>>, usize) -> usize, { let width = input.split_once('\n').map_or(0, |(f, _)| f.len()); let mut placements: Vec<_> = input .chars() .filter_map(|c| match c { 'L' => Some(Some(Seat::Vacant)), '.' => Some(None), _ => None, }) .collect::<Vec<_>>(); let mut buffer = placements.clone(); let mut occupied_seats; loop { let mut changed = false; occupied_seats = 0; for (i, seat) in placements.iter().enumerate() { let num_occupied = look_at_seats(width, &placements, i); let updated = match seat { Some(Seat::Vacant) if num_occupied == 0 => Some(Seat::Occupied), Some(Seat::Occupied) if num_occupied >= tolerance => Some(Seat::Vacant), _ => *seat, }; if let Some(Seat::Occupied) = updated { occupied_seats += 1; } if &updated != seat { changed = true; } buffer[i] = updated; } std::mem::swap(&mut placements, &mut buffer); if !changed { break; } } occupied_seats } #[wasm_bindgen(js_name = "advent11Part1")] pub fn advent_11_part_1(input: String) -> u32 { stabilize_seat_generations(input, 4, num_adjacent_seats) } #[wasm_bindgen(js_name = "advent11Part2")] pub fn advent_11_part_2(input: String) -> u32 { stabilize_seat_generations(input, 5, num_seen_seats) } #[derive(Copy, Clone)] struct Point<A> { x: A, y: A, } impl<A: Add<Output = A>> Add for Point<A> { type Output = Self; fn add(self, other: Self) -> Self { Self { x: self.x + other.x, y: self.y + other.y, } } } impl<A: Mul<Output = A>> Mul for Point<A> { type Output = Self; fn mul(self, other: Self) -> Self { Self { x: self.x * other.x, y: self.y * other.y, } } } impl<A: Mul<Output = A> + Copy> Mul<A> for Point<A> { type Output = Self; fn mul(self, other: A) -> Self { Self { x: self.x * other, y: self.y * other, } } } #[derive(FromStr, PartialEq, Clone)] enum Ferry { #[display("N{0}")] North(i32), #[display("S{0}")] South(i32), #[display("E{0}")] East(i32), #[display("W{0}")] West(i32), #[display("L{0}")] Left(i32), #[display("R{0}")] Right(i32), #[display("F{0}")] Forward(i32), } fn modulo(dividend: i32, divisor: i32) -> i32 { (dividend % divisor + divisor) % divisor } fn manhattan(point: Point<i32>) -> u32 { (point.x.abs() + point.y.abs()) as u32 } #[wasm_bindgen(js_name = "advent12Part1")] pub fn advent_12_part_1(input: String) -> u32 { let instructions = input.lines().map(|line| line.parse::<Ferry>().expect("!")); let mut angle = 90; let mut position = Point { x: 0, y: 0 }; instructions.for_each(|instruction| match instruction { Ferry::North(d) => { position.y += d; } Ferry::South(d) => { position.y -= d; } Ferry::East(d) => { position.x += d; } Ferry::West(d) => { position.x -= d; } Ferry::Left(d) => angle = modulo(angle - d, 360), Ferry::Right(d) => angle = modulo(angle + d, 360), Ferry::Forward(d) => match angle { 0 => position.y += d, 90 => position.x += d, 180 => position.y -= d, 270 => position.x -= d, _ => panic!("Non-aligned angle!"), }, }); manhattan(position) } fn swap<A: Copy>(point: &Point<A>) -> Point<A> { Point { x: point.y, y: point.x, } } fn turn_waypoint(waypoint: &mut Point<i32>, angle: i32) { let times = match angle.abs() { 0 => 0, 90 => 1, 180 => 2, 270 => 3, _ => panic!("Non-valid angle"), }; let signs = if angle < 0 { Point { x: -1, y: 1 } } else { Point { x: 1, y: -1 } }; for _ in 0..times { *waypoint = swap(waypoint) * signs; } } #[wasm_bindgen(js_name = "advent12Part2")] pub fn advent_12_part_2(input: String) -> u32 { let instructions = input.lines().map(|line| line.parse::<Ferry>().expect("!")); let mut waypoint = Point { x: 10, y: 1 }; let mut position = Point { x: 0, y: 0 }; instructions.for_each(|instruction| match instruction { Ferry::North(d) => { waypoint.y += d; } Ferry::South(d) => { waypoint.y -= d; } Ferry::East(d) => { waypoint.x += d; } Ferry::West(d) => { waypoint.x -= d; } Ferry::Left(d) => turn_waypoint(&mut waypoint, -d), Ferry::Right(d) => turn_waypoint(&mut waypoint, d), Ferry::Forward(d) => { position = position + waypoint * d; } }); manhattan(position) } #[wasm_bindgen(js_name = "advent13Part1")] pub fn advent_13_part_1(input: String) -> u32 { let (departure, buses) = input .split_once('\n') .map(|(raw_departure, raw_schedule)| { let departure = raw_departure.parse::<u32>().expect("!"); let buses = raw_schedule.split(',').filter_map(|c| { if c == "x" { None } else { Some(c.parse::<u32>().unwrap()) } }); (departure, buses) }) .expect("!"); let closest_departure = buses .map(|bus| { let wait_time = bus - (departure % bus); (bus, wait_time) }) .min_by(|x, y| x.1.cmp(&y.1)); match closest_departure { Some((bus, wait_time)) => bus * wait_time, None => panic!("There should've been a bus!"), } } #[wasm_bindgen(js_name = "advent13Part2")] pub fn advent_13_part_2(input: String) -> u64 { let buses = input .split_once('\n') .map(|(_, raw_schedule)| { raw_schedule .split(',') .enumerate() .filter_map(|(offset, str)| str.parse::<u64>().ok().map(|bus| (offset, bus))) }) .expect("!") .collect::<Vec<_>>(); let (_, mut step_size) = buses[0]; let mut timestamp = 0; for (offset, bus) in buses.iter().skip(1) { let remainder = (bus - (*offset as u64 % bus)) % bus; while timestamp % bus != remainder { timestamp += step_size; } step_size = bus * step_size; } timestamp } #[derive(FromStr, PartialEq)] enum Init { #[display("mask = {0}")] Mask(String), #[display("mem[{0}] = {1}")] Mem(u64, u64), } struct BitMask { bitset: u64, bitwild: u64, } fn parse_bitmask(mask: String) -> BitMask { let mut bitset = 0; let mut bitwild = 0; for c in mask.chars() { bitset = bitset << 1; bitwild = bitwild << 1; match c { 'X' => { bitwild = bitwild | 1; } '1' => { bitset = bitset | 1; } _ => (), } } BitMask { bitset, bitwild } } fn apply_bitmask_v1(value: u64, BitMask { bitset, bitwild }: &BitMask) -> u64 { bitset | (value & bitwild) } #[wasm_bindgen(js_name = "advent14Part1")] pub fn advent_14_part_1(input: String) -> u64 { let mut mem: HashMap<u64, u64> = HashMap::new(); let mut bitmask = BitMask { bitset: 0, bitwild: u64::MAX, }; let instructions = input.lines().map(|line| line.parse::<Init>().expect("!")); for instruction in instructions { match instruction { Init::Mask(raw) => { bitmask = parse_bitmask(raw); } Init::Mem(address, value) => { let masked_value = apply_bitmask_v1(value, &bitmask); mem.insert(address, masked_value); } } } mem.values().sum() } fn combinations(vec: Vec<u64>) -> Vec<u64> { let mut values = vec![]; for i in 0..vec.len() { let v = vec[i]; for k in 0..values.len() { let w = values[k]; values.push(v + w); } values.push(v); } values.sort(); values.dedup(); values } fn apply_bitmask_v2( address: u64, BitMask { bitset, bitwild }: &BitMask, ) -> impl Iterator<Item = u64> + '_ { let set_value = (bitset | address) & !bitwild; let mut numbers = vec![0]; let mut position = 0; let mut bits = *bitwild; while bits != 0 { if bits & 1 == 1 { numbers.push(1 << position); } position += 1; bits = bits >> 1; } combinations(numbers) .into_iter() .map(move |n| n | set_value) } #[wasm_bindgen(js_name = "advent14Part2")] pub fn advent_14_part_2(input: String) -> u64 { let mut mem = FxHashMap::<u64, u64>::default(); let mut bitmask = BitMask { bitset: 0, bitwild: u64::MAX, }; let instructions = input.lines().map(|line| line.parse::<Init>().expect("!")); for instruction in instructions { match instruction { Init::Mask(raw) => { bitmask = parse_bitmask(raw); } Init::Mem(address, value) => { let masked_addresses = apply_bitmask_v2(address, &bitmask); masked_addresses.for_each(|masked_address| { mem.insert(masked_address, value); }) } } } mem.values().sum() } fn play_numbers_game(input: String, until: usize) -> u32 { let mut memory: Vec<Option<usize>> = vec![None; until]; let mut from = 1; input.split(',').enumerate().for_each(|(i, word)| { let n = word.parse::<usize>().expect("!"); memory[n] = Some(i); from += 1; }); let mut last_spoken = 0; for i in from..until { let spoken = match memory[last_spoken] { None => 0, Some(k) => (i - 1) - k, }; memory[last_spoken] = Some(i - 1); last_spoken = spoken; } last_spoken as u32 } #[wasm_bindgen(js_name = "advent15Part1")] pub fn advent_15_part_1(input: String) -> u32 { play_numbers_game(input, 2020) } #[wasm_bindgen(js_name = "advent15Part2")] pub fn advent_15_part_2(input: String) -> u32 { play_numbers_game(input, 30000000) } #[derive(Display, FromStr, PartialEq, Debug)] #[display("{title}: {range_1.0}-{range_1.1} or {range_2.0}-{range_2.1}")] struct TicketRule { title: String, #[from_str(default)] range_1: (usize, usize), #[from_str(default)] range_2: (usize, usize), } fn parse_ticket(text: &str) -> Vec<usize> { text.split(',') .map(|n| n.parse::<usize>().expect("!")) .collect::<Vec<_>>() } fn parse_ticket_translation(input: String) -> (Vec<TicketRule>, Vec<usize>, Vec<Vec<usize>>) { match input.split("\n\n").collect::<Vec<_>>()[..] { [rules_text, ticket_text, nearby_tickets_text] => ( rules_text .lines() .map(|line| line.parse::<TicketRule>().expect("")) .collect::<Vec<_>>(), ticket_text .lines() .skip(1) .flat_map(parse_ticket) .collect::<Vec<_>>(), nearby_tickets_text .lines() .skip(1) .map(parse_ticket) .collect::<Vec<_>>(), ), _ => panic!("Faulty input!"), } } fn validate_number( TicketRule { range_1, range_2, .. }: &TicketRule, n: &usize, ) -> bool { (*n >= range_1.0 && *n <= range_1.1) || (*n >= range_2.0 && *n <= range_2.1) } fn make_valid_numbers_array(rules: &Vec<TicketRule>) -> Vec<bool> { let mut valid_numbers = vec![false; 1000]; rules.iter().for_each( |TicketRule { range_1, range_2, .. }| { (range_1.0..=range_1.1).for_each(|n| { valid_numbers[n] = true; }); (range_2.0..=range_2.1).for_each(|n| { valid_numbers[n] = true; }); }, ); valid_numbers } #[wasm_bindgen(js_name = "advent16Part1")] pub fn advent_16_part_1(input: String) -> usize { let (rules, _, nearby_tickets) = parse_ticket_translation(input); let valid_numbers = make_valid_numbers_array(&rules); nearby_tickets .into_iter() .flatten() .filter(|n| !valid_numbers[*n]) .sum() } #[wasm_bindgen(js_name = "advent16Part2")] pub fn advent_16_part_2(input: String) -> usize { let (rules, ticket, nearby_tickets) = parse_ticket_translation(input); let valid_numbers = make_valid_numbers_array(&rules); let valid_tickets = nearby_tickets .into_iter() .filter(|ns| ns.iter().all(|n| valid_numbers[*n])) .collect::<Vec<_>>(); let mut candidates: Vec<Vec<usize>> = vec![vec![]; ticket.len()]; for (i, ticket_rule) in rules.iter().enumerate() { for j in 0..valid_tickets[0].len() { if (0..valid_tickets.len()).all(|k| validate_number(ticket_rule, &valid_tickets[k][j])) { candidates[j].push(i); } } } let mut product = 1; let mut eliminated: Vec<bool> = vec![false; ticket.len()]; let mut elimination_order: Vec<_> = candidates.into_iter().enumerate().collect(); elimination_order.sort_by(|(_, a), (_, b)| a.len().cmp(&b.len())); for (i, rs) in elimination_order { for r in rs { if !eliminated[r] { eliminated[r] = true; let TicketRule { title, .. } = &rules[r]; if title.starts_with("de") { product *= ticket[i]; } break; } } } product } fn make_n_kernel(n: usize) -> Vec<Vec<i8>> { if n == 1 { return vec![vec![-1], vec![0], vec![1]]; } let mut kernel = vec![]; let smaller_kernel = make_n_kernel(n - 1); for i in -1..=1 { smaller_kernel.iter().for_each(|vs| { let mut with = vs.to_vec(); with.push(i); kernel.push(with); }) } kernel } fn neighbours_kernel(pos: &Vec<i8>, kernel: &Vec<Vec<i8>>) -> Vec<Vec<i8>> { kernel .iter() .map(|offset| pos.iter().zip(offset.iter()).map(|(a, b)| a + b).collect()) .collect() } fn cube_game_n(dimensions: usize, input: String) -> usize { let kernel: Vec<Vec<i8>> = make_n_kernel(dimensions) .into_iter() .filter(|pos| *pos != vec![0; dimensions]) .collect(); let mut cubes: FxHashSet<Vec<i8>> = input .lines() .enumerate() .flat_map(|(y, line)| { line.chars().enumerate().filter_map(move |(x, c)| match c { '#' => { let mut pos = vec![0; dimensions]; pos[0] = x as i8; pos[1] = y as i8; Some(pos) } _ => None, }) }) .collect(); for _ in 0..6 { let mut counts: FxHashMap<Vec<i8>, u8> = FxHashMap::default(); for active in cubes.iter() { counts.entry(active.to_vec()).or_insert(0); let candidates = neighbours_kernel(active, &kernel); candidates.into_iter().for_each(|pos| { counts .entry(pos) .and_modify(|i| { *i += 1; }) .or_insert(1); }); } cubes = counts .into_iter() .filter_map(|(pos, count)| match (cubes.contains(&pos), count) { (true, 2..=3) => Some(pos), (true, _) => None, (false, 3) => Some(pos), _ => None, }) .collect(); } cubes.len() } #[wasm_bindgen(js_name = "advent17Part1")] pub fn advent_17_part_1(input: String) -> usize { cube_game_n(3, input) } #[wasm_bindgen(js_name = "advent17Part2")] pub fn advent_17_part_2(input: String) -> usize { cube_game_n(4, input) } #[derive(Debug, Clone, PartialEq)] enum Exp { Constant(u64), Add, Mul, Par(Box<Vec<Exp>>), } fn parse_expression(mut tokens: &[char]) -> (&[char], Exp) { let mut result = Vec::new(); loop { let (mut cont, e) = match tokens { ['+', rest @ ..] => (rest, Exp::Add), ['*', rest @ ..] => (rest, Exp::Mul), ['(', rest @ ..] => parse_expression(rest), [')', rest @ ..] => return (rest, Exp::Par(Box::new(result))), [a, rest @ ..] => { let n = a.to_digit(10).expect("Number"); (rest, Exp::Constant(n as u64)) } [] => return (&[], Exp::Par(Box::new(result))), }; result.push(e); std::mem::swap(&mut tokens, &mut cont); } } fn eval_expression<'a>(e: &Exp, precedence: &Vec<Vec<Exp>>) -> u64 { match e { Exp::Constant(n) => *n, Exp::Par(es) => { let mut buffer = es.to_vec(); let mut remaining = vec![buffer[0].clone()]; let mut tokens = &buffer[1..]; let mut ops = precedence.to_vec(); loop { match tokens { [op, b, rest @ ..] if ops.last().map_or(false, |p| p.contains(op)) => { let n = eval_expression(&remaining.pop().unwrap(), precedence); let m = eval_expression(b, precedence); let x = match op { Exp::Add => n + m, _ => n * m, }; remaining.push(Exp::Constant(x)); tokens = rest; } [e, rest @ ..] => { remaining.push(e.clone()); tokens = rest; } [] if remaining.len() == 1 => { match remaining[0] { Exp::Constant(n) => return n, _ => panic!("Expected constant"), }; } [] => { ops.pop(); buffer = remaining; remaining = vec![buffer[0].clone()]; tokens = &buffer[1..]; } }; } } _ => panic!("Expected constant or par"), } } #[wasm_bindgen(js_name = "advent18Part1")] pub fn advent_18_part_1(input: String) -> u64 { input .lines() .map(|line| { let chars = &line .chars() .filter(|c| !c.is_whitespace()) .collect::<Vec<_>>()[..]; parse_expression(&chars).1 }) .map(|e| eval_expression(&e, &vec![vec![Exp::Mul, Exp::Add]])) .sum() } #[wasm_bindgen(js_name = "advent18Part2")] pub fn advent_18_part_2(input: String) -> u64 { input .lines() .map(|line| { let chars = &line .chars() .filter(|c| !c.is_whitespace()) .collect::<Vec<_>>()[..]; parse_expression(&chars).1 }) .map(|e| eval_expression(&e, &vec![vec![Exp::Mul], vec![Exp::Add]])) .sum() } enum MessageRule { Match(String), Ref(Vec<Vec<usize>>), } #[derive(Display, FromStr)] #[display("{0}: {1}")] struct Indexed(usize, String); fn collapse_rule<'a>( i: usize, rows: &Vec<MessageRule>, mut rules: &mut Vec<Option<Vec<String>>>, ) -> Vec<String> { if let Some(rule) = &rules[i] { return rule.to_vec(); } match &rows[i] { MessageRule::Match(text) => { rules[i] = Some(vec![text.clone()]); } MessageRule::Ref(ors) => { let texts = ors .iter() .flat_map(|or| { let collapsed = or .iter() .map(|j| collapse_rule(*j, rows, &mut rules)) .collect::<Vec<_>>(); let mut possibilities = collapsed[0].to_vec(); for o in collapsed.into_iter().skip(1) { possibilities = o .iter() .flat_map(|s2| { possibilities .iter() .map(move |s1| [s1.clone(), s2.clone()].concat()) }) .collect::<Vec<_>>(); } possibilities }) .collect::<Vec<String>>(); rules[i] = Some(texts); } }; match &rules[i] { Some(rule) => rule.to_vec(), _ => unreachable!(), } } #[derive(Display, FromStr)] #[display("\"{0}\"")] struct MessageRuleChar(String); #[wasm_bindgen(js_name = "advent19Part1")] pub fn advent_19_part_1(input: String) -> usize { let (rules_text, messages) = input.split_once("\n\n").expect("Two chunks"); let mut unsorted_rule_rows = rules_text .lines() .map(|t| t.parse::<Indexed>().expect("!")) .collect::<Vec<_>>(); unsorted_rule_rows.sort_by(|a, b| a.0.cmp(&b.0)); let mut rule_rows = unsorted_rule_rows .into_iter() .map(|r| { let text = r.1; if let Ok(c) = text.parse::<MessageRuleChar>() { MessageRule::Match(c.0) } else { let ors = text .split(" | ") .map(|refs| { refs.split(' ') .map(|n| n.parse::<usize>().expect("Index")) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); MessageRule::Ref(ors) } }) .collect::<Vec<_>>(); let mut rules = vec![None; rule_rows.len()]; collapse_rule(0, &rule_rows, &mut rules); let rule_0 = &rules[0]; match rule_0 { Some(rule) => messages .lines() .filter(|message| rule.contains(&message.to_string())) .count(), _ => panic!("There is no rule 0!"), } } #[wasm_bindgen(js_name = "advent19Part2")] pub fn advent_19_part_2(input: String) -> u32 { println!("{}", input); 1 } #[test] fn test_part_1() { let input = include_str!("./data.txt").to_string(); let before = std::time::Instant::now(); let result = advent_19_part_1(input); let after = before.elapsed(); println!("{:?}", after.as_millis()); assert_eq!(result, 1) } #[test] fn test_part_2() { let input = include_str!("./data.txt").to_string(); let before = std::time::Instant::now(); let result = advent_19_part_2(input); let after = before.elapsed(); println!("{:?}", after.as_millis()); assert_eq!(result, 1) } #[wasm_bindgen(js_name = "advent20Part1")] pub fn advent_20_part_1(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent20Part2")] pub fn advent_20_part_2(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent21Part1")] pub fn advent_21_part_1(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent21Part2")] pub fn advent_21_part_2(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent22Part1")] pub fn advent_22_part_1(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent22Part2")] pub fn advent_22_part_2(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent23Part1")] pub fn advent_23_part_1(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent23Part2")] pub fn advent_23_part_2(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent24Part1")] pub fn advent_24_part_1(input: String) -> u32 { println!("{}", input); 1 } #[wasm_bindgen(js_name = "advent24Part2")] pub fn advent_24_part_2(input: String) -> u32 { println!("{}", input); 1 }
true
ca0a40b3e7206b0948895a069041fa7deb82e48a
Rust
digitlimit/cargo-user-app
/src/app/models/user.rs
UTF-8
330
3.125
3
[]
no_license
#[allow(dead_code)] pub struct User { id: u32, email: String } impl User { #[allow(dead_code)] pub fn new(id: u32, email: &str) -> User { User { id: id, email: email.to_string() } } #[allow(dead_code)] pub fn get_id(&self) -> u32 { self.id } }
true
2fe93e3605e5b8d14d27db842972773fd50161c9
Rust
LeLeMoe/CGToy
/src/render/_render_context.rs
UTF-8
7,191
2.640625
3
[ "Unlicense" ]
permissive
use std::sync::Arc; use wgpu::util::DeviceExt; use winit::{dpi::PhysicalSize, window::Window}; /// pub struct RenderContext { size: PhysicalSize<u32>, sc_desc: wgpu::SwapChainDescriptor, swap_chain: wgpu::SwapChain, accessor: ContextAccessor, } impl RenderContext { /// pub async fn new(desc: RenderContextDescriptor<'_>) -> Result<Self, RenderContextError> { // Create instance. let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); // Create surface. let surface = unsafe { instance.create_surface(desc.window) }; // Request adapter. let adapter = match instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, compatible_surface: Some(&surface), }) .await { Some(adapter_res) => adapter_res, None => return Err(RenderContextError::FailedToRequestAdapter), }; // Check support features. let supported_features = adapter.features(); if !supported_features.contains(desc.features) { let mut unsupported_features = desc.features; unsupported_features.remove(supported_features); return Err(RenderContextError::FeaturesNotSupported( unsupported_features, )); } // Request device and queue. let (device, queue) = match adapter .request_device( &wgpu::DeviceDescriptor { label: None, features: desc.features, limits: Default::default(), }, None, ) .await { Ok(device_bundle) => device_bundle, Err(err) => return Err(RenderContextError::FailedToRequestDevice(err)), }; // Get Surface size. let size = desc.window.inner_size(); // Fill swap chain descriptor. let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::RENDER_ATTACHMENT, format: adapter.get_swap_chain_preferred_format(&surface).unwrap(), width: size.width, height: size.height, present_mode: wgpu::PresentMode::Fifo, }; // Create swap chain. let swap_chain = device.create_swap_chain(&surface, &sc_desc); Ok(Self { size, sc_desc, swap_chain, accessor: ContextAccessor(Arc::new(ContextData { surface, device, queue, })), }) } /// pub fn access(&self) -> ContextAccessor { ContextAccessor(self.accessor.0.clone()) } /// pub fn update_swap_chain(&mut self, new_size: PhysicalSize<u32>) { if self.size.width > 0 && self.size.height > 0 { self.size = new_size; // Update swap chain size. self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; // Create swap chain. self.swap_chain = self .accessor .0 .device .create_swap_chain(&self.accessor.0.surface, &self.sc_desc); } } /// pub fn get_current_frame(&mut self) -> Option<wgpu::SwapChainTexture> { match self.swap_chain.get_current_frame() { Ok(frame) => Some(frame.output), Err(error) => { match error { wgpu::SwapChainError::Lost => self.update_swap_chain(self.size), wgpu::SwapChainError::OutOfMemory => panic!("Out of memory!"), _ => (), }; None } } } } /// pub struct RenderContextDescriptor<'a> { pub window: &'a Window, pub features: wgpu::Features, } /// pub enum RenderContextError { FailedToRequestAdapter, FailedToRequestDevice(wgpu::RequestDeviceError), FeaturesNotSupported(wgpu::Features), } /// pub struct ContextAccessor(Arc<ContextData>); impl ContextAccessor { /// pub fn create_shader_module(&self, desc: &wgpu::ShaderModuleDescriptor) -> wgpu::ShaderModule { self.0.device.create_shader_module(desc) } /// pub fn create_command_encoder( &self, desc: &wgpu::CommandEncoderDescriptor, ) -> wgpu::CommandEncoder { self.0.device.create_command_encoder(desc) } /// pub fn create_bind_group(&self, desc: &wgpu::BindGroupDescriptor) -> wgpu::BindGroup { self.0.device.create_bind_group(desc) } /// pub fn create_bind_group_layout( &self, desc: &wgpu::BindGroupLayoutDescriptor, ) -> wgpu::BindGroupLayout { self.0.device.create_bind_group_layout(desc) } /// pub fn create_pipeline_layout( &self, desc: &wgpu::PipelineLayoutDescriptor, ) -> wgpu::PipelineLayout { self.0.device.create_pipeline_layout(desc) } /// pub fn create_render_pipeline( &self, desc: &wgpu::RenderPipelineDescriptor, ) -> wgpu::RenderPipeline { self.0.device.create_render_pipeline(desc) } /// pub fn create_compute_pipeline( &self, desc: &wgpu::ComputePipelineDescriptor, ) -> wgpu::ComputePipeline { self.0.device.create_compute_pipeline(desc) } /// pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> wgpu::Buffer { self.0.device.create_buffer(desc) } /// pub fn create_buffer_with_data(&self, usage: wgpu::BufferUsage, data: &[u8]) -> wgpu::Buffer { self.0 .device .create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: data, usage, }) } /// pub fn create_texture(&self, desc: &wgpu::TextureDescriptor) -> wgpu::Texture { self.0.device.create_texture(desc) } /// pub fn create_texture_with_data( &self, desc: &wgpu::TextureDescriptor, data: &[u8], ) -> wgpu::Texture { self.0 .device .create_texture_with_data(&self.0.queue, desc, data) } /// pub fn create_sampler(&self, desc: &wgpu::SamplerDescriptor) -> wgpu::Sampler { self.0.device.create_sampler(desc) } /// pub fn write_buffer(&self, buffer: &wgpu::Buffer, offset: wgpu::BufferAddress, data: &[u8]) { self.0.queue.write_buffer(buffer, offset, data); } /// pub fn write_texture( &self, texture: wgpu::ImageCopyTexture<'_>, data_layout: wgpu::ImageDataLayout, size: wgpu::Extent3d, data: &[u8], ) { self.0.queue.write_texture(texture, data, data_layout, size); } /// pub fn submit<I: IntoIterator<Item = wgpu::CommandBuffer>>(&self, cmd_buffers: I) { self.0.queue.submit(cmd_buffers); } } /// struct ContextData { pub surface: wgpu::Surface, pub device: wgpu::Device, pub queue: wgpu::Queue, }
true
5c3f33a218c2a6639ac47434dd668796c2a73216
Rust
learn-you-a-rust/basic_types
/src/main.rs
UTF-8
411
3.5625
4
[]
no_license
fn main() { //an array is specified by [type, num_elements] let typed_array: [i32; 5] = [1, 2, 3, 4, 5]; //instead of specifying the type explicitly, //the array can also be initialized to a particular value let _initialized_array = [3; 5]; //array indexing let three = typed_array[2]; //tuple type let tuple = (8, 9, 10); //tuple indexing let nine = tuple.1; }
true
8ba8e2176c9c76e02ee062b41cb5969e3eec87af
Rust
Xinkai/Minesweeper
/src/main.rs
UTF-8
9,015
2.84375
3
[]
no_license
extern crate rand; extern crate ansi_term; mod map; #[macro_use]extern crate conrod; extern crate piston; extern crate piston_window; use conrod::{ color, Canvas, Color, Colorable, Frameable, Labelable, Positionable, Sizeable, Text, Theme, Toggle, Widget, WidgetMatrix, }; use piston_window::{EventLoop, Glyphs, OpenGL, PistonWindow, UpdateEvent, WindowSettings}; use std::sync::mpsc; mod cell; /// Conrod is backend agnostic. Here, we define the `piston_window` backend to use for our `Ui`. type Backend = (<piston_window::G2d<'static> as conrod::Graphics>::Texture, Glyphs); type Ui = conrod::Ui<Backend>; type UiCell<'a> = conrod::UiCell<'a, Backend>; enum AppStatus { Playing, Failed, Finished, } /// This struct holds all of the variables used to demonstrate application data being passed /// through the widgets. If some of these seem strange, that's because they are! Most of these /// simply represent the aesthetic state of different parts of the GUI to offer visual feedback /// during interaction with the widgets. struct DemoApp { map: map::Map, /// Background color (for demonstration of button and sliders). bg_color: Color, /// Should the button be shown (for demonstration of button). /// and the title. title_pad: f64, /// The height of the vertical sliders (we will play with this /// using a number_dialer). /// The widget frame width (we'll use this to demo Framing /// and number_dialer). frame_width: f64, /// A vector of strings for drop_down_list demonstration. /// A channel for sending results from the `WidgetMatrix`. elem_sender: mpsc::Sender<(usize, usize, cell::Interaction)>, elem_receiver: mpsc::Receiver<(usize, usize, cell::Interaction)>, status: AppStatus, title: String, } impl DemoApp { /// Constructor for the Demonstration Application model. fn new() -> DemoApp { let (elem_sender, elem_receiver) = mpsc::channel(); use map::Map; let mut map : Map = Default::default(); map.populate(10, 10, 20); println!("{}", &map); DemoApp { bg_color: color::rgb(0.2, 0.35, 0.45), title_pad: 350.0, frame_width: 1.0, elem_sender: elem_sender, elem_receiver: elem_receiver, map: map, title: "Minesweeper".to_owned(), status: AppStatus::Playing, } } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Construct the window. let mut window: PistonWindow = WindowSettings::new("MineSweeper", [1100, 560]) .opengl(opengl).exit_on_esc(true).vsync(true).build().unwrap(); // construct our `Ui`. let mut ui = { let font_path = "assets/fonts/NotoSans/NotoSans-Regular.ttf"; let theme = Theme::default(); let glyph_cache = Glyphs::new(&font_path, window.factory.clone()); Ui::new(glyph_cache.unwrap(), theme) }; // Our dmonstration app that we'll control with our GUI. let mut app = DemoApp::new(); window.set_ups(60); // Poll events from the window. while let Some(event) = window.next() { ui.handle_event(&event); // We'll set all our widgets in a single function called `set_widgets`. // At the moment conrod requires that we set our widgets in the Render loop, // however soon we'll add support so that you can set your Widgets at any arbitrary // update rate. event.update(|_| ui.set_widgets(|mut ui| set_widgets(&mut ui, &mut app))); // Draw our Ui! // // The `draw_if_changed` method only re-draws the GUI if some `Widget`'s `Element` // representation has changed. Normally, a `Widget`'s `Element` should only change // if a Widget was interacted with in some way, however this is up to the `Widget` // designer's discretion. // // If instead you need to re-draw your conrod GUI every frame, use `Ui::draw`. window.draw_2d(&event, |c, g| ui.draw_if_changed(c, g)); } } /// Set all `Widget`s within the User Interface. /// /// The first time this gets called, each `Widget`'s `State` will be initialised and cached within /// the `Ui` at their given indices. Every other time this get called, the `Widget`s will avoid any /// allocations by updating the pre-existing cached state. A new graphical `Element` is only /// retrieved from a `Widget` in the case that it's `State` has changed in some way. fn set_widgets(ui: &mut UiCell, app: &mut DemoApp) { // We can use this `Canvas` as a parent Widget upon which we can place other widgets. Canvas::new() .frame(app.frame_width) .pad(30.0) .color(app.bg_color) .scroll_kids() .set(CANVAS, ui); // Text example. Text::new(app.title.as_str()) .top_left_with_margins_on(CANVAS, 0.0, app.title_pad) .font_size(32) .color(app.bg_color.plain_contrast()) .set(TITLE, ui); // A demonstration using widget_matrix to easily draw // a matrix of any kind of widget. WidgetMatrix::new(app.map.width, app.map.height) .down(20.0) .w_h(260.0, 260.0) // matrix width and height. .each_widget(|_n, col: usize, row: usize| { // called for every matrix elem. // Color effect for fun. // let (r, g, b, a) = ( // 0.5 + (col as f32 / cols as f32) / 2.0, // 0.75, // 1.0 - (row as f32 / rows as f32) / 2.0, // 1.0 // ); // Now return the widget we want to set in each element position. // You can return any type that implements `Widget`. // The returned widget will automatically be positioned and sized to the matrix // element's rectangle. let elem = app.map.grid[row * app.map.width + col].mine; let elem_sender = app.elem_sender.clone(); let ref cell_data = app.map.grid[row * app.map.width + col]; let label = match cell_data.interaction { map::Interaction::Opened => match cell_data.nearby { 0 => " ", 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", _ => "#", }, map::Interaction::Undiscovered => " ", map::Interaction::Flagged => "!", }; let (r, g, b) = match cell_data.interaction { map::Interaction::Opened => (0.8, 0.8, 0.8), map::Interaction::Undiscovered => (0.5, 0.5, 0.5), map::Interaction::Flagged => (0.5, 0.5, 0.5), }; let cell = cell::Cell::new() .w_h(200.0, 50.0) .down_from(TITLE, 45.0) .rgb(r, g, b) .label(label) .react(move |btn: cell::Interaction| elem_sender.send((col, row, btn)).unwrap()); cell }) .set(TOGGLE_MATRIX, ui); // Receive updates to the matrix from the `WidgetMatrix`. while let Ok((col, row, btn)) = app.elem_receiver.try_recv() { match btn { cell::Interaction::LeftClicked => { if app.map.grid[row * app.map.width + col].mine { app.title = "EXPLODE!".to_owned(); app.status = AppStatus::Failed; } else { app.map.reveal(col, row); } }, cell::Interaction::RightClicked => { match app.map.grid[row * app.map.width + col].interaction { map::Interaction::Flagged => app.map.grid[row * app.map.width + col].interaction = map::Interaction::Undiscovered, map::Interaction::Undiscovered => app.map.grid[row * app.map.width + col].interaction = map::Interaction::Flagged, _ => (), }; println!("Right Clicked"); }, cell::Interaction::BothClicked => { println!("Both Clicked"); } _ => (), } } } // In conrod, each widget must have its own unique identifier so that the `Ui` can keep track of // its state between updates. // To make this easier, conrod provides the `widget_ids` macro, which generates a unique `WidgetId` // for each identifier given in the list. // The `with n` syntax reserves `n` number of WidgetIds for that identifier, rather than just one. // This is often useful when you need to use an identifier in some kind of loop (i.e. like within // the use of `WidgetMatrix` as above). widget_ids! { CANVAS, TITLE, FRAME_WIDTH, TOGGLE_MATRIX, }
true
7b08e7e78a3013b1e6645fbaa0f5834336abad9c
Rust
pchiwan/rustbridge
/src/main1.rs
UTF-8
2,269
3.96875
4
[]
no_license
fn add (a: i32, b: i32) -> i32 { a + b } enum GameType { SinglePlayer, MultiPlayer(u32), } fn choose_game (game: GameType) { match game { GameType::SinglePlayer => println!("How about solitaire?"), GameType::MultiPlayer(2) => println!("How about checkers?"), GameType::MultiPlayer(4) => println!("How about bridge?"), GameType::MultiPlayer(num) => { println!("How about {}-player tag?", num) }, } } fn fizz(num: u32) -> String { if num % 3 == 0 { String::from("Fizz") } else { num.to_string() } } fn main() { let name = "Sílvia"; println!("Hello, world {}!", name); let mut apples = 100; apples += 50; println!("I have {} apples", apples); println!("{}", add(1, 2)); let color = [0, 255, 255]; let index = 2; println!("The 10th element is {:?}", color[index]); let hour = 14; match hour { 0..=6 => println!("It's dawn"), 7..=11 => println!("It's the morning"), 12..=18 => println!("It's the afternoon"), 17..=24 => println!("It's the evening"), _ => { panic!("Time is broken!"); } } let mut prices = vec![30, 100, 2]; prices[0] = 25; prices.push(40); println!("All the prices are: {:?}", prices); let names = vec!["Carol", "Jake", "Marylou", "Bruce"]; for name in names { println!("Hi {}!", name); } let mut i = 0; while i < 10 { println!("i = {}", i); i += 1; } loop { println!("i = {}", i); i += 1; if i >= 10 { break; } } for i in (0..10).map(|x| x * x ) { println!("i = {}", i); } let sum = (0..10).fold(0, |acc, x| { acc + x }); println!("sum = {}", sum); choose_game(GameType::SinglePlayer); choose_game(GameType::MultiPlayer(6)); println!("{}", fizz(3)); println!("{}", fizz(5)); let mut instructors = vec!["Carol"]; let a = instructors.pop(); println!("a is {:?}", a); let b = instructors.pop(); println!("b is {:?}", b); let c = Some("Carol"); let name = c.expect("No name present"); println!("Name is {} bytes long", name.len()); }
true
7509ea97d20e70adeb020c6e18d0d11ea19696f0
Rust
georgegerdin/guitest
/src/layout.rs
UTF-8
18,325
3.109375
3
[]
no_license
use cassowary; use std::cmp::Ordering; use std::collections::BTreeMap; use std::collections::HashMap; type WidgetHandle = i32; #[derive(Eq, PartialEq, Clone)] struct LayoutPosition(u32, u32); fn new_term (variable: cassowary::Variable, coefficient: f64) -> cassowary::Term { cassowary::Term { variable: variable, coefficient: coefficient } } impl LayoutPosition { pub fn new(icol: u32, irow: u32) -> LayoutPosition { LayoutPosition (icol, irow ) } } impl Ord for LayoutPosition { fn cmp(&self, other: &LayoutPosition) -> Ordering { if self.1 < other.1 { return Ordering::Less; } if self.1 == other.1 { if self.0 < other.0 { return Ordering::Less; } if self.0 == other.0 { return Ordering::Equal; } } return Ordering::Greater; } } impl PartialOrd for LayoutPosition { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } struct Component { leading: u32, width: u32, top: u32, height: u32, standard_width: u32, standard_height: u32, item: WidgetHandle, } struct Span { leading: u32, width: u32, top: u32, height: u32, start_position: LayoutPosition, } enum Cell { Component(Component), Span(Span) } fn new_component(item: WidgetHandle, standard_width: u32, standard_height: u32) -> Cell { Cell::Component( Component { item: item, standard_width: standard_width, standard_height: standard_height, leading: 0, width: 0, top: 0, height: 0, } ) } fn new_span(x: u32, y: u32) -> Cell { Cell::Span( Span { leading: 0, width: 0, top: 0, height: 0, start_position: LayoutPosition::new(x, y) }) } impl Cell { pub fn set_leading(&mut self, x: u32) { match *self { Cell::Component(ref mut c) => c.leading = x, Cell::Span(ref mut s) => s.leading = x } } pub fn set_width(&mut self, x: u32) { match *self { Cell::Component(ref mut c) => c.width = x, Cell::Span(ref mut s) => s.width = x } } pub fn set_top(&mut self, x: u32) { match *self { Cell::Component(ref mut c) => c.top = x, Cell::Span(ref mut s) => s.top = x } } pub fn set_height(&mut self, x: u32) { match *self { Cell::Component(ref mut c) => c.height = x, Cell::Span(ref mut s) => s.height = x } } pub fn get_preferred_height(&self) -> u32 { match *self { Cell::Component(ref c) => c.standard_height, Cell::Span(ref c) => 12 } } } pub struct GridLayout { wrap: u32, current_x: u32, current_y: u32, grid: BTreeMap<LayoutPosition, Cell> } enum Action { Add{item: WidgetHandle}, Wrap, Span(u32, u32) } pub struct AccessLayout { actions: Vec<Action>, } pub struct WrapOnlyAccessLayout<'a> { access_layout: &'a mut AccessLayout } impl<'a> WrapOnlyAccessLayout<'a> { pub fn new(al: &'a mut AccessLayout) -> WrapOnlyAccessLayout { WrapOnlyAccessLayout { access_layout: al } } pub fn wrap(&mut self) { self.access_layout.wrap(); } } impl AccessLayout { pub fn add(&mut self, item: WidgetHandle) -> &mut AccessLayout { self.actions.push(Action::Add{item}); self } pub fn span(&mut self, x: u32, y: u32) -> &mut AccessLayout { self.actions.push(Action::Span(x, y)); self } pub fn wrap(&mut self) -> WrapOnlyAccessLayout { self.actions.push(Action::Wrap); WrapOnlyAccessLayout::new(self) } } impl GridLayout { pub fn new() -> GridLayout { GridLayout { wrap: 0, current_x: 0, current_y: 0, grid: BTreeMap::new() } } pub fn set_wrap(mut self, wrap: u32) -> GridLayout { self.wrap = wrap; self } pub fn access(&mut self, access_closure: &Fn(&mut AccessLayout), standard_size_closure: &Fn(WidgetHandle) -> (u32, u32)) { let mut access_object = AccessLayout { actions: Vec::new() }; access_closure(&mut access_object); for a in access_object.actions { match a { Action::Add{item} => { let (width, height) = standard_size_closure(item); self.add(item, width, height); }, Action::Wrap => {self.current_x = 0; self.current_y = self.current_y + 1;}, Action::Span(x, y) => self.span(x, y) } } self.internal_update(); } pub fn update(&self, result_closure: &mut FnMut(WidgetHandle, (u32, u32, u32, u32))) { for (ref position, ref cell) in &self.grid { match *cell { &Cell::Component(ref c) => result_closure(c.item, (c.leading, c.top, c.width, c.height)), &Cell::Span(_) => () } } } fn move_position(&mut self) { while self.grid.contains_key( &LayoutPosition::new(self.current_x, self.current_y) ) { self.current_x = self.current_x + 1; if self.wrap > 0 { if self.current_x >= self.wrap { self.current_x = 0; self.current_y = self.current_y + 1; } } } } fn add(&mut self, item: WidgetHandle, standard_width: u32, standard_height: u32) { self.move_position(); self.grid.insert(LayoutPosition::new(self.current_x, self.current_y), new_component(item, standard_width, standard_height)); } fn span(&mut self, x: u32, y: u32) { if !self.grid.contains_key( &LayoutPosition::new(self.current_x, self.current_y) ) { panic!("Need grid cell to span from."); } for cell_y in 0..y { for cell_x in 0..x { if cell_x == 0 && cell_y == 0 {continue;} self.grid.insert(LayoutPosition::new(self.current_x + cell_x, self.current_y + cell_y), new_span(x, y)); } } } fn internal_update(&mut self) { let mut num_columns = 0usize; if self.wrap == 0 { //Find the longest row since this grid doesn't have a fixed wrap let mut current_row: i32 = -1; let mut num_in_row = 1usize; for (ref position, _) in &self.grid { if position.1 as i32 > current_row { //We have reached a new row if num_in_row > num_columns { num_columns = num_in_row; } //We have found a new longest row num_in_row = 0; current_row = position.1 as i32; } num_in_row = num_in_row + 1; } if num_in_row > num_columns { num_columns = num_in_row; } //Last row was the longest row } else { num_columns = self.wrap as usize; } //Find the number of rows let position: LayoutPosition; { position = self.grid.iter().next_back().unwrap().0.clone(); } let num_rows = position.1 as usize + 1; self.calculate_row(num_rows, num_columns); } fn calculate_row(&mut self, num_rows: usize, num_columns: usize) { use cassowary::{Solver, Variable, Term, Expression}; use cassowary::strength::{WEAK, MEDIUM, STRONG, REQUIRED}; use cassowary::WeightedRelation::*; let mut var_names: HashMap<Variable, (String, f64) > = HashMap::new(); let mut solver = Solver::new(); let widget_width: Variable = Variable::new(); let widget_height: Variable = Variable::new(); //One vector for every row in the grid let mut width_vars: Vec<Vec<Variable>> = Vec::new(); let mut height_vars: Vec<Vec<Variable>> = Vec::new(); let mut trailing_gap_vars: Vec<Vec<Variable>> = Vec::new(); let mut inferior_gap_vars: Vec<Vec<Variable>> = Vec::new(); let mut top_margin: Vec<Variable> = Vec::new(); let mut bottom_margin: Vec<Variable> = Vec::new(); let mut left_margin: Vec<Variable> = Vec::new(); let mut right_margin: Vec<Variable> = Vec::new(); let mut all_vars_equal_parent_width_expr: Vec<Expression> = Vec::new(); let mut all_vars_equal_parent_height: Vec<Vec<Term>> = Vec::new(); let mut all_vars_equal_parent_height_expr: Vec<Expression> = Vec::new(); for c in 0..num_columns { all_vars_equal_parent_height.push(Vec::new()); top_margin.push(Variable::new()); bottom_margin.push(Variable::new()); solver.add_edit_variable(bottom_margin[c], 1.0).unwrap(); solver.suggest_value(bottom_margin[c], 1000000.0).unwrap(); var_names.insert(top_margin[c].clone(), ("Top Margin".to_owned(), 0.0)); var_names.insert(bottom_margin[c].clone(), ("Bottom Margin".to_owned(), 0.0)); all_vars_equal_parent_height[c].push(new_term(top_margin[c], 1.0)); all_vars_equal_parent_height[c].push(new_term(bottom_margin[c], 1.0)); } var_names.insert(widget_width.clone(), ("Widget width".to_owned(), 0.0)); var_names.insert(widget_height.clone(), ("Widget height".to_owned(), 0.0)); for row in 0..num_rows { width_vars.push(Vec::new()); height_vars.push(Vec::new()); trailing_gap_vars.push(Vec::new()); inferior_gap_vars.push(Vec::new()); left_margin.push(Variable::new()); right_margin.push(Variable::new()); var_names.insert(left_margin[row].clone(), ("Left Margin".to_owned(), 0.0)); var_names.insert(right_margin[row].clone(), ("Right Margin".to_owned(), 0.0)); let mut all_vars_equal_parent_width: Vec<Term> = Vec::new(); all_vars_equal_parent_width.push(new_term(left_margin[row], 1.0)); all_vars_equal_parent_width.push(new_term(right_margin[row], 1.0)); for c in 0usize..num_columns { width_vars[row].push(Variable::new()); var_names.insert(width_vars[row][c].clone(), (format!("w{}", c), 0.0)); all_vars_equal_parent_width.push(new_term(width_vars[row][c], 1.0)); let mut height = 0.0; match self.grid.get(&LayoutPosition::new(c as u32, row as u32)) { Some(ref cell) => { height = cell.get_preferred_height() as f64; } None =>() } height_vars[row].push(Variable::new()); var_names.insert(height_vars[row][c], (format!("h{}", c), 0.0)); all_vars_equal_parent_height[c].push(new_term(height_vars[row][c], 1.0)); solver.add_edit_variable(height_vars[row][c], 1.0).unwrap(); solver.suggest_value(height_vars[row][c], height).unwrap(); if row + 1 != num_rows { inferior_gap_vars[row].push(Variable::new()); var_names.insert(inferior_gap_vars[row][c], (format!("i{}", c), 0.0)); all_vars_equal_parent_height[c].push(new_term(inferior_gap_vars[row][c], 1.0)); } if c + 1 != num_columns { trailing_gap_vars[row].push(Variable::new()); var_names.insert(trailing_gap_vars[row][c], (format!("g{}", c), 0.0)); all_vars_equal_parent_width.push(new_term(trailing_gap_vars[row][c], 1.0)); solver.add_edit_variable(trailing_gap_vars[row][c], 1.0).unwrap(); solver.suggest_value(trailing_gap_vars[row][c], 8.0).unwrap(); } } all_vars_equal_parent_width_expr.push(Expression::new(all_vars_equal_parent_width, 0.0)); solver.add_constraints(&[all_vars_equal_parent_width_expr[row].clone() |EQ(REQUIRED)| widget_width]).unwrap(); solver.add_constraints(&[left_margin[row] |LE(STRONG)| 12.0, right_margin[row] |LE(STRONG)| 12.0,] ).unwrap(); if num_columns > 1 { for i in 0 .. num_columns - 1 { solver.add_constraint(width_vars[row][i] |EQ(STRONG)| width_vars[row][i+1]).unwrap() } for i in 0 .. num_columns - 2 { solver.add_constraints(&[trailing_gap_vars[row][i] |EQ(STRONG)| trailing_gap_vars[row][i+1], trailing_gap_vars[row][i] |LE(STRONG)| 8.0]).unwrap() } } } for c in 0..num_columns { all_vars_equal_parent_height_expr.push(Expression::new(all_vars_equal_parent_height[c].clone(), 0.0)); solver.add_constraint(all_vars_equal_parent_height_expr[c].clone() |EQ(REQUIRED)| widget_height).unwrap(); solver.add_constraints(&[top_margin[c] |EQ(STRONG)| 12.0, bottom_margin[c] |GE(STRONG)| 12.0, ] ).unwrap(); if num_rows > 1 { for row in 0..num_rows - 1 { if c < num_columns - 1 { let num_height_vars = height_vars.len(); let num_inferior_gap_vars = inferior_gap_vars.len(); let num_height_var_row = height_vars[row].len(); let num_inferior_hap_var_row = inferior_gap_vars[row].len(); solver.add_constraint(height_vars[row][c] + inferior_gap_vars[row][c] |EQ(MEDIUM)| height_vars[row][c+1] + inferior_gap_vars[row][c+1]).unwrap(); } solver.add_constraint(inferior_gap_vars[row][c] |GE(WEAK)| 8.0).unwrap(); if row < num_rows - 2 { solver.add_constraint(inferior_gap_vars[row][c] |EQ(WEAK)| inferior_gap_vars[row+1][c]); } } } } solver.add_edit_variable(widget_width, 1.0).unwrap(); solver.add_edit_variable(widget_height, 1.0).unwrap(); solver.suggest_value(widget_width, 300.0).unwrap(); solver.suggest_value(widget_height, 300.0).unwrap(); macro_rules! get_value { ($x:expr) => { match var_names.get($x) { Some(c) => (c.0.clone(), c.1), None => ("".to_owned(), 0.0) } } } macro_rules! set_value{ ($var:ident, $value:ident) => { match var_names.get_mut($var) { Some(ref mut c) => (*c).1 = $value, None => () } } } for c in solver.fetch_changes().iter() { let (ref var, value) = *c; set_value!(var, value); } let mut y: Vec<f64> = Vec::new(); for row in 0..num_rows { let mut x = get_value!(&left_margin[row]).1; for i in 0..num_columns{ if row == 0 { y.push(get_value!(&top_margin[i]).1)} match self.grid.get_mut(&LayoutPosition::new(i as u32, row as u32)) { Some( mut c) => { (*c).set_leading(x as u32); let width = get_value!(&width_vars[row][i]).1; let height = get_value!(&height_vars[row][i]).1; (*c).set_top(y[i] as u32); (*c).set_width(width as u32); x = x + width; y[i] = y[i] + height; (*c).set_height(height as u32); }, None => x = x + get_value!(&width_vars[row][i]).1 } if i < num_columns - 1 { x = x + get_value!(&trailing_gap_vars[row][i]).1; } if row < num_rows - 1 { y[i] = y[i] + get_value!(&inferior_gap_vars[row][i]).1; } } } } pub fn print(self) { let mut last_position = LayoutPosition::new(0,0); for (ref position, ref c) in &self.grid { if position.1 > last_position.1 { println!(""); } match *c { &Cell::Component(ref c) => print!("\t{} ({}, {})", c.item, c.leading, c.top), &Cell::Span(_) => print!("\tSPAN\t") } last_position = (*position).clone(); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_basic_grid_layout() { use std::cmp::Ordering; assert_eq!(Ordering::Less, LayoutPosition(0, 1).cmp(&LayoutPosition(0, 2)) ); assert_eq!(Ordering::Less, LayoutPosition(1, 2).cmp(&LayoutPosition(2, 2)) ); assert_eq!(Ordering::Less, LayoutPosition(1, 0).cmp(&LayoutPosition(0, 1)) ); assert_ne!(Ordering::Less, LayoutPosition(0, 1).cmp(&LayoutPosition(1, 0)) ); assert_ne!(Ordering::Less, LayoutPosition(0, 2).cmp(&LayoutPosition(0, 1)) ); let mut layouter = GridLayout::new() .set_wrap(4); let w: Vec<i32> = (0..10).collect(); layouter.access(&|ref mut l| { l.add(w[0]); l.add(w[1]).span(2, 2); l.add(w[2]); l.add(w[3]); l.add(w[4]); l.add(w[5]); l.add(w[6]).wrap().wrap(); l.add(w[7]).add(w[8]).add(w[9]); }, &|l| -> (u32, u32) { (30, 12) } ); layouter.update(&mut |index: WidgetHandle, rect: (u32, u32, u32, u32)| { println!("{}: ({}, {}, {}, {})", index, rect.0, rect.1, rect.2, rect.3); }); layouter.print(); } }
true
ce895d00229c459d749f96fbfe8b6fa9ae3468da
Rust
chenyangzhi88/datafuse
/common/datavalues/src/data_array_comparison_test.rs
UTF-8
12,102
2.609375
3
[ "Apache-2.0" ]
permissive
// Copyright 2020-2021 The Datafuse Authors. // // SPDX-License-Identifier: Apache-2.0. #[test] fn test_array_comparison() { use std::sync::Arc; use pretty_assertions::assert_eq; use super::*; #[allow(dead_code)] struct ArrayTest { name: &'static str, args: Vec<Vec<DataArrayRef>>, expect: Vec<DataArrayRef>, error: Vec<&'static str>, op: DataValueComparisonOperator, } let tests = vec![ ArrayTest { name: "eq-passed", args: vec![ vec![ Arc::new(StringArray::from(vec!["x1", "x2"])), Arc::new(StringArray::from(vec!["x2", "x2"])), ], vec![ Arc::new(Int8Array::from(vec![4, 3, 2, 1])), Arc::new(Int8Array::from(vec![4, 3, 2, 1])), ], vec![ Arc::new(Int16Array::from(vec![4, 3, 2, 1])), Arc::new(Int16Array::from(vec![1, 2, 2, 4])), ], vec![ Arc::new(Int8Array::from(vec![4, 3, 2, 1])), Arc::new(Int32Array::from(vec![4, 3, 2, 1])), ], ], op: DataValueComparisonOperator::Eq, expect: vec![ Arc::new(BooleanArray::from(vec![false, true])), Arc::new(BooleanArray::from(vec![true, true, true, true])), Arc::new(BooleanArray::from(vec![false, false, true, false])), Arc::new(BooleanArray::from(vec![true, true, true, true])), ], error: vec![""], }, ArrayTest { name: "lt-passed", args: vec![vec![ Arc::new(Int8Array::from(vec![4, 3, 1, 1])), Arc::new(Int8Array::from(vec![4, 3, 2, 1])), ]], op: DataValueComparisonOperator::Lt, expect: vec![Arc::new(BooleanArray::from(vec![ false, false, true, false, ]))], error: vec![""], }, ArrayTest { name: "lt-eq-passed", args: vec![vec![ Arc::new(Int8Array::from(vec![4, 3, 1, 2])), Arc::new(Int8Array::from(vec![4, 3, 2, 1])), ]], op: DataValueComparisonOperator::LtEq, expect: vec![Arc::new(BooleanArray::from(vec![true, true, true, false]))], error: vec![""], }, ArrayTest { name: "gt-passed", args: vec![vec![ Arc::new(Int8Array::from(vec![4, 3, 1, 2])), Arc::new(Int8Array::from(vec![4, 3, 2, 1])), ]], op: DataValueComparisonOperator::Gt, expect: vec![Arc::new(BooleanArray::from(vec![ false, false, false, true, ]))], error: vec![""], }, ArrayTest { name: "gt-eq-passed", args: vec![vec![ Arc::new(Int8Array::from(vec![4, 3, 1, 2])), Arc::new(Int8Array::from(vec![4, 3, 2, 1])), ]], op: DataValueComparisonOperator::GtEq, expect: vec![Arc::new(BooleanArray::from(vec![true, true, false, true]))], error: vec![""], }, ArrayTest { name: "not-eq-passed", args: vec![vec![ Arc::new(Int8Array::from(vec![4, 3, 1, 2])), Arc::new(Int8Array::from(vec![4, 3, 2, 1])), ]], op: DataValueComparisonOperator::NotEq, expect: vec![Arc::new(BooleanArray::from(vec![false, false, true, true]))], error: vec![""], }, ArrayTest { name: "like-passed", args: vec![vec![ Arc::new(StringArray::from(vec!["abc", "abd", "abe", "abf"])), Arc::new(StringArray::from(vec!["abc", "a%", "_b_", "f"])), ]], op: DataValueComparisonOperator::Like, expect: vec![Arc::new(BooleanArray::from(vec![true, true, true, false]))], error: vec![""], }, ArrayTest { name: "not-like-passed", args: vec![vec![ Arc::new(StringArray::from(vec!["abc", "abd", "abe", "abf"])), Arc::new(StringArray::from(vec!["abc", "a%", "_b_", "f"])), ]], op: DataValueComparisonOperator::NotLike, expect: vec![Arc::new(BooleanArray::from(vec![ false, false, false, true, ]))], error: vec![""], }, ]; for t in tests { for (i, args) in t.args.iter().enumerate() { let result = DataArrayComparison::data_array_comparison_op( t.op.clone(), &DataColumnarValue::Array(args[0].clone()), &DataColumnarValue::Array(args[1].clone()), ); match result { Ok(v) => assert_eq!(v.as_ref(), t.expect[i].as_ref()), Err(e) => assert_eq!(t.error[i], e.to_string()), } } } } #[test] fn test_array_scalar_comparison() { use std::sync::Arc; use super::*; #[allow(dead_code)] struct ArrayTest { name: &'static str, array: DataArrayRef, scalar: DataValue, expect: DataArrayRef, error: &'static str, op: DataValueComparisonOperator, } let tests = vec![ ArrayTest { name: "eq-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::Eq, expect: Arc::new(BooleanArray::from(vec![false, true, false, false])), error: "", }, ArrayTest { name: "eq-different-type-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int32(Some(3)), op: DataValueComparisonOperator::Eq, expect: Arc::new(BooleanArray::from(vec![false, true, false, false])), error: "", }, ArrayTest { name: "lt-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::Lt, expect: Arc::new(BooleanArray::from(vec![false, false, true, true])), error: "", }, ArrayTest { name: "lt-eq-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::LtEq, expect: Arc::new(BooleanArray::from(vec![false, true, true, true])), error: "", }, ArrayTest { name: "gt-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::Gt, expect: Arc::new(BooleanArray::from(vec![true, false, false, false])), error: "", }, ArrayTest { name: "gt-eq-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::GtEq, expect: Arc::new(BooleanArray::from(vec![true, true, false, false])), error: "", }, ArrayTest { name: "like-passed", array: Arc::new(StringArray::from(vec!["abc", "abd", "bae", "baf"])), scalar: DataValue::Utf8(Some("a%".to_string())), op: DataValueComparisonOperator::Like, expect: Arc::new(BooleanArray::from(vec![true, true, false, false])), error: "", }, ArrayTest { name: "not-like-passed", array: Arc::new(StringArray::from(vec!["abc", "abd", "bae", "baf"])), scalar: DataValue::Utf8(Some("a%".to_string())), op: DataValueComparisonOperator::NotLike, expect: Arc::new(BooleanArray::from(vec![false, false, true, true])), error: "", }, ]; for t in tests { let result = DataArrayComparison::data_array_comparison_op( t.op.clone(), &DataColumnarValue::Array(t.array.clone()), &DataColumnarValue::Constant(t.scalar, t.array.len()), ); match result { Ok(v) => assert_eq!(v.as_ref(), t.expect.as_ref()), Err(e) => assert_eq!(t.error, e.to_string()), } } } #[test] fn test_scalar_array_comparison() { use std::sync::Arc; use super::*; #[allow(dead_code)] struct ArrayTest { name: &'static str, array: DataArrayRef, scalar: DataValue, expect: DataArrayRef, error: &'static str, op: DataValueComparisonOperator, } let tests = vec![ ArrayTest { name: "eq-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::Eq, expect: Arc::new(BooleanArray::from(vec![false, true, false, false])), error: "", }, ArrayTest { name: "eq-different-type-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int32(Some(3)), op: DataValueComparisonOperator::Eq, expect: Arc::new(BooleanArray::from(vec![false, true, false, false])), error: "", }, ArrayTest { name: "lt-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::Lt, expect: Arc::new(BooleanArray::from(vec![true, false, false, false])), error: "", }, ArrayTest { name: "lt-eq-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::LtEq, expect: Arc::new(BooleanArray::from(vec![true, true, false, false])), error: "", }, ArrayTest { name: "gt-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::Gt, expect: Arc::new(BooleanArray::from(vec![false, false, true, true])), error: "", }, ArrayTest { name: "gt-eq-passed", array: Arc::new(Int8Array::from(vec![4, 3, 2, 1])), scalar: DataValue::Int8(Some(3)), op: DataValueComparisonOperator::GtEq, expect: Arc::new(BooleanArray::from(vec![false, true, true, true])), error: "", }, ArrayTest { name: "like-passed", array: Arc::new(StringArray::from(vec!["abc", "abd", "bae", "baf"])), scalar: DataValue::Utf8(Some("a%".to_string())), op: DataValueComparisonOperator::Like, expect: Arc::new(BooleanArray::from(vec![true, true, false, false])), error: "", }, ArrayTest { name: "not-like-passed", array: Arc::new(StringArray::from(vec!["abc", "abd", "bae", "baf"])), scalar: DataValue::Utf8(Some("a%".to_string())), op: DataValueComparisonOperator::NotLike, expect: Arc::new(BooleanArray::from(vec![false, false, true, true])), error: "", }, ]; for t in tests { let result = DataArrayComparison::data_array_comparison_op( t.op.clone(), &DataColumnarValue::Constant(t.scalar, t.array.len()), &DataColumnarValue::Array(t.array), ); match result { Ok(v) => assert_eq!(v.as_ref(), t.expect.as_ref()), Err(e) => assert_eq!(t.error, e.to_string()), } } }
true
8ffca43213766ba2dd9f492f0405aa281e41baec
Rust
paulkirkwood/rs.parcoursdb
/src/col/col.rs
UTF-8
1,805
3.328125
3
[]
no_license
use crate::location::Location; use std::fmt; #[derive(Copy,Clone,PartialEq, Debug)] pub enum ColCategory { HC, C1, C2, C3, C4, UC, } impl fmt::Display for ColCategory { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ColCategory::HC => write!(f, "HC"), ColCategory::C1 => write!(f, "C.1"), ColCategory::C2 => write!(f, "C.2"), ColCategory::C3 => write!(f, "C.3"), ColCategory::C4 => write!(f, "C.4"), ColCategory::UC => write!(f, "Uncategorised"), } } } pub struct Col { location: Location, category: ColCategory, length: Option<f64>, average_gradient: Option<f64>, maximum_gradient: Option<f64> } impl Col { pub fn new(loc: Location , category: ColCategory , length: Option<f64> , average_gradient: Option<f64> , maximum_gradient: Option<f64>) -> Col { Col { location: Location::new(loc.name().to_string(), *loc.country(), loc.elevation()) , category: category , length: length , average_gradient: average_gradient , maximum_gradient: maximum_gradient } } pub fn location(&self) -> &Location { &self.location } pub fn category(&self) -> ColCategory { self.category } pub fn length(&self) -> Option<f64> { self.length } pub fn average_gradient(&self) -> Option<f64> { self.average_gradient } pub fn maximum_gradient(&self) -> Option<f64> { self.maximum_gradient } pub fn clone(&self) -> Col { Col::new(self.location.clone(), self.category.clone(), self.length, self.average_gradient, self.maximum_gradient) } }
true
64e446c7dae09d5d111ffe82acd88454eba83b14
Rust
carrotflakes/kakapo
/src/parse.rs
UTF-8
6,916
3.15625
3
[]
no_license
use crate::Ast; use std::iter::Peekable; #[derive(Debug, Clone)] pub enum Error { UnexpectedChar(char), UnexpectedParenClose, UnexpectedEOS, } pub fn parse(str: &str) -> Result<Ast, Error> { let mut cs = str.chars().peekable(); let res = parse_or(&mut cs); if let Some(c) = cs.peek() { Err(Error::UnexpectedChar(c.clone())) } else { res } } fn parse_or(cs: &mut Peekable<impl Iterator<Item = char>>) -> Result<Ast, Error> { let mut asts = Vec::new(); asts.push(parse_concat(cs)?); while let Some('|') = cs.peek() { cs.next(); asts.push(parse_concat(cs)?); } match asts.len() { 0 => Ok(Ast::Concat(Vec::new())), 1 => Ok(asts.remove(0)), _ => Ok(Ast::Or(asts)), } } fn parse_concat(cs: &mut Peekable<impl Iterator<Item = char>>) -> Result<Ast, Error> { let mut asts = Vec::new(); while let Some(c) = cs.peek() { match c { '|' | ')' | '*' | '+' => { break; } _ => { asts.push(parse_repeat(cs)?); } } } match asts.len() { 1 => Ok(asts.remove(0)), _ => Ok(Ast::Concat(asts)), } } fn parse_repeat(cs: &mut Peekable<impl Iterator<Item = char>>) -> Result<Ast, Error> { if let Some(c) = cs.peek() { let ast = match c { '|' | ')' | '*' | '+' => { return Err(Error::UnexpectedChar(cs.peek().unwrap().clone())); } '(' => { cs.next(); parse_paren(cs)? } '.' => { cs.next(); Ast::Any } '[' => { cs.next(); parse_char_class(cs)? } _ => parse_char(cs)?, }; Ok(match cs.peek() { Some('*') => { cs.next(); Ast::Repeat(0, std::u32::MAX, Box::new(ast)) } Some('+') => { cs.next(); Ast::Repeat(1, std::u32::MAX, Box::new(ast)) } Some('?') => { cs.next(); Ast::Repeat(0, 1, Box::new(ast)) } Some('{') => { cs.next(); let min = if let Ok(n) = parse_number(cs) { n } else { 0 }; expect_char(cs, ',')?; let max = if let Ok(n) = parse_number(cs) { n } else { std::u32::MAX }; expect_char(cs, '}')?; Ast::Repeat(min, max, Box::new(ast)) } Some(_) | None => ast, }) } else { Err(Error::UnexpectedEOS) } } fn parse_paren(cs: &mut Peekable<impl Iterator<Item = char>>) -> Result<Ast, Error> { let ast = if cs.peek() == Some(&'?') { cs.next(); match cs.peek() { Some(':') => { cs.next(); parse_or(cs)? } Some('=') => { cs.next(); Ast::Lookahead(Box::new(parse_or(cs)?)) } Some('!') => { cs.next(); Ast::Not(Box::new(parse_or(cs)?)) } Some(c) => { return Err(Error::UnexpectedChar(*c)); } None => { return Err(Error::UnexpectedEOS); } } } else { Ast::Capture(Box::new(parse_or(cs)?)) }; if let Some(')') = cs.peek() { cs.next(); } else { return Err(Error::UnexpectedChar(cs.peek().unwrap().clone())); } Ok(ast) } fn parse_char_class(cs: &mut Peekable<impl Iterator<Item = char>>) -> Result<Ast, Error> { let mut asts = Vec::new(); let invert = matches!(cs.peek(), Some('^')); loop { match cs.peek() { Some(']') => { cs.next(); break; } _ => { let c = parse_char_(cs)?; if let Some('-') = cs.peek() { cs.next(); let c2 = parse_char_(cs)?; asts.push(Ast::Range(c, c2)); } else { asts.push(Ast::Char(c)); } } } } let ast = match asts.len() { 1 => asts.remove(0), _ => Ast::Or(asts), }; if invert { Ok(Ast::Concat(vec![Ast::Not(Box::new(ast)), Ast::Any])) } else { Ok(ast) } } fn parse_char(cs: &mut Peekable<impl Iterator<Item = char>>) -> Result<Ast, Error> { if matches!(cs.peek(), Some('\\')) { cs.next(); return match cs.next() { Some('r') => Ok(Ast::Char('\r')), Some('n') => Ok(Ast::Char('\n')), Some('t') => Ok(Ast::Char('\t')), Some('0') => Ok(Ast::Char('\0')), Some('d') => { Ok(Ast::Range('0', '9')) } Some(c) => { Err(Error::UnexpectedChar(c)) } None => { Err(Error::UnexpectedEOS) } }; } parse_char_(cs).map(|c| Ast::Char(c)) } fn parse_char_(cs: &mut Peekable<impl Iterator<Item = char>>) -> Result<char, Error> { if let Some(c) = cs.peek().cloned() { cs.next(); if c == '\\' { let c = match cs.peek() { Some('r') => '\r', Some('n') => '\n', Some('t') => '\t', Some('0') => '\0', Some(_) | None => { return Err(Error::UnexpectedEOS); } }; cs.next(); Ok(c) } else { Ok(c.clone()) } } else { Err(Error::UnexpectedEOS) } } fn parse_number(cs: &mut Peekable<impl Iterator<Item = char>>) -> Result<u32, Error> { let mut n = 0; let mut failed = true; while let Some(c) = cs.peek() { if let Some(d) = c.to_digit(10) { n = d + n * 10; failed = false; } else { if failed { return Err(Error::UnexpectedChar(*c)); } break; } cs.next(); } Ok(n) } fn expect_char(cs: &mut Peekable<impl Iterator<Item = char>>, char: char) -> Result<(), Error> { match cs.next() { Some(c) if c == char => { Ok(()) } Some(c) => { Err(Error::UnexpectedChar(c)) } None => { Err(Error::UnexpectedEOS) } } } #[test] fn test() { dbg!(parse("abc")); dbg!(parse("(abc)")); dbg!(parse("a|b|c")); dbg!(parse("(a|bc)")); dbg!(parse("(a|bc)*")); dbg!(parse("(a|b+c)")); dbg!(parse("(a|bc+)")); }
true
27db0b6e932065a53a03abd489ea93e0f6e5f1ff
Rust
danigm/rust-euler
/euler/src/p6.rs
UTF-8
977
4.25
4
[]
no_license
//! Problem 6 //! Sum square difference //! //! The sum of the squares of the first ten natural numbers is, //! 1^2 + 2^2 + ... + 10^2 = 385 //! //! The square of the sum of the first ten natural numbers is, //! (1 + 2 + ... + 10)^2 = 55^2 = 3025 //! //! Hence the difference between the sum of the squares of the first ten //! natural numbers and the square of the sum is 3025 − 385 = 2640. //! //! Find the difference between the sum of the squares of the first one hundred //! natural numbers and the square of the sum. fn sum_squares(v: &Vec<i32>) -> i32 { v.iter().fold(0, |sum, x| sum + x*x) } fn square_sum(v: &Vec<i32>) -> i32 { let n = v.iter().fold(0, |sum, x| sum + x); n * n } /// Solves the problem /// /// Examples /// /// ``` /// extern crate problems; /// /// fn main() { /// assert_eq!(25164150, problems::p6::solve()); /// } /// ``` pub fn solve() -> i32 { let v: Vec<i32> = (1..101).collect(); square_sum(&v) - sum_squares(&v) }
true
14909f5c2344c6688d2588a4c97cac5c6b92e24b
Rust
mbarbero/koukku
/src/error.rs
UTF-8
2,872
2.671875
3
[ "MIT" ]
permissive
use std::{fmt, result, io}; use std::error::Error as StdError; use std::str::Utf8Error; use std::sync::mpsc::{SendError, RecvError}; use std::sync::PoisonError; use hyper::error::Error as HyperError; use ini::ini::Error as IniError; use rustc_serialize::hex::FromHexError; use serde_json::error::Error as JsonError; use self::Error::{Hyper, App, Utf8, Io, Ini, Hex, Json, Mutex, Channel}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug, PartialEq)] pub enum Reason { InvalidConf, InvalidSignature, InvalidRepository, InvalidBranch, InvalidPath, MissingHeader, MissingFields, MissingProject, CommandFailed, } #[derive(Debug)] pub enum Error { App(Reason, String), Ini(String), Mutex(String), Channel(String), Hyper(HyperError), Utf8(Utf8Error), Io(io::Error), Hex(FromHexError), Json(JsonError), } impl Error { pub fn app<S: Into<String>>(reason: Reason, desc: S) -> Error { App(reason, desc.into()) } } impl StdError for Error { fn description(&self) -> &str { match *self { App(_, ref s) => &s, Ini(ref s) => &s, Mutex(ref s) => &s, Channel(ref s) => &s, Hyper(ref err) => err.description(), Utf8(ref err) => err.description(), Io(ref err) => err.description(), Hex(ref err) => err.description(), Json(ref err) => err.description(), } } fn cause(&self) -> Option<&StdError> { match *self { Hyper(ref err) => Some(err), Utf8(ref err) => Some(err), Io(ref err) => Some(err), Json(ref err) => Some(err), _ => None, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.description()) } } impl From<HyperError> for Error { fn from(err: HyperError) -> Error { Hyper(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Io(err) } } impl From<Utf8Error> for Error { fn from(err: Utf8Error) -> Error { Utf8(err) } } impl From<IniError> for Error { fn from(err: IniError) -> Error { Ini(format!("{}", err)) } } impl From<FromHexError> for Error { fn from(err: FromHexError) -> Error { Hex(err) } } impl From<JsonError> for Error { fn from(err: JsonError) -> Error { Json(err) } } impl<T> From<PoisonError<T>> for Error { fn from(err: PoisonError<T>) -> Error { Mutex(format!("{}", err)) } } impl<T> From<SendError<T>> for Error { fn from(err: SendError<T>) -> Error { Channel(format!("{}", err)) } } impl From<RecvError> for Error { fn from(err: RecvError) -> Error { Channel(err.description().into()) } }
true
56ad81b9d3dc287e15aa6d62eaaf9a359ac850a3
Rust
langestefan/atsamd
/pac/atsamd51j19a/src/sdhc0/hc2r.rs
UTF-8
24,260
2.828125
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#[doc = r" Value read from the register"] pub struct R { bits: u16, } #[doc = r" Value to write to the register"] pub struct W { bits: u16, } impl super::HC2R { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits }; let mut w = W { bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `UHSMS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum UHSMSR { #[doc = "SDR12"] SDR12, #[doc = "SDR25"] SDR25, #[doc = "SDR50"] SDR50, #[doc = "SDR104"] SDR104, #[doc = "DDR50"] DDR50, #[doc = r" Reserved"] _Reserved(u8), } impl UHSMSR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { UHSMSR::SDR12 => 0, UHSMSR::SDR25 => 1, UHSMSR::SDR50 => 2, UHSMSR::SDR104 => 3, UHSMSR::DDR50 => 4, UHSMSR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> UHSMSR { match value { 0 => UHSMSR::SDR12, 1 => UHSMSR::SDR25, 2 => UHSMSR::SDR50, 3 => UHSMSR::SDR104, 4 => UHSMSR::DDR50, i => UHSMSR::_Reserved(i), } } #[doc = "Checks if the value of the field is `SDR12`"] #[inline] pub fn is_sdr12(&self) -> bool { *self == UHSMSR::SDR12 } #[doc = "Checks if the value of the field is `SDR25`"] #[inline] pub fn is_sdr25(&self) -> bool { *self == UHSMSR::SDR25 } #[doc = "Checks if the value of the field is `SDR50`"] #[inline] pub fn is_sdr50(&self) -> bool { *self == UHSMSR::SDR50 } #[doc = "Checks if the value of the field is `SDR104`"] #[inline] pub fn is_sdr104(&self) -> bool { *self == UHSMSR::SDR104 } #[doc = "Checks if the value of the field is `DDR50`"] #[inline] pub fn is_ddr50(&self) -> bool { *self == UHSMSR::DDR50 } } #[doc = "Possible values of the field `VS18EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VS18ENR { #[doc = "3.3V Signaling"] S33V, #[doc = "1.8V Signaling"] S18V, } impl VS18ENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { VS18ENR::S33V => false, VS18ENR::S18V => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> VS18ENR { match value { false => VS18ENR::S33V, true => VS18ENR::S18V, } } #[doc = "Checks if the value of the field is `S33V`"] #[inline] pub fn is_s33v(&self) -> bool { *self == VS18ENR::S33V } #[doc = "Checks if the value of the field is `S18V`"] #[inline] pub fn is_s18v(&self) -> bool { *self == VS18ENR::S18V } } #[doc = "Possible values of the field `DRVSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DRVSELR { #[doc = "Driver Type B is Selected (Default)"] B, #[doc = "Driver Type A is Selected"] A, #[doc = "Driver Type C is Selected"] C, #[doc = "Driver Type D is Selected"] D, } impl DRVSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { DRVSELR::B => 0, DRVSELR::A => 1, DRVSELR::C => 2, DRVSELR::D => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> DRVSELR { match value { 0 => DRVSELR::B, 1 => DRVSELR::A, 2 => DRVSELR::C, 3 => DRVSELR::D, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `B`"] #[inline] pub fn is_b(&self) -> bool { *self == DRVSELR::B } #[doc = "Checks if the value of the field is `A`"] #[inline] pub fn is_a(&self) -> bool { *self == DRVSELR::A } #[doc = "Checks if the value of the field is `C`"] #[inline] pub fn is_c(&self) -> bool { *self == DRVSELR::C } #[doc = "Checks if the value of the field is `D`"] #[inline] pub fn is_d(&self) -> bool { *self == DRVSELR::D } } #[doc = "Possible values of the field `EXTUN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EXTUNR { #[doc = "Not Tuned or Tuning Completed"] NO, #[doc = "Execute Tuning"] REQUESTED, } impl EXTUNR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { EXTUNR::NO => false, EXTUNR::REQUESTED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> EXTUNR { match value { false => EXTUNR::NO, true => EXTUNR::REQUESTED, } } #[doc = "Checks if the value of the field is `NO`"] #[inline] pub fn is_no(&self) -> bool { *self == EXTUNR::NO } #[doc = "Checks if the value of the field is `REQUESTED`"] #[inline] pub fn is_requested(&self) -> bool { *self == EXTUNR::REQUESTED } } #[doc = "Possible values of the field `SLCKSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLCKSELR { #[doc = "Fixed clock is used to sample data"] FIXED, #[doc = "Tuned clock is used to sample data"] TUNED, } impl SLCKSELR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SLCKSELR::FIXED => false, SLCKSELR::TUNED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SLCKSELR { match value { false => SLCKSELR::FIXED, true => SLCKSELR::TUNED, } } #[doc = "Checks if the value of the field is `FIXED`"] #[inline] pub fn is_fixed(&self) -> bool { *self == SLCKSELR::FIXED } #[doc = "Checks if the value of the field is `TUNED`"] #[inline] pub fn is_tuned(&self) -> bool { *self == SLCKSELR::TUNED } } #[doc = "Possible values of the field `ASINTEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ASINTENR { #[doc = "Disabled"] DISABLED, #[doc = "Enabled"] ENABLED, } impl ASINTENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { ASINTENR::DISABLED => false, ASINTENR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ASINTENR { match value { false => ASINTENR::DISABLED, true => ASINTENR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ASINTENR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ASINTENR::ENABLED } } #[doc = "Possible values of the field `PVALEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PVALENR { #[doc = "SDCLK and Driver Strength are controlled by Host Controller"] HOST, #[doc = "Automatic Selection by Preset Value is Enabled"] AUTO, } impl PVALENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PVALENR::HOST => false, PVALENR::AUTO => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PVALENR { match value { false => PVALENR::HOST, true => PVALENR::AUTO, } } #[doc = "Checks if the value of the field is `HOST`"] #[inline] pub fn is_host(&self) -> bool { *self == PVALENR::HOST } #[doc = "Checks if the value of the field is `AUTO`"] #[inline] pub fn is_auto(&self) -> bool { *self == PVALENR::AUTO } } #[doc = "Values that can be written to the field `UHSMS`"] pub enum UHSMSW { #[doc = "SDR12"] SDR12, #[doc = "SDR25"] SDR25, #[doc = "SDR50"] SDR50, #[doc = "SDR104"] SDR104, #[doc = "DDR50"] DDR50, } impl UHSMSW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { UHSMSW::SDR12 => 0, UHSMSW::SDR25 => 1, UHSMSW::SDR50 => 2, UHSMSW::SDR104 => 3, UHSMSW::DDR50 => 4, } } } #[doc = r" Proxy"] pub struct _UHSMSW<'a> { w: &'a mut W, } impl<'a> _UHSMSW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: UHSMSW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "SDR12"] #[inline] pub fn sdr12(self) -> &'a mut W { self.variant(UHSMSW::SDR12) } #[doc = "SDR25"] #[inline] pub fn sdr25(self) -> &'a mut W { self.variant(UHSMSW::SDR25) } #[doc = "SDR50"] #[inline] pub fn sdr50(self) -> &'a mut W { self.variant(UHSMSW::SDR50) } #[doc = "SDR104"] #[inline] pub fn sdr104(self) -> &'a mut W { self.variant(UHSMSW::SDR104) } #[doc = "DDR50"] #[inline] pub fn ddr50(self) -> &'a mut W { self.variant(UHSMSW::DDR50) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `VS18EN`"] pub enum VS18ENW { #[doc = "3.3V Signaling"] S33V, #[doc = "1.8V Signaling"] S18V, } impl VS18ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { VS18ENW::S33V => false, VS18ENW::S18V => true, } } } #[doc = r" Proxy"] pub struct _VS18ENW<'a> { w: &'a mut W, } impl<'a> _VS18ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: VS18ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "3.3V Signaling"] #[inline] pub fn s33v(self) -> &'a mut W { self.variant(VS18ENW::S33V) } #[doc = "1.8V Signaling"] #[inline] pub fn s18v(self) -> &'a mut W { self.variant(VS18ENW::S18V) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `DRVSEL`"] pub enum DRVSELW { #[doc = "Driver Type B is Selected (Default)"] B, #[doc = "Driver Type A is Selected"] A, #[doc = "Driver Type C is Selected"] C, #[doc = "Driver Type D is Selected"] D, } impl DRVSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { DRVSELW::B => 0, DRVSELW::A => 1, DRVSELW::C => 2, DRVSELW::D => 3, } } } #[doc = r" Proxy"] pub struct _DRVSELW<'a> { w: &'a mut W, } impl<'a> _DRVSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: DRVSELW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Driver Type B is Selected (Default)"] #[inline] pub fn b(self) -> &'a mut W { self.variant(DRVSELW::B) } #[doc = "Driver Type A is Selected"] #[inline] pub fn a(self) -> &'a mut W { self.variant(DRVSELW::A) } #[doc = "Driver Type C is Selected"] #[inline] pub fn c(self) -> &'a mut W { self.variant(DRVSELW::C) } #[doc = "Driver Type D is Selected"] #[inline] pub fn d(self) -> &'a mut W { self.variant(DRVSELW::D) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `EXTUN`"] pub enum EXTUNW { #[doc = "Not Tuned or Tuning Completed"] NO, #[doc = "Execute Tuning"] REQUESTED, } impl EXTUNW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { EXTUNW::NO => false, EXTUNW::REQUESTED => true, } } } #[doc = r" Proxy"] pub struct _EXTUNW<'a> { w: &'a mut W, } impl<'a> _EXTUNW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: EXTUNW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Not Tuned or Tuning Completed"] #[inline] pub fn no(self) -> &'a mut W { self.variant(EXTUNW::NO) } #[doc = "Execute Tuning"] #[inline] pub fn requested(self) -> &'a mut W { self.variant(EXTUNW::REQUESTED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SLCKSEL`"] pub enum SLCKSELW { #[doc = "Fixed clock is used to sample data"] FIXED, #[doc = "Tuned clock is used to sample data"] TUNED, } impl SLCKSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SLCKSELW::FIXED => false, SLCKSELW::TUNED => true, } } } #[doc = r" Proxy"] pub struct _SLCKSELW<'a> { w: &'a mut W, } impl<'a> _SLCKSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SLCKSELW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Fixed clock is used to sample data"] #[inline] pub fn fixed(self) -> &'a mut W { self.variant(SLCKSELW::FIXED) } #[doc = "Tuned clock is used to sample data"] #[inline] pub fn tuned(self) -> &'a mut W { self.variant(SLCKSELW::TUNED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ASINTEN`"] pub enum ASINTENW { #[doc = "Disabled"] DISABLED, #[doc = "Enabled"] ENABLED, } impl ASINTENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ASINTENW::DISABLED => false, ASINTENW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _ASINTENW<'a> { w: &'a mut W, } impl<'a> _ASINTENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ASINTENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disabled"] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(ASINTENW::DISABLED) } #[doc = "Enabled"] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(ASINTENW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PVALEN`"] pub enum PVALENW { #[doc = "SDCLK and Driver Strength are controlled by Host Controller"] HOST, #[doc = "Automatic Selection by Preset Value is Enabled"] AUTO, } impl PVALENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PVALENW::HOST => false, PVALENW::AUTO => true, } } } #[doc = r" Proxy"] pub struct _PVALENW<'a> { w: &'a mut W, } impl<'a> _PVALENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PVALENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "SDCLK and Driver Strength are controlled by Host Controller"] #[inline] pub fn host(self) -> &'a mut W { self.variant(PVALENW::HOST) } #[doc = "Automatic Selection by Preset Value is Enabled"] #[inline] pub fn auto(self) -> &'a mut W { self.variant(PVALENW::AUTO) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 15; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u16 { self.bits } #[doc = "Bits 0:2 - UHS Mode Select"] #[inline] pub fn uhsms(&self) -> UHSMSR { UHSMSR::_from({ const MASK: u8 = 7; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u16) as u8 }) } #[doc = "Bit 3 - 1.8V Signaling Enable"] #[inline] pub fn vs18en(&self) -> VS18ENR { VS18ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u16) != 0 }) } #[doc = "Bits 4:5 - Driver Strength Select"] #[inline] pub fn drvsel(&self) -> DRVSELR { DRVSELR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u16) as u8 }) } #[doc = "Bit 6 - Execute Tuning"] #[inline] pub fn extun(&self) -> EXTUNR { EXTUNR::_from({ const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u16) != 0 }) } #[doc = "Bit 7 - Sampling Clock Select"] #[inline] pub fn slcksel(&self) -> SLCKSELR { SLCKSELR::_from({ const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u16) != 0 }) } #[doc = "Bit 14 - Asynchronous Interrupt Enable"] #[inline] pub fn asinten(&self) -> ASINTENR { ASINTENR::_from({ const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u16) != 0 }) } #[doc = "Bit 15 - Preset Value Enable"] #[inline] pub fn pvalen(&self) -> PVALENR { PVALENR::_from({ const MASK: bool = true; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u16) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:2 - UHS Mode Select"] #[inline] pub fn uhsms(&mut self) -> _UHSMSW { _UHSMSW { w: self } } #[doc = "Bit 3 - 1.8V Signaling Enable"] #[inline] pub fn vs18en(&mut self) -> _VS18ENW { _VS18ENW { w: self } } #[doc = "Bits 4:5 - Driver Strength Select"] #[inline] pub fn drvsel(&mut self) -> _DRVSELW { _DRVSELW { w: self } } #[doc = "Bit 6 - Execute Tuning"] #[inline] pub fn extun(&mut self) -> _EXTUNW { _EXTUNW { w: self } } #[doc = "Bit 7 - Sampling Clock Select"] #[inline] pub fn slcksel(&mut self) -> _SLCKSELW { _SLCKSELW { w: self } } #[doc = "Bit 14 - Asynchronous Interrupt Enable"] #[inline] pub fn asinten(&mut self) -> _ASINTENW { _ASINTENW { w: self } } #[doc = "Bit 15 - Preset Value Enable"] #[inline] pub fn pvalen(&mut self) -> _PVALENW { _PVALENW { w: self } } }
true
eb067e5344071d6aa08de796946db91c1d6decca
Rust
vain0x/languages
/lambda-calc-rs/lc-v1/src/syntax/syntax_token.rs
UTF-8
657
3
3
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use crate::token::token_kind::TokenKind; use std::fmt::{self, Debug, Formatter}; #[derive(Copy, Clone)] pub(crate) struct SyntaxToken<'a> { #[allow(unused)] pub(crate) index: usize, pub(crate) kind: TokenKind, pub(crate) text: &'a str, } impl Debug for SyntaxToken<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self.kind { TokenKind::NewLine | TokenKind::Blank | TokenKind::Comment | TokenKind::BadToken | TokenKind::Number | TokenKind::Ident => Debug::fmt(&self.text, f), _ => Debug::fmt(&self.kind, f), } } }
true
a6c4bbcb34cdf3391fcd3cc809792d675f1b09f3
Rust
zubivan/games50-rust
/pong/src/states/gamestate.rs
UTF-8
6,046
2.546875
3
[ "MIT" ]
permissive
use ggez::graphics::Rect; use ggez::input::keyboard::KeyCode; use ggez::nalgebra::Point2; use ggez::Context; use std::time::Duration; use rand::{thread_rng, Rng, RngCore}; use super::gameoverstate::{GameOverState, Winner}; use super::shapes::{Ball, GameObject, Paddle}; use super::utils; use crate::constants::{FONT_SIZE, VIRTUAL_WORLD_HEIGHT, VIRTUAL_WORLD_WIDTH}; use crate::traits::{State, StateWithTransition, Transition}; const BALL_RADIUS: f32 = 4.; const PADDLE_HEIGHT: f32 = 30.; const PADDLE_WIDTH: f32 = 6.; pub struct GameState<'a> { ball: Ball, player1: Paddle, player2: Paddle, player_one_score: i32, player_two_score: i32, rng: Box<dyn RngCore + 'a>, next_round: bool, } impl StateWithTransition for GameState<'_> {} impl<'a> GameState<'a> { pub fn new() -> Self { let mut rng = thread_rng(); let player_one_serves: bool = rng.gen(); let ball_d_x = rng.gen_range(140., 200.); let ball_d_x: f32 = ball_d_x * if player_one_serves { 1. } else { -1. }; let ball_d_y: f32 = rng.gen_range(-50., 50.); GameState { ball: Ball::new( VIRTUAL_WORLD_WIDTH / 2. - BALL_RADIUS / 2., VIRTUAL_WORLD_HEIGHT / 2. - BALL_RADIUS / 2., ball_d_x, ball_d_y, BALL_RADIUS, ), player1: Paddle::new( 10., VIRTUAL_WORLD_HEIGHT / 2. - PADDLE_HEIGHT / 2., PADDLE_WIDTH, PADDLE_HEIGHT, KeyCode::W, KeyCode::S, ), player2: Paddle::new( VIRTUAL_WORLD_WIDTH - PADDLE_WIDTH - 10., VIRTUAL_WORLD_HEIGHT / 2. - PADDLE_HEIGHT / 2., PADDLE_WIDTH, PADDLE_HEIGHT, KeyCode::Up, KeyCode::Down, ), player_one_score: 0, player_two_score: 0, next_round: false, rng: Box::new(rng), } } } impl State for GameState<'_> { fn update(&mut self, ctx: &Context, dt: Duration) { self.ball.update(ctx, dt); let world_rect = Rect::new(0., 0., VIRTUAL_WORLD_WIDTH, VIRTUAL_WORLD_HEIGHT); if let Some(side) = collides_with_boundaries(&mut self.ball, world_rect) { match side { Side::Bottom => { self.ball.d_y = -self.ball.d_y; self.ball.y = VIRTUAL_WORLD_HEIGHT - self.ball.radius * 2.; } Side::Top => { self.ball.d_y = -self.ball.d_y; self.ball.y = self.ball.radius * 2.; } Side::Left => { self.player_two_score += 1; self.next_round = true; } Side::Right => { self.player_one_score += 1; self.next_round = true; } } }; if collides_with_paddle(&self.ball, &self.player1) { self.ball.d_x = -self.ball.d_x * 1.03; self.ball.x = self.player1.x + self.player1.width + self.ball.radius; self.ball.d_y = if self.ball.d_y > 0. { self.rng.gen_range(10., 150.) } else { -self.rng.gen_range(10., 150.) }; } if collides_with_paddle(&self.ball, &self.player2) { self.ball.d_x = -self.ball.d_x * 1.03; self.ball.x = self.player2.x - self.player1.width - self.ball.radius; self.ball.d_y = if self.ball.d_y > 0. { self.rng.gen_range(10., 150.) } else { -self.rng.gen_range(10., 150.) }; } self.player1.update(ctx, dt); self.player2.update(ctx, dt); } fn draw(&self, ctx: &mut Context) { self.ball.draw(ctx); self.player1.draw(ctx); self.player2.draw(ctx); draw_score(ctx, self.player_one_score, self.player_two_score); } } impl<'a> Transition for GameState<'a> { fn transition(&self) -> Option<Box<dyn StateWithTransition>> { let player_one_won = self.player_one_score == 10; let player_two_won = self.player_two_score == 10; if player_one_won || player_two_won { Some(Box::new(GameOverState::new(if player_one_won { Winner::PlayerOne } else { Winner::PlayerTwo }))) } else if self.next_round { let mut next_state = GameState::new(); next_state.player_one_score = self.player_one_score; next_state.player_two_score = self.player_two_score; Some(Box::new(next_state)) } else { None } } } enum Side { Left, Top, Right, Bottom, } fn draw_score(ctx: &mut Context, player_one_score: i32, player_two_score: i32) { utils::draw_text_at_location( ctx, format!("{}", player_one_score), Point2::new(VIRTUAL_WORLD_WIDTH / 3., VIRTUAL_WORLD_HEIGHT / 3.), FONT_SIZE, ); utils::draw_text_at_location( ctx, format!("{}", player_two_score), Point2::new(VIRTUAL_WORLD_WIDTH * 2. / 3., VIRTUAL_WORLD_HEIGHT / 3.), FONT_SIZE, ); } fn collides_with_boundaries(ball: &mut Ball, boundaries: Rect) -> Option<Side> { if ball.y < boundaries.y + ball.radius { Some(Side::Top) } else if ball.y > boundaries.h - ball.radius { Some(Side::Bottom) } else if ball.x < boundaries.x + ball.radius { Some(Side::Left) } else if ball.x > boundaries.w + ball.radius { Some(Side::Right) } else { None } } fn collides_with_paddle(ball: &Ball, paddle: &Paddle) -> bool { let ball_rect = Rect::new(ball.x, ball.y, ball.radius * 2., ball.radius * 2.); let paddle_rect = Rect::new(paddle.x, paddle.y, paddle.width, paddle.heigh); ball_rect.overlaps(&paddle_rect) }
true
ab865bb1b599b1328d115c901f81b99c16c58e0d
Rust
dongcarl/script_descriptor
/src/descriptor.rs
UTF-8
21,314
2.859375
3
[]
no_license
// Script Descriptor Language // Written in 2018 by // Andrew Poelstra <apoelstra@wpsoftware.net> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Script Descriptors //! //! Tools for representing Bitcoin scriptpubkeys as abstract spending policies, known //! as "script descriptors". //! //! The format represents EC public keys abstractly to allow wallets to replace these with //! BIP32 paths, pay-to-contract instructions, etc. //! use std::collections::HashMap; use std::hash::Hash; use std::fmt; use std::str::{self, FromStr}; use secp256k1; use bitcoin::util::hash::Sha256dHash; // TODO needs to be sha256, not sha256d use Error; /// Abstraction over "public key" which can be used when converting to/from a scriptpubkey pub trait PublicKey: Hash + Eq + Sized { /// Auxiallary data needed to convert this public key into a secp public key type Aux; fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result; /// Parse an ASCII string as this type of public key fn from_str(s: &str) -> Result<Self, Error>; /// Convert self to public key during serialization to scriptpubkey fn instantiate(&self, aux: Option<&Self::Aux>) -> Result<secp256k1::PublicKey, Error>; } impl PublicKey for secp256k1::PublicKey { type Aux = (); fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ser = self.serialize(); for x in &ser[..] { write!(f, "{:02x}", *x)?; } Ok(()) } fn from_str(s: &str) -> Result<secp256k1::PublicKey, Error> { let bytes = s.as_bytes(); let mut ret = [0; 33]; if bytes.len() != 66 { return Err(Error::Unexpected(s.to_string())) } // TODO uncompressed keys for i in 0..ret.len() { let hi = match bytes[2*i] { b @ b'0'...b'9' => (b - b'0') as u8, b @ b'a'...b'f' => (b - b'a' + 10) as u8, b @ b'A'...b'F' => (b - b'A' + 10) as u8, b => return Err(Error::Unexpected(format!("{}", b as char))) }; let lo = match bytes[2*i + 1] { b @ b'0'...b'9' => (b - b'0') as u8, b @ b'a'...b'f' => (b - b'a' + 10) as u8, b @ b'A'...b'F' => (b - b'A' + 10) as u8, b => return Err(Error::Unexpected(format!("{}", b as char))) }; ret[ret.len() - 1 - i] = hi * 0x10 + lo; } let secp = secp256k1::Secp256k1::without_caps(); secp256k1::PublicKey::from_slice(&secp, &ret[..]).map_err(Error::BadPubkey) } fn instantiate(&self, _: Option<&()>) -> Result<secp256k1::PublicKey, Error> { Ok(self.clone()) } } /// Script descriptor pub enum Descriptor<P: PublicKey> { /// A public key which must sign to satisfy the descriptor Key(P), /// A public key which must sign to satisfy the descriptor (pay-to-pubkey-hash form) KeyHash(P), /// A set of keys, signatures must be provided for `k` of them Multi(usize, Vec<P>), /// A SHA256 whose preimage must be provided to satisfy the descriptor Hash(Sha256dHash), /// A locktime restriction Time(u32), /// A set of descriptors, satisfactions must be provided for `k` of them Threshold(usize, Vec<Descriptor<P>>), /// A list of descriptors, all of which must be satisfied And(Box<Descriptor<P>>, Box<Descriptor<P>>), /// A pair of descriptors, one of which must be satisfied Or(Box<Descriptor<P>>, Box<Descriptor<P>>), /// Same as `Or`, but the second option is assumed to never be taken for costing purposes AsymmetricOr(Box<Descriptor<P>>, Box<Descriptor<P>>), /// Pay-to-Witness-PubKey-Hash Wpkh(P), /// Pay-to-ScriptHash Sh(Box<Descriptor<P>>), /// Pay-to-Witness-ScriptHash Wsh(Box<Descriptor<P>>), } impl<P: PublicKey> Descriptor<P> { /// Convert a descriptor using abstract keys to one using specific keys pub fn instantiate(&self, keymap: &HashMap<P, P::Aux>) -> Result<Descriptor<secp256k1::PublicKey>, Error> { match *self { Descriptor::Key(ref pk) => { let secp_pk = pk.instantiate(keymap.get(pk))?; Ok(Descriptor::Key(secp_pk)) } Descriptor::KeyHash(ref pk) => { let secp_pk = pk.instantiate(keymap.get(pk))?; Ok(Descriptor::KeyHash(secp_pk)) } Descriptor::Multi(k, ref keys) => { let mut new_keys = Vec::with_capacity(keys.len()); for key in keys { let secp_pk = key.instantiate(keymap.get(key))?; new_keys.push(secp_pk); } Ok(Descriptor::Multi(k, new_keys)) } Descriptor::Threshold(k, ref subs) => { let mut new_subs = Vec::with_capacity(subs.len()); for sub in subs { new_subs.push(sub.instantiate(keymap)?); } Ok(Descriptor::Threshold(k, new_subs)) } Descriptor::Hash(hash) => Ok(Descriptor::Hash(hash)), Descriptor::And(ref left, ref right) => { Ok(Descriptor::And( Box::new(left.instantiate(keymap)?), Box::new(right.instantiate(keymap)?) )) } Descriptor::Or(ref left, ref right) => { Ok(Descriptor::Or( Box::new(left.instantiate(keymap)?), Box::new(right.instantiate(keymap)?) )) } Descriptor::AsymmetricOr(ref left, ref right) => { Ok(Descriptor::AsymmetricOr( Box::new(left.instantiate(keymap)?), Box::new(right.instantiate(keymap)?) )) } Descriptor::Time(n) => Ok(Descriptor::Time(n)), Descriptor::Wpkh(ref pk) => { let secp_pk = pk.instantiate(keymap.get(pk))?; Ok(Descriptor::Wpkh(secp_pk)) } Descriptor::Sh(ref desc) => { Ok(Descriptor::Sh(Box::new(desc.instantiate(keymap)?))) } Descriptor::Wsh(ref desc) => { Ok(Descriptor::Wsh(Box::new(desc.instantiate(keymap)?))) } } } fn from_tree<'a>(top: &FunctionTree<'a>) -> Result<Descriptor<P>, Error> { match (top.name, top.args.len() as u32) { ("pk", 1) => { let pk = &top.args[0]; if pk.args.is_empty() { Ok(Descriptor::Key(P::from_str(pk.name)?)) } else { Err(errorize(pk.args[0].name)) } } ("pkh", 1) => { let pk = &top.args[0]; if pk.args.is_empty() { Ok(Descriptor::KeyHash(P::from_str(pk.name)?)) } else { Err(errorize(pk.args[0].name)) } } ("multi", nkeys) => { for arg in &top.args { if !arg.args.is_empty() { return Err(errorize(arg.args[0].name)); } } let thresh = parse_num(top.args[0].name)?; if thresh >= nkeys { return Err(errorize(top.args[0].name)); } let mut keys = Vec::with_capacity(top.args.len() - 1); for arg in &top.args[1..] { keys.push(P::from_str(arg.name)?); } Ok(Descriptor::Multi(thresh as usize, keys)) } ("hash", 1) => { let hash_t = &top.args[0]; if hash_t.args.is_empty() { if let Ok(hash) = Sha256dHash::from_hex(hash_t.args[0].name) { Ok(Descriptor::Hash(hash)) } else { Err(errorize(hash_t.args[0].name)) } } else { Err(errorize(hash_t.args[0].name)) } } ("time", 1) => { let time_t = &top.args[0]; if time_t.args.is_empty() { Ok(Descriptor::Time(parse_num(time_t.args[0].name)?)) } else { Err(errorize(time_t.args[0].name)) } } ("thresh", nsubs) => { if !top.args[0].args.is_empty() { return Err(errorize(top.args[0].args[0].name)); } let thresh = parse_num(top.args[0].name)?; if thresh >= nsubs { return Err(errorize(top.args[0].name)); } let mut subs = Vec::with_capacity(top.args.len() - 1); for arg in &top.args[1..] { subs.push(Descriptor::from_tree(arg)?); } Ok(Descriptor::Threshold(thresh as usize, subs)) } ("and", 2) => { Ok(Descriptor::And( Box::new(Descriptor::from_tree(&top.args[0])?), Box::new(Descriptor::from_tree(&top.args[1])?), )) } ("or", 2) => { Ok(Descriptor::Or( Box::new(Descriptor::from_tree(&top.args[0])?), Box::new(Descriptor::from_tree(&top.args[1])?), )) } ("aor", 2) => { Ok(Descriptor::AsymmetricOr( Box::new(Descriptor::from_tree(&top.args[0])?), Box::new(Descriptor::from_tree(&top.args[1])?), )) } ("wpkh", 1) => { let pk = &top.args[0]; if pk.args.is_empty() { Ok(Descriptor::Wpkh(P::from_str(pk.name)?)) } else { Err(errorize(pk.args[0].name)) } } ("sh", 1) => { let sub = Descriptor::from_tree(&top.args[0])?; Ok(Descriptor::Sh(Box::new(sub))) } ("wsh", 1) => { let sub = Descriptor::from_tree(&top.args[0])?; Ok(Descriptor::Wsh(Box::new(sub))) } _ => Err(errorize(top.name)) } } } fn errorize(s: &str) -> Error { Error::Unexpected(s.to_owned()) } fn parse_num(s: &str) -> Result<u32, Error> { u32::from_str(s).map_err(|_| errorize(s)) } impl<P: PublicKey> FromStr for Descriptor<P> { type Err = Error; fn from_str(s: &str) -> Result<Descriptor<P>, Error> { for ch in s.as_bytes() { if *ch < 20 || *ch > 127 { return Err(Error::Unprintable(*ch)); } } let (top, rem) = FunctionTree::from_slice(s)?; if !rem.is_empty() { return Err(errorize(rem)); } Descriptor::from_tree(&top) } } impl <P: PublicKey> fmt::Display for Descriptor<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Descriptor::Key(ref p) => { f.write_str("pk(")?; p.fmt(f)?; } Descriptor::KeyHash(ref p) => { f.write_str("pkh(")?; p.fmt(f)?; } Descriptor::Multi(k, ref keys) => { write!(f, "multi({}", k)?; for key in keys { key.fmt(f)?; f.write_str(",")?; } } Descriptor::Hash(hash) => { write!(f, "hash({}", hash)?; } Descriptor::Time(n) => { write!(f, "time({}", n)?; } Descriptor::Threshold(k, ref descs) => { write!(f, "multi({}", k)?; for desc in descs { write!(f, "{},", desc)?; } } Descriptor::And(ref left, ref right) => { write!(f, "and({}, {}", left, right)?; } Descriptor::Or(ref left, ref right) => { write!(f, "or({}, {}", left, right)?; } Descriptor::AsymmetricOr(ref left, ref right) => { write!(f, "aor({}, {}", left, right)?; } Descriptor::Wpkh(ref p) => { f.write_str("wpkh(")?; p.fmt(f)?; } Descriptor::Sh(ref desc) => { write!(f, "sh({}", desc)?; } Descriptor::Wsh(ref desc) => { write!(f, "wsh({}", desc)?; } } f.write_str(")") } } struct FunctionTree<'a> { name: &'a str, args: Vec<FunctionTree<'a>>, } impl<'a> FunctionTree<'a> { fn from_slice(mut sl: &'a str) -> Result<(FunctionTree<'a>, &'a str), Error> { enum Found { Nothing, Lparen(usize), Comma(usize), Rparen(usize) } let mut found = Found::Nothing; for (n, ch) in sl.chars().enumerate() { match ch { '(' => { found = Found::Lparen(n); break; } ',' => { found = Found::Comma(n); break; } ')' => { found = Found::Rparen(n); break; } _ => {} } } match found { // Unexpected EOF Found::Nothing => Err(Error::ExpectedChar(')')), // Terminal Found::Comma(n) | Found::Rparen(n) => { Ok(( FunctionTree { name: &sl[..n], args: vec![], }, &sl[n..], )) } // Function call Found::Lparen(n) => { let mut ret = FunctionTree { name: &sl[..n], args: vec![], }; sl = &sl[n + 1..]; loop { let (arg, new_sl) = FunctionTree::from_slice(sl)?; ret.args.push(arg); if new_sl.is_empty() { return Err(Error::ExpectedChar(')')); } sl = &new_sl[1..]; match new_sl.as_bytes()[0] { b',' => {}, b')' => break, _ => return Err(Error::ExpectedChar(',')) } } Ok((ret, sl)) } } } } #[cfg(test)] mod tests { use secp256k1; use std::collections::HashMap; use std::str::FromStr; use bitcoin::blockdata::opcodes; use bitcoin::blockdata::script::{self, Script}; use Descriptor; use ParseTree; fn pubkeys_and_a_sig(n: usize) -> (Vec<secp256k1::PublicKey>, secp256k1::Signature) { let mut ret = Vec::with_capacity(n); let secp = secp256k1::Secp256k1::new(); let mut sk = [0; 32]; for i in 1..n+1 { sk[0] = i as u8; sk[1] = (i >> 8) as u8; sk[2] = (i >> 16) as u8; let pk = secp256k1::PublicKey::from_secret_key( &secp, &secp256k1::SecretKey::from_slice(&secp, &sk[..]).expect("secret key"), ); ret.push(pk); } let sig = secp.sign( &secp256k1::Message::from_slice(&sk[..]).expect("secret key"), &secp256k1::SecretKey::from_slice(&secp, &sk[..]).expect("secret key"), ); (ret, sig) } #[test] fn compile() { let (keys, sig) = pubkeys_and_a_sig(10); let desc: Descriptor<secp256k1::PublicKey> = Descriptor::Time(100); let pt = ParseTree::compile(&desc); assert_eq!(pt.serialize(), Script::from(vec![0x01, 0x64, 0xb2])); let desc = Descriptor::Key(keys[0].clone()); let pt = ParseTree::compile(&desc); assert_eq!( pt.serialize(), script::Builder::new() .push_slice(&keys[0].serialize()[..]) .push_opcode(opcodes::All::OP_CHECKSIG) .into_script() ); // CSV reordering trick let desc = Descriptor::And( // nb the compiler will reorder this because it can avoid the DROP if it ends with the CSV Box::new(Descriptor::Time(10000)), Box::new(Descriptor::Multi(2, keys[5..8].to_owned())), ); let pt = ParseTree::compile(&desc); assert_eq!( pt.serialize(), script::Builder::new() .push_opcode(opcodes::All::OP_PUSHNUM_2) .push_slice(&keys[5].serialize()[..]) .push_slice(&keys[6].serialize()[..]) .push_slice(&keys[7].serialize()[..]) .push_opcode(opcodes::All::OP_PUSHNUM_3) .push_opcode(opcodes::All::OP_CHECKMULTISIGVERIFY) .push_int(10000) .push_opcode(opcodes::OP_CSV) .into_script() ); // Liquid policy let desc = Descriptor::AsymmetricOr( Box::new(Descriptor::Multi(3, keys[0..5].to_owned())), Box::new(Descriptor::And( Box::new(Descriptor::Time(10000)), Box::new(Descriptor::Multi(2, keys[5..8].to_owned())), )), ); let pt = ParseTree::compile(&desc); assert_eq!( pt.serialize(), script::Builder::new() .push_opcode(opcodes::All::OP_PUSHNUM_3) .push_slice(&keys[0].serialize()[..]) .push_slice(&keys[1].serialize()[..]) .push_slice(&keys[2].serialize()[..]) .push_slice(&keys[3].serialize()[..]) .push_slice(&keys[4].serialize()[..]) .push_opcode(opcodes::All::OP_PUSHNUM_5) .push_opcode(opcodes::All::OP_CHECKMULTISIG) .push_opcode(opcodes::All::OP_IFDUP) .push_opcode(opcodes::All::OP_NOTIF) .push_opcode(opcodes::All::OP_PUSHNUM_2) .push_slice(&keys[5].serialize()[..]) .push_slice(&keys[6].serialize()[..]) .push_slice(&keys[7].serialize()[..]) .push_opcode(opcodes::All::OP_PUSHNUM_3) .push_opcode(opcodes::All::OP_CHECKMULTISIGVERIFY) .push_int(10000) .push_opcode(opcodes::OP_CSV) .push_opcode(opcodes::All::OP_ENDIF) .into_script() ); assert_eq!( &pt.required_keys()[..], &keys[0..8] ); let mut map = HashMap::new(); assert!(pt.satisfy(&map, &HashMap::new(), &HashMap::new(), 0).is_err()); map.insert(keys[0].clone(), sig.clone()); map.insert(keys[1].clone(), sig.clone()); assert!(pt.satisfy(&map, &HashMap::new(), &HashMap::new(), 0).is_err()); map.insert(keys[2].clone(), sig.clone()); assert_eq!( pt.satisfy(&map, &HashMap::new(), &HashMap::new(), 0).unwrap(), vec![ sig.serialize_der(&secp256k1::Secp256k1::without_caps()), sig.serialize_der(&secp256k1::Secp256k1::without_caps()), sig.serialize_der(&secp256k1::Secp256k1::without_caps()), vec![], ] ); map.insert(keys[5].clone(), sig.clone()); map.insert(keys[6].clone(), sig.clone()); assert_eq!( pt.satisfy(&map, &HashMap::new(), &HashMap::new(), 0).unwrap(), vec![ sig.serialize_der(&secp256k1::Secp256k1::without_caps()), sig.serialize_der(&secp256k1::Secp256k1::without_caps()), sig.serialize_der(&secp256k1::Secp256k1::without_caps()), vec![], ] ); assert_eq!( pt.satisfy(&map, &HashMap::new(), &HashMap::new(), 10000).unwrap(), vec![ vec![], vec![], vec![], vec![], sig.serialize_der(&secp256k1::Secp256k1::without_caps()), sig.serialize_der(&secp256k1::Secp256k1::without_caps()), vec![], ] ); } #[test] fn parse_descriptor() { assert!(Descriptor::<secp256k1::PublicKey>::from_str("(").is_err()); assert!(Descriptor::<secp256k1::PublicKey>::from_str("(x()").is_err()); assert!(Descriptor::<secp256k1::PublicKey>::from_str("(\u{7f}()3").is_err()); assert!(Descriptor::<secp256k1::PublicKey>::from_str("pk()").is_err()); assert!(Descriptor::<secp256k1::PublicKey>::from_str("pk(020000000000000000000000000000000000000000000000000000000000000002)").is_ok()); } }
true
31eae8952b6e362e3ad826025901b82e7ff94ba2
Rust
timokae/data-node
/src/heartbeat_service.rs
UTF-8
2,666
2.859375
3
[]
no_license
use crate::storage; use crate::{logger, models}; use models::{DataNode, Heartbeat, HeartbeatResponse}; use std::error::Error; use std::sync::Arc; use std::thread; use std::time::Duration; use storage::Storage; /// The Heartbeat Service starts a thread which send periodic messages over a http connection to the name server /// /// * fingerprint: a unique identifier for this node /// * name_node_addr: the address on which the name server can be reached, e.g. 'http://localhost:3000' /// * port: the port on which the data node is listening for incoming http requests /// * storage: the storage service /// /// Example outgoing json object /// ``` /// { /// "node": { /// "address": "192.168.0.100:8080", /// "fingerprint": "client-1" /// }, /// "hashes": [ /// "hash-1", /// "hash-2" /// ] /// } /// The hashes array contain all hashes the data node has saved, not the foreign hashes of other nodes. /// ``` pub async fn start( fingerprint: String, name_node_addr: String, port: u16, storage: Arc<Storage>, ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { logger::log("Heartbeat", "Service started."); tokio::spawn(async move { loop { match send_heartbeat(&fingerprint, &name_node_addr, port, storage.clone()).await { Ok(res) => match res.json::<HeartbeatResponse>().await { Ok(body) => handle_heartbeat_response(body, storage.clone()), Err(_) => logger::log("Heartbeat", "Failed to decode heartbeat response"), }, _ => {} } thread::sleep(Duration::from_secs(20 * 1)); } }) .await .unwrap(); Ok(()) } async fn send_heartbeat( fingerprint: &str, name_node_addr: &str, port: u16, storage: Arc<Storage>, ) -> Result<reqwest::Response, Box<dyn Error + Send + Sync>> { let ip = local_ip::get().unwrap(); let hashes = storage.hashes(); let node = DataNode { address: format!("{}:{}", ip.to_string(), port), fingerprint: String::from(fingerprint.clone()), }; let heartbeat = Heartbeat { node: node, hashes: hashes, }; let uri = format!("{}/heartbeat", name_node_addr); logger::log("Heartbeat", "Sending heartbeat"); let res = reqwest::Client::new() .post(&uri) .json(&heartbeat) .send() .await?; logger::log("Heartbeat", &res.status().to_string()); Ok(res) } fn handle_heartbeat_response(response: HeartbeatResponse, storage: Arc<Storage>) { storage.insert_foreign(response.foreign_hashes); }
true
36559c5356ce5cd78f9ffb3db5fee89016024955
Rust
m4b/scroll
/src/ctx.rs
UTF-8
29,175
3.5
4
[ "MIT" ]
permissive
//! Generic context-aware conversion traits, for automatic _downstream_ extension of `Pread`, et. al //! //! The context traits are arguably the center piece of the scroll crate. In simple terms they //! define how to actually read and write, respectively, a data type from a container, being able to //! take context into account. //! //! ### Reading //! //! Types implementing [TryFromCtx](trait.TryFromCtx.html) and it's infallible cousin [FromCtx](trait.FromCtx.html) //! allow a user of [Pread::pread](../trait.Pread.html#method.pread) or respectively //! [Cread::cread](../trait.Cread.html#method.cread) and //! [IOread::ioread](../trait.IOread.html#method.ioread) to read that data type from a data source one //! of the `*read` traits has been implemented for. //! //! Implementations of `TryFromCtx` specify a source (called `This`) and an `Error` type for failed //! reads. The source defines the kind of container the type can be read from, and defaults to //! `[u8]` for any type that implements `AsRef<[u8]>`. //! //! `FromCtx` is slightly more restricted; it requires the implementer to use `[u8]` as source and //! never fail, and thus does not have an `Error` type. //! //! Types chosen here are of relevance to `Pread` implementations; of course only a container which //! can produce a source of the type `This` can be used to read a `TryFromCtx` requiring it and the //! `Error` type returned in `Err` of `Pread::pread`'s Result. //! //! ### Writing //! //! [TryIntoCtx](trait.TryIntoCtx.html) and the infallible [IntoCtx](trait.IntoCtx.html) work //! similarly to the above traits, allowing [Pwrite::pwrite](../trait.Pwrite.html#method.pwrite) or //! respectively [Cwrite::cwrite](../trait.Cwrite.html#method.cwrite) and //! [IOwrite::iowrite](../trait.IOwrite.html#method.iowrite) to write data into a byte sink for //! which one of the `*write` traits has been implemented for. //! //! `IntoCtx` is similarly restricted as `FromCtx` is to `TryFromCtx`. And equally the types chosen //! affect usable `Pwrite` implementation. //! //! ### Context //! //! Each of the traits passes along a `Ctx` to the marshalling logic. This context type contains //! any additional information that may be required to successfully parse or write the data: //! Examples would be endianness to use, field lengths of a serialized struct, or delimiters to use //! when reading/writing `&str`. The context type can be any type but must derive //! [Copy](https://doc.rust-lang.org/std/marker/trait.Copy.html). In addition if you want to use //! the `*read`-methods instead of the `*read_with` ones you must also implement //! [default::Default](https://doc.rust-lang.org/std/default/trait.Default.html). //! //! # Example //! //! Let's expand on the [previous example](../index.html#complex-use-cases). //! //! ```rust //! use scroll::{self, ctx, Pread, Endian}; //! use scroll::ctx::StrCtx; //! //! #[derive(Copy, Clone, PartialEq, Eq)] //! enum FieldSize { //! U32, //! U64 //! } //! //! // Our custom context type. As said above it has to derive Copy. //! #[derive(Copy, Clone)] //! struct Context { //! fieldsize: FieldSize, //! endianess: Endian, //! } //! //! // Our custom data type //! struct Data<'b> { //! // These u64 are encoded either as 32-bit or 64-bit wide ints. Which one it is is defined in //! // the Context. //! // Also, let's imagine they have a strict relationship: A < B < C otherwise the struct is //! // invalid. //! field_a: u64, //! field_b: u64, //! field_c: u64, //! //! // Both of these are marshalled with a prefixed length. //! name: &'b str, //! value: &'b [u8], //! } //! //! #[derive(Debug)] //! enum Error { //! // We'll return this custom error if the field* relationship doesn't hold //! BadFieldMatchup, //! Scroll(scroll::Error), //! } //! //! impl<'a> ctx::TryFromCtx<'a, Context> for Data<'a> { //! type Error = Error; //! //! // Using the explicit lifetime specification again you ensure that read data doesn't outlife //! // its source buffer without having to resort to copying. //! fn try_from_ctx (src: &'a [u8], ctx: Context) //! // the `usize` returned here is the amount of bytes read. //! -> Result<(Self, usize), Self::Error> //! { //! // The offset counter; gread and gread_with increment a given counter automatically so we //! // don't have to manually care. //! let offset = &mut 0; //! //! let field_a; //! let field_b; //! let field_c; //! //! // Switch the amount of bytes read depending on the parsing context //! if ctx.fieldsize == FieldSize::U32 { //! field_a = src.gread_with::<u32>(offset, ctx.endianess)? as u64; //! field_b = src.gread_with::<u32>(offset, ctx.endianess)? as u64; //! field_c = src.gread_with::<u32>(offset, ctx.endianess)? as u64; //! } else { //! field_a = src.gread_with::<u64>(offset, ctx.endianess)?; //! field_b = src.gread_with::<u64>(offset, ctx.endianess)?; //! field_c = src.gread_with::<u64>(offset, ctx.endianess)?; //! } //! //! // You can use type ascribition or turbofish operators, whichever you prefer. //! let namelen = src.gread_with::<u16>(offset, ctx.endianess)? as usize; //! let name: &str = src.gread_with(offset, scroll::ctx::StrCtx::Length(namelen))?; //! //! let vallen = src.gread_with::<u16>(offset, ctx.endianess)? as usize; //! let value = &src[*offset..(*offset+vallen)]; //! //! // Let's sanity check those fields, shall we? //! if ! (field_a < field_b && field_b < field_c) { //! return Err(Error::BadFieldMatchup); //! } //! //! Ok((Data { field_a, field_b, field_c, name, value }, *offset)) //! } //! } //! //! // In lieu of a complex byte buffer we hearken back to the venerable &[u8]; do note however //! // that the implementation of TryFromCtx did not specify such. In fact any type that implements //! // Pread can now read `Data` as it implements TryFromCtx. //! let bytes = b"\x00\x02\x03\x04\x01\x02\x03\x04\xde\xad\xbe\xef\x00\x08UserName\x00\x02\xCA\xFE"; //! //! // We define an appropiate context, and get going //! let contextA = Context { //! fieldsize: FieldSize::U32, //! endianess: Endian::Big, //! }; //! let data: Data = bytes.pread_with(0, contextA).unwrap(); //! //! assert_eq!(data.field_a, 0x00020304); //! assert_eq!(data.field_b, 0x01020304); //! assert_eq!(data.field_c, 0xdeadbeef); //! assert_eq!(data.name, "UserName"); //! assert_eq!(data.value, [0xCA, 0xFE]); //! //! // Here we have a context with a different FieldSize, changing parsing information at runtime. //! let contextB = Context { //! fieldsize: FieldSize::U64, //! endianess: Endian::Big, //! }; //! //! // Which will of course error with a malformed input for the context //! let err: Result<Data, Error> = bytes.pread_with(0, contextB); //! assert!(err.is_err()); //! //! let bytes_long = [0x00,0x00,0x00,0x00,0x00,0x02,0x03,0x04,0x00,0x00,0x00,0x00,0x01,0x02,0x03, //! 0x04,0x00,0x00,0x00,0x00,0xde,0xad,0xbe,0xef,0x00,0x08,0x55,0x73,0x65,0x72, //! 0x4e,0x61,0x6d,0x65,0x00,0x02,0xCA,0xFE]; //! //! let data: Data = bytes_long.pread_with(0, contextB).unwrap(); //! //! assert_eq!(data.field_a, 0x00020304); //! assert_eq!(data.field_b, 0x01020304); //! assert_eq!(data.field_c, 0xdeadbeef); //! assert_eq!(data.name, "UserName"); //! assert_eq!(data.value, [0xCA, 0xFE]); //! //! // Ergonomic conversion, not relevant really. //! use std::convert::From; //! impl From<scroll::Error> for Error { //! fn from(error: scroll::Error) -> Error { //! Error::Scroll(error) //! } //! } //! ``` use core::mem::size_of; use core::mem::transmute; use core::ptr::copy_nonoverlapping; use core::result; use core::str; #[cfg(feature = "std")] use std::ffi::{CStr, CString}; use crate::endian::Endian; use crate::error; /// A trait for measuring how large something is; for a byte sequence, it will be its length. pub trait MeasureWith<Ctx> { /// How large is `Self`, given the `ctx`? fn measure_with(&self, ctx: &Ctx) -> usize; } impl<Ctx> MeasureWith<Ctx> for [u8] { #[inline] fn measure_with(&self, _ctx: &Ctx) -> usize { self.len() } } impl<Ctx, T: AsRef<[u8]>> MeasureWith<Ctx> for T { #[inline] fn measure_with(&self, _ctx: &Ctx) -> usize { self.as_ref().len() } } /// The parsing context for converting a byte sequence to a `&str` /// /// `StrCtx` specifies what byte delimiter to use, and defaults to C-style null terminators. Be careful. #[derive(Debug, Copy, Clone)] pub enum StrCtx { Delimiter(u8), DelimiterUntil(u8, usize), Length(usize), } /// A C-style, null terminator based delimiter pub const NULL: u8 = 0; /// A space-based delimiter pub const SPACE: u8 = 0x20; /// A newline-based delimiter pub const RET: u8 = 0x0a; /// A tab-based delimiter pub const TAB: u8 = 0x09; impl Default for StrCtx { #[inline] fn default() -> Self { StrCtx::Delimiter(NULL) } } impl StrCtx { pub fn len(&self) -> usize { match *self { StrCtx::Delimiter(_) | StrCtx::DelimiterUntil(_, _) => 1, StrCtx::Length(_) => 0, } } pub fn is_empty(&self) -> bool { if let StrCtx::Length(_) = *self { true } else { false } } } /// Reads `Self` from `This` using the context `Ctx`; must _not_ fail pub trait FromCtx<Ctx: Copy = (), This: ?Sized = [u8]> { fn from_ctx(this: &This, ctx: Ctx) -> Self; } /// Tries to read `Self` from `This` using the context `Ctx` /// /// # Implementing Your Own Reader /// If you want to implement your own reader for a type `Foo` from some kind of buffer (say /// `[u8]`), then you need to implement this trait /// /// ```rust /// use scroll::{self, ctx, Pread}; /// #[derive(Debug, PartialEq, Eq)] /// pub struct Foo(u16); /// /// impl<'a> ctx::TryFromCtx<'a, scroll::Endian> for Foo { /// type Error = scroll::Error; /// fn try_from_ctx(this: &'a [u8], le: scroll::Endian) -> Result<(Self, usize), Self::Error> { /// if this.len() < 2 { return Err((scroll::Error::Custom("whatever".to_string())).into()) } /// let n = this.pread_with(0, le)?; /// Ok((Foo(n), 2)) /// } /// } /// /// let bytes: [u8; 4] = [0xde, 0xad, 0, 0]; /// let foo = bytes.pread_with::<Foo>(0, scroll::LE).unwrap(); /// assert_eq!(Foo(0xadde), foo); /// /// let foo2 = bytes.pread_with::<Foo>(0, scroll::BE).unwrap(); /// assert_eq!(Foo(0xdeadu16), foo2); /// ``` /// /// # Advanced: Using Your Own Error in `TryFromCtx` /// ```rust /// use scroll::{self, ctx, Pread}; /// use std::error; /// use std::fmt::{self, Display}; /// // make some kind of normal error which also can transformed from a scroll error /// #[derive(Debug)] /// pub struct ExternalError {} /// /// impl Display for ExternalError { /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { /// write!(fmt, "ExternalError") /// } /// } /// /// impl error::Error for ExternalError { /// fn description(&self) -> &str { /// "ExternalError" /// } /// fn cause(&self) -> Option<&dyn error::Error> { None} /// } /// /// impl From<scroll::Error> for ExternalError { /// fn from(err: scroll::Error) -> Self { /// match err { /// _ => ExternalError{}, /// } /// } /// } /// #[derive(Debug, PartialEq, Eq)] /// pub struct Foo(u16); /// /// impl<'a> ctx::TryFromCtx<'a, scroll::Endian> for Foo { /// type Error = ExternalError; /// fn try_from_ctx(this: &'a [u8], le: scroll::Endian) -> Result<(Self, usize), Self::Error> { /// if this.len() <= 2 { return Err((ExternalError {}).into()) } /// let offset = &mut 0; /// let n = this.gread_with(offset, le)?; /// Ok((Foo(n), *offset)) /// } /// } /// /// let bytes: [u8; 4] = [0xde, 0xad, 0, 0]; /// let foo: Result<Foo, ExternalError> = bytes.pread(0); /// ``` pub trait TryFromCtx<'a, Ctx: Copy = (), This: ?Sized = [u8]> where Self: 'a + Sized, { type Error; fn try_from_ctx(from: &'a This, ctx: Ctx) -> Result<(Self, usize), Self::Error>; } /// Writes `Self` into `This` using the context `Ctx` pub trait IntoCtx<Ctx: Copy = (), This: ?Sized = [u8]>: Sized { fn into_ctx(self, _: &mut This, ctx: Ctx); } /// Tries to write `Self` into `This` using the context `Ctx` /// To implement writing into an arbitrary byte buffer, implement `TryIntoCtx` /// # Example /// ```rust /// use scroll::{self, ctx, LE, Endian, Pwrite}; /// #[derive(Debug, PartialEq, Eq)] /// pub struct Foo(u16); /// /// // this will use the default `DefaultCtx = scroll::Endian` /// impl ctx::TryIntoCtx<Endian> for Foo { /// // you can use your own error here too, but you will then need to specify it in fn generic parameters /// type Error = scroll::Error; /// // you can write using your own context type, see `leb128.rs` /// fn try_into_ctx(self, this: &mut [u8], le: Endian) -> Result<usize, Self::Error> { /// if this.len() < 2 { return Err((scroll::Error::Custom("whatever".to_string())).into()) } /// this.pwrite_with(self.0, 0, le)?; /// Ok(2) /// } /// } /// // now we can write a `Foo` into some buffer (in this case, a byte buffer, because that's what we implemented it for above) /// /// let mut bytes: [u8; 4] = [0, 0, 0, 0]; /// bytes.pwrite_with(Foo(0x7f), 1, LE).unwrap(); /// ``` pub trait TryIntoCtx<Ctx: Copy = (), This: ?Sized = [u8]>: Sized { type Error; fn try_into_ctx(self, _: &mut This, ctx: Ctx) -> Result<usize, Self::Error>; } /// Gets the size of `Self` with a `Ctx`, and in `Self::Units`. Implementors can then call `Gread` related functions /// /// The rationale behind this trait is to: /// /// 1. Prevent `gread` from being used, and the offset being modified based on simply the sizeof the value, which can be a misnomer, e.g., for Leb128, etc. /// 2. Allow a context based size, which is useful for 32/64 bit variants for various containers, etc. pub trait SizeWith<Ctx = ()> { fn size_with(ctx: &Ctx) -> usize; } #[rustfmt::skip] macro_rules! signed_to_unsigned { (i8) => {u8 }; (u8) => {u8 }; (i16) => {u16}; (u16) => {u16}; (i32) => {u32}; (u32) => {u32}; (i64) => {u64}; (u64) => {u64}; (i128) => {u128}; (u128) => {u128}; (f32) => {u32}; (f64) => {u64}; } macro_rules! write_into { ($typ:ty, $size:expr, $n:expr, $dst:expr, $endian:expr) => {{ unsafe { assert!($dst.len() >= $size); let bytes = transmute::<$typ, [u8; $size]>(if $endian.is_little() { $n.to_le() } else { $n.to_be() }); copy_nonoverlapping((&bytes).as_ptr(), $dst.as_mut_ptr(), $size); } }}; } macro_rules! into_ctx_impl { ($typ:tt, $size:expr) => { impl IntoCtx<Endian> for $typ { #[inline] fn into_ctx(self, dst: &mut [u8], le: Endian) { assert!(dst.len() >= $size); write_into!($typ, $size, self, dst, le); } } impl<'a> IntoCtx<Endian> for &'a $typ { #[inline] fn into_ctx(self, dst: &mut [u8], le: Endian) { (*self).into_ctx(dst, le) } } impl TryIntoCtx<Endian> for $typ where $typ: IntoCtx<Endian>, { type Error = error::Error; #[inline] fn try_into_ctx(self, dst: &mut [u8], le: Endian) -> error::Result<usize> { if $size > dst.len() { Err(error::Error::TooBig { size: $size, len: dst.len(), }) } else { <$typ as IntoCtx<Endian>>::into_ctx(self, dst, le); Ok($size) } } } impl<'a> TryIntoCtx<Endian> for &'a $typ { type Error = error::Error; #[inline] fn try_into_ctx(self, dst: &mut [u8], le: Endian) -> error::Result<usize> { (*self).try_into_ctx(dst, le) } } }; } macro_rules! from_ctx_impl { ($typ:tt, $size:expr) => { impl<'a> FromCtx<Endian> for $typ { #[inline] fn from_ctx(src: &[u8], le: Endian) -> Self { assert!(src.len() >= $size); let mut data: signed_to_unsigned!($typ) = 0; unsafe { copy_nonoverlapping( src.as_ptr(), &mut data as *mut signed_to_unsigned!($typ) as *mut u8, $size, ); } (if le.is_little() { data.to_le() } else { data.to_be() }) as $typ } } impl<'a> TryFromCtx<'a, Endian> for $typ where $typ: FromCtx<Endian>, { type Error = error::Error; #[inline] fn try_from_ctx( src: &'a [u8], le: Endian, ) -> result::Result<(Self, usize), Self::Error> { if $size > src.len() { Err(error::Error::TooBig { size: $size, len: src.len(), }) } else { Ok((FromCtx::from_ctx(&src, le), $size)) } } } // as ref impl<'a, T> FromCtx<Endian, T> for $typ where T: AsRef<[u8]>, { #[inline] fn from_ctx(src: &T, le: Endian) -> Self { let src = src.as_ref(); assert!(src.len() >= $size); let mut data: signed_to_unsigned!($typ) = 0; unsafe { copy_nonoverlapping( src.as_ptr(), &mut data as *mut signed_to_unsigned!($typ) as *mut u8, $size, ); } (if le.is_little() { data.to_le() } else { data.to_be() }) as $typ } } impl<'a, T> TryFromCtx<'a, Endian, T> for $typ where $typ: FromCtx<Endian, T>, T: AsRef<[u8]>, { type Error = error::Error; #[inline] fn try_from_ctx(src: &'a T, le: Endian) -> result::Result<(Self, usize), Self::Error> { let src = src.as_ref(); Self::try_from_ctx(src, le) } } }; } macro_rules! ctx_impl { ($typ:tt, $size:expr) => { from_ctx_impl!($typ, $size); }; } ctx_impl!(u8, 1); ctx_impl!(i8, 1); ctx_impl!(u16, 2); ctx_impl!(i16, 2); ctx_impl!(u32, 4); ctx_impl!(i32, 4); ctx_impl!(u64, 8); ctx_impl!(i64, 8); ctx_impl!(u128, 16); ctx_impl!(i128, 16); macro_rules! from_ctx_float_impl { ($typ:tt, $size:expr) => { impl<'a> FromCtx<Endian> for $typ { #[inline] fn from_ctx(src: &[u8], le: Endian) -> Self { assert!(src.len() >= ::core::mem::size_of::<Self>()); let mut data: signed_to_unsigned!($typ) = 0; unsafe { copy_nonoverlapping( src.as_ptr(), &mut data as *mut signed_to_unsigned!($typ) as *mut u8, $size, ); transmute(if le.is_little() { data.to_le() } else { data.to_be() }) } } } impl<'a> TryFromCtx<'a, Endian> for $typ where $typ: FromCtx<Endian>, { type Error = error::Error; #[inline] fn try_from_ctx( src: &'a [u8], le: Endian, ) -> result::Result<(Self, usize), Self::Error> { if $size > src.len() { Err(error::Error::TooBig { size: $size, len: src.len(), }) } else { Ok((FromCtx::from_ctx(src, le), $size)) } } } }; } from_ctx_float_impl!(f32, 4); from_ctx_float_impl!(f64, 8); into_ctx_impl!(u8, 1); into_ctx_impl!(i8, 1); into_ctx_impl!(u16, 2); into_ctx_impl!(i16, 2); into_ctx_impl!(u32, 4); into_ctx_impl!(i32, 4); into_ctx_impl!(u64, 8); into_ctx_impl!(i64, 8); into_ctx_impl!(u128, 16); into_ctx_impl!(i128, 16); macro_rules! into_ctx_float_impl { ($typ:tt, $size:expr) => { impl IntoCtx<Endian> for $typ { #[inline] fn into_ctx(self, dst: &mut [u8], le: Endian) { assert!(dst.len() >= $size); write_into!( signed_to_unsigned!($typ), $size, transmute::<$typ, signed_to_unsigned!($typ)>(self), dst, le ); } } impl<'a> IntoCtx<Endian> for &'a $typ { #[inline] fn into_ctx(self, dst: &mut [u8], le: Endian) { (*self).into_ctx(dst, le) } } impl TryIntoCtx<Endian> for $typ where $typ: IntoCtx<Endian>, { type Error = error::Error; #[inline] fn try_into_ctx(self, dst: &mut [u8], le: Endian) -> error::Result<usize> { if $size > dst.len() { Err(error::Error::TooBig { size: $size, len: dst.len(), }) } else { <$typ as IntoCtx<Endian>>::into_ctx(self, dst, le); Ok($size) } } } impl<'a> TryIntoCtx<Endian> for &'a $typ { type Error = error::Error; #[inline] fn try_into_ctx(self, dst: &mut [u8], le: Endian) -> error::Result<usize> { (*self).try_into_ctx(dst, le) } } }; } into_ctx_float_impl!(f32, 4); into_ctx_float_impl!(f64, 8); impl<'a> TryFromCtx<'a, StrCtx> for &'a str { type Error = error::Error; #[inline] /// Read a `&str` from `src` using `delimiter` fn try_from_ctx(src: &'a [u8], ctx: StrCtx) -> Result<(Self, usize), Self::Error> { let len = match ctx { StrCtx::Length(len) => len, StrCtx::Delimiter(delimiter) => src.iter().take_while(|c| **c != delimiter).count(), StrCtx::DelimiterUntil(delimiter, len) => { if len > src.len() { return Err(error::Error::TooBig { size: len, len: src.len(), }); }; src.iter() .take_while(|c| **c != delimiter) .take(len) .count() } }; if len > src.len() { return Err(error::Error::TooBig { size: len, len: src.len(), }); }; match str::from_utf8(&src[..len]) { Ok(res) => Ok((res, len + ctx.len())), Err(_) => Err(error::Error::BadInput { size: src.len(), msg: "invalid utf8", }), } } } impl<'a, T> TryFromCtx<'a, StrCtx, T> for &'a str where T: AsRef<[u8]>, { type Error = error::Error; #[inline] fn try_from_ctx(src: &'a T, ctx: StrCtx) -> result::Result<(Self, usize), Self::Error> { let src = src.as_ref(); TryFromCtx::try_from_ctx(src, ctx) } } impl<'a> TryIntoCtx for &'a [u8] { type Error = error::Error; #[inline] fn try_into_ctx(self, dst: &mut [u8], _ctx: ()) -> error::Result<usize> { let src_len = self.len() as isize; let dst_len = dst.len() as isize; // if src_len < 0 || dst_len < 0 || offset < 0 { // return Err(error::Error::BadOffset(format!("requested operation has negative casts: src len: {} dst len: {} offset: {}", src_len, dst_len, offset)).into()) // } if src_len > dst_len { Err(error::Error::TooBig { size: self.len(), len: dst.len(), }) } else { unsafe { copy_nonoverlapping(self.as_ptr(), dst.as_mut_ptr(), src_len as usize) }; Ok(self.len()) } } } // TODO: make TryIntoCtx use StrCtx for awesomeness impl<'a> TryIntoCtx for &'a str { type Error = error::Error; #[inline] fn try_into_ctx(self, dst: &mut [u8], _ctx: ()) -> error::Result<usize> { let bytes = self.as_bytes(); TryIntoCtx::try_into_ctx(bytes, dst, ()) } } // TODO: we can make this compile time without size_of call, but compiler probably does that anyway macro_rules! sizeof_impl { ($ty:ty) => { impl SizeWith<Endian> for $ty { #[inline] fn size_with(_ctx: &Endian) -> usize { size_of::<$ty>() } } }; } sizeof_impl!(u8); sizeof_impl!(i8); sizeof_impl!(u16); sizeof_impl!(i16); sizeof_impl!(u32); sizeof_impl!(i32); sizeof_impl!(u64); sizeof_impl!(i64); sizeof_impl!(u128); sizeof_impl!(i128); sizeof_impl!(f32); sizeof_impl!(f64); impl<'a> TryFromCtx<'a, usize> for &'a [u8] { type Error = error::Error; #[inline] fn try_from_ctx(src: &'a [u8], size: usize) -> result::Result<(Self, usize), Self::Error> { if size > src.len() { Err(error::Error::TooBig { size, len: src.len(), }) } else { Ok((&src[..size], size)) } } } #[cfg(feature = "std")] impl<'a> TryFromCtx<'a> for &'a CStr { type Error = error::Error; #[inline] fn try_from_ctx(src: &'a [u8], _ctx: ()) -> result::Result<(Self, usize), Self::Error> { let null_byte = match src.iter().position(|b| *b == 0) { Some(ix) => ix, None => { return Err(error::Error::BadInput { size: 0, msg: "The input doesn't contain a null byte", }) } }; let cstr = unsafe { CStr::from_bytes_with_nul_unchecked(&src[..=null_byte]) }; Ok((cstr, null_byte + 1)) } } #[cfg(feature = "std")] impl<'a> TryFromCtx<'a> for CString { type Error = error::Error; #[inline] fn try_from_ctx(src: &'a [u8], _ctx: ()) -> result::Result<(Self, usize), Self::Error> { let (raw, bytes_read) = <&CStr as TryFromCtx>::try_from_ctx(src, _ctx)?; Ok((raw.to_owned(), bytes_read)) } } #[cfg(feature = "std")] impl<'a> TryIntoCtx for &'a CStr { type Error = error::Error; #[inline] fn try_into_ctx(self, dst: &mut [u8], _ctx: ()) -> error::Result<usize> { let data = self.to_bytes_with_nul(); if dst.len() < data.len() { Err(error::Error::TooBig { size: dst.len(), len: data.len(), }) } else { unsafe { copy_nonoverlapping(data.as_ptr(), dst.as_mut_ptr(), data.len()); } Ok(data.len()) } } } #[cfg(feature = "std")] impl TryIntoCtx for CString { type Error = error::Error; #[inline] fn try_into_ctx(self, dst: &mut [u8], _ctx: ()) -> error::Result<usize> { self.as_c_str().try_into_ctx(dst, ()) } } // example of marshalling to bytes, let's wait until const is an option // impl FromCtx for [u8; 10] { // fn from_ctx(bytes: &[u8], _ctx: Endian) -> Self { // let mut dst: Self = [0; 10]; // assert!(bytes.len() >= dst.len()); // unsafe { // copy_nonoverlapping(bytes.as_ptr(), dst.as_mut_ptr(), dst.len()); // } // dst // } // } #[cfg(test)] mod tests { use super::*; #[test] #[cfg(feature = "std")] fn parse_a_cstr() { let src = CString::new("Hello World").unwrap(); let as_bytes = src.as_bytes_with_nul(); let (got, bytes_read) = <&CStr as TryFromCtx>::try_from_ctx(as_bytes, ()).unwrap(); assert_eq!(bytes_read, as_bytes.len()); assert_eq!(got, src.as_c_str()); } #[test] #[cfg(feature = "std")] fn round_trip_a_c_str() { let src = CString::new("Hello World").unwrap(); let src = src.as_c_str(); let as_bytes = src.to_bytes_with_nul(); let mut buffer = vec![0; as_bytes.len()]; let bytes_written = src.try_into_ctx(&mut buffer, ()).unwrap(); assert_eq!(bytes_written, as_bytes.len()); let (got, bytes_read) = <&CStr as TryFromCtx>::try_from_ctx(&buffer, ()).unwrap(); assert_eq!(bytes_read, as_bytes.len()); assert_eq!(got, src); } }
true
a837f8c5f4daf0933baaf22533c7037d94fac3ab
Rust
rust-lang/rust
/tests/ui/issues/issue-35976.rs
UTF-8
544
2.78125
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
// revisions: imported unimported //[imported] check-pass mod private { pub trait Future { //[unimported]~^^ HELP perhaps add a `use` for it fn wait(&self) where Self: Sized; } impl Future for Box<dyn Future> { fn wait(&self) { } } } #[cfg(imported)] use private::Future; fn bar(arg: Box<dyn private::Future>) { // Importing the trait means that we don't autoderef `Box<dyn Future>` arg.wait(); //[unimported]~^ ERROR the `wait` method cannot be invoked on a trait object } fn main() {}
true
0c410a380f11a7f883132b71410e1b64d7218bdc
Rust
mkhan45/slang-v2
/src/parser/while_parse.rs
UTF-8
458
2.859375
3
[]
no_license
use crate::{parse_block, parse_expr, statement::While, Lexer, TokenType}; pub fn parse_while(lexer: &mut Lexer) -> While { lexer.next(); assert_eq!(lexer.next().ty, TokenType::LParen); let cond = parse_expr(lexer); assert_eq!(lexer.next().ty, TokenType::RParen); assert_eq!(lexer.next().ty, TokenType::LBrace); let loop_block = parse_block(lexer); assert_eq!(lexer.next().ty, TokenType::RBrace); While { cond, loop_block } }
true
afb7e9b0a286f5dd2973b7ba9a743b23996f826a
Rust
tmzt/isymtope
/isymtope-ast-common/src/ast/nodes/content/mod.rs
UTF-8
3,927
2.828125
3
[ "MIT" ]
permissive
use std::marker::PhantomData; use error::*; use traits::*; use expressions::*; pub mod bindings; pub mod attr; pub mod element; pub mod extern_; pub mod visitor; pub use self::bindings::*; pub use self::attr::*; pub use self::element::*; pub use self::extern_::*; pub use self::visitor::*; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ContentNode<T> { Element(ElementNode<T>, PhantomData<T>), Extern(ExternNode<T>, PhantomData<T>), // Value(ExpressionValue<T>, String, PhantomData<T>), ForNode( Option<String>, Box<ExpressionValue<T>>, Option<Box<Vec<ContentNode<T>>>>, PhantomData<T>, ), ExpressionValue(Box<ExpressionValue<T>>, String, PhantomData<T>), Primitive(Primitive, PhantomData<T>), } impl TryProcessFrom<ContentNode<SourceExpression>> for ContentNode<ProcessedExpression> { fn try_process_from( src: &ContentNode<SourceExpression>, ctx: &mut ProcessingContext, ) -> DocumentProcessingResult<Self> { match *src { ContentNode::Element(ref n, _) => Ok(ContentNode::Element( TryProcessFrom::try_process_from(n, ctx)?, Default::default(), )), ContentNode::Extern(ref e, _) => Ok(ContentNode::Extern( TryProcessFrom::try_process_from(e, ctx)?, Default::default(), )), ContentNode::ForNode(ref s, ref e, Some(ref n), _) => Ok(ContentNode::ForNode( s.to_owned(), Box::new(TryProcessFrom::try_process_from(e, ctx)?), Some(Box::new(TryProcessFrom::try_process_from(n, ctx)?)), Default::default(), )), ContentNode::ForNode(ref s, ref e, _, _) => Ok(ContentNode::ForNode( s.to_owned(), Box::new(TryProcessFrom::try_process_from(e, ctx)?), None, Default::default(), )), ContentNode::ExpressionValue(ref e, ref s, _) => Ok(ContentNode::ExpressionValue( Box::new(TryProcessFrom::try_process_from(e, ctx)?), s.to_owned(), Default::default(), )), ContentNode::Primitive(ref p, _) => { Ok(ContentNode::Primitive(p.to_owned(), Default::default())) } } } } impl TryEvalFrom<ContentNode<ProcessedExpression>> for ContentNode<OutputExpression> { fn try_eval_from( src: &ContentNode<ProcessedExpression>, ctx: &mut OutputContext, ) -> DocumentProcessingResult<Self> { match *src { ContentNode::Element(ref n, _) => Ok(ContentNode::Element( TryEvalFrom::try_eval_from(n, ctx)?, Default::default(), )), ContentNode::Extern(ref e, _) => Ok(ContentNode::Extern( TryEvalFrom::try_eval_from(e, ctx)?, Default::default(), )), ContentNode::ForNode(ref s, ref e, Some(ref n), _) => Ok(ContentNode::ForNode( s.to_owned(), Box::new(TryEvalFrom::try_eval_from(e, ctx)?), Some(Box::new(TryEvalFrom::try_eval_from(n, ctx)?)), Default::default(), )), ContentNode::ForNode(ref s, ref e, _, _) => Ok(ContentNode::ForNode( s.to_owned(), Box::new(TryEvalFrom::try_eval_from(e, ctx)?), None, Default::default(), )), ContentNode::ExpressionValue(ref e, ref s, _) => Ok(ContentNode::ExpressionValue( Box::new(TryEvalFrom::try_eval_from(e, ctx)?), s.to_owned(), Default::default(), )), ContentNode::Primitive(ref p, _) => { Ok(ContentNode::Primitive(p.to_owned(), Default::default())) } } } }
true
e4af0dd2ef165f2d6774dc6c6a66870f6b0938a3
Rust
Dyr-El/advent_of_code_2020
/mantono-rust/src/days/day2.rs
UTF-8
4,056
3.609375
4
[]
no_license
use regex::Regex; /// To try to debug the problem, they have created a list (your puzzle input) of passwords /// (according to the corrupted database) and the corporate policy when that password was set. /// /// For example, suppose you have the following list: /// /// 1-3 a: abcde /// 1-3 b: cdefg /// 2-9 c: ccccccccc /// /// Each line gives the password policy and then the password. /// The password policy indicates the lowest and highest number of times a given letter must appear /// for the password to be valid. For example, 1-3 a means that the password must contain a at /// least 1 time and at most 3 times. /// /// In the above example, 2 passwords are valid. The middle password, cdefg, is not; /// it contains no instances of b, but needs at least 1. /// The first and third passwords are valid: they contain one a or nine c, /// both within the limits of their respective policies. /// /// How many passwords are valid according to their policies? pub fn first(input: String) -> String { transform(input) .iter() .filter(|p| p.is_valid()) .count() .to_string() } fn transform(input: String) -> Vec<Password> { input.lines().map(|p| Password::from(p)).collect() } /// Each policy actually describes two positions in the password, where 1 means the first character, /// 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no /// concept of "index zero"!) Exactly one of these positions must contain the given letter. /// Other occurrences of the letter are irrelevant for the purposes of policy enforcement. /// /// Given the same example list from above: /// /// 1-3 a: abcde is valid: position 1 contains a and position 3 does not. /// 1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b. /// 2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c. /// /// How many passwords are valid according to the new interpretation of the policies? pub fn second(input: String) -> String { transform(input) .iter() .filter(|p| p.is_valid2()) .count() .to_string() } #[derive(Debug)] struct Password { pub lower_bound: u8, pub upper_bound: u8, pub char_required: char, pub content: String, } lazy_static::lazy_static! { static ref REGEX: Regex = Regex::new(r"(\d+|\w+)").unwrap(); } fn next_str<'a>(iter: &'a mut regex::Matches) -> &'a str { iter.next().unwrap().as_str() } impl Password { fn from(input: &str) -> Password { let mut input: regex::Matches = REGEX.find_iter(input); let lower_bound: u8 = next_str(&mut input).parse::<u8>().unwrap(); let upper_bound: u8 = next_str(&mut input).parse::<u8>().unwrap(); let char_required: char = next_str(&mut input).chars().nth(0).unwrap(); let content: String = next_str(&mut input).to_string(); Password { lower_bound, upper_bound, char_required, content, } } fn is_valid(&self) -> bool { let occurences: u8 = self .content .chars() .filter(|c| *c == self.char_required) .count() as u8; occurences >= self.lower_bound && occurences <= self.upper_bound } fn is_valid2(&self) -> bool { let first = self .content .chars() .nth(self.lower_bound as usize - 1) .unwrap_or('-'); let second = self .content .chars() .nth(self.upper_bound as usize - 1) .unwrap_or('-'); let first_match = first == self.char_required; let second_match = second == self.char_required; first_match ^ second_match } } #[cfg(test)] mod tests { use crate::days::day2::Password; #[test] fn test_validator2() { assert!(Password::from("1-3 a: abcde").is_valid2()); assert!(!Password::from("1-3 b: cdefg").is_valid2()); assert!(!Password::from("2-9 c: ccccccccc").is_valid2()); } }
true
6cc66bcaeb44cb54031e6927a5d3aed7457380dd
Rust
vavrusa/edgedns
/crates/sandbox/examples/memcache/src/memcache.rs
UTF-8
1,772
2.90625
3
[ "ISC" ]
permissive
/// This is a simplified implementation of [rust-memcache](https://github.com/aisk/rust-memcache) /// ported for AsyncRead + AsyncWrite. use core::fmt::Display; use futures::prelude::*; use guest::BufferedStream; use std::io::{Error, ErrorKind}; pub struct AsciiProtocol { io: BufferedStream, } impl AsciiProtocol { pub fn new(io: BufferedStream) -> Self { Self { io } } pub async fn get<'a, K: Display>(&'a mut self, key: &'a K) -> Result<Vec<u8>, Error> { // Send command let header = format!("get {}\r\n", key); await!(self.io.write_all(header.as_bytes()))?; await!(self.io.flush())?; // Read response header let header = { let v = await!(self.io.read_until(b'\n', Vec::default()))?; String::from_utf8(v).map_err(|_| Error::from(ErrorKind::InvalidInput))? }; // Check response header and parse value length if header.contains("ERROR") { return Err(Error::new(ErrorKind::Other, header)); } else if header.starts_with("END") { return Err(ErrorKind::NotFound.into()); } let length_str = header.trim_end().rsplitn(2, ' ').next(); let length: usize = match length_str { Some(x) => x .parse() .map_err(|_| Error::from(ErrorKind::InvalidInput))?, None => return Err(ErrorKind::InvalidInput.into()), }; // Read value let mut buffer: Vec<u8> = vec![0; length]; drop(await!(self.io.read_exact(&mut buffer))?); // Read the trailing header drop(await!(self.io.read_until(b'\n', Vec::default()))?); drop(await!(self.io.read_until(b'\n', Vec::default()))?); Ok(buffer) } }
true
4b7b2b8c03367402be9004b64ad93e7cbdd228d1
Rust
JamieSK/connect-4
/src/main.rs
UTF-8
1,207
3.28125
3
[]
no_license
extern crate connect_4; use connect_4::*; use std::io; fn main() { let mut game = Connect4::new(); let mut player = Player::Red; while game.state() != State::Won { print!("{}", game.to_string()); match take_input(player) { column @ 1...7 => { match game.play(player, column) { Err(e) => { println!("{}", e); continue; }, _ => {}, } player = match player { Player::Red => Player::Yellow, Player::Yellow => Player::Red, } }, _ => println!("Can't play there."), } } println!("\nYou win, {:?}.{}", game.winner.unwrap(), game.to_string()); } fn take_input(player: Player) -> usize { println!("Where would you like to play, {}?", player.pretty_print()); let mut input = String::new(); io::stdin().read_line(&mut input) .expect("Failure to read line."); let input_number: usize = match input.trim().parse() { Ok(x) => x, Err(_) => take_input(player), }; input_number }
true
0f3a0b8bececf5073440ce02527f06d3c7c88b8f
Rust
TsvetelinKostadinv/Programming-With-Rust-2020
/zz. Homework-3/solution/tests/iter.rs
UTF-8
948
3.015625
3
[]
no_license
use solution::*; use std::io::BufReader; #[test] fn iter_test() { let reader = BufReader::new( r#" name, age, birth date "Douglas Adams", "42", "1952-03-11" "Gen Z. Person", "20", "2000-01-01" "Ada Lovelace", "36", "1815-12-10" "# .trim() .as_bytes(), ); // Конструираме си CSV-то: let mut csv = Csv::new(reader).unwrap(); // Инсталираме условието -- само редове с възраст над 30 ще останат: csv.apply_selection(|row| { let age = row .get("age") .ok_or_else(|| CsvError::InvalidColumn(String::from("age")))?; let age = age .parse::<u32>() .map_err(|_| CsvError::ParseError(String::from(age)))?; Ok(age > 30) }); // Итерираме през резултата: while let Some(Ok(row)) = csv.next() { println!("{:?}", row["name"]); } }
true
b6ceb45d94ab9e35de949b2e71d64072415527c2
Rust
hamidr/rmafia
/src/scenario.rs
UTF-8
2,899
2.671875
3
[]
no_license
use std::{collections::{BTreeMap, BTreeSet}, vec}; use btreemultimap::BTreeMultiMap; use crate::waiting::PlayerId; pub type Error = String; pub enum ShootingResult { Killed(PlayerId), EmptyGun(PlayerId), NotAllowed } #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord)] pub enum Power { Guard, Paralyze, NightKill, Reveal, Heal, Enquery, HandGun, HandFakeGun, ShotOnKill, Disguise, DodgeCommando, Mafia, DayShield, } impl Power { pub fn night(&self) -> bool { self.active().contains(self) } pub fn active(&self) -> [Power; 9] { use Power::*; [NightKill, Reveal, Paralyze, Heal, Enquery, Guard, HandGun, HandFakeGun, ShotOnKill] } pub fn passive(&self) -> [Power; 4] { use Power::*; [Disguise, DodgeCommando, Mafia, DayShield] } } #[derive(Clone)] pub enum HolyMessage { Assigned(Vec<Power>), YouHaveGun, YouAreBoss, IsMafia(PlayerId, bool), } pub enum Meta { Has(Power) } pub struct Pray { pub action: Power, pub query: Vec<PlayerId>, pub meta: Option<Meta> } // impl Pray { // fn is_consistent(&self) -> bool { // use Power::*; // match (&self.action, &self.query, &self.meta) { // (Reveal, ids, Some(Meta::Has(Power::Heal|Power::DayShield|Power::Enquery|Power::ShotOnKill))) if ids.len() == 1 => true, // (NightKill|Paralyze|Heal|Enquery|HandGun|HandFakeGun|DayShield, ids, None) if ids.len() <= 2 => true, // (ShotOnKill, ids, None) if ids.len() == 1 => true, // _ => false // } // } // pub fn on(&self) -> &Vec<PlayerId> { // &self.query // } // } pub type Messages = BTreeMultiMap<PlayerId, HolyMessage>; // pub type Spells<'a> = BTreeMap<Role, Spell<'a>>; pub trait News { fn messages(&self) -> &Messages; fn kicked_out(&self) -> &BTreeSet<PlayerId>; } pub trait DeathBallot { fn list(&self) -> &BTreeSet<PlayerId>; fn hang(&mut self, from: PlayerId, on: PlayerId) -> bool; fn dead(&self) -> Option<PlayerId>; } pub trait Defendence { type Ballot: DeathBallot; fn nominate(&mut self, from: PlayerId, on: PlayerId) -> bool; fn result(&self) -> Option<Self::Ballot>; } #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)] pub enum CityState { Debate, Defend, Hang, Night, Done(State) } #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)] pub enum State { MafiaWon, CityWon, Undecided } #[derive(Clone)] pub enum Declaration { Out(PlayerId), StateChanged(CityState), FakeGun(PlayerId) } pub type Day = usize; pub trait Scenario { fn state(&self) -> CityState; fn day(&self) -> Day; fn next(&mut self) -> CityState; fn events(&self) -> &Vec<(Day, CityState, Declaration)>; fn process(&mut self); }
true
e58432561814aa3e975e82adeb8fb849bd3577fd
Rust
agerasev/hypertrace
/kernel/build.rs
UTF-8
2,442
2.5625
3
[ "Apache-2.0", "MIT" ]
permissive
use std::{ collections::BTreeMap, env, fs, path::{Path, PathBuf}, }; use walkdir::WalkDir; fn str_text(value: &str) -> String { format!("r##\"{}\"##", value) } fn dict_text(name: &str, dict: &BTreeMap<String, String>) -> String { [ format!("pub const {}: [(&str, &str); {}] = [\n", name, dict.len()), dict.iter() .map(|(k, v)| format!(" ({}, {}),\n", str_text(k), str_text(v))) .fold(String::new(), |a, b| a + &b), String::from("];\n"), ] .join("") } fn out_path() -> PathBuf { PathBuf::from(env::var("OUT_DIR").unwrap()) } fn base_path() -> PathBuf { PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()) } fn kernel_src_path() -> PathBuf { base_path().join("ocl") } fn remount_path(path: &Path, old_base: &Path, new_base: &Path) -> PathBuf { new_base.join(path.strip_prefix(old_base).unwrap()) } fn embed_kernel_source() { let mut dict = BTreeMap::new(); let src_path = kernel_src_path(); let dst_path = PathBuf::from(""); for entry in WalkDir::new(&src_path).into_iter().filter_map(|e| e.ok()) { if entry.file_type().is_file() { let r = dict.insert( format!( "{}", remount_path(entry.path(), &src_path, &dst_path).display() ), fs::read_to_string(entry.path()).unwrap(), ); assert!(r.is_none()); } } fs::write( out_path().join("kernel_source.rs"), dict_text("FILES_STATIC", &dict), ) .unwrap(); } fn rerun_if_source_changed() { let base_path = base_path(); let src_path = kernel_src_path(); for entry in WalkDir::new(&src_path).into_iter().filter_map(|e| e.ok()) { if entry.file_type().is_dir() { println!( "cargo:rerun-if-changed={}", entry.path().strip_prefix(&base_path).unwrap().display() ); } } } #[cfg(feature = "host_tests")] fn build_host_tests() { let mut cfg = cmake::Config::new(env!("CARGO_MANIFEST_DIR")); cfg.profile("Debug"); cfg.build_arg(format!("-j{}", num_cpus::get())); cfg.build(); } fn main() { embed_kernel_source(); #[cfg(feature = "host_tests")] build_host_tests(); println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=CMakeLists.txt"); rerun_if_source_changed(); }
true
491095ae3cba42812705377425cf29fd13a734be
Rust
marco-c/gecko-dev-wordified
/third_party/rust/weedle2/src/namespace.rs
UTF-8
1,547
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
use crate : : argument : : ArgumentList ; use crate : : attribute : : ExtendedAttributeList ; use crate : : common : : { Identifier Parenthesized } ; use crate : : types : : { AttributedType ReturnType } ; / / / Parses namespace members declaration pub type NamespaceMembers < ' a > = Vec < NamespaceMember < ' a > > ; ast_types ! { / / / Parses namespace member declaration enum NamespaceMember < ' a > { / / / Parses [ attributes ] ? returntype identifier ? ( ( args ) ) ; / / / / / / ( ( ) ) means ( ) chars Operation ( struct OperationNamespaceMember < ' a > { attributes : Option < ExtendedAttributeList < ' a > > return_type : ReturnType < ' a > identifier : Option < Identifier < ' a > > args : Parenthesized < ArgumentList < ' a > > semi_colon : term ! ( ; ) } ) / / / Parses [ attribute ] ? readonly attributetype type identifier ; Attribute ( struct AttributeNamespaceMember < ' a > { attributes : Option < ExtendedAttributeList < ' a > > readonly : term ! ( readonly ) attribute : term ! ( attribute ) type_ : AttributedType < ' a > identifier : Identifier < ' a > semi_colon : term ! ( ; ) } ) } } # [ cfg ( test ) ] mod test { use super : : * ; use crate : : Parse ; test ! ( should_parse_attribute_namespace_member { " readonly attribute short name ; " = > " " ; AttributeNamespaceMember ; attributes . is_none ( ) ; identifier . 0 = = " name " ; } ) ; test ! ( should_parse_operation_namespace_member { " short ( long a long b ) ; " = > " " ; OperationNamespaceMember ; attributes . is_none ( ) ; identifier . is_none ( ) ; } ) ; }
true
79741a73e3434ef7b0b8b36c3300b6c4243d11c8
Rust
scritchley/orcrs
/src/columnreader.rs
UTF-8
744
3.234375
3
[ "MIT" ]
permissive
use std::io::{Read, Bytes}; pub trait ColumnReader<T> { fn next(&self) -> Result<T, ReaderError>; } pub struct RunLengthByteReader<R: Read> { i: Bytes<R>, } impl<R: Read> RunLengthByteReader<R> { pub fn new(r: R) -> RunLengthByteReader<R> { RunLengthByteReader{ i: r.bytes(), } } pub fn next(&mut self) -> Result<bool, ReaderError> { match self.i.next() { Some(_) => Ok(true), None => Ok(false), } } } #[cfg(test)] mod tests { use super::*; #[test] fn run_length_byte_reader() { let b = vec![0x61u8, 0x00u8]; let mut r = RunLengthByteReader::new(&*b); let n = r.next(); assert_eq!(n.unwrap(), false); } }
true
556196293b52987ba2de60a4f4a75bd46ea74c77
Rust
timurista/rust-examples
/enums-demo/src/main.rs
UTF-8
1,238
3.515625
4
[]
no_license
// enums stored in lowest bytes necessary // min for actual type and contents use std::collections::HashMap; use std::env::args; #[derive(Debug)] pub struct Bed{ size:i32, count:u32, } #[derive(Debug)] pub enum Room{ Kitchen(i32), Bedroom(Bed), Lounge(i32, String) } fn main() { use self::Room::*; // use here lets you // let t = Bedroom(Bed{size:50, count:2}); let t = Kitchen(5); println!("Hello from the {:?}", t); let v = match t { Kitchen(n) => n, _ => 0 }; // only working with one if let Kitchen(n) = t { println!("Its a kitchen with {} cupboards", n); } println!("v = {}", v); let mut hm = HashMap::new(); hm.insert(3, "Hello"); hm.insert(5, "world"); // let r = match hm.get(&3) { // Some(v) => v, // _ => "Nothing", // }; let r = hm.get(&3).unwrap(); match "3".parse::<f32>() { Ok(v)=>println!("OK - {}", v), Err(e)=>println!("Error - {}",e) } println!("{}", r); } fn get_arg(n: usize)->Result<String,String>{ for (i,a) in args().enumerate(){ if (i == n) { return Ok(a) } } Err("Not enough args".to_string()); }
true
228c33579c3777ba520a7e8daf45e440fadf5264
Rust
TDHGroupWork/northwind-rs
/components/user/src/services/jwt_processor_impl.rs
UTF-8
1,505
2.609375
3
[ "MIT" ]
permissive
use async_trait::async_trait; use chrono::Utc; use color_eyre::Result; use jsonwebtoken::{Algorithm, decode, DecodingKey, encode, EncodingKey, Header, Validation}; use crate::domain::jwt_processor::JwtProcessor; use crate::domain::auth::Claims; pub struct JwtProcessorImpl {} #[async_trait] impl JwtProcessor for JwtProcessorImpl { fn generate( &self, user_id: uuid::Uuid, user_lastname: String, user_firstname: String, user_email: String, secret_key: String, jwt_lifetime: i64, ) -> Result<(String, i64), Box<dyn std::error::Error>> { let header = Header::new(Algorithm::HS512); let now = Utc::now().timestamp_nanos() / 1_000_000_000; // nanosecond -> second let expired_at = now + (jwt_lifetime * 3600); let payload = Claims { sub: user_id.clone().to_string(), exp: expired_at, iat: now, nbf: now, user_id, user_lastname, user_firstname, user_email, }; let token = encode(&header, &payload, &EncodingKey::from_secret(secret_key.as_bytes()))?; Ok((token, expired_at)) } fn parse(&self, token: String, secret_key: String) -> Result<Claims, Box<dyn std::error::Error>> { let validation = Validation::new(Algorithm::HS512); let token = decode::<Claims>(&token, &DecodingKey::from_secret(secret_key.as_bytes()), &validation)?; Ok(token.claims) } }
true
7b22711b6e4ee7fa48e46fdb61decaf8b3d39af3
Rust
toyama1710/rs_library
/src/tests/segtree_test.rs
UTF-8
1,412
3.203125
3
[ "CC0-1.0" ]
permissive
use crate::algebra::Monoid; #[allow(unused_imports)] use crate::data_structures::segment_tree::SegmentTree; #[allow(dead_code)] struct Min(); impl Monoid for Min { type T = i64; fn identity() -> i64 { return i64::max_value(); } fn op(a: &i64, b: &i64) -> i64 { return std::cmp::min(*a, *b); } } #[allow(dead_code)] struct Line(); impl Monoid for Line { type T = (i64, i64); fn identity() -> Self::T { return (1, 0); } fn op(a: &Self::T, b: &Self::T) -> Self::T { return (a.0 * b.0, a.0 * b.1 + a.1); } } #[test] fn test_min() { let v = vec![1, 2, 4, 5, 7, 1, 8]; let mut seg = SegmentTree::<Min>::from(&v); let n = v.len(); for i in 0..n { assert_eq!(*seg.get(i), v[i]); } assert_eq!(seg.fold(0..n), 1); assert_eq!(seg.fold(2..4), 4); assert_eq!(seg.fold(4..n), 1); seg.update(3, -1); assert_eq!(seg.fold(0..n), -1); assert_eq!(seg.fold(1..3), 2); assert_eq!(seg.fold(4..n), 1); } #[test] fn test_line() { let mut seg = SegmentTree::<Line>::new(8); let n = seg.len(); seg.update(0, (3, 1)); assert_eq!(seg.fold(0..n), (3, 1)); seg.update(0, Line::identity()); seg.update(2, (3, 1)); seg.update(4, (2, 3)); assert_eq!(seg.fold(0..n), (6, 10)); seg.update(2, (2, 3)); seg.update(4, (3, 1)); assert_eq!(seg.fold(0..n), (6, 5)); }
true
75e0be5697db150f7d662398311c21a13676ebb6
Rust
mdcg/a-tour-of-rust
/codewars/dia-2/will-there-be-enough-space.rs
UTF-8
526
2.96875
3
[ "MIT" ]
permissive
// https://www.codewars.com/kata/5875b200d520904a04000003/train/rust // Minha solução fn enough(cap: i32, on: i32, wait: i32) -> i32 { let fit = cap - on - wait; if fit < 0i32 { return fit.abs() } else { return 0i32; } } // Melhor solução fn enough(cap: i32, on: i32, wait: i32) -> i32 { (on + wait - cap).max(0) } // Solução interessante fn enough(cap: i32, on: i32, wait: i32) -> i32 { match on + wait < cap { true => 0, false => on + wait - cap, } }
true
2074d8e767e1cd2fe952e1ef16f52322b96274e2
Rust
avranju/iotedge-k8s
/edgelet/systemd/src/error.rs
UTF-8
2,623
2.734375
3
[ "MIT" ]
permissive
// Copyright (c) Microsoft. All rights reserved. use std::fmt; use std::fmt::Display; use failure::{Backtrace, Context, Fail}; #[cfg(target_os = "linux")] use nix::unistd::Pid; use Fd; #[derive(Debug)] pub struct Error { inner: Context<ErrorKind>, } #[derive(Debug, Fail)] pub enum ErrorKind { #[cfg(target_os = "linux")] #[fail(display = "{} syscall for socket failed.", _0)] Syscall(&'static str), #[fail(display = "File descriptor not found.")] FdNotFound, #[fail( display = "The number of file descriptors {} does not match the number of file descriptor names {}.", _0, _1 )] NumFdsDoesNotMatchNumFdNames(usize, usize), #[fail(display = "File descriptor {} is invalid.", _0)] InvalidFd(Fd), #[fail( display = "Number of file descriptors {} from environment variable {} is not a valid value.", _1, _0 )] InvalidNumFds(String, Fd), #[fail(display = "Environment variable {} is set to an invalid value.", _0)] InvalidVar(String), #[fail( display = "Could not parse process ID from environment variable {}.", _0 )] ParsePid(String), #[fail(display = "Socket corresponding to {} not found.", _0)] SocketNotFound(SocketLookupType), #[cfg(target_os = "linux")] #[fail( display = "Based on the environment variable {}, other environment variables meant for a different process (PID {}).", _0, _1 )] WrongProcess(String, Pid), } impl Fail for Error { fn cause(&self) -> Option<&Fail> { self.inner.cause() } fn backtrace(&self) -> Option<&Backtrace> { self.inner.backtrace() } } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(&self.inner, f) } } impl Error { pub fn new(inner: Context<ErrorKind>) -> Self { Error { inner } } pub fn kind(&self) -> &ErrorKind { self.inner.get_context() } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Self { Error { inner: Context::new(kind), } } } impl From<Context<ErrorKind>> for Error { fn from(inner: Context<ErrorKind>) -> Self { Error { inner } } } #[derive(Debug)] pub enum SocketLookupType { Fd(Fd), Name(String), } impl Display for SocketLookupType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { SocketLookupType::Fd(fd) => write!(f, "file descriptor {}", fd), SocketLookupType::Name(name) => write!(f, "name {}", name), } } }
true
13032587e7bb93353a6e77e605876f67ba97caa6
Rust
briarpatch1337/fast-and-feudalist
/src/hardware.rs
UTF-8
5,901
3.21875
3
[]
no_license
// NOTE: Prefixing these fields with an underscore is necessary to avoid an unused variable warning. pub struct HardwareResources { pub sdl: sdl2::Sdl, _video_subsystem: sdl2::VideoSubsystem, pub window: sdl2::video::Window, pub drawable_size: (u32, u32), pub display_dpi: (f32, f32, f32), _gl_context: sdl2::video::GLContext, pub gl: gl::Gl, pub timer_subsystem: sdl2::TimerSubsystem, _audio_subsystem: sdl2::AudioSubsystem } impl HardwareResources { pub fn init() -> HardwareResources { // SDL_Init // Use this function to initialize the SDL library. This must be called before using most other SDL functions. // The return type of init() is Result<Sdl, String> // We call unwrap() on the Result. This checks for errors and will terminate the program and // print the "String" part of the result if there was an error. On success, the "Sdl" struct is returned. let sdl = sdl2::init().unwrap(); // SDL_VideoInit // Initializes the video subsystem of SDL let video_subsystem = sdl.video().unwrap(); { // SDL_GL_SetAttribute // Obtains access to the OpenGL window attributes. let gl_attr = video_subsystem.gl_attr(); // Set OpenGL Profile and Version. This will help ensure that libraries that implement future versions of // the OpenGL standard will still always work with this code. // SDL_GL_CONTEXT_PROFILE_MASK gl_attr.set_context_profile(sdl2::video::GLProfile::Core); // SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_MINOR_VERSION gl_attr.set_context_version(4, 5); } // Initializes a new WindowBuilder, sets the window to be usable with an OpenGL context, // sets the window to be fullscreen at 1080 HD, builds the window, and checks for errors. // The Window allows you to get and set many of the SDL_Window properties (i.e., border, size, PixelFormat, etc) // However, you cannot directly access the pixels of the Window without a context. let window = video_subsystem .window("Game", 1920, 1080) .opengl() .fullscreen() .build() .unwrap(); let (window_width, window_height) = window.drawable_size(); let (ddpi, hdpi, vdpi) = video_subsystem.display_dpi(0).unwrap(); // SDL_GL_CreateContext // Creates an OpenGL context for use with an OpenGL window, and makes it the current context. let gl_context = window.gl_create_context().unwrap(); // Load the OpenGL function pointers from SDL. let gl = { // Use a closure (lambda function), to add a cast to a C-style void pointer (which must be the return type of the function passed to load_with) let gl_get_proc_address_function = |procname| { video_subsystem.gl_get_proc_address(procname) as *const std::os::raw::c_void }; gl::Gl::load_with(gl_get_proc_address_function) }; unsafe { // glViewport // We have to tell OpenGL the size of the rendering window so OpenGL knows how we want to display the data and coordinates with respect to the window. // The first two parameters of glViewport set the location of the lower left corner of the window. // The third and fourth parameter set the width and height of the rendering window in pixels, which we set equal to SDL's window size. // We could actually set the viewport dimensions at values smaller than GLFW's dimensions; // then all the OpenGL rendering would be displayed in a smaller window and we could for example display other elements outside the OpenGL viewport. // The moment a user resizes the window the viewport should be adjusted as well. gl.Viewport(0, 0, window_width as i32, window_height as i32); // set viewport // glClearColor // Whenever we call glClear and clear the color buffer, the entire color buffer will be filled with the color as configured by glClearColor. gl.ClearColor(0.0, 0.0, 0.0, 1.0); // black, fully opaque gl.Enable(gl::BLEND); gl.BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); } // SDL_GetTicks let timer_subsystem = sdl.timer().unwrap(); struct AudioEngine { sample_number: u128 } impl sdl2::audio::AudioCallback for AudioEngine { type Channel = f32; fn callback(&mut self, out: &mut [f32]) { for x in out.iter_mut() { // This is where audio output will go. *x = 0.0; self.sample_number = self.sample_number + 1; } } } // SDL_AudioInit let audio_subsystem = sdl.audio().unwrap(); let desired_spec = sdl2::audio::AudioSpecDesired { freq: Some(44100), channels: Some(1), //mono samples: None // device default sample buffer size }; let audio_device = audio_subsystem.open_playback(None, &desired_spec, |_spec| { AudioEngine { sample_number: 0 } }).unwrap(); println!("Audio device buffer size: {} samples", audio_device.spec().samples); audio_device.resume(); HardwareResources { sdl: sdl, _video_subsystem: video_subsystem, window: window, drawable_size: (window_width, window_height), display_dpi: (ddpi, hdpi, vdpi), _gl_context: gl_context, gl: gl, timer_subsystem: timer_subsystem, _audio_subsystem: audio_subsystem } } }
true
ae8019dfe5a15c1609409e7480a7705730bbcbfd
Rust
IThawk/rust-project
/rust-master/src/test/run-pass/issues/issue-46553.rs
UTF-8
356
2.78125
3
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
// run-pass #![feature(const_fn)] #![deny(const_err)] pub struct Data<T> { function: fn() -> T, } impl<T> Data<T> { pub const fn new(function: fn() -> T) -> Data<T> { Data { function: function, } } } pub static DATA: Data<i32> = Data::new(|| { 413i32 }); fn main() { print!("{:?}", (DATA.function)()); }
true
9d86430cf2aabc07e597f495f36c4d91fdc72631
Rust
kuviman/trans-gen
/src/gens/rust/trans.rs
UTF-8
4,487
3.296875
3
[ "MIT" ]
permissive
use byteorder::{ReadBytesExt, WriteBytesExt}; pub trait Trans: Sized + 'static { fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()>; fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self>; } impl Trans for bool { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { let value = reader.read_u8()?; match value { 0 => Ok(false), 1 => Ok(true), _ => Err(std::io::Error::new( std::io::ErrorKind::Other, "Bool value should be 0 or 1", )), } } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { writer.write_u8(if *self { 1 } else { 0 }) } } impl Trans for i32 { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { reader.read_i32::<byteorder::LittleEndian>() } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { writer.write_i32::<byteorder::LittleEndian>(*self) } } impl Trans for i64 { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { reader.read_i64::<byteorder::LittleEndian>() } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { writer.write_i64::<byteorder::LittleEndian>(*self) } } impl Trans for usize { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { Ok(i32::read_from(reader)? as usize) } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { let i32_value = *self as i32; i32::write_to(&i32_value, writer) } } impl Trans for f32 { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { reader.read_f32::<byteorder::LittleEndian>() } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { writer.write_f32::<byteorder::LittleEndian>(*self) } } impl Trans for f64 { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { reader.read_f64::<byteorder::LittleEndian>() } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { writer.write_f64::<byteorder::LittleEndian>(*self) } } impl Trans for String { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { let len = usize::read_from(reader)?; let mut buf = vec![0; len]; reader.read_exact(&mut buf)?; String::from_utf8(buf).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { self.len().write_to(writer)?; writer.write_all(self.as_bytes()) } } impl<T: Trans> Trans for Option<T> { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { let is_some = bool::read_from(reader)?; Ok(if is_some { Some(T::read_from(reader)?) } else { None }) } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { self.is_some().write_to(writer)?; if let Some(value) = self { value.write_to(writer)?; } Ok(()) } } impl<T: Trans> Trans for Vec<T> { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { let len = usize::read_from(reader)?; let mut result = Vec::with_capacity(len); for _ in 0..len { result.push(T::read_from(reader)?); } Ok(result) } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { self.len().write_to(writer)?; for item in self { item.write_to(writer)?; } Ok(()) } } impl<K: Trans + Eq + std::hash::Hash, V: Trans> Trans for std::collections::HashMap<K, V> { fn read_from(reader: &mut dyn std::io::Read) -> std::io::Result<Self> { let len = usize::read_from(reader)?; let mut result = Self::with_capacity(len); for _ in 0..len { result.insert(K::read_from(reader)?, V::read_from(reader)?); } Ok(result) } fn write_to(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { self.len().write_to(writer)?; for (key, value) in self { key.write_to(writer)?; value.write_to(writer)?; } Ok(()) } }
true
227859398c5486391d6aff0ece7dbfb8f4b9293e
Rust
wangyingsm/advent-of-code-2020
/day20/day20-rust/src/lib.rs
UTF-8
12,377
2.90625
3
[ "Apache-2.0" ]
permissive
use ndarray::{concatenate, s, Array1, Array2, Axis}; #[macro_use] extern crate lazy_static; peg::parser!(grammar parse_tile() for str { pub rule parse_tile_id() -> usize = "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() } pub rule parse_border() -> (u32, u32) = line:$(['#' | '.']+) { let line = line.chars().map(|x| match x { '#' => '1', '.' => '0', _ => unimplemented!("invalid image pixel"), }).collect::<String>(); (u32::from_str_radix(&line, 2).unwrap(), u32::from_str_radix(&line.chars().rev().collect::<String>(), 2).unwrap()) } pub rule parse_sub_image() -> Array1<u8> = line:$(['#' | '.']+) { let mut arr = unsafe { Array1::<u8>::uninitialized(line.len()) }; for (i, c) in line.chars().enumerate() { match c { '#' => arr[[i]] = 1, '.' => arr[[i]] = 0, _ => unimplemented!("unsupport character {}", c), } } arr } }); pub trait ImageTransformer<T> { fn original(&self) -> Array2<T>; fn rot90_clockwise(&self) -> Array2<T>; fn rot180_clockwise(&self) -> Array2<T>; fn rot270_clockwise(&self) -> Array2<T>; fn flip_vertical(&self) -> Array2<T>; fn flip_horizontal(&self) -> Array2<T>; fn flip_main_diagonal(&self) -> Array2<T>; fn flip_sub_diagonal(&self) -> Array2<T>; } impl<T> ImageTransformer<T> for Array2<T> where T: Copy, { fn original(&self) -> Array2<T> { self.clone() } fn rot90_clockwise(&self) -> Array2<T> { let mut arr = self.clone(); arr.swap_axes(0, 1); arr.flip_horizontal() } fn rot180_clockwise(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..;-1, ..;-1])); arr } fn rot270_clockwise(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![.., ..;-1])); arr.swap_axes(0, 1); arr } fn flip_vertical(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..;-1, ..])); arr } fn flip_horizontal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![.., ..;-1])); arr } fn flip_main_diagonal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.t()); arr } fn flip_sub_diagonal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr: Array2<T> = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.rot270_clockwise().t()); arr.rot90_clockwise() } } #[allow(unused)] #[derive(Eq)] pub struct Tile { tile_id: usize, sub_image: Array2<u8>, borders: Vec<(u32, u32, u32, u32)>, } impl PartialEq for Tile { fn eq(&self, other: &Self) -> bool { self.tile_id == other.tile_id } } use std::fmt::Debug; impl Debug for Tile { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "[{}]", self.tile_id)?; Ok(()) } } impl Tile { pub fn new(data: &str) -> Self { let lines = data .split('\n') .map(|s| s.trim_end().to_string()) .collect::<Vec<_>>(); let shape = lines[1].len() - 2; let tile_id = parse_tile::parse_tile_id(&lines[0]).unwrap(); let (top, top_rev) = parse_tile::parse_border(&lines[1]).unwrap(); let left_col = lines .iter() .skip(1) .map(|s| s.chars().next().unwrap()) .collect::<String>(); let (left, left_rev) = parse_tile::parse_border(&left_col).unwrap(); let right_col = lines .iter() .skip(1) .map(|s| s.chars().last().unwrap()) .collect::<String>(); let (right, right_rev) = parse_tile::parse_border(&right_col).unwrap(); let (bottom, bottom_rev) = parse_tile::parse_border(&lines[lines.len() - 1]).unwrap(); let mut sub_image = unsafe { Array2::<u8>::uninitialized((shape, shape)) }; for (i, row) in lines.iter().enumerate().skip(2).take(shape) { let row_pixels = parse_tile::parse_sub_image(&row[1..row.len() - 1]).unwrap(); sub_image.row_mut(i - 2).assign(&row_pixels); } Self { tile_id, sub_image, borders: vec![ (top, right, bottom, left), // original sub image (left_rev, top, right_rev, bottom), // rotate 90 degree clockwise (bottom_rev, left_rev, top_rev, right_rev), // rotate 180 degree clockwise (right, bottom_rev, left, top_rev), // rotate 270 degree clockwise (bottom, right_rev, top, left_rev), // flip vertical (top_rev, left, bottom_rev, right), // flip horizontal (left, bottom, right, top), // flip along main diagonal (right_rev, top_rev, left_rev, bottom_rev), // flip along sub diagonal ], } } pub fn get_sub_image(&self, idx: usize) -> Array2<u8> { match idx { 0 => self.sub_image.original(), 1 => self.sub_image.rot90_clockwise(), 2 => self.sub_image.rot180_clockwise(), 3 => self.sub_image.rot270_clockwise(), 4 => self.sub_image.flip_vertical(), 5 => self.sub_image.flip_horizontal(), 6 => self.sub_image.flip_main_diagonal(), 7 => self.sub_image.flip_sub_diagonal(), _ => unreachable!("not a valid form index: {}", idx), } } } pub struct BigImage { tiles: Vec<Tile>, shape: usize, } impl BigImage { pub fn new(tiles: Vec<Tile>) -> Self { let shape = (tiles.len() as f64).sqrt() as usize; Self { shape, tiles } } pub fn fits<'a>( &'a self, row: usize, col: usize, prev_images: &[(&'a Tile, usize)], ) -> Vec<(&'a Tile, usize)> { let mut result: Vec<(&Tile, usize)> = vec![]; result.extend_from_slice(prev_images); for tile in self.tiles.iter() { if result.iter().any(|(t, _)| t == &tile) { continue; } result.push((tile, 0)); let upper_tile = if row > 0 { Some(result[(row - 1) * self.shape + col]) } else { None }; let left_tile = if col > 0 { Some(result[row * self.shape + col - 1]) } else { None }; for idx in 0..8 { result.last_mut().unwrap().1 = idx; if (row == 0 || tile.borders[idx].0 == upper_tile.unwrap().0.borders[upper_tile.unwrap().1].2) && (col == 0 || tile.borders[idx].3 == left_tile.unwrap().0.borders[left_tile.unwrap().1].1) { if row == self.shape - 1 && col == self.shape - 1 { return result; } let (new_row, new_col) = if col + 1 >= self.shape { (row + 1, 0) } else { (row, col + 1) }; let ret = self.fits(new_row, new_col, &result); if !ret.is_empty() { return ret; } } } result.pop(); } vec![] } pub fn splice_result(&self, fit_result: &[(&Tile, usize)]) -> Array2<u8> { let pixels = fit_result[0].0.sub_image.shape()[0]; let mut big_image = Array2::<u8>::zeros((0, self.shape * pixels)); for row in 0..self.shape { let mut row_image = Array2::<u8>::zeros((pixels, 0)); for col in 0..self.shape { let result = fit_result[row * self.shape + col]; row_image = concatenate![Axis(1), row_image, result.0.get_sub_image(result.1)]; } big_image = concatenate![Axis(0), big_image, row_image]; } big_image } } pub fn part1_solution(fit_result: &[(&Tile, usize)]) -> usize { let shape = (fit_result.len() as f64).sqrt() as usize; let corner_idx = &[0, shape - 1, shape * (shape - 1), shape * shape - 1]; fit_result .iter() .enumerate() .filter(|(idx, _)| corner_idx.contains(idx)) .map(|(_, (t, _))| t.tile_id) .product() } lazy_static! { static ref MONSTER: Array2<u8> = unsafe { Array2::from_shape_vec_unchecked( (3, 20), vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, ], ) }; } fn find_all_monsters(image: &Array2<u8>) -> Vec<(usize, usize)> { let shape = image.shape()[0]; let mut found = vec![]; for row in 0..=shape - MONSTER.shape()[0] { for col in 0..=shape - MONSTER.shape()[1] { if &image.slice(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) & &MONSTER.slice(s![.., ..]) == MONSTER.slice(s![.., ..]) { found.push((row, col)); } } } found } pub fn part2_solution(big_image: &BigImage, fit_result: &[(&Tile, usize)]) -> usize { let mut image = big_image.splice_result(fit_result); let monsters_pos = find_all_monsters(&image); for (row, col) in monsters_pos { let region = &image.slice(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) - &MONSTER.slice(s![.., ..]); image .slice_mut(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) .assign(&(region)); } image.iter().map(|x| *x as usize).sum::<usize>() } pub fn read_input(input_file: &str) -> Vec<Tile> { std::fs::read_to_string(input_file) .unwrap() .split("\n\n") .filter(|&b| !b.trim().is_empty()) .map(|b| Tile::new(b)) .collect() } #[cfg(test)] mod tests { use super::*; use ndarray::Array; #[test] fn test_matrix_transforms() { let m = Array::range(1., 5., 1.).into_shape((2, 2)).unwrap(); assert_eq!(m.original(), ndarray::arr2(&[[1., 2.], [3., 4.]])); assert_eq!(m.rot90_clockwise(), ndarray::arr2(&[[3., 1.], [4., 2.]])); assert_eq!(m.rot180_clockwise(), ndarray::arr2(&[[4., 3.], [2., 1.]])); assert_eq!(m.rot270_clockwise(), ndarray::arr2(&[[2., 4.], [1., 3.]])); assert_eq!(m.flip_vertical(), ndarray::arr2(&[[3., 4.], [1., 2.]])); assert_eq!(m.flip_horizontal(), ndarray::arr2(&[[2., 1.], [4., 3.]])); assert_eq!(m.flip_main_diagonal(), ndarray::arr2(&[[1., 3.], [2., 4.]])); assert_eq!(m.flip_sub_diagonal(), ndarray::arr2(&[[4., 2.], [3., 1.]])); } #[test] fn test_part1() { let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part1_solution(&result), 20899048083289); } #[test] fn test_part2() { let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part2_solution(&test_image, &result), 273); } }
true
08942663e7d7108894e82425fe1534e30dddb72b
Rust
mtak-/swym
/src/internal/alloc/dyn_vec.rs
UTF-8
16,802
2.96875
3
[ "MIT" ]
permissive
//! An contiguous container of Dynamically Sized Types. use core::{ borrow::{Borrow, BorrowMut}, marker::PhantomData, mem::{self, ManuallyDrop}, ops::{Deref, DerefMut}, ptr::{self, NonNull}, }; #[repr(C)] #[derive(Copy, Clone)] pub struct TraitObject { pub data: *mut (), pub vtable: *mut (), } impl TraitObject { #[inline] pub fn from_pointer<T: ?Sized>(fat: NonNull<T>) -> Self { assert_eq!(mem::size_of::<Self>(), mem::size_of::<NonNull<T>>()); unsafe { mem::transmute_copy::<NonNull<T>, Self>(&fat) } } #[inline] pub unsafe fn from_flat(flat: NonNull<usize>) -> Self { let vtable = (*flat.as_ref()) as *mut (); let data = flat.as_ptr().add(1) as *mut (); TraitObject { data, vtable } } #[inline] pub unsafe fn cast<T: ?Sized>(self) -> NonNull<T> { debug_assert!(!self.data.is_null()); debug_assert!(!self.vtable.is_null()); assert_eq!(mem::size_of::<Self>(), mem::size_of::<NonNull<T>>()); let result = mem::transmute_copy::<Self, NonNull<T>>(&self); debug_assert!(mem::align_of_val(result.as_ref()) <= mem::align_of::<usize>()); result } } #[inline] pub fn vtable<T: ?Sized>(value: &T) -> *mut () { TraitObject::from_pointer(value.into()).vtable } macro_rules! dyn_vec_decl { ($vis:vis struct $name:ident: $trait:path;) => { #[repr(C)] #[derive(Debug)] $vis struct $name<'a> { data: $crate::internal::alloc::FVec<usize>, phantom: ::core::marker::PhantomData<dyn $trait + 'a>, } impl Drop for $name<'_> { fn drop(&mut self) { self.clear() } } #[allow(unused)] impl<'a> $name<'a> { #[inline] $vis fn new() -> Self { $name { data: $crate::internal::alloc::FVec::new(), phantom: ::core::marker::PhantomData, } } #[inline] $vis fn with_capacity(capacity: usize) -> Self { $name { data: $crate::internal::alloc::FVec::with_capacity(capacity), phantom: ::core::marker::PhantomData, } } #[inline] $vis fn is_empty(&self) -> bool { self.data.is_empty() } #[inline] $vis fn word_capacity(&self) -> usize { self.data.capacity() } #[inline] $vis fn word_len(&self) -> usize { self.data.len() } #[inline] $vis unsafe fn word_index_unchecked(&self, word_index: usize) -> &(dyn $trait + 'a) { let raw = $crate::internal::alloc::dyn_vec::TraitObject::from_flat(self.data.get_unchecked(word_index).into()); &*raw.cast().as_ptr() } #[inline] $vis unsafe fn word_index_unchecked_mut(&mut self, word_index: usize) -> $crate::internal::alloc::dyn_vec::DynElemMut<'_, dyn $trait + 'a> { let raw = $crate::internal::alloc::dyn_vec::TraitObject::from_flat(self.data.get_unchecked_mut(word_index).into()); $crate::internal::alloc::dyn_vec::DynElemMut::from_raw(&mut *raw.cast().as_ptr()) } #[inline] $vis fn next_push_allocates<U: $trait>(&self) -> bool { assert!( mem::align_of::<U>() == mem::align_of::<usize>(), "over/under aligned types are currently unimplemented" ); debug_assert!(mem::size_of::<$crate::internal::alloc::dyn_vec::Elem<U>>() % mem::size_of::<usize>() == 0); self.data .next_n_pushes_allocates(mem::size_of::<$crate::internal::alloc::dyn_vec::Elem<U>>() / mem::size_of::<usize>()) } #[inline] $vis fn push<U: $trait>(&mut self, u: U) { assert!( mem::align_of::<U>() == mem::align_of::<usize>(), "over/under aligned types are currently unimplemented" ); let elem = $crate::internal::alloc::dyn_vec::Elem::new($crate::internal::alloc::dyn_vec::vtable::<dyn $trait>(&u), u); self.data.extend(elem.as_slice()); mem::forget(elem) } #[inline] $vis unsafe fn push_unchecked<U: $trait>(&mut self, u: U) { assert!( mem::align_of::<U>() == mem::align_of::<usize>(), "over/under aligned types are currently unimplemented" ); let elem = $crate::internal::alloc::dyn_vec::Elem::new($crate::internal::alloc::dyn_vec::vtable::<dyn $trait>(&u), u); self.data.extend_unchecked(elem.as_slice()); mem::forget(elem) } #[inline] $vis fn clear(&mut self) { self.drain().for_each(|_| {}) } #[inline] $vis fn clear_no_drop(&mut self) { self.data.clear(); } #[inline] $vis fn iter(&self) -> $crate::internal::alloc::dyn_vec::Iter<'_, dyn $trait> { unsafe { $crate::internal::alloc::dyn_vec::Iter::new( self.data.iter() ) } } #[inline] $vis fn iter_mut(&mut self) -> $crate::internal::alloc::dyn_vec::IterMut<'_, dyn $trait> { unsafe { $crate::internal::alloc::dyn_vec::IterMut::new( self.data.iter_mut() ) } } #[inline] $vis fn drain(&mut self) -> $crate::internal::alloc::dyn_vec::Drain<'_, dyn $trait> { let slice: &mut [_] = &mut self.data; let raw: ::core::ptr::NonNull<_> = slice.into(); self.data.clear(); unsafe { $crate::internal::alloc::dyn_vec::Drain::new( (*raw.as_ptr()).iter_mut() ) } } } impl<'a> IntoIterator for &'a $name<'_> { type IntoIter = $crate::internal::alloc::dyn_vec::Iter<'a, dyn $trait + 'static>; type Item = &'a (dyn $trait + 'static); #[inline] fn into_iter(self) -> $crate::internal::alloc::dyn_vec::Iter<'a, dyn $trait> { self.iter() } } impl<'a> IntoIterator for &'a mut $name<'_> { type IntoIter = $crate::internal::alloc::dyn_vec::IterMut<'a, dyn $trait>; type Item = $crate::internal::alloc::dyn_vec::DynElemMut<'a, dyn $trait>; #[inline] fn into_iter(self) -> $crate::internal::alloc::dyn_vec::IterMut<'a, dyn $trait> { self.iter_mut() } } }; } #[repr(C)] pub struct Elem<U> { vtable: *const (), elem: U, } impl<U> Elem<U> { #[inline] pub fn new(vtable: *const (), elem: U) -> Self { Elem { vtable, elem } } #[inline] pub fn as_slice(&self) -> &[usize] { unsafe { core::slice::from_raw_parts( self as *const _ as _, mem::size_of::<Self>() / mem::size_of::<usize>(), ) } } } #[derive(Debug)] pub struct DynElemMut<'a, T: ?Sized> { value: &'a mut T, } impl<'a, T: ?Sized> DynElemMut<'a, T> { pub unsafe fn from_raw(value: &'a mut T) -> Self { DynElemMut { value } } } impl<'a, T: ?Sized> Deref for DynElemMut<'a, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<'a, T: ?Sized> DerefMut for DynElemMut<'a, T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.value } } impl<'a, T: ?Sized> DynElemMut<'a, T> { #[inline] pub unsafe fn assign_unchecked<U>(this: Self, new_vtable: *const (), rhs: U) { debug_assert_eq!( mem::size_of_val(this.value), mem::size_of::<U>(), "attempt to assign DynElemMut a value with a different size" ); debug_assert!( mem::align_of_val(this.value) >= mem::align_of::<U>(), "attempt to assign DynElemMut a value with an incompatible alignment" ); debug_assert!( mem::align_of_val(this.value) <= mem::align_of::<*const ()>(), "attempt to assign DynElemMut a value with an incompatible alignment" ); // not the safest code ever let mut punned = ManuallyDrop::new(ptr::read(this.value as *const T as *const U)); let vtable_storage; let old_raw = { let mut raw = TraitObject::from_pointer(this.value.into()); vtable_storage = (mem::replace(&mut raw.data, &mut punned as *mut _ as _) as *mut *const ()).sub(1); raw }; vtable_storage.write(new_vtable); (this.value as *mut T as *mut U).write(rhs); ptr::drop_in_place(mem::transmute_copy::<_, *mut T>(&old_raw)); } } #[derive(Debug)] pub struct Iter<'a, T: ?Sized> { iter: core::slice::Iter<'a, usize>, phantom: PhantomData<&'a T>, } impl<'a, T: ?Sized> Iter<'a, T> { pub unsafe fn new(iter: core::slice::Iter<'a, usize>) -> Self { Iter { iter, phantom: PhantomData, } } } impl<'a, T: ?Sized> Iterator for Iter<'a, T> { type Item = &'a T; #[inline] fn next(&mut self) -> Option<Self::Item> { unsafe { let raw = TraitObject::from_flat(self.iter.next()?.into()); let result = &*raw.cast().as_ptr(); let size = mem::size_of_val(result); debug_assert!( size % mem::size_of::<usize>() == 0, "invalid size detected for dyn T" ); for _ in 0..size / mem::size_of::<usize>() { match self.iter.next() { None => core::hint::unreachable_unchecked(), _ => {} } } Some(result) } } } #[derive(Debug)] pub struct IterMut<'a, T: ?Sized> { iter: core::slice::IterMut<'a, usize>, phantom: PhantomData<&'a mut T>, } impl<'a, T: ?Sized> IterMut<'a, T> { pub unsafe fn new(iter: core::slice::IterMut<'a, usize>) -> Self { IterMut { iter, phantom: PhantomData, } } } impl<'a, T: ?Sized> Iterator for IterMut<'a, T> { type Item = DynElemMut<'a, T>; #[inline] fn next(&mut self) -> Option<Self::Item> { unsafe { let raw = TraitObject::from_flat(self.iter.next()?.into()); let result = &mut *raw.cast().as_ptr(); let size = mem::size_of_val(result); debug_assert!( size % mem::size_of::<usize>() == 0, "invalid size detected for dyn T" ); for _ in 0..size / mem::size_of::<usize>() { match self.iter.next() { None => core::hint::unreachable_unchecked(), _ => {} } } Some(DynElemMut { value: result }) } } } pub struct Owned<'a, T: ?Sized> { value: &'a mut T, } impl<'a, T: ?Sized> Drop for Owned<'a, T> { #[inline] fn drop(&mut self) { unsafe { ptr::drop_in_place(self.value) } } } impl<'a, T: ?Sized> Borrow<T> for Owned<'a, T> { #[inline] fn borrow(&self) -> &T { self.value } } impl<'a, T: ?Sized> BorrowMut<T> for Owned<'a, T> { #[inline] fn borrow_mut(&mut self) -> &mut T { self.value } } impl<'a, T: ?Sized> Deref for Owned<'a, T> { type Target = T; #[inline] fn deref(&self) -> &Self::Target { self.value } } impl<'a, T: ?Sized> DerefMut for Owned<'a, T> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { self.value } } pub struct Drain<'a, T: ?Sized> { iter: IterMut<'a, T>, phantom: PhantomData<Box<T>>, } impl<'a, T: ?Sized> Drain<'a, T> { pub unsafe fn new(iter: core::slice::IterMut<'a, usize>) -> Self { Drain { iter: IterMut::new(iter), phantom: PhantomData, } } } impl<'a, T: 'a + ?Sized> Iterator for Drain<'a, T> { type Item = Owned<'a, T>; #[inline] fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|DynElemMut { value }| Owned { value }) } } #[cfg(test)] mod trait_object { #[cfg(feature = "nightly")] #[test] fn layout() { use super::TraitObject; use core::{mem, raw::TraitObject as StdTraitObject}; assert_eq!( mem::size_of::<TraitObject>(), mem::size_of::<StdTraitObject>() ); assert_eq!( mem::align_of::<TraitObject>(), mem::align_of::<StdTraitObject>() ); let x = String::from("hello there"); unsafe { let y: &dyn core::fmt::Debug = &x; let std = mem::transmute::<&dyn core::fmt::Debug, StdTraitObject>(y); let raw = TraitObject::from_pointer(y.into()); assert_eq!(raw.vtable, std.vtable); assert_eq!(raw.data, std.data); } } } #[cfg(test)] mod test { use super::*; use core::any::Any; trait MyAny: Send { fn as_any<'a>(&'a self) -> &'a (dyn Any + 'static); } impl<T: Any + Send> MyAny for T { fn as_any<'a>(&'a self) -> &'a (dyn Any + 'static) { &*self } } dyn_vec_decl! { struct AnyDynVec: MyAny; } #[test] fn iter() { let mut v = AnyDynVec::with_capacity(0); assert!(v.iter().next().is_none()); let first: Vec<usize> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; v.push(first.clone()); let second = [42usize; 3]; v.push(second.clone()); let mut iter = v.iter(); let first_ref = iter.next().unwrap(); let first_ref = first_ref.as_any().downcast_ref::<Vec<usize>>().unwrap(); assert_eq!(&first, first_ref); let second_ref = iter.next().unwrap(); let second_ref = second_ref.as_any().downcast_ref::<[usize; 3]>().unwrap(); assert_eq!(&second, second_ref); assert!(iter.next().is_none()); } #[test] fn iter_mut() { dyn_vec_decl! { struct SliceDynVec: AsMut<[usize]>; } let mut v = SliceDynVec::with_capacity(0); assert!(v.iter_mut().next().is_none()); let first: Vec<usize> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; v.push(first.clone()); let second = [42usize; 3]; v.push(second.clone()); let mut iter = v.iter_mut(); let mut first_mut_ref = iter.next().unwrap(); assert_eq!(first.as_slice(), first_mut_ref.as_mut()); let mut second_mut_ref = iter.next().unwrap(); assert_eq!(&second, second_mut_ref.as_mut()); assert!(iter.next().is_none()); let mut iter = v.iter_mut(); let first_mut_ref = iter.next().unwrap(); unsafe { DynElemMut::assign_unchecked( first_mut_ref, vtable::<dyn AsMut<[usize]>>(&second), second, ); } let mut iter = v.iter_mut(); assert_eq!(&second, iter.next().unwrap().as_mut()); } #[test] fn drain() { use core::cell::Cell; thread_local! { static DROP_COUNT: Cell<usize> = Cell::new(0); } struct Bar(usize); impl Drop for Bar { fn drop(&mut self) { DROP_COUNT.with(|x| x.set(x.get() + self.0)); } } let mut v = AnyDynVec::with_capacity(0); v.push(Bar(42)); v.push(Bar(43)); let mut iter = v.drain(); let first = iter.next().unwrap(); assert_eq!(DROP_COUNT.with(|x| x.get()), 0); drop(first); assert_eq!(DROP_COUNT.with(|x| x.get()), 42); let second = iter.next().unwrap(); assert_eq!(DROP_COUNT.with(|x| x.get()), 42); drop(second); assert_eq!(DROP_COUNT.with(|x| x.get()), 85); assert!(iter.next().is_none()); assert!(v.is_empty()); v.push(Bar(42)); v.push(Bar(43)); assert!(!v.is_empty()); core::mem::forget(v.drain()); assert!(v.is_empty()); drop(v); assert_eq!(DROP_COUNT.with(|x| x.get()), 85); } }
true
36705f0db2eb3ea61b33848f7a77fee4e34d2931
Rust
usagi/vec-dimension-shift
/examples/d2_and_d3.rs
UTF-8
840
2.859375
3
[ "MIT" ]
permissive
use vec_dimension_shift::{ VecDimensionShift2D, VecDimensionShift2DFlatten, VecDimensionShift3D, VecDimensionShift3DFlatten }; fn d2_and_d3() { let original = vec![0.0, 1.1, 2.2, 3.3, 4.4, 5.5]; dbg!(&original); let mut d2_shifted = original.as_2d_array().unwrap(); dbg!(&d2_shifted); assert_eq!(d2_shifted[0], [0.0, 1.1]); assert_eq!(d2_shifted[1], [2.2, 3.3]); assert_eq!(d2_shifted[2], [4.4, 5.5]); d2_shifted[1][1] = -1.0; let flatten = d2_shifted.as_flatten(); dbg!(&flatten); let mut d3_shifted = flatten.as_3d_array().unwrap(); dbg!(&d3_shifted); assert_eq!(d3_shifted[0], [0.0, 1.1, 2.2]); assert_eq!(d3_shifted[1], [-1.0, 4.4, 5.5]); d3_shifted[1][1] = -2.0; let flatten = d3_shifted.as_flatten(); dbg!(&flatten); assert_eq!(flatten, vec![0.0, 1.1, 2.2, -1.0, -2.0, 5.5]) } fn main() { d2_and_d3(); }
true
1ee8829702da7ee9a3024e7e32d614167e15fd3c
Rust
jo12bar/weekend-tracer-rs
/src/pdf/mod.rs
UTF-8
2,318
3.53125
4
[ "Unlicense" ]
permissive
//! Probability Density Functions (PDFs), and their associated structs and methods. pub mod cosine_pdf; pub mod hittable_pdf; pub mod mixture_pdf; use crate::{hittable::Hittable, vec3::Vec3}; use rand::prelude::*; use std::sync::Arc; /// A probability density function. Supports generating either floats or vectors. #[derive(Clone, Debug)] pub enum PDF { Cosine(cosine_pdf::CosinePDF), Hittable(hittable_pdf::HittablePDF), Mixture(mixture_pdf::MixturePDF), } impl PDF { /// Create a new cosine density PDF. pub fn cosine(w: Vec3) -> Self { Self::Cosine(cosine_pdf::CosinePDF::new(w)) } /// Create a new PDF for some `Hittable` object. pub fn hittable(obj: Arc<dyn Hittable>, origin: Vec3) -> Self { Self::Hittable(hittable_pdf::HittablePDF::new(obj, origin)) } /// Mix together two PDFs with a 50/50 split. pub fn mixture(pdf1: &Self, pdf2: &Self) -> Self { Self::Mixture(mixture_pdf::MixturePDF(pdf1.box_clone(), pdf2.box_clone())) } /// Generate a float for some vector. /// Calls the `value()` method on the underlying PDF struct. pub fn value(&self, direction: &Vec3) -> f32 { match self { Self::Cosine(c) => c.value(direction), Self::Hittable(h) => h.value(direction), Self::Mixture(m) => m.value(direction), } } /// Generate a vector. /// Calls the `generate()` method on the underlying PDF struct. pub fn generate<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 { match self { Self::Cosine(c) => c.generate(rng), Self::Hittable(h) => h.generate(rng), Self::Mixture(m) => m.generate(rng), } } /// Clone the PDF into a `Box<PDF>`. pub fn box_clone(&self) -> Box<PDF> { Box::new(self.clone()) } } /// A utility function for getting a special PDF-ready vector on a sphere. pub fn random_to_sphere<R: Rng + ?Sized>(rng: &mut R, radius: f32, distance_squared: f32) -> Vec3 { let r1: f32 = rng.gen(); let r2: f32 = rng.gen(); let z = 1.0 + r2 * ((1.0 - radius * radius / distance_squared).sqrt() - 1.0); let phi = 2.0 * std::f32::consts::PI * r1; let x = phi.cos() * (1.0 - z * z).sqrt(); let y = phi.sin() * (1.0 - z * z).sqrt(); Vec3::new(x, y, z) }
true
57ea5dd72de15361d7c63b03d32e651764319de9
Rust
RusPiRo/ruspiro-mailbox
/src/propertytags/mod.rs
UTF-8
20,083
3.03125
3
[ "MIT", "Apache-2.0" ]
permissive
/*********************************************************************************************************************** * Copyright (c) 2020 by the authors * * Author: André Borrmann <pspwizard@gmx.de> * License: Apache License 2.0 / MIT **********************************************************************************************************************/ //! # Property Tag definitions //! //! This module defines all possible property tags and provides the message definitions for a set of //! property tags that are currently supported and could be accessed with the corresponding functions //! of the Mailbox accessor or being used as part of a batch request. //! //! # Example //! //! ```no_run //! # use ruspiro_mailbox::*; //! # fn doc() { //! let mut mb = Mailbox::new(); //! // create a property tag to request the clock rate of the core clock. //! let tag = ClockrateGet::new(ClockId::Core); //! // this could be used in a batch message like so //! let batch = MailboxBatch::empty().with_tag(tag); //! if let Ok(response) = mb.send_batch(batch) { //! println!("Core rate: {}", response.get_tag::<ClockrateGet, _>().response().clock_rate()); //! } //! //! // more convinient for single property tags to be processed is to use the corresponding //! // functions of the mailbox accessor //! if let Ok(clock_rate) = mb.get_clockrate(ClockId::Core) { //! println!("Core rate: {}", clock_rate); //! } //! # } //! ``` use crate::{ClockId, DeviceId, VoltageId}; #[macro_use] mod macros; /// Proprty tag ID's used for the different mailbox messages /// The same id's have to be used to define the property tag structures /// as the mailbox request message tag id will be automatically set #[repr(u32)] #[allow(dead_code)] #[derive(Copy, Clone, Debug)] pub enum PropertyTagId { /// Retrieve the firmware revision code FirmwareRevisionGet = 0x0_0001, /// Retrieve the board model code BoardModelGet = 0x1_0001, /// Retrieve the board revision code. /// Check https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md /// for a decoding of the returned value. BoardRevisionGet = 0x1_0002, /// Retrieve the serial number BoardSerialGet = 0x1_0004, /// Retrieve ARM memory base address and size ArmMemoryGet = 0x1_0005, /// Retrieve the MAC address BoardMACAddressGet = 0x1_0003, /// Retrieve VC/GPU memory base address and size VcMemoryGet = 0x1_0006, /// Retrieve all usable DMA channels DmaChannelsGet = 0x6_0001, /// Get the power state of a specific device PowerStateGet = 0x2_0001, /// Set the power state of a specific device PowerStateSet = 0x2_8001, /// Get the state of a specific clock ClockStateGet = 0x3_0001, /// Set the state of a specific clock ClockStateSet = 0x3_8001, /// Reading the current clock rate of a given clock ID ClockrateGet = 0x3_0002, /// Setting the current clockrate of a given clock ID ClockrateSet = 0x3_8002, /// Get the max possible rate for a given clock ID MaxClockrateGet = 0x3_0004, /// Get the minimal possible rate for a given clock ID MinClockrateGet = 0x3_0007, /// Get the current voltage value for the given [VoltageId] VoltageGet = 0x3_0003, /// Set the current voltage value for the given [VoltageId] VoltageSet = 0x3_8003, /// Get the maximum voltage value for the given [VoltageId] MaxVoltageGet = 0x3_0005, /// Get the minimum voltage value for the given [VoltageId] MinVoltageGet = 0x3_0008, /// Retrieve the current temperature in thousandths of a degree Celsius TemperatureGet = 0x3_0006, /// Retrieve the maximum safe temperature in thousandths of a degree Celsius MaxTemperatureGet = 0x3_000A, /// Allocate a frame buffer based on the size and pixel config given in a batch mailbox message FramebufferAllocate = 0x4_0001, /// Release and disable the frame buffer FramebufferRelease = 0x4_8001, /// clear the framebuffer (only the virtual part?) BlankScreen = 0x4_0002, /// Retrieve the current physical (display) size of the frame buffer PhysicalSizeGet = 0x4_0003, /// Set the physical (display) size of the frame buffer (allocation will be made based on this size, even /// though there might be pitching applied to the requested width) PhysicalSizeSet = 0x4_8003, /// Retrieve the virtual display size VirtualSizeGet = 0x4_0004, /// Set the virtual display size that has to be less than or equal to the physical size and is the /// visible part of the frame buffer VirtualSizeSet = 0x4_8004, /// Get the actual pixel bit depth DepthGet = 0x4_0005, /// Set the actual pixel bit depth DepthSet = 0x4_8005, /// Retrieve the current pixel color ordering PixelOrderGet = 0x4_0006, /// Set the pixel color ordering (RGB or BGR) PixelOrderSet = 0x4_8006, /// Retrieve the current alpha mode setting AlphaModeGet = 0x4_0007, /// Set the alpha mode AlphaModeSet = 0x4_8007, /// Get the actual pitch for the physical (display) size PitchGet = 0x4_0008, /// Retrieve the current offset of the virtual buffer into the physical one VirtualOffsetGet = 0x4_0009, /// Set the offset of the virtual buffer into the physical one in pixels VirtualOffsetSet = 0x4_8009, /// Retrieve the current overscan settings OverscanGet = 0x4_000A, /// Set the overscan values OverscanSet = 0x4_800A, /// Retrieve the current used palette color values PaletteGet = 0x4_000B, /// Set/Update the palette color values PaletteSet = 0x4_800B, /// VideoCore Host Interface initialization VchiqInit = 0x4_8010, /* not yet implemented property tags ClocksGet = 0x1_0007, TimingGet = 0x2_0002, TurboGet = 0x3_0009, TurboSet = 0x3_8009, MemoryAllocate = 0x3_000C, MemoryLock = 0x3_000D, MemoryUnlock = 0x3_000E, MemoryRelease = 0x3_000F, ExecuteCode = 0x3_0010, */ } /// The trait that each PropertyTag need to implement. The most convinient way to define mailbox /// property tags is to use the corresponding macro. This will create the required /// structure and implement this trait accoridingly pub trait PropertyTag: Send { /// Type of the property tag request type Request; /// Type of the property tag response type Response; /// Return the [PropertyTagId] of this property tag fn tagid(&self) -> PropertyTagId; /// Return the current state of the property tag. This value is 0x0 for Requests and for a /// response the bit 31 is set to 1 and bits \[30..0\] contains the size of the response as it /// is known to the sender. If this value is greater then the payload passed as the size value /// for this tag, the response is truncated to fit into the response payload buffer provided. fn state(&self) -> u32; /// Return the reference to the response data of this property tag fn response(&self) -> &Self::Response; /// Returns the size of the property tag as defined by it's structure definition fn size(&self) -> u32; } property_tag!( /// Retrieve the VideoCore firmware revision FirmwareRevisionGet: { REQUEST: {}, RESPONSE: { firmware_revision: u32 } } ); property_tag!( /// Retrieve the current board model BoardModelGet: { REQUEST: {}, RESPONSE: { board_model: u32 } } ); property_tag!( /// Retrieve the board revision code. Refer to /// https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md for /// the encoding of it. BoardRevisionGet: { REQUEST: {}, RESPONSE: { board_revision: u32 } } ); property_tag!( /// Retrieve the MAC address of this Raspberry Pi. The address is given in "network byte order" BoardMACAddressGet: { REQUEST: { }, RESPONSE: { mac_address: [u8;6] }, PADDING: u16 } ); property_tag!( /// Retrieve the board serial number BoardSerialGet: { REQUEST: {}, RESPONSE: { board_serial: u32 } } ); property_tag!( /// Get the memory base address and size that is dedicated to the ARM CPU. The split between /// Arm and GPU can be configured in the config.txt file that need to be present on the SD card /// while booting the Raspberry Pi. ArmMemoryGet: { REQUEST: {}, RESPONSE: { base_address: u32, size: u32 } } ); property_tag!( /// Get the memory base and size that is dedicated to the VideoCore/GPU. The split between /// Arm and GPU can be configured in the config.txt file that need to be present on the SD card /// while booting the Raspberry Pi. VcMemoryGet: { REQUEST: {}, RESPONSE: { base_address: u32, size: u32 } } ); property_tag!( /// Get the DMA channels that are usable /// Response: /// Bits 0-15 represents the DMA channels 0-15. If the corresponding bit is set for a /// channel it is usable. Bits 16-31 are reserved DmaChannelsGet: { REQUEST: {}, RESPONSE: { channel_mask: u32 } } ); property_tag!( /// Retrieve the power state of a device PowerStateGet: { REQUEST: { device_id: DeviceId }, RESPONSE: { device_id: DeviceId, state: u32 } } ); property_tag!( /// Set the power sate of a device PowerStateSet: { REQUEST: { device_id: DeviceId, state: u32 }, RESPONSE: { device_id: DeviceId, state: u32 } } ); property_tag!( /// Retrieve the current state of a clock ClockStateGet: { REQUEST: { clock_id: ClockId }, RESPONSE: { clock_id: ClockId, state: u32 } } ); property_tag!( /// Set the state of a clock ClockStateSet: { REQUEST: { clock_id: ClockId, state: u32 }, RESPONSE: { clock_id: ClockId, state: u32 } } ); property_tag! ( /// Retrieve the current clock rate in Hz. A value of 0 indicates that the /// specified clock does not exist. The rate is returned even if the clock is not active ClockrateGet: { REQUEST: { clock_id: ClockId }, RESPONSE: { clock_id: ClockId, clock_rate: u32 } } ); property_tag! ( /// Set the current clock rate in Hz to the next supported value. Setting the Arm clock will /// activate turbo settings for other devices. This can be ommited by passing 'skip_turbo' as 1 ClockrateSet: { REQUEST: { clock_id: ClockId, clock_rate: u32, skip_turbo: u32 }, RESPONSE: { clock_id: ClockId, clock_rate: u32 } } ); property_tag!( /// Retrieve the maximum available rate in Hz for a clock MaxClockrateGet: { REQUEST: { clock_id: ClockId }, RESPONSE: { clock_id: ClockId, clock_rate: u32 } } ); property_tag!( /// Retrieve the minimum available rate in Hz for a clock MinClockrateGet: { REQUEST: { clock_id: ClockId }, RESPONSE: { clock_id: ClockId, clock_rate: u32 } } ); property_tag!( /// Retrieve the current voltage of the given [VoltageId]. The value represents an offset from /// 1.2V in units of 0.025V. VoltageGet: { REQUEST: { voltage_id: VoltageId }, RESPONSE: { voltage_id: VoltageId, value: u32 } } ); property_tag!( /// Set the current voltage of the given [VoltageId]. The value represents an offset from /// 1.2V in units of 0.025V. VoltageSet: { REQUEST: { voltage_id: VoltageId, value: u32 }, RESPONSE: { voltage_id: VoltageId, value: u32 } } ); property_tag!( /// Retrieve the maximum supported voltage of the given [VoltageId]. The value represents an offset from /// 1.2V in units of 0.025V. MaxVoltageGet: { REQUEST: { voltage_id: VoltageId }, RESPONSE: { voltage_id: VoltageId, value: u32 } } ); property_tag!( /// Retrieve the minimum supported voltage of the given [VoltageId]. The value represents an offset from /// 1.2V in units of 0.025V. MinVoltageGet: { REQUEST: { voltage_id: VoltageId }, RESPONSE: { voltage_id: VoltageId, value: u32 } } ); property_tag!( /// Retrieve the current temperature in thousandths of a degree Celsius. The temperature id /// should always be passed as 0 TemperatureGet: { REQUEST: { temperature_id: u32 }, RESPONSE: { temperature_id: u32, value: u32 } } ); property_tag!( /// Retrieve the maximum safe temperature in thousandths of a degree Celsius. The temperature id /// should always be passed as 0. Above this temperature the CPU might turn off overclock. MaxTemperatureGet: { REQUEST: { temperature_id: u32 }, RESPONSE: { temperature_id: u32, value: u32 } } ); property_tag!( /// Allocate a frame buffer with the given byte alignment FramebufferAllocate: { REQUEST: { alignment: u32 }, RESPONSE: { base_address: u32, size: u32 } } ); property_tag!( /// Release and disable the framebuffer FramebufferRelease: { REQUEST: {}, RESPONSE: {} } ); property_tag!( BlankScreen: { REQUEST: { state: u32 }, RESPONSE: { state: u32 } } ); property_tag!( /// Retrieve the physical display/framebuffer size which actually is the the size of the allocated /// frame buffer but usually larger than the displayed part that is passed to the monitor PhysicalSizeGet: { REQUEST: {}, RESPONSE: { width: u32, height: u32 } } ); property_tag!( /// Set the physical display/framebuffer size which actually is the the size of the allocated /// frame buffer but usually larger than the displayed part that is passed to the monitor. The size /// returned by this tag might not match the requested size but is the closest supported one or /// 0 if no matching supported configuration could be determined. PhysicalSizeSet: { REQUEST: { width: u32, height: u32 }, RESPONSE: { width: u32, height: u32 } } ); property_tag!( /// Retreive the virtual display/framebuffer size. This is actually the size of the buffer passed to /// the monitor and might be only a part of the allocated frame buffer VirtualSizeGet: { REQUEST: {}, RESPONSE: { width: u32, height: u32 } } ); property_tag!( /// Set the virtual display/framebuffer size. This is actually the size of the buffer passed to /// the monitor and might be only a part of the allocated frame buffer. The size returned by this /// tag might not match the requested size but is the closest supported one or 0 if no matching /// supported configuration could be determined. VirtualSizeSet: { REQUEST: { width: u32, height: u32 }, RESPONSE: { width: u32, height: u32 } } ); property_tag!( /// Retrieve the bits per pixel used for depth information DepthGet: { REQUEST: {}, RESPONSE: { depth: u32 } } ); property_tag!( /// Set the bits per pixel used for depth information. If the provided depth value is not supported /// it will return 0 in the response. DepthSet: { REQUEST: { depth: u32 }, RESPONSE: { depth: u32 } } ); property_tag!( /// Retrieve the current pixel order. The returned value is:<br> /// 0x0 - BGR<br> /// 0x1 - RGB PixelOrderGet: { REQUEST: {}, RESPONSE: { order: u32 } } ); property_tag!( /// Set the current pixel order. The possible values are:<br> /// 0x0 - BGR<br> /// 0x1 - RGB PixelOrderSet: { REQUEST: { order: u32 }, RESPONSE: { order: u32 } } ); property_tag!( /// Retrieve the current alpha mode. The possible values are:<br> /// 0x0 - alpha enabled, 0x0 in this channel of a pixel means full opaque /// 0x1 - alpha enabled, 0x0 in this channel of a pixel means full transparent /// 0x2 - alpha ignored, value in this channel of a pixel is ignored AlphaModeGet: { REQUEST: {}, RESPONSE: { mode: u32 } } ); property_tag!( /// Retrieve the current alpha mode. The possible values are:<br> /// 0x0 - alpha enabled, 0x0 in this channel of a pixel means full opaque /// 0x1 - alpha enabled, 0x0 in this channel of a pixel means full transparent /// 0x2 - alpha ignored, value in this channel of a pixel is ignored /// If the rsponded mode differs from the requested it might not be supported AlphaModeSet: { REQUEST: { mode: u32 }, RESPONSE: { mode: u32 } } ); property_tag!( /// Retrieve the pitch in bytes per line PitchGet: { REQUEST: {}, RESPONSE: { pitch: u32 } } ); property_tag!( /// Retrieve the current offset that is applied when retrieving the virtual display from the /// physical one. VirtualOffsetGet: { REQUEST: {}, RESPONSE: { offset_x: u32, offset_y: u32 } } ); property_tag!( /// Set the current offset that is applied when retrieving the virtual display from the /// physical one. VirtualOffsetSet: { REQUEST: { offset_x: u32, offset_y: u32 }, RESPONSE: { offset_x: u32, offset_y: u32 } } ); property_tag!( OverscanGet: { REQUEST: {}, RESPONSE: { top: u32, bottom: u32, left: u32, right: u32 } } ); property_tag!( OverscanSet: { REQUEST: { top: u32, bottom: u32, left: u32, right: u32 }, RESPONSE: { top: u32, bottom: u32, left: u32, right: u32 } } ); property_tag!( /// Retrieve the current palette color entries PaletteGet: { REQUEST: {}, RESPONSE: { palette: [u32; 256] } } ); property_tag!( /// Set/update the palette entries. As the palette buffer given is always a fixed sized array the /// offset need to be 0 and the length 256 and all palette colors need to be passed. PaletteSet: { REQUEST: { offset: u32, length: u32, palette: [u32; 256] }, RESPONSE: { status: u32 } } ); property_tag!( /// Set the base address of the memory region used for the VCHIQ transmissions between ARM and GPU (VideoCore) VchiqInit: { REQUEST: { base_address: u32 }, RESPONSE: { status: u32 } } );
true
6610b015b7a371ac8d908d1a8325b7de776586c1
Rust
MDoerner/AdventOfCode2020
/Rust/adventOfCode2020/src/day/day15.rs
UTF-8
5,759
3.40625
3
[]
no_license
use std::collections::HashMap; use std::convert::TryFrom; pub struct Day15 {} impl super::Day for Day15{ type PuzzleInput = Vec<u128>; fn parse_input(&self, text: std::string::String) -> Self::PuzzleInput { text.split(',') .filter_map(|number| number.parse::<u128>().ok()) .collect() } fn solve_part1(&self, initial_numbers: Self::PuzzleInput) -> std::string::String { let number = number_spoken(&initial_numbers,2020 - 1); number.to_string() } fn solve_part2(&self, initial_numbers: Self::PuzzleInput) -> std::string::String { let number = number_spoken(&initial_numbers,30000000 - 1); number.to_string() } } fn number_spoken(initial_numbers: &[u128], position: u128) -> u128{ if initial_numbers.is_empty() && position == 0{ return 0; } let maybe_position_pointer = usize::try_from(position); //If these two conditions to not hold, position is guaranteed to be larger than or equal to initial_numbers.len(), //since the first conversion can only fail because position is larger than any usize. if let Ok(position_pointer) = maybe_position_pointer{ if position_pointer < initial_numbers.len(){ return initial_numbers[position_pointer]; } } let mut memory = initial_memory(initial_numbers); //The conversion cannot fail because we already know that the valid u128 position is larger at least as large as nitial_numbers.len(). let start_position = u128::try_from(initial_numbers.len()).unwrap(); let last_initial_number = match initial_numbers.last() { Some(number) => number.to_owned(), None => 0, }; //This cannot be None since start_position is smaller than or equal to position. number_at_position(&mut memory, last_initial_number, start_position, position).unwrap() } fn initial_memory(initial_numbers: &[u128]) -> HashMap<u128, u128>{ let mut memory = HashMap::new(); if initial_numbers.is_empty(){ return memory; } for (index, number) in initial_numbers .split_last().unwrap().1 .iter() .enumerate() .filter_map(|(ind, value)| match u128::try_from(ind){ Ok(i) => Some((i, value.to_owned())), Err(_) => None, }){ memory.insert(number, index); } memory } fn number_at_position(memory: &mut HashMap<u128, u128>, initial_last_number: u128, start_position: u128, target_position: u128) -> Option<u128>{ if target_position < start_position{ return None; } let mut last_number = initial_last_number; for position in start_position..(target_position + 1){ let current_number = match memory.get(&last_number){ Some(previous_position) => (position- 1) -previous_position, None => 0, }; memory.insert(last_number, position - 1); last_number = current_number; } Some(last_number) } #[cfg(test)] mod day15_tests { use super::*; use crate::input; use crate::day; use rstest::rstest; #[rstest] #[case(1, 0)] #[case(2, 3)] #[case(3, 6)] #[case(4, 0)] #[case(5, 3)] #[case(6, 3)] #[case(7, 1)] #[case(8, 0)] #[case(9, 4)] #[case(10, 0)] fn number_spoken_tests(#[case] turn: u128, #[case] expected_result: u128) { let input = vec![0,3,6]; let actual_result = number_spoken(&input, turn - 1); assert_eq!(actual_result, expected_result); } #[rstest] #[case(String::from("0,3,6"), 436)] #[case(String::from("1,3,2"), 1)] #[case(String::from("2,1,3"), 10)] #[case(String::from("1,2,3"), 27)] #[case(String::from("2,3,1"), 78)] #[case(String::from("3,2,1"), 438)] #[case(String::from("3,1,2"), 1836)] fn examples_part1(#[case] problem_input: String, #[case] expected_result: u128) { let day: Box<dyn day::DaySolver> = Box::new(Day15{}); let expected_result = expected_result.to_string(); let actual_result = day.solve_part1(problem_input); assert_eq!(actual_result, expected_result); } /* Takes too long!!!! #[rstest] #[case(String::from("0,3,6"), 175594)] #[case(String::from("1,3,2"), 2578)] #[case(String::from("2,1,3"), 3544142)] #[case(String::from("1,2,3"), 261214)] #[case(String::from("2,3,1"), 6895259)] #[case(String::from("3,2,1"), 18)] #[case(String::from("3,1,2"), 362)] fn example_part2(#[case] problem_input: String, #[case] expected_result: u128) { let day: Box<dyn day::DaySolver> = Box::new(Day15{}); let expected_result = expected_result.to_string(); let actual_result = day.solve_part2(problem_input); assert_eq!(actual_result, expected_result); } */ #[test] fn correct_part1() { let day: Box<dyn day::DaySolver> = Box::new(Day15{}); let problem_input = input::puzzle_input(&input::PuzzleConfiguration{day: 15, part: 1}).unwrap(); let expected_result = String::from("929"); let actual_result = day.solve_part1(problem_input); assert_eq!(actual_result, expected_result); } /* Takes too long!!!! #[test] fn correct_part2() { let day: Box<dyn day::DaySolver> = Box::new(Day15{}); let problem_input = input::puzzle_input(&input::PuzzleConfiguration{day: 15, part: 2}).unwrap(); let expected_result = String::from("16671510"); let actual_result = day.solve_part2(problem_input); assert_eq!(actual_result, expected_result); } */ }
true
44286119538a7c64b63bbac8cb66ab7d6079685d
Rust
yjh0502/ch
/src/bin/osm-tools.rs
UTF-8
3,537
2.75
3
[]
no_license
use std::fs::File; use anyhow::Error; use clap::{Arg, Command}; use memmap::MmapOptions; use osmpbf::*; use rayon::prelude::*; type Result<T> = std::result::Result<T, Error>; // const FILENAME: &'static str = "data/planet-latest.osm.pbf"; const FILENAME: &'static str = "data/seoul.osm.pbf"; use std::f64; #[derive(Clone, Copy)] struct BBox { top: f64, bottom: f64, left: f64, right: f64, } impl BBox { fn new() -> Self { Self { top: f64::MIN, bottom: f64::MAX, left: f64::MAX, right: f64::MIN, } } fn push(&mut self, lat: f64, lon: f64) { self.top = f64::max(lat, self.top); self.bottom = f64::min(lat, self.bottom); self.left = f64::min(lon, self.left); self.right = f64::max(lon, self.right); } #[allow(unused)] fn is_empty(&self) -> bool { self.top <= self.bottom || self.right <= self.left } } impl std::fmt::Debug for BBox { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { if self.is_empty() { write!(fmt, "[bbox empty]") } else { write!( fmt, "[bbox top={} left={} bottom={} right={}]", self.top, self.left, self.bottom, self.right ) } } } #[derive(Debug)] struct Stats { bbox: BBox, node_count: usize, way_count: usize, rel_count: usize, } fn data_to_stats(block: &PrimitiveBlock) -> Stats { let mut stats = Stats { bbox: BBox::new(), node_count: 0, way_count: 0, rel_count: 0, }; for group in block.groups() { for node in group.nodes() { stats.node_count += 1; stats.bbox.push(node.lat(), node.lon()); } for node in group.dense_nodes() { stats.node_count += 1; stats.bbox.push(node.lat(), node.lon()); } stats.way_count += group.ways().count(); stats.rel_count += group.relations().count(); } stats } #[allow(unused)] fn seq_mmap(filename: &str) -> Result<()> { let file = File::open(filename)?; let mmap = unsafe { Mmap::from_file(&file) }.unwrap(); let mut blobs = Vec::new(); for blob in mmap.blob_iter() { blobs.push(blob.unwrap()); } blobs.par_iter().enumerate().for_each(|(i, blob)| { if let BlobDecode::OsmData(data) = blob.decode().unwrap() { let stats = data_to_stats(&data); eprintln!("{}/{:?}", i, stats); } }); println!("Number of blobs: {}", blobs.len()); Ok(()) } #[allow(unused)] fn par_mmap() -> Result<()> { let file = File::open(FILENAME)?; let mmap = unsafe { MmapOptions::new().map(&file)? }; let slice: &[u8] = &mmap; let reader = ElementReader::new(slice); // Count the ways let ways = reader .par_map_reduce( |element| match element { Element::Way(_) => 1, _ => 0, }, || 0_u64, // Zero is the identity value for addition |a, b| a + b, // Sum the partial results ) .unwrap(); println!("Number of ways: {}", ways); Ok(()) } fn main() { let args = Command::new("ch-build") .author("Jihyun Yu <j.yu@naverlabs.com>") .arg(Arg::new("filename").short('f').required(true)) .get_matches(); let filename = args.get_one::<String>("filename").unwrap(); seq_mmap(&filename).expect("failed to read"); }
true
da036c0579b449952fefb110b7b2db97a3990664
Rust
ralvescosta/rust_exercism
/triangle/src/lib.rs
UTF-8
699
3.515625
4
[]
no_license
use std::ops::Add; pub struct Triangle<T>(T, T, T); impl<T: Copy + PartialOrd + Add<Output = T>> Triangle<T> { pub fn build(sides: [T; 3]) -> Option<Triangle<T>> { let a = sides[0]; let b = sides[1]; let c = sides[2]; if a + b > c && b + c > a && a + c > b { return Some(Triangle(a, b, c)); } return None; } pub fn is_equilateral(&self) -> bool { self.0 == self.1 && self.1 == self.2 } pub fn is_scalene(&self) -> bool { self.0 != self.1 && self.0 != self.2 && self.1 != self.2 } pub fn is_isosceles(&self) -> bool { self.0 == self.1 || self.0 == self.2 || self.1 == self.2 } }
true
4bb909bb49e875c064facb6ed4fc09ef605153e7
Rust
phial3/hakutaku
/kern/src/device/pci/class.rs
UTF-8
5,490
2.625
3
[]
no_license
use super::class::HeaderType::*; use cpuio::UnsafePort; #[derive(Debug, Clone, Copy)] pub enum HeaderType { RegularDevice(u8), PCIBridge(u8), OtherHeaderType(u8) } impl HeaderType { pub fn is_multi_function(&self) -> bool { match self { RegularDevice(a) => { a & 0x80 != 0 }, PCIBridge(a) => { a & 0x80 != 0 }, OtherHeaderType(a) => { a & 0x80 != 0 }, } } } impl From<u8> for HeaderType { fn from(header: u8) -> Self { match header & 0x7F { 0x0 => RegularDevice(header), 0x1 => PCIBridge(header), _ => OtherHeaderType(header) } } } #[derive(Debug, Clone, Copy)] pub enum PCIDeviceClass { Unclassified(u8, u8), MassStorageController(PCIClassMassStorageClass), NetworkController(u8, u8), SerialBusController(PCISerialBusControllerClass), BridgeDevice(PCIBridgeDeviceClass), SimpleCommunicationController(PCISimpleCommunicationControllerClass), Other(u8, u8, u8) } impl PCIDeviceClass { pub fn from(class_group: u32) -> PCIDeviceClass { use self::PCIDeviceClass::*; let class = (class_group >> 16) as u8; let sub = (class_group >> 8) as u8; let progif = class_group as u8; match class { 0x01 => MassStorageController(PCIClassMassStorageClass::from(sub, progif)), 0x02 => NetworkController(sub, progif), 0x06 => BridgeDevice(PCIBridgeDeviceClass::from(sub, progif)), 0x07 => SimpleCommunicationController(PCISimpleCommunicationControllerClass::from(sub, progif)), 0x0C => SerialBusController(PCISerialBusControllerClass::from(sub, progif)), _ => Other(class, sub, progif) } } } #[derive(Debug, Copy, Clone)] pub enum PCIBridgeDeviceClass { HostBridge, ISABridge, PCItoPCIBridge(u8), PCItoPCIHostBridge(u8), Other(u8, u8) } impl PCIBridgeDeviceClass { pub fn from(sub: u8, progif: u8) -> Self { use self::PCIBridgeDeviceClass::*; match sub { 0x0 => HostBridge, 0x1 => ISABridge, 0x4 => PCItoPCIBridge(progif), 0x9 => PCItoPCIHostBridge(progif), _ => Other(sub, progif), } } } #[derive(Debug, Clone, Copy)] pub enum PCIClassMassStorageClass { /// Prog If IDEController(u8), FloppyDiskController, IPIBusController, RAIDController, ATAController(u8), SATA(PCIClassMassStroageSATA), SAS(u8), NonVolatileMemory(u8), Other(u8), Unknown(u8, u8) } #[derive(Debug, Clone, Copy)] pub enum PCIClassMassStroageSATA { AHCI, Other(u8) } impl PCIClassMassStroageSATA { pub fn from(prog_if: u8) -> PCIClassMassStroageSATA { match prog_if { 0x1 => PCIClassMassStroageSATA::AHCI, _ => PCIClassMassStroageSATA::Other(prog_if), } } } impl PCIClassMassStorageClass { pub fn from(sub: u8, prog_if: u8) -> PCIClassMassStorageClass { match sub { 0x06 => PCIClassMassStorageClass::SATA(PCIClassMassStroageSATA::from(prog_if)), _ => PCIClassMassStorageClass::Unknown(sub, prog_if), } } } #[derive(Debug, Clone, Copy)] pub enum PCIClassNetworkController { Ethernet, TokenRing, FDDI, ATM, ISDN, WorldFip, PICMG, Infiniband, Fabric, Other(u8, u8) } #[derive(Debug, Clone, Copy)] pub enum PCIClassDisplayController { VGACompatible(u8), XGA, NonVGACompatible3D, Other(u8, u8) } #[derive(Debug, Clone, Copy)] pub enum PCISerialBusControllerClass { FireWire(u8), ACCESSBus, SSA, USBController(PCISerialBusUSB), FibreChannel, SMBus, InfiniBand, IPMIInterface(u8), CAN, Other(u8, u8) } impl PCISerialBusControllerClass { pub fn from(sub: u8, progif: u8) -> PCISerialBusControllerClass { use self::PCISerialBusControllerClass::*; match sub { 0x0 => FireWire(progif), 0x1 => ACCESSBus, 0x2 => SSA, 0x3 => USBController(progif.into()), 0x4 => FibreChannel, _ => PCISerialBusControllerClass::Other(sub, progif) } } } #[derive(Debug, Copy, Clone)] pub enum PCISerialBusUSB { UHCI, OHCI, EHCI, XHCI, Other(u8), Device } impl From<u8> for PCISerialBusUSB { fn from(progif: u8) -> Self { use self::PCISerialBusUSB::*; match progif { 0x0 => UHCI, 0x10 => OHCI, 0x20 => EHCI, 0x30 => XHCI, 0xFE => Device, _ => PCISerialBusUSB::Other(progif) } } } #[derive(Debug, Copy, Clone)] pub enum PCISimpleCommunicationControllerClass { SerialController(u8), ParallelController(u8), MultiPortSerial, Modem(u8), GPIB, SmartCard, Other(u8), Unknown(u8, u8) } impl PCISimpleCommunicationControllerClass { pub fn from(sub: u8, progif: u8) -> Self { use self::PCISimpleCommunicationControllerClass::*; match sub { 0x0 => SerialController(progif), 0x1 => ParallelController(progif), 0x2 => MultiPortSerial, 0x3 => Modem(progif), 0x4 => GPIB, 0x5 => SmartCard, 0x80 => Other(progif), _ => Unknown(sub, progif) } } }
true
7302cbba49b62a534f46f3d3f2666cdb8566900f
Rust
JonasRSV/Friday
/friday/friday-vad/src/vad_energy.rs
UTF-8
2,511
2.90625
3
[ "MIT" ]
permissive
use crate::core::{SpeakDetector, VADResponse}; use serde_derive::{Deserialize, Serialize}; use friday_storage; use friday_logging; use friday_error::{FridayError, propagate}; #[derive(Deserialize, Serialize)] struct Config { threshold: f64, // Will print the energy if provided and is true verbose: Option<bool> } pub struct EnergyBasedDetector { energy_threshold: f64, verbose: bool } impl EnergyBasedDetector { fn energy(audio: &Vec<i16>) -> f64 { let mut e = 0.0; for sample in audio.iter() { let f64sample = (sample.clone() as f64) / 32768.0; e += f64::sqrt(f64sample * f64sample); } return e / audio.len() as f64; } pub fn new() -> Result<EnergyBasedDetector, FridayError> { friday_storage::config::get_config("vad_energy.json").map_or_else( propagate!("Failed to initialize EnergyBased VAD"), |config: Config| Ok(EnergyBasedDetector::from_config(config))) } fn from_config(config: Config) -> EnergyBasedDetector { EnergyBasedDetector { energy_threshold: config.threshold, verbose: match config.verbose { None => false, Some(v) => v } } } } impl SpeakDetector for EnergyBasedDetector { fn detect(&mut self, audio: &Vec<i16>) -> VADResponse { let energy = EnergyBasedDetector::energy(audio); if self.verbose { friday_logging::debug!("Energy threshold {} -- Energy {}", self.energy_threshold, energy); } if energy > self.energy_threshold { VADResponse::Voice } else { VADResponse::Silence } } } #[cfg(test)] mod tests { use super::*; use std::env; #[test] fn energy_based_detector() { env::set_var("FRIDAY_CONFIG", "./test-resources"); let config_dir = friday_storage::config::get_config_directory().unwrap(); let files = friday_storage::files::Files::new(config_dir).unwrap(); let (quiet_audio, _) = files.read_audio("silence.wav").unwrap(); let (voice_audio, _) = files.read_audio("voice.wav").unwrap(); let mut detector = EnergyBasedDetector::from_config(Config{ threshold: 0.08275, verbose: Some(true) }); assert!(detector.detect(&voice_audio) == VADResponse::Voice); assert!(detector.detect(&quiet_audio) == VADResponse::Silence); } }
true
e2fee85e8d739b3370a107ee801e50699a522a47
Rust
imlyzh/riscv-process-rs
/src/parser.rs
UTF-8
6,148
2.5625
3
[ "MIT" ]
permissive
use pest::iterators::{Pair, Pairs}; use pest::{error::Error, Parser}; use pest_derive::*; use crate::node::*; #[derive(Parser)] #[grammar = "./grammar.pest"] struct RiscVAsm {} pub trait ParseFrom<T> where Self: std::marker::Sized, { fn parse_from(pair: Pair<T>) -> Self; } impl ParseFrom<Rule> for Register { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::registers); Register::from(pair.as_str()) } } impl ParseFrom<Rule> for RfKeyword { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::rf_keyword); RfKeyword::from(pair.as_str()) } } impl ParseFrom<Rule> for Rf { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::rf); let mut pairs = pair.into_inner(); let keyword = pairs.next().unwrap(); let symbol = pairs.next().unwrap(); Self(RfKeyword::parse_from(keyword), Symbol::parse_from(symbol)) } } impl ParseFrom<Rule> for Symbol { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::symbol); let pair = pair.into_inner().next().unwrap(); match pair.as_rule() { Rule::num => Self(pair.as_str().to_string(), 0), Rule::sym => { let mut pairs = pair.into_inner(); let sym = pairs.next().unwrap(); let offset = pairs.next(); if offset.is_none() { return Self(sym.as_str().to_string(), 0); } let offset = offset.unwrap().as_str().parse().unwrap(); Self(sym.as_str().to_string(), offset) } _ => unreachable!(), } } } impl ParseFrom<Rule> for Offset { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::offset); let mut pairs = pair.into_inner(); let pair = pairs.next().unwrap(); let right = pairs.next().map(Register::parse_from); match pair.as_rule() { Rule::symbol => Offset::Imm(Symbol::parse_from(pair), right), Rule::rf => Offset::Rf(Rf::parse_from(pair), right), _ => unreachable!(), } } } impl ParseFrom<Rule> for InstExpr { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::inst_expr); let pair = pair.into_inner().next().unwrap(); match pair.as_rule() { Rule::registers => InstExpr::Reg(Register::parse_from(pair)), Rule::offset => InstExpr::RealTimeOffset(Offset::parse_from(pair)), _ => unreachable!(), } } } impl ParseFrom<Rule> for Instruction { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::inst); let mut pairs = pair.into_inner(); let inst = pairs.next().unwrap().as_str(); let exprs = pairs.map(InstExpr::parse_from); Self(inst.to_string(), exprs.collect()) } } impl ParseFrom<Rule> for PseudoInst { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::pseudo_inst); let pair = pair.into_inner().next().unwrap(); if let Rule::generic_pseudo_inst = pair.as_rule() { let mut pairs = pair.into_inner(); let inst = pairs.next().unwrap().as_str(); let exprs = pairs.map(InstExpr::parse_from); PseudoInst(Instruction(inst.to_string(), exprs.collect())) } else if let Rule::io_pinst = pair.as_rule() { let mut pairs = pair.into_inner(); let inst = pairs.next().unwrap().as_str(); let reg = pairs.next().unwrap(); let sym = pairs.next().unwrap(); let reg = InstExpr::Reg(Register::parse_from(reg)); let sym = InstExpr::RealTimeOffset(Offset::Imm(Symbol::parse_from(sym), None)); PseudoInst(Instruction(inst.to_string(), vec![reg, sym])) } else { unreachable!() } } } impl ParseFrom<Rule> for Expr { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::expr); let pair = pair.into_inner().next().unwrap(); match pair.as_rule() { Rule::sym => Expr::Sym(pair.as_str().to_string()), Rule::str => Expr::Str(pair.as_str().to_string()), Rule::num => Expr::Num(pair.as_str().to_string()), _ => unreachable!(), } } } impl ParseFrom<Rule> for Pseudo { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::pseudo); let pair = pair.into_inner().next().unwrap(); let mut pairs = pair.into_inner(); let pseudo_op = pairs.next().unwrap().as_str(); let exprs = pairs.map(Expr::parse_from); Self(pseudo_op.to_string(), exprs.collect()) } } impl ParseFrom<Rule> for Label { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::label); let pair = pair.into_inner().next().unwrap(); Self(Symbol::parse_from(pair)) } } impl ParseFrom<Rule> for Node { fn parse_from(pair: Pair<Rule>) -> Self { debug_assert_eq!(pair.as_rule(), Rule::line); let pair = pair.into_inner().next().unwrap(); match pair.as_rule() { Rule::inst => Node::Inst(Instruction::parse_from(pair)), Rule::pseudo_inst => Node::PseudoInst(PseudoInst::parse_from(pair)), Rule::pseudo => Node::PseudoOps(Pseudo::parse_from(pair)), Rule::label => Node::Label(Label::parse_from(pair)), _ => unreachable!(), } } } pub fn parse(i: &str) -> Result<Vec<Node>, Error<Rule>> { let r: Result<Vec<Pairs<Rule>>, Error<Rule>> = i .split('\n') .map(str::trim) .map(|x| RiscVAsm::parse(Rule::line, x)) .collect(); let r = r?; let r = r .into_iter() .flatten() .filter(|pair| pair.clone().into_inner().next().is_some()) .map(Node::parse_from) .collect(); Ok(r) }
true
b48ef9ec1d8678f0bac3b8beee3e6cd0381365b8
Rust
teloxide/teloxide
/crates/teloxide-core/src/types/inline_query_result_venue.rs
UTF-8
4,724
3.0625
3
[ "MIT" ]
permissive
use serde::{Deserialize, Serialize}; use crate::types::{InlineKeyboardMarkup, InputMessageContent}; /// Represents a venue. /// /// By default, the venue will be sent by the user. Alternatively, you can use /// `input_message_content` to send a message with the specified content instead /// of the venue. /// /// [The official docs](https://core.telegram.org/bots/api#inlinequeryresultvenue). #[serde_with_macros::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct InlineQueryResultVenue { /// Unique identifier for this result, 1-64 Bytes. pub id: String, /// Latitude of the venue location in degrees. pub latitude: f64, /// Longitude of the venue location in degrees. pub longitude: f64, /// Title of the venue. pub title: String, /// Address of the venue. pub address: String, /// Foursquare identifier of the venue if known. pub foursquare_id: Option<String>, /// Foursquare type of the venue, if known. (For example, /// `arts_entertainment/default`, `arts_entertainment/aquarium` or /// `food/icecream`.) pub foursquare_type: Option<String>, /// Google Places identifier of the venue. pub google_place_id: Option<String>, /// Google Places type of the venue. (See [supported types].) /// /// [supported types]: https://developers.google.com/places/web-service/supported_types pub google_place_type: Option<String>, /// [Inline keyboard] attached to the message. /// /// [Inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub reply_markup: Option<InlineKeyboardMarkup>, /// Content of the message to be sent instead of the venue. pub input_message_content: Option<InputMessageContent>, /// Url of the thumbnail for the result. pub thumb_url: Option<reqwest::Url>, /// Thumbnail width. pub thumb_width: Option<u32>, /// Thumbnail height. pub thumb_height: Option<u32>, } impl InlineQueryResultVenue { pub fn new<S1, S2, S3>(id: S1, latitude: f64, longitude: f64, title: S2, address: S3) -> Self where S1: Into<String>, S2: Into<String>, S3: Into<String>, { Self { id: id.into(), latitude, longitude, title: title.into(), address: address.into(), foursquare_id: None, foursquare_type: None, google_place_id: None, google_place_type: None, reply_markup: None, input_message_content: None, thumb_url: None, thumb_width: None, thumb_height: None, } } pub fn id<S>(mut self, val: S) -> Self where S: Into<String>, { self.id = val.into(); self } #[must_use] pub fn latitude(mut self, val: f64) -> Self { self.latitude = val; self } #[must_use] pub fn longitude(mut self, val: f64) -> Self { self.longitude = val; self } pub fn title<S>(mut self, val: S) -> Self where S: Into<String>, { self.title = val.into(); self } pub fn address<S>(mut self, val: S) -> Self where S: Into<String>, { self.address = val.into(); self } pub fn foursquare_id<S>(mut self, val: S) -> Self where S: Into<String>, { self.foursquare_id = Some(val.into()); self } pub fn foursquare_type<S>(mut self, val: S) -> Self where S: Into<String>, { self.foursquare_type = Some(val.into()); self } pub fn google_place_id<S>(mut self, val: S) -> Self where S: Into<String>, { self.google_place_id = Some(val.into()); self } pub fn google_place_type<S>(mut self, val: S) -> Self where S: Into<String>, { self.google_place_type = Some(val.into()); self } #[must_use] pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self } #[must_use] pub fn input_message_content(mut self, val: InputMessageContent) -> Self { self.input_message_content = Some(val); self } #[must_use] pub fn thumb_url(mut self, val: reqwest::Url) -> Self { self.thumb_url = Some(val); self } #[must_use] pub fn thumb_width(mut self, val: u32) -> Self { self.thumb_width = Some(val); self } #[must_use] pub fn thumb_height(mut self, val: u32) -> Self { self.thumb_height = Some(val); self } }
true
e55276cd160497784f6d0142f592aee5baaa4975
Rust
aleixjf/onetagger
/src/playlist/mod.rs
UTF-8
2,090
2.90625
3
[ "Apache-2.0" ]
permissive
use std::error::Error; use std::fs::File; use std::io::prelude::*; use serde::{Serialize, Deserialize}; use crate::tag::EXTENSIONS; use crate::ui::OTError; pub const PLAYLIST_EXTENSIONS: [&str; 2] = [".m3u", ".m3u8"]; // Playlist info from UI #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UIPlaylist { // base64 pub data: String, pub filename: String, pub format: PlaylistFormat } impl UIPlaylist { pub fn get_files(&self) -> Result<Vec<String>, Box<dyn Error>> { let files = match self.format { PlaylistFormat::M3U => { // Decode base64 from JS let bytes = base64::decode(self.data[self.data.find(';').ok_or("Invalid data!")? + 8..].trim())?; let m3u = String::from_utf8(bytes)?; get_files_from_m3u(&m3u) } }; // Filter extensions let out = files.iter().filter(|f| EXTENSIONS.iter().any(|e| f.to_lowercase().ends_with(e))) .map(String::from).collect(); Ok(out) } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PlaylistFormat { M3U } pub fn get_files_from_playlist_file(path: &str) -> Result<Vec<String>, Box<dyn Error>> { // Validate extension if !PLAYLIST_EXTENSIONS.iter().any(|e| path.to_lowercase().ends_with(e)) { return Err(OTError::new("Unsupported playlist!").into()); }; // Load file let mut file = File::open(path)?; let mut buf = vec![]; file.read_to_end(&mut buf)?; // TODO: Check format if multiple // M3U let data = String::from_utf8(buf)?; Ok(get_files_from_m3u(&data)) } // Get file list from M3U playlist pub fn get_files_from_m3u(m3u: &str) -> Vec<String> { let clean = m3u.replace("\r", "\n").replace("\n\n", "\n"); let entries = clean.split("\n"); let mut out = vec![]; for entry in entries { if !entry.starts_with("#") && !entry.starts_with("http://") && !entry.is_empty() { out.push(entry.trim().to_string()); } } out }
true
00b97baa529682d7054c5bbc7395515ed7e5a13d
Rust
frankegoesdown/LeetCode-in-Go
/Algorithms/0122.best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.go
UTF-8
190
2.65625
3
[ "MIT" ]
permissive
package problem0122 func maxProfit(prices []int) int { res := 0 for i := 1; i < len(prices); i++ { if prices[i] > prices[i-1] { res += prices[i] - prices[i-1] } } return res }
true
8d71733460759451cd9147f32362bba27971320d
Rust
museun/shaken
/shaken/src/registry.rs
UTF-8
4,915
2.921875
3
[ "Unlicense" ]
permissive
use crate::prelude::*; use rusqlite::{Connection, NO_PARAMS}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum Error { AlreadyExists, } #[derive(Debug, PartialEq, PartialOrd)] pub struct Command { name: String, help: String, namespace: String, } impl Command { pub fn replace_name(&mut self, name: impl ToString) { self.name = name.to_string() } pub fn name(&self) -> &str { self.name.as_str() } pub fn help(&self) -> &str { self.help.as_str() } pub fn has_help(&self) -> bool { self.help != "no help provided" // TODO make this some sigil value (or an Option) } pub fn namespace(&self) -> &str { self.namespace.as_str() } } #[derive(Default)] pub struct CommandBuilder { name: String, help: Option<String>, namespace: Option<String>, // for future use } impl CommandBuilder { pub fn command<S>(name: S) -> Self where S: ToString, { Self { name: name.to_string(), ..Self::default() } } pub fn help<S>(mut self, help: S) -> Self where S: ToString, { std::mem::replace(&mut self.help, Some(help.to_string())); self } pub fn namespace<S>(mut self, namespace: S) -> Self where S: ToString, { std::mem::replace(&mut self.namespace, Some(namespace.to_string())); self } pub fn build(self) -> Command { Command { name: self.name, help: self.help.unwrap_or_else(|| "no help provided".into()), namespace: self.namespace.expect("namespace is required"), } } } pub struct Registry; impl Registry { fn ensure_table(conn: &Connection) { conn.execute( r#"CREATE TABLE IF NOT EXISTS CommandRegistry( id INTEGER PRIMARY KEY AUTOINCREMENT, command TEXT NOT NULL, description TEXT NOT NULL, namespace TEXT NOT NULL )"#, NO_PARAMS, ) .expect("create CommandRegistry table"); } pub fn commands() -> Vec<Command> { let conn = database::get_connection(); Self::ensure_table(&conn); let mut s = conn .prepare("SELECT command, description, namespace FROM CommandRegistry") .expect("valid sql"); s.query_map(NO_PARAMS, |row| { Ok(Command { name: row.get(0)?, help: row.get(1)?, namespace: row.get(2)?, }) }) .expect("valid sql") .filter_map(Result::ok) .collect() } pub fn is_available(name: impl AsRef<str>) -> bool { let name = name.as_ref(); !Self::commands().iter().any(|cmd| cmd.name == name) } #[must_use] pub fn register(cmd: &Command) -> Result<(), Error> { let conn = database::get_connection(); Self::ensure_table(&conn); struct Command { name: String, namespace: String, } let mut s = conn .prepare("SELECT command, namespace FROM CommandRegistry") .expect("valid sql"); let commands = s .query_map(NO_PARAMS, |row| { Ok(Command { name: row.get(0)?, namespace: row.get(1)?, }) }) .expect("valid sql") .filter_map(Result::ok); for command in commands { if command.name == cmd.name { if command.namespace != cmd.namespace { return Err(Error::AlreadyExists); } else { return Ok(()); } } } conn.execute( "INSERT INTO CommandRegistry (command, description, namespace) VALUES (?1, ?2, ?3)", &[&cmd.name, &cmd.help, &cmd.namespace], ) .expect("valid sql"); Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn command_registry() { let _conn = database::get_connection(); // to keep the in-memory db alive let cmd = CommandBuilder::command("!test").namespace("test").build(); assert_eq!(Registry::commands().len(), 0); Registry::register(&cmd).unwrap(); let commands = Registry::commands(); assert_eq!(commands.len(), 1); assert_eq!(commands[0], cmd); let mut cmd = CommandBuilder::command("!test").namespace("test1").build(); let err = Registry::register(&cmd).unwrap_err(); assert_eq!(err, Error::AlreadyExists); cmd.replace_name("!test1"); Registry::register(&cmd).unwrap(); let commands = Registry::commands(); assert_eq!(commands.len(), 2); assert_eq!(commands[1], cmd); } }
true
b3c83e0f19baead4d1557fa17bc23d66d37118bf
Rust
Timidger/awesome-wayland
/src/object/class.rs
UTF-8
1,924
2.8125
3
[]
no_license
//! These methods set up a interface to be a class for Lua. use libc; use lua_sys::*; use std::cell::Cell; use super::signal::Signal; use super::property::Property; /// Method that allocates new objects for the class. pub type AllocatorF = unsafe extern fn(*mut lua_State) -> *mut Object; /// Method that is called when the object is garbage collected. pub type CollectorF = unsafe fn(*mut Object); /// Function to call when accessing a property in some way. pub type PropF = unsafe fn(*mut lua_State, *mut Object) -> libc::c_int; /// Function to call to check if an object is valid. pub type CheckerF = unsafe fn(*mut Object) -> bool; #[repr(C)] pub struct Object { pub signals: Vec<Signal> } /// A Lua object that is a class. #[repr(C)] pub struct Class { pub name: String, pub signals: Vec<Signal>, pub parent: *mut Class, /// Method that allocates new objects for the class. pub allocator: Option<AllocatorF>, /// Method that is called when the object is garbage collected. pub collector: Option<CollectorF>, pub properties: Vec<Property>, pub index_miss_prop: Option<PropF>, pub newindex_miss_prop: Option<PropF>, pub checker: Option<CheckerF>, pub instances: Cell<i32>, pub tostring: Option<PropF>, pub index_miss_handler: libc::c_int, pub newindex_miss_handler: libc::c_int } unsafe impl Send for Class {} unsafe impl Sync for Class {} impl Default for Class { fn default() -> Self { Class { name: String::new(), signals: Vec::new(), parent: 0 as _, allocator: None, collector: None, properties: Vec::new(), index_miss_prop: None, newindex_miss_prop: None, checker: None, instances: Cell::new(0), tostring: None, index_miss_handler: 0, newindex_miss_handler: 0 } } }
true
1d3c9992ea20a77d3539ab8314a916f5c65a1263
Rust
winksaville/fuchsia
/src/lib/cobalt/rust/src/cobalt_event_builder.rs
UTF-8
10,720
3.265625
3
[ "BSD-3-Clause" ]
permissive
// 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. //! Helper builder for constructing a `CobaltEvent`. use { crate::traits::AsEventCodes, fidl_fuchsia_cobalt::{CobaltEvent, CountEvent, EventPayload, HistogramBucket}, }; /// Adds the `builder()` method to `CobaltEvent`. pub trait CobaltEventExt { /// Returns a `CobaltEventBuilder` for the specified `metric_id`. /// /// # Examples /// /// ``` /// assert_eq!(CobaltEvent::builder(5).as_event().metric_id, 0); /// ``` fn builder(metric_id: u32) -> CobaltEventBuilder; } impl CobaltEventExt for CobaltEvent { fn builder(metric_id: u32) -> CobaltEventBuilder { CobaltEventBuilder { metric_id, ..CobaltEventBuilder::default() } } } /// CobaltEventBuilder allows for a chained construction of `CobaltEvent` objects. #[derive(Debug, Default, Clone)] pub struct CobaltEventBuilder { metric_id: u32, event_codes: Vec<u32>, component: Option<String>, } impl CobaltEventBuilder { /// Appends the provided `event_code` to the `event_codes` list. /// /// # Examples /// /// ``` /// assert_eq!(CobaltEvent::builder(6).with_event_code(10).as_event().event_codes, vec![10]); /// ``` pub fn with_event_code(mut self, event_code: u32) -> CobaltEventBuilder { self.event_codes.push(event_code); self } /// Overrides the list of event_codes with the provided `event_codes`. /// /// # Examples /// /// ``` /// assert_eq!( /// CobaltEvent::builder(7).with_event_codes([1, 2, 3]).as_event().event_codes, /// vec![1,2,3]); /// ``` pub fn with_event_codes<Codes: AsEventCodes>( mut self, event_codes: Codes, ) -> CobaltEventBuilder { self.event_codes = event_codes.as_event_codes(); self } /// Writes an `event_code` to a particular `index`. This method is useful when not assigning /// event codes in order. /// /// # Examples /// /// ``` /// assert_eq!( /// CobaltEvent::builder(8).with_event_code_at(1, 10).as_event().event_codes, /// vec![0, 10]); /// ``` /// /// # Panics /// /// Panics if the `value` is greater than or equal to 5. pub fn with_event_code_at(mut self, index: usize, event_code: u32) -> CobaltEventBuilder { assert!( index < 5, "Invalid index passed to CobaltEventBuilder::with_event_code. Cobalt events cannot support more than 5 event_codes." ); while self.event_codes.len() <= index { self.event_codes.push(0); } self.event_codes[index] = event_code; self } /// Adds the provided `component` string to the resulting `CobaltEvent`. /// /// # Examples /// /// ``` /// assert_eq!( /// CobaltEvent::builder(9).with_component("Comp").as_event.component, /// Some("Comp".to_owned())); /// ``` pub fn with_component<S: Into<String>>(mut self, component: S) -> CobaltEventBuilder { self.component = Some(component.into()); self } /// Constructs a `CobaltEvent` with the provided `EventPayload`. /// /// # Examples /// ``` /// let payload = EventPayload::Event(fidl_fuchsia_cobalt::Event); /// assert_eq!(CobaltEvent::builder(10).build(payload.clone()).payload, payload); /// ``` pub fn build(self, payload: EventPayload) -> CobaltEvent { CobaltEvent { metric_id: self.metric_id, event_codes: self.event_codes, component: self.component, payload, } } /// Constructs a `CobaltEvent` with a payload type of `EventPayload::Event`. /// /// # Examples /// ``` /// asert_eq!( /// CobaltEvent::builder(11).as_event().payload, /// EventPayload::Event(fidl_fuchsia_cobalt::Event)); /// ``` pub fn as_event(self) -> CobaltEvent { self.build(EventPayload::Event(fidl_fuchsia_cobalt::Event)) } /// Constructs a `CobaltEvent` with a payload type of `EventPayload::EventCount`. /// /// # Examples /// ``` /// asert_eq!( /// CobaltEvent::builder(12).as_count_event(5, 10).payload, /// EventPayload::EventCount(CountEvent { period_duration_micros: 5, count: 10 })); /// ``` pub fn as_count_event(self, period_duration_micros: i64, count: i64) -> CobaltEvent { self.build(EventPayload::EventCount(CountEvent { period_duration_micros, count })) } /// Constructs a `CobaltEvent` with a payload type of `EventPayload::ElapsedMicros`. /// /// # Examples /// ``` /// asert_eq!( /// CobaltEvent::builder(13).as_elapsed_time(30).payload, /// EventPayload::ElapsedMicros(30)); /// ``` pub fn as_elapsed_time(self, elapsed_micros: i64) -> CobaltEvent { self.build(EventPayload::ElapsedMicros(elapsed_micros)) } /// Constructs a `CobaltEvent` with a payload type of `EventPayload::Fps`. /// /// # Examples /// ``` /// asert_eq!( /// CobaltEvent::builder(14).as_frame_rate(99.).payload, /// EventPayload::Fps(99.)); /// ``` pub fn as_frame_rate(self, fps: f32) -> CobaltEvent { self.build(EventPayload::Fps(fps)) } /// Constructs a `CobaltEvent` with a payload type of `EventPayload::MemoryBytesUsed`. /// /// # Examples /// ``` /// asert_eq!( /// CobaltEvent::builder(15).as_memory_usage(1000).payload, /// EventPayload::MemoryBytesUsed(1000)); /// ``` pub fn as_memory_usage(self, memory_bytes_used: i64) -> CobaltEvent { self.build(EventPayload::MemoryBytesUsed(memory_bytes_used)) } /// Constructs a `CobaltEvent` with a payload type of `EventPayload::StringEvent`. /// /// # Examples /// ``` /// asert_eq!( /// CobaltEvent::builder(16).as_string_event("Event!").payload, /// EventPayload::StringEvent("Event!".to_owned())); /// ``` pub fn as_string_event<S: Into<String>>(self, string_event: S) -> CobaltEvent { self.build(EventPayload::StringEvent(string_event.into())) } /// Constructs a `CobaltEvent` with a payload type of `EventPayload::IntHistogram`. /// /// # Examples /// ``` /// let histogram = vec![HistogramBucket { index: 0, count: 1 }]; /// asert_eq!( /// CobaltEvent::builder(17).as_int_histogram(histogram.clone()).payload, /// EventPayload::IntHistogram(histogram)); /// ``` pub fn as_int_histogram(self, int_histogram: Vec<HistogramBucket>) -> CobaltEvent { self.build(EventPayload::IntHistogram(int_histogram)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_builder_as_event() { let event = CobaltEvent::builder(1).with_event_code(2).as_event(); let expected = CobaltEvent { metric_id: 1, event_codes: vec![2], component: None, payload: EventPayload::Event(fidl_fuchsia_cobalt::Event), }; assert_eq!(event, expected); } #[test] fn test_builder_as_count_event() { let event = CobaltEvent::builder(2).with_event_code(3).with_component("A").as_count_event(4, 5); let expected = CobaltEvent { metric_id: 2, event_codes: vec![3], component: Some("A".into()), payload: EventPayload::EventCount(CountEvent { count: 5, period_duration_micros: 4 }), }; assert_eq!(event, expected); } #[test] fn test_as_elapsed_time() { let event = CobaltEvent::builder(3).with_event_code(4).with_component("B").as_elapsed_time(5); let expected = CobaltEvent { metric_id: 3, event_codes: vec![4], component: Some("B".into()), payload: EventPayload::ElapsedMicros(5), }; assert_eq!(event, expected); } #[test] fn test_as_frame_rate() { let event = CobaltEvent::builder(4).with_event_code(5).with_component("C").as_frame_rate(6.); let expected = CobaltEvent { metric_id: 4, event_codes: vec![5], component: Some("C".into()), payload: EventPayload::Fps(6.), }; assert_eq!(event, expected); } #[test] fn test_as_memory_usage() { let event = CobaltEvent::builder(5).with_event_code(6).with_component("D").as_memory_usage(7); let expected = CobaltEvent { metric_id: 5, event_codes: vec![6], component: Some("D".into()), payload: EventPayload::MemoryBytesUsed(7), }; assert_eq!(event, expected); } #[test] fn test_as_string_event() { let event = CobaltEvent::builder(6).as_string_event("String Value"); let expected = CobaltEvent { metric_id: 6, event_codes: vec![], component: None, payload: EventPayload::StringEvent("String Value".into()), }; assert_eq!(event, expected); } #[test] fn test_as_int_histogram() { let event = CobaltEvent::builder(7) .with_event_code(8) .with_component("E") .as_int_histogram(vec![HistogramBucket { index: 0, count: 1 }]); let expected = CobaltEvent { metric_id: 7, event_codes: vec![8], component: Some("E".into()), payload: EventPayload::IntHistogram(vec![HistogramBucket { index: 0, count: 1 }]), }; assert_eq!(event, expected); } #[test] #[should_panic(expected = "Invalid index")] fn test_bad_event_code_at_index() { CobaltEvent::builder(8).with_event_code_at(5, 10).as_event(); } #[test] fn test_clone() { let e = CobaltEvent::builder(102).with_event_code_at(1, 15); assert_eq!( e.clone().with_event_code_at(0, 10).as_string_event("Event 1"), CobaltEvent { metric_id: 102, event_codes: vec![10, 15], component: None, payload: EventPayload::StringEvent("Event 1".to_owned()) } ); assert_eq!( e.with_event_code_at(0, 11).as_string_event("Event 2"), CobaltEvent { metric_id: 102, event_codes: vec![11, 15], component: None, payload: EventPayload::StringEvent("Event 2".to_owned()) } ); } }
true
aa9bd61e45a7eacd307d4c6c5bda34c1016b6dc0
Rust
exit91/miniserve
/tests/upload_files.rs
UTF-8
1,973
2.71875
3
[ "MIT" ]
permissive
mod fixtures; use assert_cmd::prelude::*; use assert_fs::fixture::TempDir; use fixtures::{port, tmpdir, Error}; use reqwest::multipart; use rstest::rstest; use select::document::Document; use select::predicate::{Attr, Text}; use std::process::{Command, Stdio}; use std::thread::sleep; use std::time::Duration; #[rstest] fn uploading_files_works(tmpdir: TempDir, port: u16) -> Result<(), Error> { let test_file_name = "uploaded test file.txt"; let mut child = Command::cargo_bin("miniserve")? .arg(tmpdir.path()) .arg("-p") .arg(port.to_string()) .arg("-u") .stdout(Stdio::null()) .spawn()?; sleep(Duration::from_secs(1)); // Before uploading, check whether the uploaded file does not yet exist. let body = reqwest::get(format!("http://localhost:{}", port).as_str())?.error_for_status()?; let parsed = Document::from_read(body)?; assert!(parsed.find(Text).all(|x| x.text() != test_file_name)); // Perform the actual upload. let upload_action = parsed .find(Attr("id", "file_submit")) .next() .expect("Couldn't find element with id=file_submit") .attr("action") .expect("Upload form doesn't have action attribute"); let form = multipart::Form::new(); let part = multipart::Part::text("this should be uploaded") .file_name(test_file_name) .mime_str("text/plain")?; let form = form.part("file_to_upload", part); let client = reqwest::Client::new(); client .post(format!("http://localhost:{}{}", port, upload_action).as_str()) .multipart(form) .send()? .error_for_status()?; // After uploading, check whether the uploaded file is now getting listed. let body = reqwest::get(format!("http://localhost:{}", port).as_str())?; let parsed = Document::from_read(body)?; assert!(parsed.find(Text).any(|x| x.text() == test_file_name)); child.kill()?; Ok(()) }
true
83c7c81b6f1e4f60d7d8f4ff920221f8cd2f0a30
Rust
i2p/i2p-rs
/src/net/addr.rs
UTF-8
9,179
3.34375
3
[ "MIT" ]
permissive
use std::fmt; use std::io; use std::iter; use std::option; use std::slice; use std::vec; use serde_derive::{Deserialize, Serialize}; use crate::net::i2p::I2pAddr; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hash)] pub struct I2pSocketAddr { port: u16, dest: I2pAddr, } impl I2pSocketAddr { /// Creates a new socket address from the (dest, port) pair. /// /// # Examples /// /// ``` /// use i2p::net::{I2pAddr, I2pSocketAddr}; /// /// let socket = I2pSocketAddr::new(I2pAddr::new("example.i2p"), 8080); /// assert_eq!(socket.dest(), I2pAddr::new("example.i2p")); /// assert_eq!(socket.port(), 8080); /// ``` pub fn new(dest: I2pAddr, port: u16) -> I2pSocketAddr { I2pSocketAddr { port: port, dest: dest, } } /// Returns the I2P address associated with this socket address. /// /// # Examples /// /// ``` /// use i2p::net::{I2pAddr, I2pSocketAddr}; /// /// let socket = I2pSocketAddr::new(I2pAddr::new("example.i2p"), 8080); /// assert_eq!(socket.dest(), I2pAddr::new("example.i2p")); /// ``` pub fn dest(&self) -> I2pAddr { self.dest.clone() } /// Change the I2P address associated with this socket address. /// /// # Examples /// /// ``` /// use i2p::net::{I2pAddr, I2pSocketAddr}; /// /// let mut socket = I2pSocketAddr::new(I2pAddr::new("example.i2p"), 8080); /// socket.set_dest(I2pAddr::new("foobar.i2p")); /// assert_eq!(socket.dest(), I2pAddr::new("foobar.i2p")); /// ``` pub fn set_dest(&mut self, new_dest: I2pAddr) { self.dest = new_dest; } /// Returns the port number associated with this socket address. /// /// # Examples /// /// ``` /// use i2p::net::{I2pAddr, I2pSocketAddr}; /// /// let socket = I2pSocketAddr::new(I2pAddr::new("example.i2p"), 8080); /// assert_eq!(socket.port(), 8080); /// ``` pub fn port(&self) -> u16 { self.port } /// Change the port number associated with this socket address. /// /// # Examples /// /// ``` /// use i2p::net::{I2pAddr, I2pSocketAddr}; /// /// let mut socket = I2pSocketAddr::new(I2pAddr::new("example.i2p"), 8080); /// socket.set_port(1025); /// assert_eq!(socket.port(), 1025); /// ``` pub fn set_port(&mut self, new_port: u16) { self.port = new_port; } } impl fmt::Display for I2pSocketAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.dest(), self.port()) } } /// A trait for objects which can be converted or resolved to one or more /// `I2pSocketAddr` values. /// /// This trait is used for generic address resolution when constructing network /// objects. By default it is implemented for the following types: /// /// * `I2pSocketAddr` - `to_socket_addrs` is identity function. /// /// * `(I2pAddr, u16)` - `to_socket_addrs` constructs `I2pSocketAddr` trivially. /// /// * `(&str, u16)` - the string should be either a string representation of an /// I2P address expected by `FromStr` implementation for `I2pAddr` or a host /// name. /// /// * `&str` - the string should be either a string representation of a /// `I2pSocketAddr` as expected by its `FromStr` implementation or a string like /// `<host_name>:<port>` pair where `<port>` is a `u16` value. /// /// This trait allows constructing network objects like `I2PStream` or /// `I2PDatagramSocket` easily with values of various types for the bind/connection /// address. It is needed because sometimes one type is more appropriate than /// the other: for simple uses a string like `"example.i2p:12345"` is much nicer /// than manual construction of the corresponding `I2pSocketAddr`, but sometimes /// `I2pSocketAddr` value is *the* main source of the address, and converting it to /// some other type (e.g. a string) just for it to be converted back to /// `I2pSocketAddr` in constructor methods is pointless. /// /// Addresses returned by the operating system that are not IP addresses are /// silently ignored. /// /// Some examples: /// /// ```no_run /// use i2p::net::{I2pSocketAddr, I2pStream, I2pDatagramSocket, I2pListener, I2pAddr}; /// /// fn main() { /// let dest = I2pAddr::new("example.i2p"); /// let port = 12345; /// /// // The following lines are equivalent /// let i2p_s = I2pStream::connect(I2pSocketAddr::new(dest.clone(), port)); /// let i2p_s = I2pStream::connect((dest.clone(), port)); /// let i2p_s = I2pStream::connect(("example.i2p", port)); /// let i2p_s = I2pStream::connect("example.i2p:12345"); /// /// // I2pListener::bind(), I2pDatagramSocket::bind() and I2pDatagramSocket::send_to() /// // behave similarly /// let i2p_l = I2pListener::bind(); /// /// let mut i2p_dg_s = I2pDatagramSocket::bind(("127.0.0.1", port)).unwrap(); /// i2p_dg_s.send_to(&[7], (dest, 23451)).unwrap(); /// } /// ``` pub trait ToI2pSocketAddrs { /// Returned iterator over socket addresses which this type may correspond /// to. type Iter: Iterator<Item = I2pSocketAddr>; /// Converts this object to an iterator of resolved `I2pSocketAddr`s. /// /// The returned iterator may not actually yield any values depending on the /// outcome of any resolution performed. /// /// Note that this function may block the current thread while resolution is /// performed. /// /// # Errors /// /// Any errors encountered during resolution will be returned as an `Err`. fn to_socket_addrs(&self) -> io::Result<Self::Iter>; } impl ToI2pSocketAddrs for I2pSocketAddr { type Iter = option::IntoIter<I2pSocketAddr>; fn to_socket_addrs(&self) -> io::Result<option::IntoIter<I2pSocketAddr>> { Ok(Some(self.clone()).into_iter()) } } impl ToI2pSocketAddrs for (I2pAddr, u16) { type Iter = option::IntoIter<I2pSocketAddr>; fn to_socket_addrs(&self) -> io::Result<option::IntoIter<I2pSocketAddr>> { let (dest, port) = self.clone(); I2pSocketAddr::new(dest, port).to_socket_addrs() } } impl<'a> ToI2pSocketAddrs for (&'a str, u16) { type Iter = vec::IntoIter<I2pSocketAddr>; fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<I2pSocketAddr>> { let (host, port) = *self; let addr = I2pSocketAddr::new(I2pAddr::new(host), port); Ok(vec![addr].into_iter()) } } // accepts strings like 'example.i2p:12345' impl ToI2pSocketAddrs for str { type Iter = vec::IntoIter<I2pSocketAddr>; fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<I2pSocketAddr>> { macro_rules! try_opt { ($e:expr, $msg:expr) => { match $e { Some(r) => r, None => return Err(io::Error::new(io::ErrorKind::InvalidInput, $msg)), } }; } // split the string by ':' and convert the second part to u16 let mut parts_iter = self.rsplitn(2, ':'); let port_str = try_opt!(parts_iter.next(), "invalid I2P socket address"); let host = try_opt!(parts_iter.next(), "invalid I2P socket address"); let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value"); (host, port).to_socket_addrs() } } impl<'a> ToI2pSocketAddrs for &'a [I2pSocketAddr] { type Iter = iter::Cloned<slice::Iter<'a, I2pSocketAddr>>; fn to_socket_addrs(&self) -> io::Result<Self::Iter> { Ok(self.iter().cloned()) } } impl<'a, T: ToI2pSocketAddrs + ?Sized> ToI2pSocketAddrs for &'a T { type Iter = T::Iter; fn to_socket_addrs(&self) -> io::Result<T::Iter> { (**self).to_socket_addrs() } } impl ToI2pSocketAddrs for String { type Iter = vec::IntoIter<I2pSocketAddr>; fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<I2pSocketAddr>> { (&**self).to_socket_addrs() } } #[cfg(test)] mod tests { use crate::net::test::{isa, tsa}; use crate::net::*; #[test] fn to_socket_addr_i2paddr_u16() { let a = I2pAddr::new("example.i2p"); let p = 12345; let e = I2pSocketAddr::new(a.clone(), p); assert_eq!(Ok(vec![e]), tsa((a, p))); } #[test] fn to_socket_addr_str_u16() { let a = isa(I2pAddr::new("example.i2p"), 24352); assert_eq!(Ok(vec![a]), tsa(("example.i2p", 24352))); let a = isa(I2pAddr::new("example.i2p"), 23924); assert!(tsa(("example.i2p", 23924)).unwrap().contains(&a)); } #[test] fn to_socket_addr_str() { let a = isa(I2pAddr::new("example.i2p"), 24352); assert_eq!(Ok(vec![a]), tsa("example.i2p:24352")); let a = isa(I2pAddr::new("example.i2p"), 23924); assert!(tsa("example.i2p:23924").unwrap().contains(&a)); } #[test] fn to_socket_addr_string() { let a = isa(I2pAddr::new("example.i2p"), 24352); assert_eq!( Ok(vec![a.clone()]), tsa(&*format!("{}:{}", "example.i2p", "24352")) ); assert_eq!( Ok(vec![a.clone()]), tsa(&format!("{}:{}", "example.i2p", "24352")) ); assert_eq!( Ok(vec![a.clone()]), tsa(format!("{}:{}", "example.i2p", "24352")) ); let s = format!("{}:{}", "example.i2p", "24352"); assert_eq!(Ok(vec![a]), tsa(s)); // s has been moved into the tsa call } #[test] fn set_dest() { fn i2p(low: u8) -> I2pAddr { I2pAddr::new(&format!("example{}.i2p", low)) } let mut addr = I2pSocketAddr::new(i2p(12), 80); assert_eq!(addr.dest(), i2p(12)); addr.set_dest(i2p(13)); assert_eq!(addr.dest(), i2p(13)); } #[test] fn set_port() { let mut addr = I2pSocketAddr::new(I2pAddr::new("example.i2p"), 80); assert_eq!(addr.port(), 80); addr.set_port(8080); assert_eq!(addr.port(), 8080); } }
true
373f66f5c6b544f7efdf3ef63d79eb08e538ff07
Rust
zhengrenzhe/nand2tetris
/compiler/utils/tests/io.rs
UTF-8
1,030
2.953125
3
[]
no_license
extern crate utils; use utils::io::{read_lines, write_lines}; const TEST_FILE_PATH: &str = "tests/test.txt"; fn get_lines() -> Vec<String> { vec![ String::from("a"), String::from("b"), String::from("c"), String::from("1"), String::from("2"), String::from("3"), ] } #[test] fn test_write_lines() { let lines = get_lines(); let write_result = write_lines(&lines, TEST_FILE_PATH); match write_result { Ok(result) => assert_eq!(result, true), Err(err) => panic!("{}", err), } } #[test] fn test_read_lines() { let lines = get_lines(); let read_result = read_lines(TEST_FILE_PATH); match read_result { Ok(file) => { assert_eq!(file.stem, String::from("test")); assert_eq!(file.lines.len(), lines.len()); for (index, content) in file.lines.iter().enumerate() { assert_eq!(*content, lines[index]); } } Err(err) => panic!("{}", err), } }
true
ff1313a8dc1d50062ad9d387e2e2f1432497b01f
Rust
rehwinkel/OliveScript
/oliveparser/src/ast.rs
UTF-8
2,172
3.125
3
[ "GPL-3.0-only" ]
permissive
#[derive(Debug)] pub enum Statement<'a> { Break, Continue, Return { value: Located<Expression<'a>>, }, Block { statements: Vec<Located<Statement<'a>>>, }, While { condition: Located<Expression<'a>>, block: Vec<Located<Statement<'a>>>, }, If { condition: Located<Expression<'a>>, block: Vec<Located<Statement<'a>>>, elseblock: Option<Vec<Located<Statement<'a>>>>, }, Assign { left: Box<Located<Expression<'a>>>, right: Box<Located<Expression<'a>>>, }, Call { expression: Box<Located<Expression<'a>>>, args: Vec<Located<Expression<'a>>>, }, } #[derive(Debug)] pub enum BinaryOperator { Add, Sub, Mul, IntDiv, FloatDiv, Mod, BitLsh, BitRsh, BitAnd, BitOr, BitXOr, Equals, NotEquals, LessThan, LessEquals, GreaterThan, GreaterEquals, BoolAnd, BoolOr, Concat, Access, } #[derive(Debug)] pub enum UnaryOperator { Neg, BoolNot, } #[derive(Debug)] pub enum Expression<'a> { List { elements: Vec<Located<Expression<'a>>>, }, Bendy { elements: Vec<(Located<&'a str>, Located<Expression<'a>>)>, }, Integer { value: &'a str, }, Float { value: &'a str, }, String { value: String, }, Boolean { value: bool, }, None, Variable { name: &'a str, }, Binary { left: Box<Located<Expression<'a>>>, right: Box<Located<Expression<'a>>>, operator: BinaryOperator, }, Unary { expression: Box<Located<Expression<'a>>>, operator: UnaryOperator, }, Index { expression: Box<Located<Expression<'a>>>, index: Box<Located<Expression<'a>>>, }, Call { expression: Box<Located<Expression<'a>>>, args: Vec<Located<Expression<'a>>>, }, Function { parameters: Vec<Located<&'a str>>, block: Vec<Located<Statement<'a>>>, }, } #[derive(Debug)] pub struct Located<T> { pub start: usize, pub end: usize, pub inner: T, }
true