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
75e4215deab54039a8ca863ecdedf495d8b66675
Rust
ah-/zinc
/platformtree/node.rs
UTF-8
8,907
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::cell::{Cell, RefCell}; use std::collections::hashmap::HashMap; use std::gc::Gc; use syntax::codemap::{Span, DUMMY_SP}; use syntax::ext::base::ExtCtxt; /// Holds a value for an attribute. /// /// The value can be an unsigned integer, string or reference. #[deriving(Clone)] pub enum AttributeValue { IntValue(uint), StrValue(String), RefValue(String), } /// Expected attribute type. /// /// Used in Node::expect_attributes to provide the expected type of the /// attribute. pub enum AttributeType { IntAttribute, StrAttribute, RefAttribute, } /// Attribute value and metadata. /// /// Stored inside of a HashMap, the key to HashMap is the attribute name. /// Provides spans for both key and value. #[deriving(Clone)] pub struct Attribute { pub value: AttributeValue, pub key_span: Span, pub value_span: Span, } impl Attribute { pub fn new(value: AttributeValue, key_span: Span, value_span: Span) -> Attribute { Attribute { value: value, key_span: key_span, value_span: value_span, } } pub fn new_nosp(value: AttributeValue) -> Attribute { Attribute { value: value, key_span: DUMMY_SP, value_span: DUMMY_SP, } } } /// PlatformTree node. /// /// Might have an optional name, is the name is missing, name_span is equal to /// path_span. Attributes are stored by name, subnodes are stored by path. /// Type_name, if present, must specify the type path for the node's /// materialized object. pub struct Node { pub name: Option<String>, pub name_span: Span, pub path: String, pub path_span: Span, pub attributes: RefCell<HashMap<String, Attribute>>, pub subnodes: HashMap<String, Gc<Node>>, pub type_name: Cell<Option<&'static str>>, } impl Node { pub fn new(name: Option<String>, name_span: Span, path: String, path_span: Span) -> Node { Node { name: name, name_span: name_span, path: path, path_span: path_span, attributes: RefCell::new(HashMap::new()), subnodes: HashMap::new(), type_name: Cell::new(None), } } /// Returns attribute by name or fail!()s. pub fn get_attr(&self, key: &str) -> Attribute { self.attributes.borrow().get(&key.to_str()).clone() } /// Returns a string attribute by name or None, if it's not present or not of /// a StrAttribute type. pub fn get_string_attr(&self, key: &str) -> Option<String> { self.attributes.borrow().find(&key.to_str()).and_then(|av| match av.value { StrValue(ref s) => Some(s.clone()), _ => None, }) } /// Returns an integer attribute by name or None, if it's not present or not /// of an IntAttribute type. pub fn get_int_attr(&self, key: &str) -> Option<uint> { self.attributes.borrow().find(&key.to_str()).and_then(|av| match av.value { IntValue(ref u) => Some(*u), _ => None, }) } /// Returns a reference attribute by name or None, if it's not present or not /// of a RefAttribute type. pub fn get_ref_attr(&self, key: &str) -> Option<String> { self.attributes.borrow().find(&key.to_str()).and_then(|av| match av.value { RefValue(ref s) => Some(s.clone()), _ => None, }) } /// Returns a string attribute by name or None, if it's not present or not of /// a StrAttribute type. Reports a parser error if an attribute is /// missing. pub fn get_required_string_attr(&self, cx: &ExtCtxt, key: &str) -> Option<String> { match self.get_string_attr(key) { Some(val) => Some(val), None => { cx.parse_sess().span_diagnostic.span_err(self.name_span, format!("required string attribute `{}` is missing", key) .as_slice()); None } } } /// Returns an integer attribute by name or None, if it's not present or not /// of an IntAttribute type. Reports a parser error if an attribute is /// missing. pub fn get_required_int_attr(&self, cx: &ExtCtxt, key: &str) -> Option<uint> { match self.get_int_attr(key) { Some(val) => Some(val), None => { cx.parse_sess().span_diagnostic.span_err(self.name_span, format!("required integer attribute `{}` is missing", key) .as_slice()); None } } } /// Returns a reference attribute by name or None, if it's not present or not /// of a RefAttribute type. Reports a parser error if an attribute is /// missing. pub fn get_required_ref_attr(&self, cx: &ExtCtxt, key: &str) -> Option<String> { match self.get_ref_attr(key) { Some(val) => Some(val), None => { cx.parse_sess().span_diagnostic.span_err(self.name_span, format!("required ref attribute `{}` is missing", key) .as_slice()); None } } } /// Returns true if node has no attributes. Returs false and reports a parser /// error for each found attribute otherwise. pub fn expect_no_attributes(&self, cx: &ExtCtxt) -> bool { let mut ok = true; for (_, v) in self.attributes.borrow().iter() { ok = false; cx.parse_sess().span_diagnostic.span_err(v.key_span, "no attributes expected"); } ok } /// Returns true if node has no subnodes. Returs false and reports a parser /// error for each found subnode otherwise. pub fn expect_no_subnodes(&self, cx: &ExtCtxt) -> bool { let mut ok = true; for (_, sub) in self.subnodes.iter() { ok = false; cx.parse_sess().span_diagnostic.span_err(sub.name_span, "no subnodes expected"); } ok } /// Returns true if node has all of the requested attributes and their types /// match. Reports parser errors and returns false otherwise. pub fn expect_attributes(&self, cx: &ExtCtxt, expectations: &[(&str, AttributeType)]) -> bool { let mut ok = true; for &(n, ref t) in expectations.iter() { match t { &StrAttribute => { if self.get_required_string_attr(cx, n).is_none() {ok = false} }, &IntAttribute => { if self.get_required_int_attr(cx, n).is_none() {ok = false} }, &RefAttribute => { if self.get_required_ref_attr(cx, n).is_none() {ok = false} }, } } ok } /// Returns true if node has all of the requested subnodes matched by path. /// Reports parser errors and returns false otherwise. pub fn expect_subnodes(&self, cx: &ExtCtxt, expectations: &[&str]) -> bool { let mut ok = true; for (path, sub) in self.subnodes.iter() { if !expectations.contains(&path.as_slice()) { ok = false; cx.parse_sess().span_diagnostic.span_err(sub.path_span, format!("unknown subnode `{}` in node `{}`", path, self.path).as_slice()); } } ok } /// Returns a subnode by path or None, if not found. pub fn get_by_path<'a>(&'a self, path: &str) -> Option<&'a Gc<Node>> { self.subnodes.find(&path.to_str()) } } /// PlatformTree root object. /// /// Root nodes are stored by path in `nodes`, All the nmaed nodes are also /// stored by name in `named`. pub struct PlatformTree { nodes: HashMap<String, Gc<Node>>, named: HashMap<String, Gc<Node>>, } impl PlatformTree { pub fn new(nodes: HashMap<String, Gc<Node>>, named: HashMap<String, Gc<Node>>) -> PlatformTree { PlatformTree { nodes: nodes, named: named, } } /// Returns a node by name or None, if not found. pub fn get_by_name<'a>(&'a self, name: &str) -> Option<&'a Gc<Node>> { self.named.find(&name.to_str()) } /// Returns a root node by path or None, if not found. pub fn get_by_path<'a>(&'a self, name: &str) -> Option<&'a Gc<Node>> { self.nodes.find(&name.to_str()) } /// Returns true if PT has all of the requested root odes matched by path. /// Reports parser errors and returns false otherwise. pub fn expect_subnodes(&self, cx: &ExtCtxt, expectations: &[&str]) -> bool { let mut ok = true; for (path, sub) in self.nodes.iter() { if !expectations.contains(&path.as_slice()) { ok = false; cx.parse_sess().span_diagnostic.span_err(sub.path_span, format!("unknown root node `{}`", path).as_slice()); } } ok } }
true
5560613f03344de2ee3c5d14013090766b9f3754
Rust
image-rs/image
/src/codecs/gif.rs
UTF-8
21,396
2.78125
3
[ "MIT" ]
permissive
//! Decoding of GIF Images //! //! GIF (Graphics Interchange Format) is an image format that supports lossless compression. //! //! # Related Links //! * <http://www.w3.org/Graphics/GIF/spec-gif89a.txt> - The GIF Specification //! //! # Examples //! ```rust,no_run //! use image::codecs::gif::{GifDecoder, GifEncoder}; //! use image::{ImageDecoder, AnimationDecoder}; //! use std::fs::File; //! # fn main() -> std::io::Result<()> { //! // Decode a gif into frames //! let file_in = File::open("foo.gif")?; //! let mut decoder = GifDecoder::new(file_in).unwrap(); //! let frames = decoder.into_frames(); //! let frames = frames.collect_frames().expect("error decoding gif"); //! //! // Encode frames into a gif and save to a file //! let mut file_out = File::open("out.gif")?; //! let mut encoder = GifEncoder::new(file_out); //! encoder.encode_frames(frames.into_iter()); //! # Ok(()) //! # } //! ``` #![allow(clippy::while_let_loop)] use std::convert::TryFrom; use std::convert::TryInto; use std::io::{self, Cursor, Read, Write}; use std::marker::PhantomData; use std::mem; use gif::ColorOutput; use gif::{DisposalMethod, Frame}; use crate::animation::{self, Ratio}; use crate::color::{ColorType, Rgba}; use crate::error::{ DecodingError, EncodingError, ImageError, ImageResult, ParameterError, ParameterErrorKind, UnsupportedError, UnsupportedErrorKind, }; use crate::image::{self, AnimationDecoder, ImageDecoder, ImageFormat}; use crate::io::Limits; use crate::traits::Pixel; use crate::ImageBuffer; /// GIF decoder pub struct GifDecoder<R: Read> { reader: gif::Decoder<R>, limits: Limits, } impl<R: Read> GifDecoder<R> { /// Creates a new decoder that decodes the input steam `r` pub fn new(r: R) -> ImageResult<GifDecoder<R>> { let mut decoder = gif::DecodeOptions::new(); decoder.set_color_output(ColorOutput::RGBA); Ok(GifDecoder { reader: decoder.read_info(r).map_err(ImageError::from_decoding)?, limits: Limits::default(), }) } /// Creates a new decoder that decodes the input steam `r`, using limits `limits` pub fn with_limits(r: R, limits: Limits) -> ImageResult<GifDecoder<R>> { let mut decoder = gif::DecodeOptions::new(); decoder.set_color_output(ColorOutput::RGBA); Ok(GifDecoder { reader: decoder.read_info(r).map_err(ImageError::from_decoding)?, limits, }) } } /// Wrapper struct around a `Cursor<Vec<u8>>` pub struct GifReader<R>(Cursor<Vec<u8>>, PhantomData<R>); impl<R> Read for GifReader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { if self.0.position() == 0 && buf.is_empty() { mem::swap(buf, self.0.get_mut()); Ok(buf.len()) } else { self.0.read_to_end(buf) } } } impl<'a, R: 'a + Read> ImageDecoder<'a> for GifDecoder<R> { type Reader = GifReader<R>; fn dimensions(&self) -> (u32, u32) { ( u32::from(self.reader.width()), u32::from(self.reader.height()), ) } fn color_type(&self) -> ColorType { ColorType::Rgba8 } fn into_reader(self) -> ImageResult<Self::Reader> { Ok(GifReader( Cursor::new(image::decoder_to_vec(self)?), PhantomData, )) } fn read_image(mut self, buf: &mut [u8]) -> ImageResult<()> { assert_eq!(u64::try_from(buf.len()), Ok(self.total_bytes())); let frame = match self .reader .next_frame_info() .map_err(ImageError::from_decoding)? { Some(frame) => FrameInfo::new_from_frame(frame), None => { return Err(ImageError::Parameter(ParameterError::from_kind( ParameterErrorKind::NoMoreData, ))) } }; let (width, height) = self.dimensions(); if frame.left == 0 && frame.width == width && (frame.top as u64 + frame.height as u64 <= height as u64) { // If the frame matches the logical screen, or, as a more general case, // fits into it and touches its left and right borders, then // we can directly write it into the buffer without causing line wraparound. let line_length = usize::try_from(width) .unwrap() .checked_mul(self.color_type().bytes_per_pixel() as usize) .unwrap(); // isolate the portion of the buffer to read the frame data into. // the chunks above and below it are going to be zeroed. let (blank_top, rest) = buf.split_at_mut(line_length.checked_mul(frame.top as usize).unwrap()); let (buf, blank_bottom) = rest.split_at_mut(line_length.checked_mul(frame.height as usize).unwrap()); debug_assert_eq!(buf.len(), self.reader.buffer_size()); // this is only necessary in case the buffer is not zeroed for b in blank_top { *b = 0; } // fill the middle section with the frame data self.reader .read_into_buffer(buf) .map_err(ImageError::from_decoding)?; // this is only necessary in case the buffer is not zeroed for b in blank_bottom { *b = 0; } } else { // If the frame does not match the logical screen, read into an extra buffer // and 'insert' the frame from left/top to logical screen width/height. let buffer_size = self.reader.buffer_size(); self.limits.reserve_usize(buffer_size)?; let mut frame_buffer = vec![0; buffer_size]; self.limits.free_usize(buffer_size); self.reader .read_into_buffer(&mut frame_buffer[..]) .map_err(ImageError::from_decoding)?; let frame_buffer = ImageBuffer::from_raw(frame.width, frame.height, frame_buffer); let image_buffer = ImageBuffer::from_raw(width, height, buf); // `buffer_size` uses wrapping arithmetic, thus might not report the // correct storage requirement if the result does not fit in `usize`. // `ImageBuffer::from_raw` detects overflow and reports by returning `None`. if frame_buffer.is_none() || image_buffer.is_none() { return Err(ImageError::Unsupported( UnsupportedError::from_format_and_kind( ImageFormat::Gif.into(), UnsupportedErrorKind::GenericFeature(format!( "Image dimensions ({}, {}) are too large", frame.width, frame.height )), ), )); } let frame_buffer = frame_buffer.unwrap(); let mut image_buffer = image_buffer.unwrap(); for (x, y, pixel) in image_buffer.enumerate_pixels_mut() { let frame_x = x.wrapping_sub(frame.left); let frame_y = y.wrapping_sub(frame.top); if frame_x < frame.width && frame_y < frame.height { *pixel = *frame_buffer.get_pixel(frame_x, frame_y); } else { // this is only necessary in case the buffer is not zeroed *pixel = Rgba([0, 0, 0, 0]); } } } Ok(()) } } struct GifFrameIterator<R: Read> { reader: gif::Decoder<R>, width: u32, height: u32, non_disposed_frame: ImageBuffer<Rgba<u8>, Vec<u8>>, } impl<R: Read> GifFrameIterator<R> { fn new(decoder: GifDecoder<R>) -> GifFrameIterator<R> { let (width, height) = decoder.dimensions(); // intentionally ignore the background color for web compatibility // create the first non disposed frame let non_disposed_frame = ImageBuffer::from_pixel(width, height, Rgba([0, 0, 0, 0])); GifFrameIterator { reader: decoder.reader, width, height, non_disposed_frame, } } } impl<R: Read> Iterator for GifFrameIterator<R> { type Item = ImageResult<animation::Frame>; fn next(&mut self) -> Option<ImageResult<animation::Frame>> { // begin looping over each frame let frame = match self.reader.next_frame_info() { Ok(frame_info) => { if let Some(frame) = frame_info { FrameInfo::new_from_frame(frame) } else { // no more frames return None; } } Err(err) => return Some(Err(ImageError::from_decoding(err))), }; let mut vec = vec![0; self.reader.buffer_size()]; if let Err(err) = self.reader.read_into_buffer(&mut vec) { return Some(Err(ImageError::from_decoding(err))); } // create the image buffer from the raw frame. // `buffer_size` uses wrapping arithmetic, thus might not report the // correct storage requirement if the result does not fit in `usize`. // on the other hand, `ImageBuffer::from_raw` detects overflow and // reports by returning `None`. let mut frame_buffer = match ImageBuffer::from_raw(frame.width, frame.height, vec) { Some(frame_buffer) => frame_buffer, None => { return Some(Err(ImageError::Unsupported( UnsupportedError::from_format_and_kind( ImageFormat::Gif.into(), UnsupportedErrorKind::GenericFeature(format!( "Image dimensions ({}, {}) are too large", frame.width, frame.height )), ), ))) } }; // blend the current frame with the non-disposed frame, then update // the non-disposed frame according to the disposal method. fn blend_and_dispose_pixel( dispose: DisposalMethod, previous: &mut Rgba<u8>, current: &mut Rgba<u8>, ) { let pixel_alpha = current.channels()[3]; if pixel_alpha == 0 { *current = *previous; } match dispose { DisposalMethod::Any | DisposalMethod::Keep => { // do not dispose // (keep pixels from this frame) // note: the `Any` disposal method is underspecified in the GIF // spec, but most viewers treat it identically to `Keep` *previous = *current; } DisposalMethod::Background => { // restore to background color // (background shows through transparent pixels in the next frame) *previous = Rgba([0, 0, 0, 0]); } DisposalMethod::Previous => { // restore to previous // (dispose frames leaving the last none disposal frame) } } } // if `frame_buffer`'s frame exactly matches the entire image, then // use it directly, else create a new buffer to hold the composited // image. let image_buffer = if (frame.left, frame.top) == (0, 0) && (self.width, self.height) == frame_buffer.dimensions() { for (x, y, pixel) in frame_buffer.enumerate_pixels_mut() { let previous_pixel = self.non_disposed_frame.get_pixel_mut(x, y); blend_and_dispose_pixel(frame.disposal_method, previous_pixel, pixel); } frame_buffer } else { ImageBuffer::from_fn(self.width, self.height, |x, y| { let frame_x = x.wrapping_sub(frame.left); let frame_y = y.wrapping_sub(frame.top); let previous_pixel = self.non_disposed_frame.get_pixel_mut(x, y); if frame_x < frame_buffer.width() && frame_y < frame_buffer.height() { let mut pixel = *frame_buffer.get_pixel(frame_x, frame_y); blend_and_dispose_pixel(frame.disposal_method, previous_pixel, &mut pixel); pixel } else { // out of bounds, return pixel from previous frame *previous_pixel } }) }; Some(Ok(animation::Frame::from_parts( image_buffer, 0, 0, frame.delay, ))) } } impl<'a, R: Read + 'a> AnimationDecoder<'a> for GifDecoder<R> { fn into_frames(self) -> animation::Frames<'a> { animation::Frames::new(Box::new(GifFrameIterator::new(self))) } } struct FrameInfo { left: u32, top: u32, width: u32, height: u32, disposal_method: DisposalMethod, delay: animation::Delay, } impl FrameInfo { fn new_from_frame(frame: &Frame) -> FrameInfo { FrameInfo { left: u32::from(frame.left), top: u32::from(frame.top), width: u32::from(frame.width), height: u32::from(frame.height), disposal_method: frame.dispose, // frame.delay is in units of 10ms so frame.delay*10 is in ms delay: animation::Delay::from_ratio(Ratio::new(u32::from(frame.delay) * 10, 1)), } } } /// Number of repetitions for a GIF animation #[derive(Clone, Copy, Debug)] pub enum Repeat { /// Finite number of repetitions Finite(u16), /// Looping GIF Infinite, } impl Repeat { pub(crate) fn to_gif_enum(&self) -> gif::Repeat { match self { Repeat::Finite(n) => gif::Repeat::Finite(*n), Repeat::Infinite => gif::Repeat::Infinite, } } } /// GIF encoder. pub struct GifEncoder<W: Write> { w: Option<W>, gif_encoder: Option<gif::Encoder<W>>, speed: i32, repeat: Option<Repeat>, } impl<W: Write> GifEncoder<W> { /// Creates a new GIF encoder with a speed of 1. This prioritizes quality over performance at any cost. pub fn new(w: W) -> GifEncoder<W> { Self::new_with_speed(w, 1) } /// Create a new GIF encoder, and has the speed parameter `speed`. See /// [`Frame::from_rgba_speed`](https://docs.rs/gif/latest/gif/struct.Frame.html#method.from_rgba_speed) /// for more information. pub fn new_with_speed(w: W, speed: i32) -> GifEncoder<W> { assert!( (1..=30).contains(&speed), "speed needs to be in the range [1, 30]" ); GifEncoder { w: Some(w), gif_encoder: None, speed, repeat: None, } } /// Set the repeat behaviour of the encoded GIF pub fn set_repeat(&mut self, repeat: Repeat) -> ImageResult<()> { if let Some(ref mut encoder) = self.gif_encoder { encoder .set_repeat(repeat.to_gif_enum()) .map_err(ImageError::from_encoding)?; } self.repeat = Some(repeat); Ok(()) } /// Encode a single image. pub fn encode( &mut self, data: &[u8], width: u32, height: u32, color: ColorType, ) -> ImageResult<()> { let (width, height) = self.gif_dimensions(width, height)?; match color { ColorType::Rgb8 => self.encode_gif(Frame::from_rgb(width, height, data)), ColorType::Rgba8 => { self.encode_gif(Frame::from_rgba(width, height, &mut data.to_owned())) } _ => Err(ImageError::Unsupported( UnsupportedError::from_format_and_kind( ImageFormat::Gif.into(), UnsupportedErrorKind::Color(color.into()), ), )), } } /// Encode one frame of animation. pub fn encode_frame(&mut self, img_frame: animation::Frame) -> ImageResult<()> { let frame = self.convert_frame(img_frame)?; self.encode_gif(frame) } /// Encodes Frames. /// Consider using `try_encode_frames` instead to encode an `animation::Frames` like iterator. pub fn encode_frames<F>(&mut self, frames: F) -> ImageResult<()> where F: IntoIterator<Item = animation::Frame>, { for img_frame in frames { self.encode_frame(img_frame)?; } Ok(()) } /// Try to encode a collection of `ImageResult<animation::Frame>` objects. /// Use this function to encode an `animation::Frames` like iterator. /// Whenever an `Err` item is encountered, that value is returned without further actions. pub fn try_encode_frames<F>(&mut self, frames: F) -> ImageResult<()> where F: IntoIterator<Item = ImageResult<animation::Frame>>, { for img_frame in frames { self.encode_frame(img_frame?)?; } Ok(()) } pub(crate) fn convert_frame( &mut self, img_frame: animation::Frame, ) -> ImageResult<Frame<'static>> { // get the delay before converting img_frame let frame_delay = img_frame.delay().into_ratio().to_integer(); // convert img_frame into RgbaImage let mut rbga_frame = img_frame.into_buffer(); let (width, height) = self.gif_dimensions(rbga_frame.width(), rbga_frame.height())?; // Create the gif::Frame from the animation::Frame let mut frame = Frame::from_rgba_speed(width, height, &mut rbga_frame, self.speed); // Saturate the conversion to u16::MAX instead of returning an error as that // would require a new special cased variant in ParameterErrorKind which most // likely couldn't be reused for other cases. This isn't a bad trade-off given // that the current algorithm is already lossy. frame.delay = (frame_delay / 10).try_into().unwrap_or(std::u16::MAX); Ok(frame) } fn gif_dimensions(&self, width: u32, height: u32) -> ImageResult<(u16, u16)> { fn inner_dimensions(width: u32, height: u32) -> Option<(u16, u16)> { let width = u16::try_from(width).ok()?; let height = u16::try_from(height).ok()?; Some((width, height)) } // TODO: this is not very idiomatic yet. Should return an EncodingError. inner_dimensions(width, height).ok_or_else(|| { ImageError::Parameter(ParameterError::from_kind( ParameterErrorKind::DimensionMismatch, )) }) } pub(crate) fn encode_gif(&mut self, mut frame: Frame) -> ImageResult<()> { let gif_encoder; if let Some(ref mut encoder) = self.gif_encoder { gif_encoder = encoder; } else { let writer = self.w.take().unwrap(); let mut encoder = gif::Encoder::new(writer, frame.width, frame.height, &[]) .map_err(ImageError::from_encoding)?; if let Some(ref repeat) = self.repeat { encoder .set_repeat(repeat.to_gif_enum()) .map_err(ImageError::from_encoding)?; } self.gif_encoder = Some(encoder); gif_encoder = self.gif_encoder.as_mut().unwrap() } frame.dispose = gif::DisposalMethod::Background; gif_encoder .write_frame(&frame) .map_err(ImageError::from_encoding) } } impl ImageError { fn from_decoding(err: gif::DecodingError) -> ImageError { use gif::DecodingError::*; match err { err @ Format(_) => { ImageError::Decoding(DecodingError::new(ImageFormat::Gif.into(), err)) } Io(io_err) => ImageError::IoError(io_err), } } fn from_encoding(err: gif::EncodingError) -> ImageError { use gif::EncodingError::*; match err { err @ Format(_) => { ImageError::Encoding(EncodingError::new(ImageFormat::Gif.into(), err)) } Io(io_err) => ImageError::IoError(io_err), } } } #[cfg(test)] mod test { use super::*; #[test] fn frames_exceeding_logical_screen_size() { // This is a gif with 10x10 logical screen, but a 16x16 frame + 6px offset inside. let data = vec![ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x0A, 0x00, 0x0A, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0xFF, 0x1F, 0x21, 0xF9, 0x04, 0x09, 0x64, 0x00, 0x00, 0x00, 0x2C, 0x06, 0x00, 0x06, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x23, 0x84, 0x8F, 0xA9, 0xBB, 0xE1, 0xE8, 0x42, 0x8A, 0x0F, 0x50, 0x79, 0xAE, 0xD1, 0xF9, 0x7A, 0xE8, 0x71, 0x5B, 0x48, 0x81, 0x64, 0xD5, 0x91, 0xCA, 0x89, 0x4D, 0x21, 0x63, 0x89, 0x4C, 0x09, 0x77, 0xF5, 0x6D, 0x14, 0x00, 0x3B, ]; let decoder = GifDecoder::new(Cursor::new(data)).unwrap(); let mut buf = vec![0u8; decoder.total_bytes() as usize]; assert!(decoder.read_image(&mut buf).is_ok()); } }
true
bb4c1f700b02c994faa7e35a1e91b6c19ff6ffb2
Rust
Riey/kes-rs
/src/location.rs
UTF-8
502
3.15625
3
[ "MIT" ]
permissive
use serde::{Deserialize, Serialize}; use std::fmt; #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)] pub struct Location { pub line: usize, } impl Location { pub fn new(line: usize) -> Self { Self { line } } pub fn next_line(mut self) -> Self { self.line += 1; self } } impl fmt::Display for Location { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "L{}", self.line) } }
true
3bb06c36d4af50a1162665cf9a54d92796811bbc
Rust
mckernant1/timeit
/src/main.rs
UTF-8
2,677
3.125
3
[]
no_license
#[macro_use] extern crate clap; use clap::{App, AppSettings}; use std::process::{Command, Stdio, exit, Child}; use std::time::SystemTime; fn main() { let yml = load_yaml!("cli.yml"); let mut app = App::from_yaml(yml); app = app.setting(AppSettings::TrailingVarArg); let matches = app.get_matches(); let cmd: Vec<&str> = matches.values_of("COMMAND").unwrap().collect::<Vec<&str>>(); let disable_output = matches.is_present("disable-output"); let parallel = matches.is_present("parallel"); let continue_on_failure = matches.is_present("continue-on-failure"); let num_times_res = matches .value_of("number-of-times-to-run") .unwrap_or("1") .parse::<i32>(); let num_times = match num_times_res { Ok(num) => num, Err(_) => { eprintln!("That is not an integer"); exit(1); } }; let mut children: Vec<(Child, SystemTime)> = vec![]; let mut times_vec: Vec<u128> = vec![]; let command = cmd.to_owned(); for _ in 0..num_times { if parallel { let t = run_command(command.to_owned(), true); children.push((t, SystemTime::now())); } else { let start_time = SystemTime::now(); let exit_status = run_command(command.to_owned(), disable_output.to_owned()) .wait().unwrap(); if !exit_status.success() && !continue_on_failure { break; } match start_time.elapsed() { Ok(time) => { times_vec.push(time.as_millis()) } Err(e) => eprintln!("{:?}", e) } } } // Print parallel times for (mut child, time) in children { child.wait().unwrap(); match time.elapsed() { Ok(time) => { println!("{}", time.as_millis()) } Err(e) => eprintln!("{:?}", e) } } // Print consecutive times for elapsed in times_vec { println!("{}", elapsed); } } fn run_command(command: Vec<&str>, disable_output: bool) -> Child { return match Command::new(command[0]) .args(&command[1..]) .stdin(if disable_output { Stdio::null() } else { Stdio::inherit() }) .stderr(if disable_output { Stdio::null() } else { Stdio::inherit() }) .stdout(if disable_output { Stdio::null() } else { Stdio::inherit() }) .spawn() { Ok(child) => child, Err(_) => { eprintln!("This command does not exist."); exit(1); } } }
true
137c71eb046cb53a51efa0f2fbedd7c9c62dbc39
Rust
youngspe/gramma
/tests/json.rs
UTF-8
4,567
3.234375
3
[ "MIT" ]
permissive
#[macro_use] pub mod common; use common::unwrap_display; use gramma::lex::{Eof, RealDecimal, StringToken, Whitespace}; use gramma::{grammar, tokens}; use std::collections::BTreeMap; use std::str::FromStr; tokens! { pub struct LBrace => symbol("{"); pub struct RBrace => symbol("}"); pub struct LBracket => symbol("["); pub struct RBracket => symbol("]"); pub struct Colon => symbol(":"); pub struct Comma => symbol(","); pub struct True => symbol("true"); pub struct False => symbol("false"); pub struct Null => symbol("null"); pub enum JsonToken => { | LBrace | RBrace | LBracket | RBracket | Colon | Comma | Whitespace | StringToken | RealDecimal | True | False | Null | Eof }; } grammar! { JsonToken; pub struct Kvp => { key: StringToken, Colon, value: Value }; pub struct List => { LBracket, vals: [(Value)(Comma)*], RBracket }; pub struct Object => { LBrace, vals: [(Kvp)(Comma)*], RBrace }; pub enum Bool => { True | False }; pub enum Value => { | Object | List | String(StringToken) | Number(RealDecimal) | Bool | Null }; pub struct Root => { value: Value, Eof }; } #[derive(Clone, Debug, PartialEq)] enum JsonValue { Object(BTreeMap<String, JsonValue>), List(Vec<JsonValue>), String(String), Number(f64), Bool(bool), Null, } fn parse(src: &str) -> JsonValue { fn parse_kvp(src: &str, tree: &Kvp) -> (String, JsonValue) { let key = tree.key.inner_str(src).to_string(); let value = inner(src, &tree.value); (key, value) } fn inner(src: &str, tree: &Value) -> JsonValue { match tree { Value::Object(Object { vals, .. }) => { JsonValue::Object(vals.iter().map(|kvp| parse_kvp(src, kvp)).collect()) } Value::List(List { vals, .. }) => { JsonValue::List(vals.iter().map(|v| inner(src, v)).collect()) } Value::String(s) => JsonValue::String(s.inner_str(src).to_string()), Value::Number(n) => JsonValue::Number(f64::from_str(n.get_str(src)).unwrap()), Value::Bool(Bool::True(..)) => JsonValue::Bool(true), Value::Bool(Bool::False(..)) => JsonValue::Bool(false), Value::Null(..) => JsonValue::Null, } } let (_, ast) = unwrap_display(gramma::parse(src)); inner(src, &ast) } macro_rules! object { ($($k:expr => $v:expr),*$(,)?) => {{ #[allow(unused)] let mut map = BTreeMap::new(); $(map.insert($k.into(), $v.into());)* JsonValue::Object(map) }}; } macro_rules! list { ($($x:expr),*$(,)?) => { JsonValue::List(vec![$($x.into()),*]) }; } macro_rules! json { ({$($key:literal => $val:tt),*$(,)?}) => { object! { $($key => json!($val)),* } }; ([$($val:tt),*$(,)?]) => { list![$(json!($val)),*] }; (null) => { JsonValue::Null }; ($lit:literal) => { JsonValue::from($lit) }; ($val:expr) => { Jso nValue::from($val) }; } impl From<&str> for JsonValue { fn from(src: &str) -> Self { Self::String(src.into()) } } impl From<String> for JsonValue { fn from(src: String) -> Self { Self::String(src) } } impl From<f64> for JsonValue { fn from(src: f64) -> Self { Self::Number(src) } } impl From<i64> for JsonValue { fn from(src: i64) -> Self { Self::Number(src as f64) } } impl From<bool> for JsonValue { fn from(src: bool) -> Self { Self::Bool(src) } } impl<T: Into<JsonValue> + Clone> From<&[T]> for JsonValue { fn from(src: &[T]) -> Self { JsonValue::List(src.iter().cloned().map(Into::into).collect()) } } impl From<Vec<JsonValue>> for JsonValue { fn from(src: Vec<JsonValue>) -> Self { JsonValue::List(src) } } impl<T: Into<JsonValue>> From<Option<T>> for JsonValue { fn from(src: Option<T>) -> Self { match src { Some(v) => v.into(), None => Self::Null, } } } #[test] fn parse_json() { parse("{ }"); let expected = json!({ "x" => "x", "y" => ["z", [], { "a" => ["c"], "d" => 3.5 }], "z" => {}, "w" => [true, null, 4.0, false], }); let src = r#"{ "x": "x", "y": ["z", [], {"a":["c"], "d": 3.5}], "z": {}, "w": [true, null, 4, false] }"#; assert_eq!(parse(src), expected); }
true
3a2ac700a46db1988f56cb521598cba74eba36ae
Rust
ia7ck/competitive-programming
/AtCoder/abc229/src/bin/b/main.rs
UTF-8
950
2.828125
3
[]
no_license
use input_i_scanner::InputIScanner; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let a = scan!(String); let a: Vec<u32> = a.chars().map(|ch| ch as u32 - '0' as u32).collect(); let b = scan!(String); let b: Vec<u32> = b.chars().map(|ch| ch as u32 - '0' as u32).collect(); for (a, b) in a.into_iter().rev().zip(b.into_iter().rev()) { if a + b >= 10 { println!("Hard"); return; } } println!("Easy"); }
true
4c6ea7d9c24651b0f0088ca2291b14090f140892
Rust
gibiansky/rustboot
/main.rs
UTF-8
2,833
2.84375
3
[ "MIT" ]
permissive
#![no_std] #![allow(improper_ctypes)] #![feature(lang_items)] #![feature(intrinsics)] #[allow(unstable)] extern crate core; use core::marker::Copy; use core::iter::*; use core::num::{from_u8,FromPrimitive}; use core::option::*; use core::option::Option::*; extern "rust-intrinsic" { pub fn volatile_store<T>(src: *mut T, value: T); pub fn volatile_load<T>(src: *const T) -> T; } static VIDEO_MEMORY : u32 = 0xB8000; pub enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Pink = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightPink = 13, Yellow = 14, White = 15, } static COLORS: [Color; 16] = [Color::Black, Color::Blue, Color::Green, Color::Cyan, Color::Red, Color::Pink, Color::Brown, Color::LightGray, Color::DarkGray, Color::LightBlue, Color::LightGreen, Color::LightCyan, Color::LightRed, Color::LightPink, Color::Yellow, Color::White]; impl Copy for Color {} impl FromPrimitive for Color { fn from_i64(n: i64) -> Option<Self> { if n < 0 || n > 15 { None } else { Some(COLORS[n as usize]) } } fn from_u64(n: u64) -> Option<Self> { if n > 15 { None } else { Some(COLORS[n as usize]) } } } fn clear_screen(background: Color) { for x in range(0, 80) { for y in range(0, 25) { set_background(x, y, background); set_char(x, y, 0); } } } unsafe fn read_video_mem(x: u8, y: u8) -> u16 { let addr = VIDEO_MEMORY + 2 * (y as u32 * 80 + x as u32); return volatile_load(addr as *const u16); } unsafe fn write_video_mem(x: u8, y: u8, val: u16) { let addr = VIDEO_MEMORY + 2 * (y as u32 * 80 + x as u32); volatile_store(addr as *mut u16, val); } fn set_char(x: u8, y: u8, ch: u8) { unsafe { let old_val: u16 = read_video_mem(x, y); let new_val = (old_val & 0xFF00) | (ch as u16); write_video_mem(x, y, new_val); } } fn set_background(x: u8, y: u8, color: Color) { unsafe { let old_val: u16 = read_video_mem(x, y); let new_val = (old_val & 0x0FFF) | ((color as u16) << 12); write_video_mem(x, y, new_val); } } fn set_foreground(x: u8, y: u8, color: Color) { unsafe { let old_val: u16 = read_video_mem(x, y); let new_val = (old_val & 0xF0FF) | ((color as u16) << 8); write_video_mem(x, y, new_val); } } #[no_mangle] pub fn main() { clear_screen(Color::Yellow); for x in range(0, 80) { for y in range(0, 25) { set_foreground(x, y, from_u8((x + y * 80) % 16).unwrap()); set_char(x, y, '.' as u8); } } }
true
4e574c7d5c791b185684eb188d9c38545c46809f
Rust
conradludgate/array_tools
/src/mut_ref.rs
UTF-8
944
2.90625
3
[]
no_license
//! ArrayIterator implementations on &mut [T; N] use crate::{ArrayIterator, IntoArrayIterator}; use core::marker::PhantomData; /// ArrayIter is an implementation of [`ArrayIterator`] for &[T; N] pub struct ArrayIter<'a, T: 'a, const N: usize> { ptr: *mut T, i: usize, _marker: PhantomData<&'a mut T>, } impl<'a, T, const N: usize> IntoArrayIterator<N> for &'a mut [T; N] { type Item = &'a mut T; type ArrayIter = ArrayIter<'a, T, N>; fn into_array_iter(self) -> Self::ArrayIter { ArrayIter { ptr: self.as_mut_ptr(), i: 0, _marker: PhantomData, } } } impl<'a, T, const N: usize> ArrayIterator<N> for ArrayIter<'a, T, N> { type Item = &'a mut T; unsafe fn next(&mut self) -> Self::Item { debug_assert_ne!(self.i, N, "Called next too many times"); let n = self.i + 1; &mut *self.ptr.add(core::mem::replace(&mut self.i, n)) } }
true
07f321e241042553be3c8a2ab3128472f1baa94c
Rust
killercup/rune
/crates/runestick/src/modules/future.rs
UTF-8
2,114
2.921875
3
[ "MIT", "Apache-2.0" ]
permissive
//! The `std::future` module. use crate::future::SelectFuture; use crate::{ContextError, Future, Module, Shared, Stack, Value, VmError, VmErrorKind}; /// Construct the `std::future` module. pub fn module() -> Result<Module, ContextError> { let mut module = Module::new(&["std", "future"]); module.ty(&["Future"]).build::<Future>()?; module.raw_fn(&["join"], raw_join)?; Ok(module) } async fn try_join_impl<'a, I, F>(values: I, len: usize, factory: F) -> Result<Value, VmError> where I: IntoIterator<Item = &'a Value>, F: FnOnce(Vec<Value>) -> Value, { use futures::StreamExt as _; let mut futures = futures::stream::FuturesUnordered::new(); let mut results = Vec::with_capacity(len); for (index, value) in values.into_iter().enumerate() { let future = match value { Value::Future(future) => future.clone().into_mut()?, value => return Err(VmError::bad_argument::<Future>(index, value)?), }; futures.push(SelectFuture::new(index, future)); results.push(Value::Unit); } while !futures.is_empty() { let (index, value) = futures.next().await.unwrap()?; *results.get_mut(index).unwrap() = value; } Ok(factory(results)) } async fn join(value: Value) -> Result<Value, VmError> { match value { Value::Tuple(tuple) => { let tuple = tuple.borrow_ref()?; Ok(try_join_impl(tuple.iter(), tuple.len(), Value::tuple).await?) } Value::Vec(vec) => { let vec = vec.borrow_ref()?; Ok(try_join_impl(vec.iter(), vec.len(), Value::vec).await?) } value => Err(VmError::bad_argument::<Vec<Value>>(0, &value)?), } } /// The join implementation. fn raw_join(stack: &mut Stack, args: usize) -> Result<(), VmError> { if args != 1 { return Err(VmError::from(VmErrorKind::BadArgumentCount { actual: args, expected: 1, })); } let value = stack.pop()?; let value = Value::Future(Shared::new(Future::new(join(value)))); stack.push(value); Ok(()) }
true
a09b4fde9a2865b4df60ff8ae8e4ef66ca805a75
Rust
0ncorhynchus/ndarray-matops
/src/utils.rs
UTF-8
3,404
2.90625
3
[]
no_license
use ndarray::{ArrayBase, Data, Ix2}; #[cfg(feature = "blas")] pub use blas_utils::*; #[derive(Clone, Copy, PartialEq)] pub enum MemoryOrder { C, F, } pub fn memory_layout<S>(a: &ArrayBase<S, Ix2>) -> Option<MemoryOrder> where S: Data, { let (m, n) = a.dim(); let s0 = a.strides()[0]; let s1 = a.strides()[1]; if s1 == 1 || n == 1 { return Some(MemoryOrder::C); } if s0 == 1 || m == 1 { return Some(MemoryOrder::F); } None } #[cfg(feature = "blas")] mod blas_utils { use super::*; use cblas_sys::CBLAS_LAYOUT; use ndarray::{ArrayBase, Data, Ix1, Ix2}; use std::any::TypeId; use std::os::raw::c_int; /// Return a pointer to the starting element in BLAS's view. /// /// BLAS wants a pointer to the element with lowest address, /// which agrees with our pointer for non-negative strides, but /// is at the opposite end for negative strides. pub unsafe fn blas_1d_params<A>( ptr: *const A, len: usize, stride: isize, ) -> (*const A, c_int, c_int) { // [x x x x] // ^--ptr // stride = -1 // ^--blas_ptr = ptr + (len - 1) * stride if stride >= 0 || len == 0 { (ptr, len as c_int, stride as c_int) } else { let ptr = ptr.offset((len - 1) as isize * stride); (ptr, len as c_int, stride as c_int) } } #[inline(always)] /// Return `true` if `A` and `B` are the same type pub fn same_type<A: 'static, B: 'static>() -> bool { TypeId::of::<A>() == TypeId::of::<B>() } // Read pointer to type `A` as type `B`. // // **Panics** if `A` and `B` are not the same type pub fn cast_as<A: 'static + Copy, B: 'static + Copy>(a: &A) -> B { assert!(same_type::<A, B>()); unsafe { ::std::ptr::read(a as *const _ as *const B) } } pub fn is_blas_compat_1d<S: Data>(a: &ArrayBase<S, Ix1>) -> bool { if !is_blas_compat_dim(a.len()) { return false; } if !is_blas_compat_stride(a.strides()[0]) { return false; } true } impl MemoryOrder { pub fn stride<S: Data>(&self, a: &ArrayBase<S, Ix2>) -> c_int { match self { MemoryOrder::C => a.strides()[0] as c_int, MemoryOrder::F => a.strides()[1] as c_int, } } } impl From<MemoryOrder> for CBLAS_LAYOUT { fn from(order: MemoryOrder) -> Self { match order { MemoryOrder::C => CBLAS_LAYOUT::CblasRowMajor, MemoryOrder::F => CBLAS_LAYOUT::CblasColMajor, } } } fn is_blas_compat_stride(s: isize) -> bool { s <= c_int::max_value() as isize && s >= c_int::min_value() as isize } fn is_blas_compat_dim(n: usize) -> bool { n <= c_int::max_value() as usize } pub fn is_blas_compat_2d<S: Data>(a: &ArrayBase<S, Ix2>) -> bool { let (m, n) = a.dim(); let strides = a.strides(); if strides[0] < 1 || strides[1] < 1 { return false; } if !is_blas_compat_stride(strides[0]) || !is_blas_compat_stride(strides[1]) { return false; } if !is_blas_compat_dim(m) || !is_blas_compat_dim(n) { return false; } true } }
true
fce326bb15c8a9d54b7ea532dce4e4fe94cbd386
Rust
ultramario1998/simple-rust-sql-parser
/main.rs
UTF-8
644
3.453125
3
[]
no_license
use std::io; use regex::Regex; fn main() { let mut math_string = String::new(); println!("Please input the math expression to parse: "); io::stdin().read_line(&mut math_string); do_math(&math_string.trim()); } fn do_math(test_string: &str){ println!("parsing string \"{}\".", test_string); let regex_string = Regex::new("[a-zA-Z!@#$%&()^,.<>?_=`~;:'\"\\[\\]{}|]").unwrap(); let regex_digits_only = Regex::new("\\D").unwrap(); let parsed_string = regex_string.replace_all(test_string, ""); let split_iterator: Vec<&str> = regex_digits_only.split(&parsed_string).collect(); for x in split_iterator { println!("{:?}", x.trim()); } }
true
0d6e419f183e7c4fa232211c83d56bcb0d8765eb
Rust
eugene-bulkin/nanodb-rust
/src/expressions/from_clause.rs
UTF-8
16,348
3.125
3
[]
no_license
//! This module contains `FROM` clause information. use std::collections::HashSet; use std::default::Default; use ::commands::{ExecutionError, InvalidSchemaError, JoinSide}; use ::expressions::{CompareType, Expression, SelectValue}; use ::relations::{ColumnInfo, Schema}; use ::storage::{FileManager, TableManager}; /// For FROM clauses that contain join expressions, this enumeration specifies the kind of /// join-condition for each join expression. #[derive(Clone, Debug, PartialEq)] pub enum JoinConditionType { /// Perform a natural join, which implicitly specifies that values in all shared columns must be /// equal. NaturalJoin, /// The join clause specifies an ON clause with an expression that must evaluate to true. OnExpr(Expression), /// The join clause specifies a USING clause, which explicitly lists the shared columns whose /// values must be equal. Using(Vec<String>), } impl Default for JoinConditionType { fn default() -> Self { JoinConditionType::OnExpr(Expression::True) } } impl ::std::fmt::Display for JoinConditionType { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { JoinConditionType::NaturalJoin => write!(f, "NaturalJoin"), JoinConditionType::OnExpr(ref expr) => write!(f, "JoinOn({})", expr), JoinConditionType::Using(ref names) => write!(f, "JoinUsing({})", names.join(", ")), } } } /// An enumeration specifying the different types of join operation. #[derive(Copy, Clone, Debug, PartialEq)] pub enum JoinType { /// Inner joins, where only matching rows are included in the result. Inner, /// Left outer joins, where non-matching rows from the left table are included in the results. LeftOuter, /// Right outer joins, where non-matching rows from the right table are included in the results. RightOuter, /// Full outer joins, where non-matching rows from either the left or right table are included /// in the results. FullOuter, /// Cross joins, which are simply a Cartesian product. Cross, /// Semijoin, where the left table's rows are included when they match one or more rows from the /// right table. Semijoin, /// Antijoin (aka anti-semijoin), where the left table's rows are included when they match none /// of the rows from the right table. Antijoin, } impl ::std::fmt::Display for JoinType { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { JoinType::Inner => write!(f, "Inner"), JoinType::LeftOuter => write!(f, "Left Outer"), JoinType::RightOuter => write!(f, "Right Outer"), JoinType::FullOuter => write!(f, "Full Outer"), JoinType::Cross => write!(f, "Cross"), JoinType::Semijoin => write!(f, "Semijoin"), JoinType::Antijoin => write!(f, "Antijoin"), } } } #[derive(Clone, Debug, PartialEq)] /// This enum represents a hierarchy of one or more base and derived relations that produce the rows /// considered by `SELECT` clauses. pub struct FromClause { /// The actual FROM clause data. pub clause_type: FromClauseType, computed_join_expr: Option<Expression>, computed_schema: Option<Schema>, computed_select_values: Option<Vec<SelectValue>>, } impl ::std::ops::Deref for FromClause { type Target = FromClauseType; fn deref(&self) -> &Self::Target { &self.clause_type } } fn check_join_column<S: Into<String>>(schema: &Schema, side: JoinSide, name: S) -> Result<(), InvalidSchemaError> { let name = name.into(); let count = schema.num_columns_with_name(name.as_ref()); if count == 0 { Err(InvalidSchemaError::MissingJoinColumn(name.clone(), side)) } else if count > 1 { Err(InvalidSchemaError::AmbiguousJoinColumn(name.clone(), side)) } else { Ok(()) } } fn build_join_schema(left: Schema, right: Schema, common: HashSet<String>, result: &mut Schema, join_type: JoinType) -> Result<(Option<Expression>, Option<Vec<SelectValue>>), ExecutionError> { let mut join_expr = None; let mut select_values = Vec::new(); if !common.is_empty() { // We will need to generate a join expression using the common // columns. We will also need a project-spec that will project down // to only one copy of the common columns. let mut and_clauses: Vec<Expression> = Vec::new(); // Handle the shared columns. We need to check that the // names aren't ambiguous on one or the other side. for name in common.iter() { try!(check_join_column(&left, JoinSide::Left, name.as_ref())); try!(check_join_column(&right, JoinSide::Right, name.as_ref())); let left_info = left.get_column(name.as_ref()).unwrap(); let right_info = right.get_column(name.as_ref()).unwrap(); try!(result.add_column(ColumnInfo::with_name(left_info.column_type, name.as_ref())).map_err(ExecutionError::CouldNotCreateSchema)); let compare_expr = Expression::Compare(Box::new(Expression::ColumnValue(left_info.get_column_name())), CompareType::Equals, Box::new(Expression::ColumnValue(right_info.get_column_name()))); and_clauses.push(compare_expr); // Add a select-value that projects the appropriate source column down to the common // column. match join_type { JoinType::Inner | JoinType::LeftOuter => { // We can use the left column in the result, as it will always be non-NULL. select_values.push(SelectValue::Expression { expression: Expression::ColumnValue(left_info.get_column_name()), alias: Some(name.clone()), }); } JoinType::RightOuter => { // We can use the right column in the result, as it will always be non-NULL. select_values.push(SelectValue::Expression { expression: Expression::ColumnValue(right_info.get_column_name()), alias: Some(name.clone()), }); } JoinType::FullOuter => { // In this case, the LHS column-value could be null, or the RHS column-value // could be null. Thus, we need to produce a result of // COALESCE(lhs.col, rhs.col) AS col. let coalesce = Expression::Function { name: "COALESCE".into(), distinct: false, args: vec![ Expression::ColumnValue(left_info.get_column_name()), Expression::ColumnValue(right_info.get_column_name()), ], }; select_values.push(SelectValue::Expression { expression: coalesce, alias: Some(name.clone()), }); } _ => { // Do nothing...? } } } join_expr = Some(Expression::AND(and_clauses)); } // Handle the non-shared columns for col_info in left.iter().chain(right.iter()) { let col_name = col_info.get_column_name(); match col_name { (_, Some(ref name)) => { if !common.contains(name) { try!(result.add_column(col_info.clone()).map_err(ExecutionError::CouldNotCreateSchema)); select_values.push(SelectValue::Expression { expression: Expression::ColumnValue(col_name.clone()), alias: None, }); } } _ => {} } } Ok((join_expr, if select_values.is_empty() { None } else { Some(select_values) })) } #[derive(Clone, Debug, PartialEq)] /// This enum contains information about what kind of FROM clause the clause is. pub enum FromClauseType { /// A `FROM` clause that just selects a base table and possibly an alias. BaseTable { /// The name of the table being selected from. table: String, /// An optional alias to rename the table with. alias: Option<String>, }, /// A `FROM` clause that is a join expression (may be nested). JoinExpression { /// The left child of the join. left: Box<FromClause>, /// The right child of the join. right: Box<FromClause>, /// The join type. join_type: JoinType, /// The join condition type. condition_type: JoinConditionType, }, } impl ::std::fmt::Display for FromClauseType { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { FromClauseType::BaseTable { .. } => write!(f, "BaseTable"), FromClauseType::JoinExpression { .. } => write!(f, "JoinExpression"), } } } impl FromClause { /// Instantiate a FROM clause that is a base table. pub fn base_table(table: String, alias: Option<String>) -> FromClause { FromClause { clause_type: FromClauseType::BaseTable { table: table, alias: alias, }, computed_schema: None, computed_join_expr: None, computed_select_values: None, } } /// Instantiate a FROM clause that is a join expression. pub fn join_expression(left: Box<FromClause>, right: Box<FromClause>, join_type: JoinType, condition_type: JoinConditionType) -> FromClause { FromClause { clause_type: FromClauseType::JoinExpression { left: left, right: right, join_type: join_type, condition_type: condition_type, }, computed_schema: None, computed_join_expr: None, computed_select_values: None, } } /// Retrieve the computed join expression. pub fn get_computed_join_expr(&self) -> Option<Expression> { self.computed_join_expr.clone() } /// Retrieve the computed select values. pub fn get_computed_select_values(&self) -> Option<Vec<SelectValue>> { self.computed_select_values.clone() } /// Calculate the schema and computed join expression for the FROM clause. pub fn compute_schema(&mut self, file_manager: &FileManager, table_manager: &TableManager) -> Result<Schema, ExecutionError> { let result = match self.clause_type { FromClauseType::BaseTable { ref table, ref alias } => { debug!("Preparing BASE_TABLE from-clause."); if !table_manager.table_exists(file_manager, table.as_ref()) { return Err(ExecutionError::TableDoesNotExist(table.clone())); } let table = try!(table_manager.get_table(file_manager, table.clone()).map_err(ExecutionError::CouldNotComputeSchema)); let mut schema = table.get_schema(); if let Some(ref name) = *alias { try!(schema.set_table_name(name.as_ref()) .map_err(ExecutionError::CouldNotCreateSchema)); } self.computed_schema = Some(schema.clone()); schema.clone() } FromClauseType::JoinExpression { ref mut left, ref mut right, ref condition_type, ref join_type } => { debug!("Preparing JOIN_EXPR from-clause. Condition type = {}", condition_type); let mut schema = Schema::new(); let left_schema = try!(left.compute_schema(file_manager, table_manager)); let right_schema = try!(right.compute_schema(file_manager, table_manager)); match *condition_type { JoinConditionType::NaturalJoin => { if left_schema.has_multiple_columns_with_same_name() { return Err(ExecutionError::InvalidSchema(InvalidSchemaError::LeftSchemaDuplicates)); } if right_schema.has_multiple_columns_with_same_name() { return Err(ExecutionError::InvalidSchema(InvalidSchemaError::RightSchemaDuplicates)); } let common_cols = left_schema.get_common_column_names(&right_schema); if common_cols.is_empty() { return Err(ExecutionError::InvalidSchema(InvalidSchemaError::NoShared)); } let built = try!(build_join_schema(left_schema, right_schema, common_cols, &mut schema, *join_type)); self.computed_join_expr = built.0; self.computed_select_values = built.1; } JoinConditionType::Using(ref names) => { let mut common_cols: HashSet<String> = HashSet::new(); for name in names { if !common_cols.insert(name.clone()) { return Err(ExecutionError::InvalidSchema(InvalidSchemaError::UsingDuplicate(name.clone()))); } } let built = try!(build_join_schema(left_schema, right_schema, common_cols, &mut schema, *join_type)); self.computed_join_expr = built.0; self.computed_select_values = built.1; } JoinConditionType::OnExpr(ref expr) => { try!(schema.add_columns(left_schema)); try!(schema.add_columns(right_schema)); self.computed_join_expr = Some(expr.clone()); } } self.computed_schema = Some(schema.clone()); schema.clone() } }; Ok(result) } } impl ::std::fmt::Display for FromClause { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { try!(write!(f, "JoinClause[type={}", self.clause_type)); match self.clause_type { FromClauseType::BaseTable { ref table, ref alias } => { try!(write!(f, ", table={}", table)); if let Some(ref name) = *alias { try!(write!(f, " AS {}", name)); } } FromClauseType::JoinExpression { ref left, ref right, ref join_type, ref condition_type } => { try!(write!(f, ", join_type={}", join_type)); try!(write!(f, ", cond_type={}", condition_type)); match *condition_type { JoinConditionType::NaturalJoin => { try!(write!(f, ", computed_join_expr={}", self.computed_join_expr.clone().unwrap())); } JoinConditionType::Using(ref names) => { try!(write!(f, ", using_names={}", names.join(", "))); try!(write!(f, ", computed_join_expr={}", self.computed_join_expr.clone().unwrap())); } JoinConditionType::OnExpr(ref expr) => { if *expr != Expression::True { try!(write!(f, ", on_expr={}", expr)); } } } try!(write!(f, ", left_child={}", left)); try!(write!(f, ", right_child={}", right)); } } write!(f, "]") } }
true
9020e1b85f32c705cbfc874f165d84158d120878
Rust
wartyz/atari_emul
/src/debugger.rs
UTF-8
1,677
2.671875
3
[]
no_license
#![allow(non_snake_case)] use crate::cpu::*; pub struct Debugger {} impl Debugger { pub fn DumpCPU(cpu: &mut CPU) { //print!("Dumping CPU state: "); print!("A = {:02X}, ({:03}) ", cpu.A, cpu.A); print!("X = {:02X}, ({:03}) ", cpu.X, cpu.X); print!("Y = {:02X}, ({:03}) ", cpu.Y, cpu.Y); print!("PC = {:04X}, ({:05}) ", cpu.PC, cpu.PC); print!("S = {:02X}, ({:03}) ", cpu.S, cpu.S); print!("Flags = "); if cpu.IsSetFlag(CPU::NEGATIVE_FLAG) { print!("{}", "N"); } else { print!("{}", "n"); } if cpu.IsSetFlag(CPU::OVERFLOW_FLAG) { print!("{}", "O"); } else { print!("{}", "o"); } if cpu.IsSetFlag(CPU::IGNORED_FLAG) { print!("{}", "X"); } else { print!("{}", "x"); } if cpu.IsSetFlag(CPU::BREAK_FLAG) { print!("{}", "B"); } else { print!("{}", "b"); } if cpu.IsSetFlag(CPU::DECIMAL_FLAG) { print!("{}", "D"); } else { print!("{}", "d"); } if cpu.IsSetFlag(CPU::INTERRUPT_FLAG) { print!("{}", "I"); } else { print!("{}", "i"); } if cpu.IsSetFlag(CPU::ZERO_FLAG) { print!("{}", "Z"); } else { print!("{}", "z"); } if cpu.IsSetFlag(CPU::CARRY_FLAG) { print!("{}", "C"); } else { print!("{}", "c"); } println!(" {:08b}", cpu.F); } } /* pub const NEGATIVE_FLAG: flag_t = 0b1000_0000; pub const OVERFLOW_FLAG: flag_t = 0b0100_0000; pub const IGNORED_FLAG: flag_t = 0b0010_0000; pub const BREAK_FLAG: flag_t = 0b0001_0000; pub const DECIMAL_FLAG: flag_t = 0b0000_1000; pub const INTERRUPT_FLAG: flag_t = 0b0000_0100; pub const ZERO_FLAG: flag_t = 0b0000_0010; pub const CARRY_FLAG: flag_t = 0b0000_0001; */
true
ce470a4c042ea1ff013ee6724020d51961993bda
Rust
spacejam/automerge-rs
/automerge-frontend/src/object.rs
UTF-8
1,987
3
3
[ "MIT" ]
permissive
use crate::{MapType, SequenceType, Value}; use automerge_protocol as amp; use std::{cell::RefCell, collections::HashMap, rc::Rc}; /// Represents the set of conflicting values for a register in an automerge /// document. #[derive(Clone, Debug)] pub struct Values(pub(crate) HashMap<amp::OpID, Rc<RefCell<Object>>>); impl Values { fn to_value(&self) -> Value { self.default_value().borrow().value() } pub(crate) fn default_value(&self) -> Rc<RefCell<Object>> { let mut op_ids: Vec<&amp::OpID> = self.0.keys().collect(); op_ids.sort(); let default_op_id = op_ids.first().unwrap(); self.0.get(default_op_id).cloned().unwrap() } pub(crate) fn update_for_opid(&mut self, opid: amp::OpID, value: Rc<RefCell<Object>>) { self.0.insert(opid, value); } } /// Internal data type used to represent the values of an automerge document #[derive(Clone, Debug)] pub enum Object { Sequence(amp::ObjectID, Vec<Option<Values>>, SequenceType), Map(amp::ObjectID, HashMap<String, Values>, MapType), Primitive(amp::Value), } impl Object { pub(crate) fn value(&self) -> Value { match self { Object::Sequence(_, vals, seq_type) => Value::Sequence( vals.iter() .filter_map(|v| v.clone().map(|v2| v2.to_value())) .collect(), seq_type.clone(), ), Object::Map(_, vals, map_type) => Value::Map( vals.iter() .map(|(k, v)| (k.to_string(), v.to_value())) .collect(), map_type.clone(), ), Object::Primitive(v) => Value::Primitive(v.clone()), } } pub(crate) fn id(&self) -> Option<amp::ObjectID> { match self { Object::Sequence(oid, _, _) => Some(oid.clone()), Object::Map(oid, _, _) => Some(oid.clone()), Object::Primitive(..) => None, } } }
true
e06ca14986419c9c96518b0af2afdf65f1664086
Rust
qualiaa/aoc
/2022/17/ab.rs
UTF-8
6,431
3.375
3
[]
no_license
use std::collections::HashSet; use std::ops::{Add, AddAssign, Deref}; use std::str::FromStr; use std::iter::IntoIterator; use std::io::Read; use std::cmp::max; #[derive(Debug, PartialEq, Eq, Hash, Clone)] struct Coord(isize, isize); impl Add<Self> for Coord { type Output = Self; fn add(self, rhs: Self) -> Self::Output { self + &rhs } } impl AddAssign<Self> for Coord { fn add_assign(&mut self, rhs: Self) { *self += &rhs } } impl Add<&Self> for Coord { type Output = Self; fn add(mut self, rhs: &Self) -> Self::Output { self += rhs; self } } impl AddAssign<&Self> for Coord { fn add_assign(&mut self, rhs: &Self) { self.0 += rhs.0; self.1 += rhs.1; } } impl Add<Self> for &Coord { type Output = <Self as Deref>::Target; fn add(self, rhs: Self) -> Self::Output { self.clone() + rhs } } impl Add<Coord> for &Coord { type Output = <Self as Deref>::Target; fn add(self, rhs: Coord) -> Self::Output { rhs + self } } const LEFT: Coord = Coord(-1, 0); const RIGHT: Coord = Coord(1, 0); const DOWN: Coord = Coord(0, -1); type Shape = HashSet<Coord>; type Chamber = HashSet<Coord>; #[derive(Debug, Clone)] struct Tetromino { shape: Shape, width: usize, height: usize } impl FromStr for Tetromino { type Err = String; fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { let lines: Vec<_> = s.trim().split('\n').collect(); let height = lines.len(); let shape: Shape = lines.into_iter().rev().enumerate().flat_map(|(j, line)| line.chars() .enumerate() .filter_map(move |(i, c)| if c == '@' {Some(Coord(i as isize, j as isize))} else {None}) ).collect(); let width = shape.iter().map(|Coord(i, _)| *i).max().unwrap() as usize; Ok(Tetromino { shape, width, height }) } } impl Tetromino { fn collision(&self, position: &Coord, chamber: &Chamber) -> bool { self.shape.iter().map(|p| p+position).any(|p| chamber.contains(&p)) } fn out_of_bounds(&self, position: &Coord) -> bool { position.1 < 0 || position.0 < 0 || position.0 + self.width as isize > 6 } fn check(&self, position: Coord, chamber: &Chamber) -> Option<Coord> { if self.out_of_bounds(&position) || self.collision(&position, &chamber) { None } else { Some(position) } } fn step(&self, position: Coord, shift: Coord, chamber: &Chamber) -> Result<Coord, Coord> { // Very normal thing to write self.check(&position + shift, &chamber).ok_or(()).or(Ok(position)).and_then(|p| { self.check(&p + DOWN, &chamber).ok_or(p) }) } fn place(&self, position: &Coord, chamber: &mut Chamber) { for p in self.shape.iter() { chamber.insert(p+position); } } fn settle(&self, mut position: Coord, mut chamber: &mut Chamber, moves: &mut impl Iterator<Item=Coord>) -> Coord { for shift in moves { match self.step(position, shift, &chamber) { Ok(new_position) => position = new_position, Err(last_position) => { self.place(&last_position, &mut chamber); return last_position } } } panic!("unreachable"); } fn cycle() -> impl Iterator<Item=Tetromino> { IntoIterator::into_iter([ r#" @@@@ "#, r#" .@. @@@ .@. "#, r#" ..@ ..@ @@@ "#, r#" @ @ @ @"#, r#" @@ @@"# ]).map(Tetromino::from_str).filter_map(Result::ok).cycle() } } fn find_cycle<T: Eq>(xs: &[T], min: usize) -> Option<(usize, usize)> { for cycle_size in (min..=xs.len()/2).rev() { let (start, end) = xs.split_at(xs.len()-cycle_size); if start.ends_with(end) { return Some((cycle_size, xs.len() - 2 * cycle_size)) } } return None; } fn main() { let mut input = String::new(); std::io::stdin().read_to_string(&mut input).unwrap(); let instructions: Vec<_> = input.trim().chars().map(|c| match c { '<' => LEFT, '>' => RIGHT, _ => panic!("panik!") }).collect(); let num_instructions = instructions.len(); let target_pieces: usize = 1_000_000_000_000; let mut chamber = HashSet::new(); let mut instruction_cycle = instructions.iter().cloned().cycle(); let iter = Tetromino::cycle() .scan((0, 0), |(last_y, steps), piece| { let start_y = *last_y as isize + 3; let end_y = piece.settle(Coord(2, start_y), &mut chamber, &mut instruction_cycle).1; let max_y = max(end_y as usize + piece.height, *last_y); *last_y = max_y; *steps += start_y - end_y; Some((max_y as usize, *steps as usize)) }); let mut all_heights = Vec::<usize>::new(); let mut heights = Vec::<usize>::new(); let mut deltas = Vec::<usize>::new(); let mut pieces = Vec::<usize>::new(); for (piece, (tower_height, step)) in iter.enumerate().map(|(i,x)| (i+1, x)) { if piece == 2022 { println!("{}", tower_height); } all_heights.push(tower_height); if step % num_instructions != 0 || piece % 5 != 0 {continue} deltas.push(tower_height - heights.last().unwrap_or(&0)); heights.push(tower_height); pieces.push(piece); if let Some((cycle_size, start_index)) = find_cycle(&deltas, 349) { let start_pieces = pieces[start_index]; let end_pieces = pieces[start_index + cycle_size]; let cycle_pieces = end_pieces - start_pieces; let start_height = heights[start_index]; let end_height = heights[start_index + cycle_size]; let cycle_height = end_height - start_height; let skipped_cycles = (target_pieces - start_pieces) / cycle_pieces; let remaining_pieces = target_pieces - start_pieces - skipped_cycles * cycle_pieces; let skipped_height = skipped_cycles * cycle_height; println!("{}", start_height + skipped_height + (all_heights[start_pieces + remaining_pieces - 1] - all_heights[start_pieces-1])); break; } } }
true
47968b2682a8b4317f7f80a496530185bae1fb1b
Rust
saeedtabrizi/moleculer-rs
/src/channels/disconnect.rs
UTF-8
1,975
2.515625
3
[ "Apache-2.0" ]
permissive
use crate::{ broker::ServiceBroker, config::{Channel, Config}, nats::Conn, }; use super::messages::incoming::DisconnectMessage; use act_zero::*; use async_nats::Message; use async_trait::async_trait; use log::{debug, error, info}; use std::sync::Arc; #[async_trait] impl Actor for Disconnect { async fn started(&mut self, pid: Addr<Self>) -> ActorResult<()> { let pid_clone = pid.clone(); send!(pid_clone.listen(pid)); Produces::ok(()) } async fn error(&mut self, error: ActorError) -> bool { error!("Disconnect Actor Error: {:?}", error); // do not stop on actor error false } } pub(crate) struct Disconnect { broker: WeakAddr<ServiceBroker>, config: Arc<Config>, conn: Conn, } impl Disconnect { pub(crate) async fn new( broker: WeakAddr<ServiceBroker>, config: &Arc<Config>, conn: &Conn, ) -> Self { Self { broker, conn: conn.clone(), config: Arc::clone(config), } } pub(crate) async fn listen(&mut self, pid: Addr<Self>) { info!("Listening for DISCONNECT messages"); let channel = self .conn .subscribe(&Channel::Disconnect.channel_to_string(&self.config)) .await .unwrap(); pid.clone().send_fut(async move { while let Some(msg) = channel.next().await { match call!(pid.handle_message(msg)).await { Ok(_) => debug!("Successfully handled DISCONNECT message"), Err(e) => error!("Unable to handle DISCONNECT message: {}", e), } } }) } async fn handle_message(&self, msg: Message) -> ActorResult<()> { let disconnect_msg: DisconnectMessage = self.config.serializer.deserialize(&msg.data)?; send!(self.broker.handle_disconnect_message(disconnect_msg)); Produces::ok(()) } }
true
1eeeb09a60342e8b058d5cc2f1117d8b56ce6215
Rust
viest/pico-php-parser
/src/ast.rs
UTF-8
8,973
2.984375
3
[]
no_license
use std::rc::Rc; use tokenizer::Span; use interner::RcStr; #[derive(Clone, Debug, PartialEq)] pub enum ParsedItem { Text(RcStr), CodeBlock(Vec<Expr>), } pub type UseAlias = Option<RcStr>; #[derive(Clone, Debug, PartialEq)] pub enum UseClause { QualifiedName(Path, UseAlias), } #[derive(Clone, Debug, PartialEq)] pub struct Path { pub is_absolute: bool, pub namespace: Option<RcStr>, /// mostly something like the trait or class name pub identifier: RcStr, } impl Path { pub fn identifier(absolute: bool, name: RcStr) -> Path { Path { namespace: None, identifier: name, is_absolute: absolute, } } pub fn ns_identifier(absolute: bool, namespace: RcStr, name: RcStr) -> Path { Path { namespace: Some(namespace), identifier: name, is_absolute: absolute, } } } /// binary operators #[derive(Clone, Debug, PartialEq)] pub enum Op { Concat, // arith Add, Sub, Mul, Div, Pow, Mod, // logical Or, And, // equality Identical, NotIdentical, Eq, Neq, // relational Lt, Gt, Le, Ge, // bitwise BitwiseAnd, BitwiseInclOr, /// XOR BitwiseExclOr, /// spaceship operator, <=> Spaceship, Sl, Sr, } #[derive(Clone, Debug, PartialEq)] pub enum UnaryOp { Positive, Negative, Not, PreInc, PreDec, PostInc, PostDec, BitwiseNot, /// "@"" http://php.net/manual/en/language.operators.errorcontrol.php /// any error messages that might be generated by that expression will be ignored. SilenceErrors, } #[derive(Copy, Clone, Debug, PartialEq)] pub enum Visibility { None, Public, Private, Protected, } #[derive(Copy, Clone, Debug, PartialEq)] pub enum ClassModifier { Abstract = 1<<0, Final = 1<<1, } #[derive(Copy, Clone, Debug, PartialEq)] pub struct ClassModifiers(u8); impl ClassModifiers { pub fn none() -> ClassModifiers { ClassModifiers(0) } pub fn new(cms: &[ClassModifier]) -> ClassModifiers { let mut flag = 0; for modifier in cms { flag |= *modifier as u8; } ClassModifiers(flag) } #[inline] pub fn has(&self, m: ClassModifier) -> bool { self.0 & (m as u8) != 0 } } /// the boolean indicates whether the underlying item is static or not /// TODO: error validation of duplicate and invalid states in ::new #[derive(Copy, Clone, Debug, PartialEq)] pub enum MemberModifier { Public = 1<<0, Protected = 1<<1, Private = 1<<2, Static = 1<<3, Abstract = 1<<4, Final = 1<<5, } #[derive(Copy, Clone, Debug, PartialEq)] pub struct MemberModifiers(u8); impl MemberModifiers { pub fn none() -> MemberModifiers { MemberModifiers(0) } pub fn new(ms: &[MemberModifier]) -> MemberModifiers { let mut flag = 0; for modifier in ms { flag |= *modifier as u8; } MemberModifiers(flag) } pub fn has(&self, m: MemberModifier) -> bool { self.0 & (m as u8) != 0 } } #[derive(Clone, Debug, PartialEq)] pub struct Expr(pub Expr_, pub Span); #[derive(Clone, Debug, PartialEq)] pub struct Stmt(pub Stmt_, pub Span); #[derive(Clone, Debug, PartialEq)] pub struct Block(pub Vec<Stmt>); impl Block { pub fn empty() -> Block { Block(vec![]) } pub fn is_empty(&self) -> bool { self.0.is_empty() } } #[derive(Clone, Debug, PartialEq)] pub enum Variable { Name(RcStr), /// something like $$test, where another expression contains the name of the variable to be fetched Fetch(Box<Expr>), } impl<T: Into<RcStr>> From<T> for Variable { fn from(t: T) -> Variable { Variable::Name(t.into()) } } #[derive(Clone, Debug, PartialEq)] pub enum Expr_ { /// indicates the path to e.g. a namespace or is a simple identifier (e.g. a runtime-constant) /// or a builtin (internal) constant like true, false, null or any magic-constant Path(Path), String(RcStr), BinaryString(Rc<Vec<u8>>), Int(i64), Double(f64), Array(Vec<(Option<Expr>, Expr)>), Variable(Variable), Reference(Box<Expr>), Clone(Box<Expr>), Isset(Vec<Expr>), Empty(Box<Expr>), Exit(Option<Box<Expr>>), Include(IncludeTy, Box<Expr>), ArrayIdx(Box<Expr>, Vec<Option<Expr>>), ObjMember(Box<Expr>, Vec<Expr>), StaticMember(Box<Expr>, Vec<Expr>), Call(Box<Expr>, Vec<Expr>), New(Box<Expr>, Vec<Expr>), /// variadic unpack ... Unpack(Box<Expr>), UnaryOp(UnaryOp, Box<Expr>), BinaryOp(Op, Box<Expr>, Box<Expr>), InstanceOf(Box<Expr>, Box<Expr>), Cast(Ty, Box<Expr>), Yield(Option<Box<Expr>>), /// an anonymous function Function(FunctionDecl), // statements Assign(Box<Expr>, Box<Expr>), /// compound (binary) assign e.g. $test += 3; which is equal to $test = $test + 3; (Assign, BinaryOp) CompoundAssign(Box<Expr>, Op, Box<Expr>), AssignRef(Box<Expr>, Box<Expr>), List(Vec<(Option<Expr>, Expr)>), /// same as if, just will pass the return-value of either expression to the parent /// if .1 (then) is None, the value of .0 (condition) will be used /// this can be desugared into an `If` during post-processing TernaryIf(Box<Expr>, Option<Box<Expr>>, Box<Expr>), } #[derive(Clone, Debug, PartialEq)] pub enum Stmt_ { /// an empty statement such as simply ";" None, Block(Block), Decl(Decl), Use(Vec<UseClause>), /// An expression which is terminated by a semicolon Expr(Expr), Echo(Vec<Expr>), Return(Option<Box<Expr>>), Break(Option<Box<Expr>>), Continue(Option<Box<Expr>>), Unset(Vec<Expr>), /// If (condition=.0) { Block=.1 } else Else_Expr=.2 If(Box<Expr>, Block, Block), While(Box<Expr>, Block), DoWhile(Block, Box<Expr>), /// For(initializer=.0; cond=.1; end_of_loop=.2) statement=.3 For(Vec<Expr>, Vec<Expr>, Vec<Expr>, Block), ForEach(Box<Expr>, Option<Box<Expr>>, Box<Expr>, Block), /// Try(TryBlock, CatchClauses, FinallyClause) Try(Block, Vec<CatchClause>, Option<Block>), Throw(Box<Expr>), /// switch (stmt=.0) [case item: body]+=.1 /// All item-cases for a body will be included in the first-member Vec /// so basically we have a mapping from all-cases -> body in .1 /// TODO: should be desugared into an if-statement Switch(Box<Expr>, Vec<SwitchCase>), Goto(RcStr), } #[derive(Clone, Debug, PartialEq)] pub enum Ty { Array, Callable, Bool, Float, Int, Double, String, Object(Option<Path>), } /// A type and flag describing whether it's nullable #[derive(Clone, Debug, PartialEq)] pub enum NullableTy { NonNullable(Ty), Nullable(Ty), } #[derive(Clone, Debug, PartialEq)] pub enum IncludeTy { Include, IncludeOnce, Require, RequireOnce, } #[derive(Clone, Debug, PartialEq)] pub enum TraitUse { InsteadOf(Path, RcStr, Vec<Path>), As(Option<Path>, RcStr, MemberModifiers, Option<RcStr>), } #[derive(Clone, Debug, PartialEq)] pub struct ParamDefinition { pub name: RcStr, pub as_ref: bool, pub variadic: bool, /// The type of the parameter pub ty: Option<NullableTy>, /// The default value for the parameter pub default: Option<Expr>, } #[derive(Clone, Debug, PartialEq)] pub struct FunctionDecl { pub params: Vec<ParamDefinition>, pub body: Option<Block>, /// A list of variables to pass from the parent scope to the scope of this function /// So variables which are basically available shared into this function's scope /// the boolean indicates whether to bind by-reference (true) pub usev: Vec<(bool, RcStr)>, pub ret_ref: bool, pub ret_ty: Option<NullableTy>, } #[derive(Clone, Debug, PartialEq)] pub struct ClassDecl { pub cmod: ClassModifiers, pub name: RcStr, pub base_class: Option<Path>, /// The implemented interfaces of this class pub implements: Vec<Path>, pub members: Vec<Member>, } #[derive(Clone, Debug, PartialEq)] pub enum Member { Constant(MemberModifiers, RcStr, Expr), Property(MemberModifiers, RcStr, Option<Expr>), Method(MemberModifiers, RcStr, FunctionDecl), TraitUse(Vec<Path>, Vec<TraitUse>), } #[derive(Clone, Debug, PartialEq)] pub enum Decl { Namespace(Path), GlobalFunction(RcStr, FunctionDecl), Class(ClassDecl), Interface(RcStr, Vec<Path>, Vec<Member>), Trait(RcStr, Vec<Member>), StaticVars(Vec<(RcStr, Option<Expr>)>), GlobalVars(Vec<Variable>), // a goto jump target Label(RcStr), } #[derive(Clone, Debug, PartialEq)] pub struct CatchClause { pub ty: Path, pub var: RcStr, pub block: Block, } #[derive(Clone, Debug, PartialEq)] pub struct SwitchCase { pub conds: Vec<Expr>, pub default: bool, pub block: Block, }
true
20138fa9f562120157fdb4317e3775f3449c26e1
Rust
kavitaasiwal/guide
/code/2_11_timeseries.rs
UTF-8
1,041
2.640625
3
[ "MIT" ]
permissive
use chrono::{TimeZone, Utc}; use plotters::prelude::*; fn main() { let root_area = BitMapBackend::new("images/2.11.png", (600, 400)).into_drawing_area(); root_area.fill(&WHITE).unwrap(); let start_date = Utc.ymd(2019, 10, 1); let end_date = Utc.ymd(2019, 10, 18); let mut ctx = ChartBuilder::on(&root_area) .set_label_area_size(LabelAreaPosition::Left, 40) .set_label_area_size(LabelAreaPosition::Bottom, 40) .caption("MSFT daily close price", ("Arial", 40)) .build_ranged(start_date..end_date, 130.0..145.0) .unwrap(); ctx.configure_mesh().draw().unwrap(); ctx.draw_series(LineSeries::new( (0..).zip(DATA.iter()).map(|(idx, price)| { let day = (idx / 5) * 7 + idx % 5 + 1; let date = Utc.ymd(2019, 10, day); (date, *price) }), &BLUE, )) .unwrap(); } const DATA: [f64; 14] = [ 137.24, 136.37, 138.43, 137.41, 139.69, 140.41, 141.58, 139.55, 139.68, 139.10, 138.24, 135.67, 137.12, 138.12, ];
true
54fcd2f103e2d5fa218f64373003cfabeedc5ecc
Rust
fenhl/rust-bitbar
/crate/bitbar/src/lib.rs
UTF-8
14,501
2.6875
3
[ "MIT" ]
permissive
#![deny(missing_docs, rust_2018_idioms, unused, unused_crate_dependencies, unused_import_braces, unused_qualifications, warnings)] #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] //! This is `bitbar`, a library crate which includes helpers for writing BitBar plugins in Rust. BitBar is a system that makes it easy to add menus to the macOS menu bar. There are two apps implementing the BitBar system: [SwiftBar](https://swiftbar.app/) and [xbar](https://xbarapp.com/). This crate supports both of them, as well as [the discontinued original BitBar app](https://github.com/matryer/xbar/tree/a595e3bdbb961526803b60be6fd32dd0c667b6ec). //! //! There are two main entry points: //! //! * It's recommended to use the [`main`](crate::main) attribute and write a `main` function that returns a [`Menu`](crate::Menu), along with optional [`command`](crate::command) functions and an optional [`fallback_command`](crate::fallback_command) function. //! * For additional control over your plugin's behavior, you can directly [`Display`](std::fmt::Display) a [`Menu`](crate::Menu). //! //! BitBar plugins must have filenames of the format `name.duration.extension`, even though macOS binaries normally don't have extensions. You will have to add an extension, e.g. `.o`, to make Rust binaries work as plugins. //! //! # Example //! //! ```rust //! use bitbar::{Menu, MenuItem}; //! //! #[bitbar::main] //! fn main() -> Menu { //! Menu(vec![ //! MenuItem::new("Title"), //! MenuItem::Sep, //! MenuItem::new("Menu Item"), //! ]) //! } //! ``` //! //! Or: //! //! ```rust //! use bitbar::{Menu, MenuItem}; //! //! fn main() { //! print!("{}", Menu(vec![ //! MenuItem::new("Title"), //! MenuItem::Sep, //! MenuItem::new("Menu Item"), //! ])); //! } //! ``` //! //! There is also [a list of real-world examples](https://github.com/fenhl/rust-bitbar#example-plugins). use { std::{ borrow::Cow, collections::BTreeMap, convert::TryInto, fmt, iter::FromIterator, process, vec, }, url::Url, }; #[cfg(feature = "tokio")] use std::{ future::Future, pin::Pin, }; pub use { bitbar_derive::{ command, fallback_command, main, }, crate::flavor::Flavor, }; #[doc(hidden)] pub use { // used in proc macro notify_rust, structopt, }; #[cfg(feature = "tokio")] #[doc(hidden)] pub use tokio; pub mod attr; pub mod flavor; /// A menu item that's not a separator. #[derive(Debug, Default)] pub struct ContentItem { /// This menu item's main content text. /// /// Any `|` in the text will be displayed as `¦`, and any newlines will be displayed as spaces. pub text: String, /// This menu item's alternate-mode menu item or submenu. pub extra: Option<attr::Extra>, /// Corresponds to BitBar's `href=` parameter. pub href: Option<Url>, /// Corresponds to BitBar's `color=` parameter. pub color: Option<attr::Color>, /// Corresponds to BitBar's `font=` parameter. pub font: Option<String>, /// Corresponds to BitBar's `size=` parameter. pub size: Option<usize>, /// Corresponds to BitBar's `bash=`, `terminal=`, `param1=`, etc. parameters. pub command: Option<attr::Command>, /// Corresponds to BitBar's `refresh=` parameter. pub refresh: bool, /// Corresponds to BitBar's `image=` or `templateImage=` parameter. pub image: Option<attr::Image>, /// Parameters for flavor-specific features. pub flavor_attrs: Option<flavor::Attrs>, } impl ContentItem { /// Returns a new menu item with the given text. /// /// Any `|` in the text will be displayed as `¦`, and any newlines will be displayed as spaces. pub fn new(text: impl ToString) -> ContentItem { ContentItem { text: text.to_string(), ..ContentItem::default() } } /// Adds a submenu to this menu item. pub fn sub(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self { self.extra = Some(attr::Extra::Submenu(Menu::from_iter(items))); self } /// Adds a clickable link to this menu item. pub fn href(mut self, href: impl attr::IntoUrl) -> Result<Self, url::ParseError> { self.href = Some(href.into_url()?); Ok(self) } /// Sets this menu item's text color. Alpha channel is ignored. pub fn color<C: TryInto<attr::Color>>(mut self, color: C) -> Result<Self, C::Error> { self.color = Some(color.try_into()?); Ok(self) } /// Sets this menu item's text font. pub fn font(mut self, font: impl ToString) -> Self { self.font = Some(font.to_string()); self } /// Sets this menu item's font size. pub fn size(mut self, size: usize) -> Self { self.size = Some(size); self } /// Make this menu item run the given command when clicked. pub fn command<C: TryInto<attr::Command>>(mut self, cmd: C) -> Result<Self, C::Error> { self.command = Some(cmd.try_into()?); Ok(self) } /// Causes the BitBar plugin to be refreshed when this menu item is clicked. pub fn refresh(mut self) -> Self { self.refresh = true; self } /// Adds an alternate menu item, which is shown instead of this one as long as the option key ⌥ is held. pub fn alt(mut self, alt: impl Into<ContentItem>) -> Self { self.extra = Some(attr::Extra::Alternate(Box::new(alt.into()))); self } /// Adds a template image to this menu item. pub fn template_image<T: TryInto<attr::Image>>(mut self, img: T) -> Result<Self, T::Error> { self.image = Some(attr::Image::template(img)?); Ok(self) } /// Adds an image to this menu item. The image will not be considered a template image unless specified as such by the `img` parameter. pub fn image<T: TryInto<attr::Image>>(mut self, img: T) -> Result<Self, T::Error> { self.image = Some(img.try_into()?); Ok(self) } fn render(&self, f: &mut fmt::Formatter<'_>, is_alt: bool) -> fmt::Result { // main text write!(f, "{}", self.text.replace('|', "¦").replace('\n', " "))?; // parameters let mut rendered_params = BTreeMap::default(); if let Some(ref href) = self.href { rendered_params.insert(Cow::Borrowed("href"), Cow::Borrowed(href.as_ref())); } if let Some(ref color) = self.color { rendered_params.insert(Cow::Borrowed("color"), Cow::Owned(color.to_string())); } if let Some(ref font) = self.font { rendered_params.insert(Cow::Borrowed("font"), Cow::Borrowed(font)); } if let Some(size) = self.size { rendered_params.insert(Cow::Borrowed("size"), Cow::Owned(size.to_string())); } if let Some(ref cmd) = self.command { //TODO (xbar) prefer “shell” over “bash” rendered_params.insert(Cow::Borrowed("bash"), Cow::Borrowed(&cmd.params.cmd)); for (i, param) in cmd.params.params.iter().enumerate() { rendered_params.insert(Cow::Owned(format!("param{}", i + 1)), Cow::Borrowed(param)); } if !cmd.terminal { rendered_params.insert(Cow::Borrowed("terminal"), Cow::Borrowed("false")); } } if self.refresh { rendered_params.insert(Cow::Borrowed("refresh"), Cow::Borrowed("true")); } if is_alt { rendered_params.insert(Cow::Borrowed("alternate"), Cow::Borrowed("true")); } if let Some(ref img) = self.image { rendered_params.insert(Cow::Borrowed(if img.is_template { "templateImage" } else { "image" }), Cow::Borrowed(&img.base64_data)); } if let Some(ref flavor_attrs) = self.flavor_attrs { flavor_attrs.render(&mut rendered_params); } if !rendered_params.is_empty() { write!(f, " |")?; for (name, value) in rendered_params { let quoted_value = if value.contains(' ') { Cow::Owned(format!("\"{}\"", value)) } else { value }; //TODO check for double quotes in value, fall back to single quotes? (test if BitBar supports these first) write!(f, " {}={}", name, quoted_value)?; } } writeln!(f)?; // additional items match &self.extra { Some(attr::Extra::Alternate(ref alt)) => { alt.render(f, true)?; } Some(attr::Extra::Submenu(ref sub)) => { let sub_fmt = format!("{}", sub); for line in sub_fmt.lines() { writeln!(f, "--{}", line)?; } } None => {} } Ok(()) } } impl fmt::Display for ContentItem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.render(f, false) } } /// A menu item can either be a separator or a content item. #[derive(Debug)] pub enum MenuItem { /// A content item, i.e. any menu item that's not a separator. Content(ContentItem), /// A separator bar. Sep } impl MenuItem { /// Returns a new menu item with the given text. See `ContentItem::new` for details. pub fn new(text: impl fmt::Display) -> MenuItem { MenuItem::Content(ContentItem::new(text)) } } impl Default for MenuItem { fn default() -> MenuItem { MenuItem::Content(ContentItem::default()) } } impl From<ContentItem> for MenuItem { fn from(i: ContentItem) -> MenuItem { MenuItem::Content(i) } } impl fmt::Display for MenuItem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MenuItem::Content(content) => write!(f, "{}", content), MenuItem::Sep => writeln!(f, "---") } } } /// A BitBar menu. /// /// Usually constructed by calling [`collect`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect) on an [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) of `MenuItem`s. #[derive(Debug, Default)] pub struct Menu(pub Vec<MenuItem>); impl Menu { /// Adds a menu item to the bottom of the menu. pub fn push(&mut self, item: impl Into<MenuItem>) { self.0.push(item.into()); } } impl<A: Into<MenuItem>> FromIterator<A> for Menu { fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Menu { Menu(iter.into_iter().map(Into::into).collect()) } } impl<A: Into<MenuItem>> Extend<A> for Menu { fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) { self.0.extend(iter.into_iter().map(Into::into)) } } impl IntoIterator for Menu { type Item = MenuItem; type IntoIter = vec::IntoIter<MenuItem>; fn into_iter(self) -> vec::IntoIter<MenuItem> { self.0.into_iter() } } /// This provides the main functionality of this crate: rendering a BitBar plugin. /// /// Note that the output this generates already includes a trailing newline, so it should be used with `print!` instead of `println!`. impl fmt::Display for Menu { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for menu_item in &self.0 { write!(f, "{}", menu_item)?; } Ok(()) } } /// Members of this trait can be returned from a main function annotated with [`main`]. pub trait MainOutput { /// Displays this value as a menu, using the given template image in case of an error. fn main_output(self, error_template_image: Option<attr::Image>); } impl<T: Into<Menu>> MainOutput for T { fn main_output(self, _: Option<attr::Image>) { print!("{}", self.into()); } } /// In the `Err` case, the menu will be prefixed with a menu item displaying the `error_template_image` and the text `?`. impl<T: MainOutput, E: MainOutput> MainOutput for Result<T, E> { fn main_output(self, error_template_image: Option<attr::Image>) { match self { Ok(x) => x.main_output(error_template_image), Err(e) => { let mut header = ContentItem::new("?"); if let Some(error_template_image) = error_template_image { header = match header.template_image(error_template_image) { Ok(header) => header, Err(never) => match never {}, }; } print!("{}", Menu(vec![header.into(), MenuItem::Sep])); e.main_output(None); } } } } #[cfg(feature = "tokio")] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] /// Members of this trait can be returned from a main function annotated with [`main`]. pub trait AsyncMainOutput<'a> { /// Displays this value as a menu, using the given template image in case of an error. fn main_output(self, error_template_image: Option<attr::Image>) -> Pin<Box<dyn Future<Output = ()> + 'a>>; } #[cfg(feature = "tokio")] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] impl<'a, T: MainOutput + 'a> AsyncMainOutput<'a> for T { fn main_output(self, error_template_image: Option<attr::Image>) -> Pin<Box<dyn Future<Output = ()> + 'a>> { Box::pin(async move { MainOutput::main_output(self, error_template_image); }) } } /// Members of this trait can be returned from a subcommand function annotated with [`command`] or [`fallback_command`]. pub trait CommandOutput { /// Reports any errors in this command output as macOS notifications. fn report(self, cmd_name: &str); } impl CommandOutput for () { fn report(self, _: &str) {} } impl<T: CommandOutput, E: fmt::Display> CommandOutput for Result<T, E> { fn report(self, cmd_name: &str) { match self { Ok(x) => x.report(cmd_name), Err(e) => { notify(format!("{}: {}", cmd_name, e)); process::exit(1); } } } } #[doc(hidden)] pub fn notify(body: impl fmt::Display) { // used in proc macro //let _ = notify_rust::set_application(&notify_rust::get_bundle_identifier_or_default("BitBar")); //TODO uncomment when https://github.com/h4llow3En/mac-notification-sys/issues/8 is fixed let _ = notify_rust::Notification::default() .summary(&env!("CARGO_PKG_NAME")) .sound_name("Funky") .body(&body.to_string()) .show(); }
true
c69ff90db7f96031ca4a1a000b9c4d98b86718a9
Rust
brson/treasuretree
/src/geonft_sync/src/main.rs
UTF-8
4,519
2.6875
3
[]
no_license
use anyhow::Result; use log::{error, info, warn}; use std::collections::HashMap; use std::thread; use geonft_shared::io::{self, SyncStatus}; mod solana; fn main() -> Result<()> { env_logger::init(); loop { let plan = make_plan()?; execute_plan(plan)?; wait_for_next_round(); } } struct Plan { statuses: HashMap<String, io::SyncStatus>, steps: Vec<(String, Step)>, } #[derive(Debug)] enum Step { UploadBlobToIpfs, UploadPlantToSolana, UploadClaimToSolana, } fn make_plan() -> Result<Plan> { info!("making new plan"); let statuses = io::get_all_sync_statuses()?; let treasure_events = io::get_all_plants_and_claims_time_sorted()?; let mut steps = Vec::new(); for (event, treasure) in treasure_events { let pubkey = treasure.public_key; let status = statuses.get(&pubkey); use io::PlantClaim::{Claim, Plant}; use io::SyncStatus::*; use Step::*; match (event, status) { (Plant, None) => { steps.push((pubkey.clone(), UploadBlobToIpfs)); steps.push((pubkey, UploadPlantToSolana)); } (Plant, Some(BlobSynced)) => { steps.push((pubkey, UploadPlantToSolana)); } (Plant, Some(PlantSynced | ClaimSynced)) => { /* plant is synced */ } (Claim, None) | (Claim, Some(BlobSynced | PlantSynced)) => { steps.push((pubkey, UploadClaimToSolana)); } (Claim, Some(ClaimSynced)) => { /* claim is synced */ } } } Ok(Plan { statuses, steps }) } fn execute_plan(plan: Plan) -> Result<()> { info!("executing plan with {} steps", plan.steps.len()); let config = solana::load_config()?; let client = solana::connect(&config)?; let program_keypair = solana::get_program_keypair(&client)?; let program_instance_account = solana::get_program_instance_account(&client, &config.keypair, &program_keypair)?; let mut statuses = plan.statuses; for (pubkey, step) in plan.steps { info!("executing step {:?} for {}", step, pubkey); let r = || -> Result<()> { let status = statuses.get(&pubkey).cloned(); match step { Step::UploadBlobToIpfs => { if status == None { // todo io::record_sync_status(&pubkey, SyncStatus::BlobSynced)?; statuses.insert(pubkey, SyncStatus::BlobSynced); } else { warn!("unexpected sync status: {:?}", status); } } Step::UploadPlantToSolana => { if status == Some(SyncStatus::BlobSynced) { solana::upload_plant( &pubkey, &config, &client, &program_keypair, &program_instance_account, )?; io::record_sync_status(&pubkey, SyncStatus::PlantSynced)?; statuses.insert(pubkey, SyncStatus::PlantSynced); } else { warn!("unexpected sync status: {:?}", status); } } Step::UploadClaimToSolana => { if status == Some(SyncStatus::PlantSynced) { solana::upload_claim( &pubkey, &config, &client, &program_keypair, &program_instance_account, )?; io::record_sync_status(&pubkey, SyncStatus::ClaimSynced)?; statuses.insert(pubkey, SyncStatus::ClaimSynced); } else { warn!("unexpected sync status: {:?}", status); } } } Ok(()) }(); if let Err(e) = r { error!("{}", e); } else { // info!("successfully executed step {:?} for {}", step, pubkey); info!("successfully executed step {:?}", step); } } Ok(()) } fn wait_for_next_round() { let delay_ms = 1000; info!("sleeping for {} ms", delay_ms); #[allow(deprecated)] thread::sleep_ms(delay_ms); }
true
8927476721f7dde08667bc4f79ad25c0ba2ce67d
Rust
Geigerkind/rusty_leasing_ninja
/src/sales/domain_values/amount.rs
UTF-8
349
2.609375
3
[]
no_license
use crate::rocket::serde::Serialize; use crate::sales::domain_values::Currency; #[derive(Getters, Debug, Clone, Serialize, PartialEq)] #[serde(crate = "rocket::serde")] pub struct Amount { amount: u32, currency: Currency, } impl Amount { pub fn new(amount: u32, currency: Currency) -> Self { Amount { amount, currency } } }
true
b59b37873c27b991194400c05e2ba8bc08f11c74
Rust
rigma/geometrize
/src/libgeometrize/math/shapes/polygon.rs
UTF-8
4,310
3.578125
4
[]
no_license
use crate::math::{Point, Vector}; use super::Shape; /// Defines a polygon shape thanks to a vector of points defining /// its vertices. This shape can be validated by using [`is_valid`] /// method that we'll check that the polygon is convex. If the current /// polygon is not degenerated and convex, then we'll validate it. /// /// # Example /// /// ``` /// use libgeometrize::math::{shapes::{Polygon, Shape}, Point}; /// /// // Produces a new convex polygon which represents the unit square. /// let polygon = Polygon::from(vec![ /// Point::zero(), /// Point::new(1.0, 0.0), /// Point::new(1.0, 1.0), /// Point::new(0.0, 1.0) /// ]); /// assert!(polygon.is_valid()); /// /// // Produces a new non-convex polygon /// let polygon = Polygon::from(vec![ /// Point::zero(), /// Point::new(0.0, 1.0), /// Point::new(10.0, 10.0), /// Point::new(1.0, 1.0), /// Point::new(1.0, 0.0) /// ]); /// assert!(!polygon.is_valid()); /// ``` /// /// [`is_valid`]: ./struct.Polygon.html#method.is_valid #[derive(Clone, Debug, Default)] pub struct Polygon { vertices: Vec<Point> } impl Polygon { /// Instanciates a new polygon shape from a vector of points. pub fn new(vertices: Vec<Point>) -> Self { Self { vertices } } /// Returns the order of the current polygon. #[inline] pub fn order(&self) -> usize { self.vertices.len() } /// Checks if the current polygon is valid or not. To do so, the /// method we'll check that the polygon is not dengenerated or not /// convex by checking that the cross products of all its vertices /// have the same sign. pub fn is_valid(&self) -> bool { let order = self.order(); if order < 3 { return false; } let sign = { let u: Vector = self.vertices[1] - self.vertices[0]; let v: Vector = self.vertices[2] - self.vertices[1]; u.cross(&v) > 0.0 }; for idx in 1..order { let (u, v): (Vector, Vector) = { let i = idx % order; let j = (idx + 1) % order; let k = (idx + 2) % order; (self.vertices[j] - self.vertices[i], self.vertices[k] - self.vertices[j]) }; if (u.cross(&v) > 0.0) != sign { return false; } } true } } impl From<&[Point]> for Polygon { fn from(vertices: &[Point]) -> Self { Self::new(Vec::from(vertices)) } } impl From<Vec<Point>> for Polygon { fn from(vertices: Vec<Point>) -> Self { Self { vertices } } } impl Shape for Polygon { fn mutate(&mut self) { // } /// Checks if the current polygon is valid or not. To do so, the /// method we'll check that the polygon is not dengenerated or not /// convex by checking that the cross products of all its vertices /// have the same sign. fn is_valid(&self) -> bool { let order = self.order(); if order < 3 { return false; } let sign = { let u: Vector = self.vertices[1] - self.vertices[0]; let v: Vector = self.vertices[2] - self.vertices[1]; u.cross(&v) > 0.0 }; for idx in 1..order { let (u, v): (Vector, Vector) = { let i = idx % order; let j = (idx + 1) % order; let k = (idx + 2) % order; (self.vertices[j] - self.vertices[i], self.vertices[k] - self.vertices[j]) }; if (u.cross(&v) > 0.0) != sign { return false; } } true } } #[cfg(test)] mod tests { use super::*; #[test] fn it_validates_a_polygon() { let polygon = Polygon::from(vec![ Point::zero(), Point::new(1.0, 0.0), Point::new(1.0, 1.0), Point::new(0.0, 1.0) ]); assert!(polygon.is_valid()); } #[test] fn it_invalidates_a_polygon() { let polygon = Polygon::from(vec![ Point::zero(), Point::new(0.0, 1.0), Point::new(10.0, 10.0), Point::new(1.0, 1.0), Point::new(1.0, 0.0) ]); assert!(!polygon.is_valid()); } }
true
5464c5f09dc1186527c7eaa02dc6a8ae2430090f
Rust
jethrosun/peel-ip
/src/layer2/ipv6.rs
UTF-8
5,107
2.796875
3
[ "MIT" ]
permissive
//! Internet Protocol version 6 related packet processing use prelude::*; /// The IPv6 parser #[derive(Debug)] pub struct Ipv6Parser; impl Parsable<PathIp> for Ipv6Parser { /// Parse an `Ipv6Packet` from an `&[u8]` fn parse<'a>( &mut self, input: &'a [u8], result: Option<&ParserResultVec>, _: Option<&mut PathIp>, ) -> IResult<&'a [u8], ParserResult> { do_parse!( input, // Check the type from the parent parser (Ethernet) expr_opt!(match result { Some(vector) => match vector.last() { // Check the correct EtherType or IP encapsulation Some(ref any) => match (any.downcast_ref::<EthernetPacket>(), any.downcast_ref::<Ipv4Packet>(), any.downcast_ref::<Ipv6Packet>()) { // Ethernet (Some(eth), _, _) => if eth.ethertype == EtherType::Ipv6 { Some(()) } else { None }, // IPv6 in IPv4 (_, Some(ipv4), _) => if ipv4.protocol == IpProtocol::Ipv6 { Some(()) } else { None }, // IPv6 in IPv6 (_, _, Some(ipv6)) => if ipv6.next_header == IpProtocol::Ipv6 { Some(()) } else { None }, _ => None, }, // Previous result found, but not correct parent _ => None, }, // Parse also if no result is given, for testability None => Some(()), }) >> // Parse the actual packet ver_tc_fl: bits!(tuple!(tag_bits!(u8, 4, 6), take_bits!(u8, 8), take_bits!(u32, 20))) >> payload_length: be_u16 >> next_header: map_opt!(be_u8, IpProtocol::from_u8) >> hop_limit: be_u8 >> src: tuple!(be_u16, be_u16, be_u16, be_u16, be_u16, be_u16, be_u16, be_u16) >> dst: tuple!(be_u16, be_u16, be_u16, be_u16, be_u16, be_u16, be_u16, be_u16) >> (Box::new(Ipv6Packet { version: ver_tc_fl.0, traffic_class: ver_tc_fl.1, flow_label: ver_tc_fl.2, payload_length: payload_length, next_header: next_header, hop_limit: hop_limit, src: Ipv6Addr::new(src.0, src.1, src.2, src.3, src.4, src.5, src.6, src.7), dst: Ipv6Addr::new(dst.0, dst.1, dst.2, dst.3, dst.4, dst.5, dst.6, dst.7), })) ) } } impl fmt::Display for Ipv6Parser { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "IPv6") } } #[derive(Debug, Eq, PartialEq)] /// Representation of an Internet Protocol version 6 packet pub struct Ipv6Packet { /// The constant 6 (bit sequence 0110). pub version: u8, /// The bits of this field hold two values. The 6 most-significant bits are used for /// differentiated services, which is used to classify packets. The remaining two bits are used /// for ECN; priority values subdivide into ranges: traffic where the source provides /// congestion control and non-congestion control traffic. pub traffic_class: u8, /// Originally created for giving real-time applications special service. The flow label when /// set to a non-zero value now serves as a hint to routers and switches with multiple outbound /// paths that these packets should stay on the same path so that they will not be reordered. /// It has further been suggested that the flow label be used to help detect spoofed packets. pub flow_label: u32, /// The size of the payload in octets, including any extension headers. The length is set to /// zero when a Hop-by-Hop extension header carries a Jumbo Payload option. pub payload_length: u16, /// Specifies the type of the next header. This field usually specifies the transport layer /// protocol used by a packet's payload. When extension headers are present in the packet this /// field indicates which extension header follows. The values are shared with those used for /// the IPv4 protocol field, as both fields have the same function. pub next_header: IpProtocol, /// Replaces the time to live field of IPv4. This value is decremented by one at each /// intermediate node visited by the packet. When the counter reaches 0 the packet is /// discarded. pub hop_limit: u8, /// Source address pub src: Ipv6Addr, /// Destination address pub dst: Ipv6Addr, }
true
f39139a73dcb42e08c4f20692abc040c7c4b356b
Rust
plippe/exercism-exercises
/rust/prime-factors/src/lib.rs
UTF-8
384
3.140625
3
[ "Unlicense" ]
permissive
pub fn push(mut vec: Vec<u64>, n: u64) -> Vec<u64> { vec.push(n); vec } pub fn factors(n: u64) -> Vec<u64> { fn recursive(n: u64, d: u64, vec: Vec<u64>) -> Vec<u64> { match n { 1 => vec, _n if _n % d == 0 => recursive(_n / d, d, push(vec, d)), _n => recursive(_n, d + 1, vec), } } recursive(n, 2, Vec::new()) }
true
564a4f13ebe7746c9ab6045f7fc74ffcc156bc98
Rust
jmalubay1/blobs
/src/main.rs
UTF-8
7,321
2.609375
3
[ "MIT" ]
permissive
//! Attack of the Blobs //! Roguelike game binary //! //! Jordan Malubay CS410 - June 2021 use rltk::{GameState, Point, Rltk, RGB}; use specs::prelude::*; mod components; pub use components::*; mod map; pub use map::*; mod map_index; pub use map_index::*; mod player; use player::*; mod rect; pub use rect::Rect; mod blob; pub use blob::*; mod view; pub use view::VisibilitySystem; mod melee; pub use melee::*; mod damage_system; pub use damage_system::*; mod gui; mod inventory; pub use inventory::*; /// States used to control the flow of the game #[derive(PartialEq, Copy, Clone)] pub enum RunState { AwaitingInput, PreRun, PlayerTurn, BlobTurn, Menu, } /// World is the Entity Control System pub struct State { pub ecs: World, } /// Set and run the World control systems from each module impl State { fn run_systems(&mut self) { let mut vis = VisibilitySystem {}; vis.run_now(&self.ecs); let mut mob = BlobAi {}; mob.run_now(&self.ecs); let mut mapindex = MapIndexingSystem {}; mapindex.run_now(&self.ecs); let mut melee = MeleeCombatSystem {}; melee.run_now(&self.ecs); let mut damage = DamageSystem {}; damage.run_now(&self.ecs); let mut pickup = ItemCollectionSystem {}; pickup.run_now(&self.ecs); self.ecs.maintain(); } } impl GameState for State { /// Each tick represents a round of turns within the game fn tick(&mut self, ctx: &mut Rltk) { // Clear the screen and draw the map ctx.cls(); draw_map(&self.ecs, ctx); // Get all the entities and draw them { let positions = self.ecs.read_storage::<Position>(); let renderables = self.ecs.read_storage::<Renderable>(); for (pos, render) in (&positions, &renderables).join() { ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph) } } // Draw the HUD gui::draw_ui(&self.ecs, ctx); // Set the run state let mut newrunstate; { let runstate = self.ecs.fetch::<RunState>(); newrunstate = *runstate; } // Check the run state match newrunstate { RunState::PreRun => { self.run_systems(); newrunstate = RunState::AwaitingInput; } RunState::AwaitingInput => { newrunstate = player_input(self, ctx); } RunState::PlayerTurn => { self.run_systems(); newrunstate = RunState::BlobTurn; } RunState::BlobTurn => { self.run_systems(); newrunstate = RunState::AwaitingInput; } RunState::Menu => { if gui::show_menu(ctx) == gui::MenuResult::Cancel { newrunstate = RunState::AwaitingInput; } } } { let mut runwriter = self.ecs.write_resource::<RunState>(); *runwriter = newrunstate; } damage_system::delete_the_dead(&mut self.ecs); } } fn main() -> rltk::BError { // Initialize a new window use rltk::RltkBuilder; let mut context = RltkBuilder::simple80x50() .with_title("Roguelike Tutorial") .build()?; context.with_post_scanlines(true); // Initialize the gamestate let mut gs = State { ecs: World::new() }; // Start all the compenent systems in the gamestate gs.ecs.register::<Position>(); gs.ecs.register::<Renderable>(); gs.ecs.register::<Player>(); gs.ecs.register::<Viewshed>(); gs.ecs.register::<Blob>(); gs.ecs.register::<Name>(); gs.ecs.register::<BlocksTile>(); gs.ecs.register::<CombatStats>(); gs.ecs.register::<WantsToMelee>(); gs.ecs.register::<SufferDamage>(); gs.ecs.register::<Item>(); gs.ecs.register::<Heal>(); gs.ecs.register::<WantsToPickupItem>(); gs.ecs.register::<Inventory>(); // Generate map and player start location in one of the rooms let map = Map::map_gen(); let (player_x, player_y) = map.rooms[0].center(); // Spawn the Player let player_entity = gs .ecs .create_entity() .with(Position { x: player_x, y: player_y, }) .with(Renderable { glyph: rltk::to_cp437('@'), fg: RGB::named(rltk::YELLOW), bg: RGB::named(rltk::BLACK), }) .with(Player {}) .with(Viewshed { visible_tiles: Vec::new(), range: 8, }) .with(Name { name: "Player".to_string(), }) .with(CombatStats { max_hp: 10, hp: 10 }) .build(); // Spawn blobs, first 4 are 'boss' blobs, any after are regular let mut rng = rltk::RandomNumberGenerator::new(); for i in 0..8 { //Ensure blobs are outside of rooms let (mut x, mut y); loop { let mut inside = false; x = rng.roll_dice(1, 79); y = rng.roll_dice(1, 42); for room in map.rooms.iter() { if room.inside((x, y)) { inside = true; break; } } if !inside { break; } } // Select the main colored blobs or generic grey blobs let glyph: rltk::FontCharType; let name: String; let color: RGB; match i { //Important Blobs 1 => { glyph = rltk::to_cp437('O'); name = "RED".to_string(); color = RGB::named(rltk::RED) } 2 => { glyph = rltk::to_cp437('O'); name = "BLUE".to_string(); color = RGB::named(rltk::BLUE) } 3 => { glyph = rltk::to_cp437('O'); name = "PURPLE".to_string(); color = RGB::named(rltk::PURPLE) } 4 => { glyph = rltk::to_cp437('O'); name = "YELLOW".to_string(); color = RGB::named(rltk::YELLOW) } // Extra Blobs _ => { glyph = rltk::to_cp437('O'); name = "GREY".to_string(); color = RGB::named(rltk::GREY) } } // Create each blob gs.ecs .create_entity() .with(Position { x, y }) .with(Renderable { glyph, fg: color, bg: RGB::named(rltk::BLACK), }) .with(Viewshed { visible_tiles: Vec::new(), range: 8, }) .with(Blob {}) .with(Name { name: format!("{} #{}", &name, i), }) .with(BlocksTile {}) .with(CombatStats { max_hp: 1, hp: 1 }) .build(); } // Add the map, player and set the initial run state gs.ecs.insert(map); gs.ecs.insert(player_entity); gs.ecs.insert(RunState::PreRun); gs.ecs.insert(Point::new(player_x, player_y)); // Run the game rltk::main_loop(context, gs) }
true
bb04ca9117e55a83674d8b4491fe72ac1f17774f
Rust
hktr92/flyte
/examples/basic.rs
UTF-8
759
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::path::PathBuf; use bytes::Bytes; use tokio; use flyte::{local::LocalFilesystem, local::LocalFilesystemBuilder, Filesystem}; #[tokio::main] async fn main() -> anyhow::Result<()> { let local_fs: LocalFilesystem = LocalFilesystemBuilder::new().into(); let tmp_path = String::from("test"); local_fs.create_directory(&tmp_path).await?; for i in 1..=10 { local_fs .write_file( &format!("{}/foo{}.txt", tmp_path, i), Some(&Bytes::from(format!("bar{}", i))), ) .await?; } let nodes = local_fs.list_directory(&tmp_path).await?; for node in nodes { println!("- {}", node); } local_fs.delete_directory(&tmp_path).await?; Ok(()) }
true
6f88b25c82cc3c16ed090445137708ffd075c918
Rust
npj/rust-scheme
/src/lexer/io_lexer.rs
UTF-8
4,755
3.53125
4
[]
no_license
use super::Lexer; use std::io::Read; use std::io::BufReader; pub struct IOLexer<T: Read> { input: BufReader<T>, buf: [u8; 1], eof: bool, line: u32, chr: u32 } impl<T: Read> IOLexer<T> { pub fn new(input: T) -> IOLexer<T> { let mut lexer = IOLexer { input: BufReader::new(input), buf: [0], eof: false, line: 1, chr: 1 }; lexer.read_char(); lexer } fn read_char(&mut self) { match self.input.read(&mut self.buf) { Ok(0) | Err(_) => { self.eof = true; }, Ok(_) => () } } } impl<T: Read> Lexer for IOLexer<T> { fn get(&mut self) -> Option<char> { match self.peek() { None => None, Some(c) => { self.read_char(); self.count(c); Some(c) } } } fn peek(&self) -> Option<char> { if self.eof { None } else { Some(self.buf[0] as char) } } fn set_line(&mut self, line: u32) -> () { self.line = line } fn set_chr(&mut self, chr: u32) -> () { self.chr = chr } fn line(&self) -> u32 { self.line } fn chr(&self) -> u32 { self.chr } } #[cfg(test)] mod tests { use super::*; use lexer::Lexer; use std::io::Read; use std::io::Result; static TEST_STRING : &'static str = "ab\ncd"; struct FakeFile { cursor: usize, data: Vec<u8> } impl FakeFile { fn new() -> FakeFile { FakeFile { cursor : 0, data: TEST_STRING.to_string().into_bytes() } } fn at(&self, i: usize) -> u8 { self.data[i] } fn len(&self) -> usize { self.data.len() } fn move_cursor(&mut self, by: usize) { self.cursor = self.cursor + by; } fn cursor(&self) -> usize { self.cursor } } impl Read for FakeFile { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let mut count : usize = 0; for i in 0..(buf.len() - 1) { let offset = self.cursor() + i; if offset < self.len() { buf[i] = self.at(offset); count = count + 1; } else { break; } } self.move_cursor(count); Ok(count) } } #[test] fn new() { let lexer = IOLexer::new(FakeFile::new()); assert_eq!(lexer.eof, false); assert_eq!(lexer.line, 1); assert_eq!(lexer.chr, 1); } #[test] fn peek() { let mut lexer = IOLexer::new(FakeFile::new()); assert_eq!(Some('a'), lexer.peek()); assert_eq!(lexer.chr, 1); assert_eq!(lexer.line, 1); assert_eq!(Some('a'), lexer.peek()); assert_eq!(lexer.chr, 1); assert_eq!(lexer.line, 1); lexer.get(); assert_eq!(Some('b'), lexer.peek()); assert_eq!(lexer.chr, 2); assert_eq!(lexer.line, 1); assert_eq!(Some('b'), lexer.peek()); assert_eq!(lexer.chr, 2); assert_eq!(lexer.line, 1); } #[test] fn get() { let mut lexer = IOLexer::new(FakeFile::new()); let result = lexer.get(); assert_eq!(Some('a'), result); assert_eq!(lexer.chr, 2); assert_eq!(lexer.line, 1); assert_eq!(Some('b'), lexer.get()); assert_eq!(lexer.chr, 3); assert_eq!(lexer.line, 1); assert_eq!(Some('\n'), lexer.get()); assert_eq!(lexer.chr, 1); assert_eq!(lexer.line, 2); assert_eq!(Some('c'), lexer.get()); assert_eq!(lexer.chr, 2); assert_eq!(lexer.line, 2); assert_eq!(Some('d'), lexer.get()); assert_eq!(lexer.chr, 3); assert_eq!(lexer.line, 2); assert_eq!(None, lexer.get()); } #[test] fn line() { let mut lexer = IOLexer::new(FakeFile::new()); assert_eq!(lexer.line(), 1); lexer.line = 43; assert_eq!(lexer.line(), 43); } #[test] fn set_line() { let mut lexer = IOLexer::new(FakeFile::new()); assert_eq!(lexer.line(), 1); lexer.set_line(43); assert_eq!(lexer.line(), 43); } #[test] fn chr() { let mut lexer = IOLexer::new(FakeFile::new()); assert_eq!(lexer.chr(), 1); lexer.chr = 43; assert_eq!(lexer.chr(), 43); } #[test] fn set_chr() { let mut lexer = IOLexer::new(FakeFile::new()); assert_eq!(lexer.chr(), 1); lexer.chr = 43; assert_eq!(lexer.chr(), 43); } }
true
b2b97e8efa090df245f0e3f05865e2ec02b6e742
Rust
dtulig/gotham
/examples/websocket/src/main.rs
UTF-8
2,561
2.734375
3
[ "MIT", "Apache-2.0" ]
permissive
use futures::prelude::*; use gotham::hyper::{Body, HeaderMap, Response, StatusCode}; use gotham::state::{request_id, FromState, State}; mod ws; fn main() { pretty_env_logger::init(); let addr = "127.0.0.1:7878"; println!("Listening on http://{}/", addr); gotham::start(addr, || Ok(handler)); } fn handler(mut state: State) -> (State, Response<Body>) { let body = Body::take_from(&mut state); let headers = HeaderMap::take_from(&mut state); if ws::requested(&headers) { let (response, ws) = match ws::accept(&headers, body) { Ok(res) => res, Err(_) => return bad_request(state), }; let req_id = request_id(&state).to_owned(); let ws = ws .map_err(|err| eprintln!("websocket init error: {}", err)) .and_then(move |ws| connected(req_id, ws)); hyper::rt::spawn(ws); (state, response) } else { (state, Response::new(Body::from(INDEX_HTML))) } } fn connected<S>(req_id: String, stream: S) -> impl Future<Output = Result<(), ()>> where S: Stream<Item = ws::Message, Error = ws::Error> + Sink<SinkItem = ws::Message, SinkError = ws::Error>, { let (sink, stream) = stream.split(); println!("Client {} connected", req_id); sink.send_all(stream.map({ let req_id = req_id.clone(); move |msg| { println!("{}: {:?}", req_id, msg); msg } })) .map_err(|err| println!("Websocket error: {}", err)) .map(move |_| println!("Client {} disconnected", req_id)) } fn bad_request(state: State) -> (State, Response<Body>) { let response = Response::builder() .status(StatusCode::BAD_REQUEST) .body(Body::empty()) .unwrap(); (state, response) } const INDEX_HTML: &str = r#" <!DOCTYPE html> <body> <h1>Websocket Echo Server</h1> <form id="ws" onsubmit="return send(this.message);"> <input name="message"> <input type="submit" value="Send"> </form> <script> var sock = new WebSocket("ws://" + window.location.host); sock.onopen = recv.bind(window, "Connected"); sock.onclose = recv.bind(window, "Disconnected"); sock.onmessage = function(msg) { recv(msg.data) }; sock.onerror = function(err) { recv("Error: " + e); }; function recv(msg) { var e = document.createElement("PRE"); e.innerText = msg; document.body.appendChild(e); } function send(msg) { sock.send(msg.value); msg.value = ""; return false; } </script> </body> "#;
true
bf75c93bf34b5cdcdba2d75f29be12308ed49214
Rust
lazylook2/rust_study
/src/error.rs
UTF-8
3,938
3.703125
4
[]
no_license
use std::fs::File; use std::io::{ErrorKind, Read, Error}; use std::{io, fs}; /*pub fn e1 () { // 使用result处理潜在的错误 // enum Result<T, E> { // Ok(T), // Err(E), // } let f = File::open("fuck.txt"); let f = match f { Ok(file) => file, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("fuck.txt") { Ok(fc) => fc, Err(e) => panic!("Problem creating the file: {:?}", e), }, other_kind=> panic!("Problem opening the file: {:?}", other_error), } }; // 用了闭包 let f = File::open("fuck.txt").unwrap_or_else(|error| { if error.kind() == ErrorKind::NotFound { File::create("fuck.txt").unwrap_or_else(|error| { panic!("Problem creating the file: {:?}", error); }) } else { panic!("Problem opening the file: {:?}", error); } }); // 失败时 panic 的简写:unwrap 和 expect // unwrap 那样使用默认的 panic! 信息 // expect 用来调用 panic! 的错误信息将会作为参数传递给 expect // 如果 Result 值是成员 Ok,unwrap 会返回 Ok 中的值。 // 如果 Result 是成员 Err,unwrap 会为我们调用 panic!。 let f = File::open("hello.txt").unwrap(); // 使用 expect 提供一个好的错误信息可以表明你的意图并更易于追踪 panic 的根源。 let f = File::open("hello.txt").expect("无法打开。。。。 hello.txt"); }*/ pub fn e2 () { // 传播错误(方法里编写,直接抛出错误) fn read_username_from_file() -> Result<String, io::Error> { let mut f = File::open("fuck.txt"); let mut f = match f { Ok(file) => file, Err(e) => return Err(e), }; let mut s = String::new(); match f.read_to_string(&mut s) { Ok(_) => Ok(s), Err(e) => Err(e), } } let f = read_username_from_file(); match f { Ok(string) => println!("fuck.txt的内容为:{}", string), Err(e) => panic!("读取fuck.txt的内容失败: {:?}", e), } /// Result 值之后的 ? 与match 表达式有着完全相同的工作方式。 /// 如果 Result 的值是 Ok,这个表达式将会返回 Ok 中的值而程序将继续执行。 /// 如果值是 Err,Err 中的值将作为整个函数的返回值,就好像使用了 return 关键字一样 fn read_username_from_file1() -> Result<String, io::Error> { /*let mut f = File::open("fuck.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?;*/ // 可以链式调用,下面可以取代注释内容 /*let mut s = String::new(); File::open("fuck.txt")?.read_to_string(&mut s)?;*/ // 更简便的写法如下: fs::read_to_string("fuck.txt") } let f = read_username_from_file(); match f { Ok(string) => println!("fuck.txt的内容为:{}", string), Err(e) => panic!("读取fuck.txt的内容失败: {:?}", e), } let secret_number = 3; loop { let mut guess = String::new(); // --snip-- let guess: i32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; if guess < 1 || guess > 100 { println!("The secret number will be between 1 and 100."); continue; } match guess.cmp(&secret_number) { _ => (), } } pub struct Guess { value: i32, } impl Guess { pub fn new(value: i32) -> Guess { if value < 1 || value > 100 { panic!("Guess value must be between 1 and 100, got {}.", value); } Guess { value } } pub fn value(&self) -> i32 { self.value } } }
true
6d411a13e52a02551c4bc56a8ef6155e41fd01fb
Rust
N1ghtStorm/actix_send
/examples/basic.rs
UTF-8
3,738
3.546875
4
[ "MIT" ]
permissive
use std::time::Duration; use futures_util::stream::StreamExt; use actix_send::prelude::*; use crate::my_actor::*; /* By default we don't enable async-std runtime. Please run this example with: cargo run --example basic --no-default-features --features async-std-runtime */ #[async_std::main] async fn main() { // create an actor instance. The create function would return our Actor struct. let builder = MyActor::builder(|| async { let state1 = String::from("running"); let state2 = String::from("running"); MyActor { state1, state2 } }); // build and start the actor(s). let address: Address<MyActor> = builder.start().await; // construct new messages. let msg = Message1 { from: "a simple test".to_string(), }; let msg2 = Message2(22); let msg3 = Message3; // use address to send messages to actor and await on result. // send method would return the message's result type in #[message] macro together with a possible actix_send::prelude::ActixSendError let res: Result<u8, ActixSendError> = address.send(msg).await; let res = res.unwrap(); let res2 = address.send(msg2).await.unwrap(); let res3 = address.send(msg3).await.unwrap(); println!("We got result for Message1\r\nResult is: {}\r\n", res); println!("We got result for Message2\r\nResult is: {}\r\n", res2); println!("We got result for Message3\r\nResult is: {:?}\r\n", res3); // register an interval future for actor with given duration. let handler = address .run_interval(Duration::from_secs(1), |actor| { // Box the closure directly and wrap some async code in it. Box::pin(async move { println!("actor state is: {}", &actor.state1); }) }) .await .unwrap(); let mut interval = async_std::stream::interval(Duration::from_secs(1)); for i in 0..5 { if i == 3 { // cancel the interval future after 3 seconds. handler.cancel(); println!("interval future stopped"); } interval.next().await; } println!("example finish successfully"); } /* Implementation of actor */ // we pack all possible messages types and all handler methods for one actor into a mod. // actor_mod macro would take care for the detailed implementation. #[actor_mod] pub mod my_actor { use super::*; // our actor type #[actor] pub struct MyActor { pub state1: String, pub state2: String, } // message types #[message(result = "u8")] pub struct Message1 { pub from: String, } #[message(result = "u16")] pub struct Message2(pub u32); #[message(result = "()")] pub struct Message3; // we impl handler trait for all message types // The compiler would complain if there are message types don't have an according Handler trait impl. #[handler] impl Handler for MyActor { // The msg and handle's return type must match former message macro's result type. async fn handle(&mut self, msg123: Message1) -> u8 { println!("Actor State1 : {}", self.state1); println!("We got an Message1.\r\nfrom : {}\r\n", msg123.from); 8 } } #[handler] impl Handler for MyActor { async fn handle(&mut self, msg: Message2) -> u16 { println!("Actor State2 : {}", self.state2); println!("We got an Message2.\r\nsize : {}\r\n", msg.0); 16 } } #[handler] impl Handler for MyActor { async fn handle(&mut self, _msg: Message3) { println!("We got an Message3.\r\n"); } } }
true
0120848d62fb530c6873a74b25fd139004aef59d
Rust
kebabtent/aoc2020
/day11/src/main.rs
UTF-8
1,472
3.1875
3
[]
no_license
use common::read_lines; use X::*; #[derive(Clone, Copy, PartialEq)] enum X { F, E, O, } impl From<char> for X { fn from(c: char) -> Self { match c { '.' => F, 'L' => E, '#' => O, _ => unreachable!(), } } } fn n(d: &[(isize, isize)], f: bool, p: &Vec<Vec<X>>, ix: isize, iy: isize) -> usize { let mut c = 0; let ly = p.len() as isize; let lx = p[0].len() as isize; for &(dx, dy) in d { let mut x = ix; let mut y = iy; loop { x += dx; y += dy; if x < 0 || x >= lx || y < 0 || y >= ly { break; } let v = p[y as usize][x as usize]; if f || v != F { if v == O { c += 1; } break; } } } c } fn u(d: &[(isize, isize)], f: bool, mut p: Vec<Vec<X>>) -> usize { let mut a; let t = if f { 4 } else { 5 }; loop { a = 0; let q = p.clone(); for y in 0..p.len() { for x in 0..p[0].len() { let n = n(d, f, &q, x as isize, y as isize); p[y][x] = match q[y][x] { E if n == 0 => O, O if n >= t => E, v => v, }; if p[y][x] == O { a += 1; } } } if p == q { break; } } a } fn main() { let mut d = Vec::with_capacity(8); for i in -1isize..=1 { for j in -1isize..=1 { if i == 0 && j == 0 { continue; } d.push((i, j)); } } let p: Vec<Vec<X>> = read_lines("11") .map(|l| l.chars().map(|c| c.into()).collect()) .collect(); let a = u(&d, true, p.clone()); let b = u(&d, false, p); println!("{}", a); println!("{}", b); }
true
5550b6e49b01f2b73508374af95cb89361110a9a
Rust
stanislav-tkach/mlc
/src/logger.rs
UTF-8
866
2.8125
3
[ "MIT" ]
permissive
extern crate simplelog; use simplelog::*; arg_enum! { #[derive(Debug)] pub enum LogLevel { Info, Warn, Debug } } impl Default for LogLevel { fn default() -> Self { LogLevel::Warn } } pub fn init(log_level: &LogLevel) { let level_filter = match log_level { LogLevel::Info => LevelFilter::Info, LogLevel::Warn => LevelFilter::Warn, LogLevel::Debug => LevelFilter::Debug, }; let mut logger_array = vec![]; match TermLogger::new(level_filter, Config::default(), TerminalMode::Mixed) { Some(logger) => logger_array.push(logger as Box<dyn SharedLogger>), None => logger_array.push(SimpleLogger::new(level_filter, Config::default())), } CombinedLogger::init(logger_array).expect("No logger should be already set"); debug!("Initialized logging") }
true
e8e1915d987ccd6c290b4cb3dcf611ba8addf311
Rust
atsamd-rs/atsamd
/hal/src/sercom/uart/flags.rs
UTF-8
3,779
3.015625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
//! Flag definitions use bitflags::bitflags; use core::convert::TryFrom; //============================================================================= // Interrupt flags //============================================================================= const DRE: u8 = 0x01; const TXC: u8 = 0x02; const RXC: u8 = 0x04; const RXS: u8 = 0x08; pub(super) const CTSIC: u8 = 0x10; const RXBRK: u8 = 0x20; const ERROR: u8 = 0x80; /// Interrupt flags available for RX transactions pub const RX_FLAG_MASK: u8 = RXC | RXS | RXBRK | ERROR; /// Interrupt flags available for TX transactions pub const TX_FLAG_MASK: u8 = DRE | TXC; /// Interrupt flags available for Duplex transactions pub const DUPLEX_FLAG_MASK: u8 = RX_FLAG_MASK | TX_FLAG_MASK; bitflags! { /// Interrupt bit flags for UART Rx transactions /// /// The available interrupt flags are `DRE`, `TXC`, `RXC`, `RXS`, `CTSIC`, `RXBRK` and /// `ERROR`. The binary format of the underlying bits exactly matches the /// INTFLAG bits. pub struct Flags: u8 { const DRE = DRE; const TXC = TXC; const RXC = RXC; const RXS = RXS ; const CTSIC = CTSIC; const RXBRK = RXBRK; const ERROR = ERROR; } } //============================================================================= // Status flags //============================================================================= const PERR: u16 = 0x01; const FERR: u16 = 0x02; const BUFOVF: u16 = 0x04; const CTS: u16 = 0x08; const ISF: u16 = 0x10; const COLL: u16 = 0x20; /// Status flags available for RX transactions pub const RX_STATUS_MASK: u16 = PERR | FERR | BUFOVF | ISF | COLL; /// Status flags available for Duplex transactions pub const DUPLEX_STATUS_MASK: u16 = RX_STATUS_MASK; bitflags! { /// Status flags for UART Rx transactions /// /// The available status flags are `PERR`, `FERR`, `BUFOVF`, /// `CTS`, `ISF` and `COLL`. /// The binary format of the underlying bits exactly matches /// the STATUS bits. pub struct Status: u16 { const PERR = PERR; const FERR = FERR; const BUFOVF = BUFOVF; const CTS = CTS; const ISF = ISF; const COLL = COLL; } } //============================================================================= // Error //============================================================================= /// Errors available for UART transactions #[derive(Debug, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Error { /// Detected a parity error ParityError, /// Detected a frame error FrameError, /// Detected a buffer overflow Overflow, /// Detected an inconsistent sync field InconsistentSyncField, /// Detected a collision CollisionDetected, } impl TryFrom<Status> for () { type Error = Error; #[inline] fn try_from(errors: Status) -> Result<(), Error> { use Error::*; if errors.contains(Status::PERR) { Err(ParityError) } else if errors.contains(Status::FERR) { Err(FrameError) } else if errors.contains(Status::BUFOVF) { Err(Overflow) } else if errors.contains(Status::ISF) { Err(InconsistentSyncField) } else if errors.contains(Status::COLL) { Err(CollisionDetected) } else { Ok(()) } } } impl From<Error> for Status { #[inline] fn from(err: Error) -> Self { use Error::*; match err { ParityError => Status::PERR, FrameError => Status::FERR, Overflow => Status::BUFOVF, InconsistentSyncField => Status::ISF, CollisionDetected => Status::COLL, } } }
true
a23d9ed634f9fd9dadbc3bc30482a483b3b2a04f
Rust
Detegr/readline-sys
/src/readline/funmap.rs
UTF-8
8,517
3.046875
3
[ "MIT" ]
permissive
//! [2.4.4 Associating Function Names and Bindings] //! [2.4.4 associating function names and bindings]: https://goo.gl/CrXrWQ //! //! These functions allow you to find out what keys invoke named functions and the functions invoked //! by a particular key sequence. You may also associate a new function name with an arbitrary //! function. use readline::{CommandFunction, Keymap}; use readline::binding::BindType; use std::ffi::{CStr, CString}; use std::ptr; mod ext_funmap { use libc::{c_char, c_int}; use readline::{CommandFunction, Keymap}; extern "C" { pub fn rl_named_function(name: *const c_char) -> Option<CommandFunction>; pub fn rl_function_of_keyseq(keyseq: *const c_char, map: Keymap, bind_type: *mut c_int) -> Option<CommandFunction>; pub fn rl_invoking_keyseqs(f: CommandFunction) -> *mut *mut c_char; pub fn rl_invoking_keyseqs_in_map(f: CommandFunction, map: Keymap) -> *mut *mut c_char; pub fn rl_function_dumper(readable: c_int) -> (); pub fn rl_list_funmap_names() -> (); pub fn rl_add_funmap_entry(name: *const c_char, f: CommandFunction) -> c_int; } } /// Return the function with name `name`. /// /// # Examples /// /// ``` /// use rl_sys::readline::{funmap, util}; /// /// util::init(); /// /// assert!(funmap::named_function("self-insert").is_ok()) /// ``` pub fn named_function(name: &str) -> Result<CommandFunction, ::ReadlineError> { let csname = try!(CString::new(name)); let func_ptr = unsafe { ext_funmap::rl_named_function(csname.as_ptr()) }; if func_ptr.is_none() { Err(::ReadlineError::new("Funmap Error", "Unable to find name function!")) } else { Ok(func_ptr.expect("Unable to get function pointer")) } } /// Return the function invoked by `keyseq` in keymap `map`. If `map` is None, the current keymap is /// used. If `add_type` is true, the type of the object is returned (one of `Func`, `Kmap`, or /// `Macr`). /// /// # Examples /// /// ``` /// use rl_sys::readline::binding::BindType; /// use rl_sys::readline::{funmap, util}; /// /// util::init(); /// /// match funmap::function_of_keyseq("1", None, true) { /// Ok((_, Some(t))) => assert!(t == BindType::from(0)), /// Ok((_, None)) => assert!(false), /// Err(_) => assert!(false), /// } /// ``` pub fn function_of_keyseq (keyseq: &str, map: Option<Keymap>, add_type: bool) -> Result<(Option<CommandFunction>, Option<BindType>), ::ReadlineError> { let cskeyseq = try!(CString::new(keyseq)); let km = match map { Some(km) => km, None => ptr::null_mut(), }; let bind_type: *mut i32 = if add_type { &mut 1 } else { ptr::null_mut() }; let func_ptr = unsafe { ext_funmap::rl_function_of_keyseq(cskeyseq.as_ptr(), km, bind_type) }; if func_ptr.is_none() { Err(::ReadlineError::new("Funmap Error", "Unable to get function associated with keyseq!")) } else if add_type { Ok((func_ptr, Some(BindType::from(unsafe { *bind_type })))) } else { Ok((func_ptr, None)) } } /// Return an array of strings representing the key sequences used to invoke function in the current /// keymap. /// /// # Examples /// /// ``` /// use rl_sys::readline::{funmap, util}; /// /// util::init(); /// /// let cmd = funmap::named_function("self-insert").unwrap(); /// let names = funmap::invoking_keyseqs(cmd).unwrap(); /// assert!(names.len() > 0); /// ``` pub fn invoking_keyseqs(f: CommandFunction) -> Result<Vec<String>, ::ReadlineError> { unsafe { let arr_ptr = ext_funmap::rl_invoking_keyseqs(f); if arr_ptr.is_null() { Err(::ReadlineError::new("Funmap Error", "Unable to find invoking key seqs!")) } else { let mut entries = Vec::new(); for i in 0.. { let entry_ptr = *arr_ptr.offset(i as isize); if entry_ptr.is_null() { break; } else { entries.push(CStr::from_ptr(entry_ptr).to_string_lossy().into_owned()); } } Ok(entries) } } } /// Return an array of strings representing the key sequences used to invoke function in the current /// keymap. /// /// # Examples /// /// ``` /// use rl_sys::readline::{funmap, keymap, util}; /// /// util::init(); /// /// let cmd = funmap::named_function("self-insert").unwrap(); /// let km = keymap::get().unwrap(); /// let names = funmap::invoking_keyseqs_in_map(cmd, km).unwrap(); /// assert!(names.len() > 0); /// ``` pub fn invoking_keyseqs_in_map(f: CommandFunction, map: Keymap) -> Result<Vec<String>, ::ReadlineError> { unsafe { let arr_ptr = ext_funmap::rl_invoking_keyseqs_in_map(f, map); if arr_ptr.is_null() { Err(::ReadlineError::new("Funmap Error", "Unable to find invoking key seqs in map!")) } else { let mut entries = Vec::new(); for i in 0.. { let entry_ptr = *arr_ptr.offset(i as isize); if entry_ptr.is_null() { break; } else { entries.push(CStr::from_ptr(entry_ptr).to_string_lossy().into_owned()); } } Ok(entries) } } } /// Print the readline function names and the key sequences currently bound to them to /// `rl_outstream`. If `readable` is true, the list is formatted in such a way that it can be made /// part of an `inputrc` file and re-read. /// /// # Examples /// /// ``` /// use rl_sys::readline::{funmap, util}; /// /// util::init(); /// /// funmap::function_dumper(true); /// ``` pub fn function_dumper(readable: bool) -> () { let i = if readable { 1 } else { 0 }; unsafe { ext_funmap::rl_function_dumper(i) } } /// Print the names of all bindable Readline functions to `rl_outstream`. /// /// # Examples /// /// ``` /// use rl_sys::readline::{funmap, util}; /// /// util::init(); /// /// funmap::list_funmap_names(); /// ``` pub fn list_funmap_names() -> () { unsafe { ext_funmap::rl_list_funmap_names() } } /// Add `name` to the list of bindable Readline command names, and make function `f` the function to /// be called when `name` is invoked. /// /// # Examples /// /// ```rust /// # extern crate libc; /// # extern crate rl_sys; /// # fn main() { /// use libc::c_int; /// use rl_sys::readline::{funmap, util}; /// /// util::init(); /// /// extern "C" fn test_cmd_func(_count: c_int, _key: c_int) -> c_int { /// 0 /// } /// /// match funmap::add_funmap_entry("test-cmd", test_cmd_func) { /// Ok(res) => assert!(res >= 0), /// Err(_) => assert!(false), /// } /// # } /// ``` pub fn add_funmap_entry(name: &str, cmd: CommandFunction) -> Result<i32, ::ReadlineError> { let csname = try!(CString::new(name)); let res = unsafe { ext_funmap::rl_add_funmap_entry(csname.as_ptr(), cmd) }; if res >= 0 { Ok(res) } else { Err(::ReadlineError::new("Funmap Error", "Unable to add funmap entry!")) } } #[cfg(test)] mod test { use readline::util; use readline::binding::BindType; use super::*; // #[test] // fn test_function_dumper() { // util::init(); // function_dumper(true); // } // // #[test] // fn test_list_funmap_names() { // util::init(); // list_funmap_names(); // } #[test] fn test_function_of_keyseq() { util::init(); match function_of_keyseq("1", None, true) { Ok((_, Some(t))) => assert!(t == BindType::from(0)), Ok((_, None)) => assert!(false), Err(_) => assert!(false), } match function_of_keyseq("2", None, false) { Ok((_, Some(_))) => assert!(false), Ok((_, None)) => assert!(true), Err(_) => assert!(false), } } #[test] fn test_add_funmap_entry() { use libc::c_int; #[no_mangle] #[allow(private_no_mangle_fns)] extern "C" fn test_cmd_func(_count: c_int, _key: c_int) -> c_int { 0 } util::init(); match add_funmap_entry("test-cmd", test_cmd_func) { Ok(res) => assert!(res >= 0), Err(_) => assert!(false), } } }
true
2ee3f0e6374b8b30b68b60e38fb243dce2df9a37
Rust
creativcoder/forest
/ipld/hamt/src/hamt.rs
UTF-8
9,006
2.796875
3
[ "MIT", "Apache-2.0" ]
permissive
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use crate::node::Node; use crate::{Error, Hash, HashAlgorithm, Sha256, DEFAULT_BIT_WIDTH}; use cid::{Cid, Code::Blake2b256}; use forest_hash_utils::BytesKey; use ipld_blockstore::BlockStore; use serde::{de::DeserializeOwned, Serialize, Serializer}; use std::borrow::Borrow; use std::error::Error as StdError; use std::marker::PhantomData; /// Implementation of the HAMT data structure for IPLD. /// /// # Examples /// /// ``` /// use ipld_hamt::Hamt; /// /// let store = db::MemoryDB::default(); /// /// let mut map: Hamt<_, _, usize> = Hamt::new(&store); /// map.set(1, "a".to_string()).unwrap(); /// assert_eq!(map.get(&1).unwrap(), Some(&"a".to_string())); /// assert_eq!(map.delete(&1).unwrap(), Some((1, "a".to_string()))); /// assert_eq!(map.get::<_>(&1).unwrap(), None); /// let cid = map.flush().unwrap(); /// ``` #[derive(Debug)] pub struct Hamt<'a, BS, V, K = BytesKey, H = Sha256> { root: Node<K, V, H>, store: &'a BS, bit_width: u32, hash: PhantomData<H>, } impl<BS, V, K, H> Serialize for Hamt<'_, BS, V, K, H> where K: Serialize, V: Serialize, H: HashAlgorithm, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.root.serialize(serializer) } } impl<'a, K: PartialEq, V: PartialEq, S: BlockStore, H: HashAlgorithm> PartialEq for Hamt<'a, S, V, K, H> { fn eq(&self, other: &Self) -> bool { self.root == other.root } } impl<'a, BS, V, K, H> Hamt<'a, BS, V, K, H> where K: Hash + Eq + PartialOrd + Serialize + DeserializeOwned, V: Serialize + DeserializeOwned, BS: BlockStore, H: HashAlgorithm, { pub fn new(store: &'a BS) -> Self { Self::new_with_bit_width(store, DEFAULT_BIT_WIDTH) } /// Construct hamt with a bit width pub fn new_with_bit_width(store: &'a BS, bit_width: u32) -> Self { Self { root: Node::default(), store, bit_width, hash: Default::default(), } } /// Lazily instantiate a hamt from this root Cid. pub fn load(cid: &Cid, store: &'a BS) -> Result<Self, Error> { Self::load_with_bit_width(cid, store, DEFAULT_BIT_WIDTH) } /// Lazily instantiate a hamt from this root Cid with a specified bit width. pub fn load_with_bit_width(cid: &Cid, store: &'a BS, bit_width: u32) -> Result<Self, Error> { match store.get(cid)? { Some(root) => Ok(Self { root, store, bit_width, hash: Default::default(), }), None => Err(Error::CidNotFound(cid.to_string())), } } /// Sets the root based on the Cid of the root node using the Hamt store pub fn set_root(&mut self, cid: &Cid) -> Result<(), Error> { match self.store.get(cid)? { Some(root) => self.root = root, None => return Err(Error::CidNotFound(cid.to_string())), } Ok(()) } /// Returns a reference to the underlying store of the Hamt. pub fn store(&self) -> &'a BS { self.store } /// Inserts a key-value pair into the HAMT. /// /// If the HAMT did not have this key present, `None` is returned. /// /// If the HAMT did have this key present, the value is updated, and the old /// value is returned. The key is not updated, though; /// /// # Examples /// /// ``` /// use ipld_hamt::Hamt; /// /// let store = db::MemoryDB::default(); /// /// let mut map: Hamt<_, _, usize> = Hamt::new(&store); /// map.set(37, "a".to_string()).unwrap(); /// assert_eq!(map.is_empty(), false); /// /// map.set(37, "b".to_string()).unwrap(); /// map.set(37, "c".to_string()).unwrap(); /// ``` pub fn set(&mut self, key: K, value: V) -> Result<Option<V>, Error> where V: PartialEq, { self.root .set(key, value, self.store, self.bit_width, true) .map(|(r, _)| r) } /// Inserts a key-value pair into the HAMT only if that key does not already exist. /// /// If the HAMT did not have this key present, `true` is returned and the key/value is added. /// /// If the HAMT did have this key present, this function will return false /// /// # Examples /// /// ``` /// use ipld_hamt::Hamt; /// /// let store = db::MemoryDB::default(); /// /// let mut map: Hamt<_, _, usize> = Hamt::new(&store); /// let a = map.set_if_absent(37, "a".to_string()).unwrap(); /// assert_eq!(map.is_empty(), false); /// assert_eq!(a, true); /// /// let b = map.set_if_absent(37, "b".to_string()).unwrap(); /// assert_eq!(b, false); /// assert_eq!(map.get(&37).unwrap(), Some(&"a".to_string())); /// /// let c = map.set_if_absent(30, "c".to_string()).unwrap(); /// assert_eq!(c, true); /// ``` pub fn set_if_absent(&mut self, key: K, value: V) -> Result<bool, Error> where V: PartialEq, { self.root .set(key, value, self.store, self.bit_width, false) .map(|(_, set)| set) } /// Returns a reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, but /// `Hash` and `Eq` on the borrowed form *must* match those for /// the key type. /// /// # Examples /// /// ``` /// use ipld_hamt::Hamt; /// /// let store = db::MemoryDB::default(); /// /// let mut map: Hamt<_, _, usize> = Hamt::new(&store); /// map.set(1, "a".to_string()).unwrap(); /// assert_eq!(map.get(&1).unwrap(), Some(&"a".to_string())); /// assert_eq!(map.get(&2).unwrap(), None); /// ``` #[inline] pub fn get<Q: ?Sized>(&self, k: &Q) -> Result<Option<&V>, Error> where K: Borrow<Q>, Q: Hash + Eq, V: DeserializeOwned, { match self.root.get(k, self.store, self.bit_width)? { Some(v) => Ok(Some(v)), None => Ok(None), } } /// Returns `true` if a value exists for the given key in the HAMT. /// /// The key may be any borrowed form of the map's key type, but /// `Hash` and `Eq` on the borrowed form *must* match those for /// the key type. /// /// # Examples /// /// ``` /// use ipld_hamt::Hamt; /// /// let store = db::MemoryDB::default(); /// /// let mut map: Hamt<_, _, usize> = Hamt::new(&store); /// map.set(1, "a".to_string()).unwrap(); /// assert_eq!(map.contains_key(&1).unwrap(), true); /// assert_eq!(map.contains_key(&2).unwrap(), false); /// ``` #[inline] pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> Result<bool, Error> where K: Borrow<Q>, Q: Hash + Eq, { Ok(self.root.get(k, self.store, self.bit_width)?.is_some()) } /// Removes a key from the HAMT, returning the value at the key if the key /// was previously in the HAMT. /// /// The key may be any borrowed form of the HAMT's key type, but /// `Hash` and `Eq` on the borrowed form *must* match those for /// the key type. /// /// # Examples /// /// ``` /// use ipld_hamt::Hamt; /// /// let store = db::MemoryDB::default(); /// /// let mut map: Hamt<_, _, usize> = Hamt::new(&store); /// map.set(1, "a".to_string()).unwrap(); /// assert_eq!(map.delete(&1).unwrap(), Some((1, "a".to_string()))); /// assert_eq!(map.delete(&1).unwrap(), None); /// ``` pub fn delete<Q: ?Sized>(&mut self, k: &Q) -> Result<Option<(K, V)>, Error> where K: Borrow<Q>, Q: Hash + Eq, { self.root.remove_entry(k, self.store, self.bit_width) } /// Flush root and return Cid for hamt pub fn flush(&mut self) -> Result<Cid, Error> { self.root.flush(self.store)?; Ok(self.store.put(&self.root, Blake2b256)?) } /// Returns true if the HAMT has no entries pub fn is_empty(&self) -> bool { self.root.is_empty() } /// Iterates over each KV in the Hamt and runs a function on the values. /// /// This function will constrain all values to be of the same type /// /// # Examples /// /// ``` /// use ipld_hamt::Hamt; /// /// let store = db::MemoryDB::default(); /// /// let mut map: Hamt<_, _, usize> = Hamt::new(&store); /// map.set(1, 1).unwrap(); /// map.set(4, 2).unwrap(); /// /// let mut total = 0; /// map.for_each(|_, v: &u64| { /// total += v; /// Ok(()) /// }).unwrap(); /// assert_eq!(total, 3); /// ``` #[inline] pub fn for_each<F>(&self, mut f: F) -> Result<(), Box<dyn StdError>> where V: DeserializeOwned, F: FnMut(&K, &V) -> Result<(), Box<dyn StdError>>, { self.root.for_each(self.store, &mut f) } }
true
e0cf4cbd5bebfaf65522c756e6b4c780487ac8f1
Rust
scotttrinh/automerge-rs
/automerge/src/sync/state.rs
UTF-8
2,041
2.8125
3
[ "MIT" ]
permissive
use std::{borrow::Cow, collections::HashSet}; use super::{decode_hashes, encode_hashes, BloomFilter}; use crate::{decoding, decoding::Decoder, ChangeHash}; const SYNC_STATE_TYPE: u8 = 0x43; // first byte of an encoded sync state, for identification /// The state of synchronisation with a peer. #[derive(Debug, Clone, Default)] pub struct State { pub shared_heads: Vec<ChangeHash>, pub last_sent_heads: Vec<ChangeHash>, pub their_heads: Option<Vec<ChangeHash>>, pub their_need: Option<Vec<ChangeHash>>, pub their_have: Option<Vec<Have>>, pub sent_hashes: HashSet<ChangeHash>, } /// A summary of the changes that the sender of the message already has. /// This is implicitly a request to the recipient to send all changes that the /// sender does not already have. #[derive(Debug, Clone, Default)] pub struct Have { /// The heads at the time of the last successful sync with this recipient. pub last_sync: Vec<ChangeHash>, /// A bloom filter summarising all of the changes that the sender of the message has added /// since the last sync. pub bloom: BloomFilter, } impl State { pub fn new() -> Self { Default::default() } pub fn encode(&self) -> Vec<u8> { let mut buf = vec![SYNC_STATE_TYPE]; encode_hashes(&mut buf, &self.shared_heads); buf } pub fn decode(bytes: &[u8]) -> Result<Self, decoding::Error> { let mut decoder = Decoder::new(Cow::Borrowed(bytes)); let record_type = decoder.read::<u8>()?; if record_type != SYNC_STATE_TYPE { return Err(decoding::Error::WrongType { expected_one_of: vec![SYNC_STATE_TYPE], found: record_type, }); } let shared_heads = decode_hashes(&mut decoder)?; Ok(Self { shared_heads, last_sent_heads: Vec::new(), their_heads: None, their_need: None, their_have: Some(Vec::new()), sent_hashes: HashSet::new(), }) } }
true
03eb98277ce924ee5a3cc7eb835dc6b00d4bd79e
Rust
sww1235/connection-diagram-manager
/src/datatypes/internal_types.rs
UTF-8
65,989
3.046875
3
[ "Apache-2.0", "MIT" ]
permissive
///`cable_type` represents a cable with multiple cores pub mod cable_type; /// `connector_type` represents a connector pub mod connector_type; /// `equipment_type` represents a type of equipment pub mod equipment_type; /// `location_type` represents a type of location pub mod location_type; /// `pathway_type` represents a type of pathway for wires or cables pub mod pathway_type; /// `svg` represents a complete SVG image pub mod svg; /// `term_cable_type` represents a cable that has connectors assembled on to it pub mod term_cable_type; /// `wire_type` represents an individual wire with optional insulation pub mod wire_type; /// `equipment` represents an instance of an `EquipmentType`. This is a physical item /// you hold in your hand. pub mod equipment; /// `location` represents an instance of a `LocationType` pub mod location; /// `pathway` represents an instance of a `PathwayType` pub mod pathway; /// `wire_cable` represents an instance of either a `WireType`, `CableType` or `TermCableType` pub mod wire_cable; use log::{error, trace, warn}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use super::file_types::DataFile; use super::util_types::CrossSection; use cable_type::CableCore; use svg::Svg; /// `Library` represents all library data used in program #[derive(Debug, Default, PartialEq)] pub struct Library { /// contains all wire types read in from file, and/or added in via program logic pub wire_types: HashMap<String, Rc<RefCell<wire_type::WireType>>>, /// contains all cable types read in from file, and/or added in via program logic pub cable_types: HashMap<String, Rc<RefCell<cable_type::CableType>>>, /// contains all terminated cable types read in from file, and/or added in via program logic pub term_cable_types: HashMap<String, Rc<RefCell<term_cable_type::TermCableType>>>, /// contains all location types read in from file, and/or added in via program logic pub location_types: HashMap<String, Rc<RefCell<location_type::LocationType>>>, /// contains all connector types read in from file, and/or added in via program logic pub connector_types: HashMap<String, Rc<RefCell<connector_type::ConnectorType>>>, /// contains all equipment types read in from file, and/or added in via program logic pub equipment_types: HashMap<String, Rc<RefCell<equipment_type::EquipmentType>>>, /// contains all pathway types read in from file pub pathway_types: HashMap<String, Rc<RefCell<pathway_type::PathwayType>>>, } /// `Project` represents all project specific data used in program #[derive(Debug, Default, PartialEq)] pub struct Project { /// `equipment` contains all equipment instances read in from files, and/or added in via program logic pub equipment: HashMap<String, Rc<RefCell<equipment::Equipment>>>, /// `wire_cables` contains all wire, cable and termcable instances read in from files, and/or /// added in via program logic pub wire_cables: HashMap<String, Rc<RefCell<wire_cable::WireCable>>>, /// `pathways`contains all pathway instances read in from files and/or added in via program /// logic pub pathways: HashMap<String, Rc<RefCell<pathway::Pathway>>>, /// `locations` contains all location instances read in from files and/or added in via program /// logic pub locations: HashMap<String, Rc<RefCell<location::Location>>>, } /// `Mergable` indicates that an object has the necessary utilities to merge itself with another /// instance of the same object type. pub trait Mergable { /// `merge_prompt` assists the user in merging 2 object instances by prompting the user with /// the difference between the object, field by field, and providing sensible defaults. fn merge_prompt( &mut self, other: &Self, prompt_fn: fn(HashMap<String, [String; 2]>) -> HashMap<String, u8>, ) -> Self; // pass a hashmap of string arrays, return a hashmap of integers which are the selected value // index out of the array, with keys as struct field names } /// `Empty` indicates that an object can be checked for PartialEq to Object::new() pub trait Empty { /// `is_empty` checks to see if self is PartialEq to Object::new() fn is_empty(&self) -> bool; } /// `PartialEmpty` indicates that an object can be checked to be almost PartialEq to Object::new(), /// excepting the id field pub trait PartialEmpty { /// `is_partial_empty` checks to see if self is almost PartialEq to Object::new() but id can be /// different fn is_partial_empty(&self) -> bool; } //TODO: need to add datafile reference to each internal_type struct so each appropriate datafile //can be updated with new serialized data impl Library { ///Initializes an empty `Library` pub fn new() -> Self { Library { wire_types: HashMap::new(), cable_types: HashMap::new(), term_cable_types: HashMap::new(), location_types: HashMap::new(), connector_types: HashMap::new(), equipment_types: HashMap::new(), pathway_types: HashMap::new(), } } /// `from_datafiles` converts between the textual representation of datafiles, and the struct /// object representation of the internal objects pub fn from_datafiles(&mut self, datafiles: Vec<DataFile>) { // parse all datafiles for datafile in datafiles { self.from_datafile(datafile) } for (_, wire_type) in &self.wire_types { //TODO: check for empty objects } for (_, cable_type) in &self.cable_types { //TODO: check for empty objects } for (_, term_cable_type_type) in &self.term_cable_types { //TODO: check for empty objects } for (_, location_type) in &self.location_types { //TODO: check for empty objects } for (_, connector_type) in &self.connector_types { //TODO: check for empty objects } for (_, equipment_type) in &self.equipment_types { //TODO: check for empty objects } for (_, pathway_type) in &self.pathway_types { //TODO: check for empty objects } } /// inserts the correct values from a datafile into the called upon `Library` struct #[allow(clippy::wrong_self_convention)] // this is not a type conversion function so does not // need to follow the same rules // TODO: maybe rename this to something that doesn't // sound like a type conversion function fn from_datafile(&mut self, datafile: DataFile) { // wire_types if let Some(wire_types) = datafile.wire_types { for (k, v) in &wire_types { if self.wire_types.contains_key(k) { //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically warn! {concat!{ "WireType: {} with contents: {:#?} ", "has already been loaded. Found again ", "in file {}. Check this and merge if necessary"}, k, v, datafile.file_path.display() } } else { trace! {"Inserted WireType: {}, value: {:#?} into main library.",k,v} self.wire_types.insert( k.to_string(), Rc::new(RefCell::new(wire_type::WireType { id: k.to_string(), manufacturer: wire_types[k].manufacturer.clone(), model: wire_types[k].model.clone(), part_number: wire_types[k].part_number.clone(), manufacturer_part_number: wire_types[k] .manufacturer_part_number .clone(), supplier: wire_types[k].supplier.clone(), supplier_part_number: wire_types[k].supplier_part_number.clone(), material: wire_types[k].material.clone(), insulated: wire_types[k].insulated, insulation_material: wire_types[k].insulation_material.clone(), wire_type_code: wire_types[k].wire_type_code.clone(), conductor_cross_sect_area: wire_types[k].conductor_cross_sect_area, overall_cross_sect_area: wire_types[k].overall_cross_sect_area, stranded: wire_types[k].stranded, num_strands: wire_types[k].num_strands, strand_cross_sect_area: wire_types[k].strand_cross_sect_area, insul_volt_rating: wire_types[k].insul_volt_rating, insul_temp_rating: wire_types[k].insul_temp_rating, insul_color: wire_types[k].insul_color.clone(), })), ); } } } // cable_types if let Some(cable_types) = datafile.cable_types { for (k, v) in &cable_types { if self.cable_types.contains_key(k) { warn! {concat!{ "CableType: {} with contents: {:#?} ", "has already been loaded. Found again in ", "file {}. Check this and merge if necessary"}, k, v, datafile.file_path.display() } //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted CableType: {}, value: {:#?} into main datastore.",k,v} // need to build cable_core first, so we can insert into self.cable_types if // needed. let mut cable_core_map = HashMap::new(); for (core_id, core) in &cable_types[k].cable_core { //TODO: this could result in issues where the cable type is in //the file, but not read before it is checked for here. if core.is_wire && self.wire_types.contains_key(&core.type_str) { cable_core_map.insert( core_id.to_string(), CableCore::WireType(self.wire_types[&core.type_str].clone()), ); } else if !core.is_wire && self.cable_types.contains_key(&core.type_str) { cable_core_map.insert( core_id.to_string(), CableCore::CableType(self.cable_types[&core.type_str].clone()), ); } else { warn! {concat!{ "can't find CableCore Type: {} ", "referenced in CableType: {} in ", "datafile: {}, in any file or ", "library imported into Project. ", "Creating empty object for now"}, core.type_str, k, datafile.file_path.display() } if core.is_wire { let new_wire_type = Rc::new(RefCell::new(wire_type::WireType::new())); // need to set id of wire type correctly. type_str not // core_id new_wire_type.borrow_mut().id = core.type_str.to_string(); // insert new_wire_type as core into cable_core_map cable_core_map.insert( core_id.to_string(), CableCore::WireType(new_wire_type.clone()), ); // also insert new_wire_type into library self.wire_types .insert(core.type_str.to_string(), new_wire_type.clone()); } else { //cable type let new_cable_type = Rc::new(RefCell::new(cable_type::CableType::new())); new_cable_type.borrow_mut().id = core.type_str.to_string(); // insert new_cable_type as core into cable_core_map cable_core_map.insert( core_id.to_string(), CableCore::CableType(new_cable_type.clone()), ); // also insert new_cable_type into library self.cable_types .insert(core.type_str.to_string(), new_cable_type.clone()); } } } self.cable_types.insert( k.to_string(), Rc::new(RefCell::new(cable_type::CableType { id: k.to_string(), manufacturer: cable_types[k].manufacturer.clone(), model: cable_types[k].model.clone(), part_number: cable_types[k].part_number.clone(), manufacturer_part_number: cable_types[k].manufacturer_part_number.clone(), supplier: cable_types[k].supplier.clone(), supplier_part_number: cable_types[k].supplier_part_number.clone(), cable_type_code: cable_types[k].cable_type_code.clone(), cross_sect_area: cable_types[k].cross_sect_area, height: cable_types[k].height, width: cable_types[k].width, diameter: cable_types[k].diameter, cross_section: { match cable_types[k].cross_section.to_uppercase().as_str() { "OVAL" => CrossSection::Oval, "CIRCULAR" => CrossSection::Circular, "SIAMESE" => CrossSection::Siamese, //TODO: handle this better _ => panic! {concat!{ "Cross Section: {} in CableType: {} ", "in file: {} not recognized. ", "Check your spelling and try again."} ,cable_types[k].cross_section, k, datafile.file_path.display() } } }, // cable_core_map defined above main struct definition to avoid multiple mutable // borrows of self.cable_types cable_core: cable_core_map, insul_layers: { let mut new_layers = Vec::new(); for layer in &cable_types[k].insul_layers { let new_layer = cable_type::CableLayer { layer_number: layer.layer_number, layer_type: layer.layer_type.clone(), material: layer.material.clone(), volt_rating: layer.volt_rating, temp_rating: layer.temp_rating, color: layer.color.clone(), }; new_layers.push(new_layer); } new_layers }, })), ); } } } // pathway_types if let Some(pathway_types) = datafile.pathway_types { for (k, v) in &pathway_types { if self.pathway_types.contains_key(k) { warn! {concat!{"PathwayType : {} with ", "contents: {:#?} has already been ", "loaded. Found again in file {}. ", "Check this and merge if necessary"}, k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted PathwayType: {}, value: {:#?} into main datastore.",k,v} self.pathway_types.insert( k.to_string(), Rc::new(RefCell::new(pathway_type::PathwayType { id: k.to_string(), manufacturer: pathway_types[k].manufacturer.clone(), model: pathway_types[k].model.clone(), part_number: pathway_types[k].part_number.clone(), manufacturer_part_number: pathway_types[k] .manufacturer_part_number .clone(), supplier: pathway_types[k].supplier.clone(), supplier_part_number: pathway_types[k].supplier_part_number.clone(), description: pathway_types[k].description.clone(), size: pathway_types[k].size.clone(), trade_size: pathway_types[k].trade_size.clone(), // no clone needed since numeric types have easy copy implementation cross_sect_area: pathway_types[k].cross_sect_area, material: pathway_types[k].material.clone(), })), ); } } } // location_types if let Some(location_types) = datafile.location_types { for (k, v) in &location_types { if self.location_types.contains_key(k) { warn! {concat!{"LocationType : {} with ", "contents: {:#?} has already been loaded. ", "Found again in file {}. Check this ", "and merge if necessary"}, k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted LocationType: {}, value: {:#?} into main datastore.",k,v} self.location_types.insert( k.to_string(), Rc::new(RefCell::new(location_type::LocationType { id: k.to_string(), manufacturer: location_types[k].manufacturer.clone(), model: location_types[k].model.clone(), part_number: location_types[k].part_number.clone(), manufacturer_part_number: location_types[k] .manufacturer_part_number .clone(), supplier: location_types[k].supplier.clone(), supplier_part_number: location_types[k].supplier_part_number.clone(), description: location_types[k].description.clone(), material: location_types[k].material.clone(), height: location_types[k].height, width: location_types[k].width, depth: location_types[k].depth, usable_width: location_types[k].usable_width, usable_height: location_types[k].usable_height, usable_depth: location_types[k].usable_depth, })), ); } } } // connector_types if let Some(connector_types) = datafile.connector_types { for (k, v) in &connector_types { if self.connector_types.contains_key(k) { warn! {concat!{ "ConnectorType : {} with contents: ", "{:#?} has already been loaded. Found ", "again in file {}. Check this and merge if necessary" }, k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted ConnectorType: {}, value: {:#?} into main datastore.",k,v} self.connector_types.insert( k.to_string(), Rc::new(RefCell::new(connector_type::ConnectorType { id: k.to_string(), manufacturer: connector_types[k].manufacturer.clone(), model: connector_types[k].model.clone(), part_number: connector_types[k].part_number.clone(), manufacturer_part_number: connector_types[k] .manufacturer_part_number .clone(), supplier: connector_types[k].supplier.clone(), supplier_part_number: connector_types[k].supplier_part_number.clone(), description: connector_types[k].description.clone(), mount_type: connector_types[k].mount_type.clone(), panel_cutout: connector_types[k].panel_cutout.clone(), gender: connector_types[k].gender.clone(), height: connector_types[k].height, width: connector_types[k].width, depth: connector_types[k].depth, diameter: connector_types[k].diameter, pins: { let mut new_pins = Vec::new(); for pin in &connector_types[k].pins { let new_pin = connector_type::ConnectorPin { id: pin.id.clone(), label: pin.label.clone(), signal_type: pin.signal_type.clone(), color: pin.color.clone(), visual_rep: pin.visual_rep.clone().map(Svg::from), gender: pin.gender.clone(), }; new_pins.push(new_pin); } new_pins }, visual_rep: Svg::from(connector_types[k].visual_rep.clone()), })), ); } } } // term_cable_types if let Some(term_cable_types) = datafile.term_cable_types { for (k, v) in &term_cable_types { if self.term_cable_types.contains_key(k) { warn! {concat!{ "TermCableType : {} with contents: ", "{:#?} has already been loaded. ", "Found again in file {}. Check this and merge if necessary"}, k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted TermCableType: {}, value: {:#?} into main datastore.",k,v} self.term_cable_types.insert(k.to_string(), Rc::new(RefCell::new(term_cable_type::TermCableType { id: k.to_string(), manufacturer: term_cable_types[k].manufacturer.clone(), model: term_cable_types[k].model.clone(), part_number: term_cable_types[k].part_number.clone(), manufacturer_part_number: term_cable_types[k].manufacturer_part_number.clone(), supplier: term_cable_types[k].supplier.clone(), supplier_part_number: term_cable_types[k].supplier_part_number.clone(), description: term_cable_types[k].description.clone(), wire_cable: { if term_cable_types[k].wire.is_some() && term_cable_types[k].cable.is_some() { panic! {concat!{ "Both wire and cable ", "values of TermCableType {} ", "are specified. Please correct this."}, k} } else if term_cable_types[k].wire.is_none() && term_cable_types[k].cable.is_none() { panic! {concat!{ "Neither wire or cable ", "values of TermCableType {} ", "are specified. Please correct this."}, k} } else { #[allow(clippy::collapsible_else_if)] // This would change the // meaning of the logic if let Some(wire_type_id) = term_cable_types[k].wire.clone() { if self.wire_types.contains_key(&wire_type_id) { term_cable_type::WireCable::WireType(self.wire_types[&wire_type_id].clone()) } else { warn!{concat!{ "WireType: {} in TermCableType: ", "{} specified in datafile: {} is not ", "found in any library either read from ", "datafiles, or implemented in program ", "logic. Creating empty object for now"}, wire_type_id, k, datafile.file_path.display() } let new_wire_type = Rc::new(RefCell::new( wire_type::WireType::new())); new_wire_type.borrow_mut().id = wire_type_id.to_string(); // first insert new_wire_type into library self.wire_types.insert(wire_type_id.to_string(), new_wire_type.clone()); // then return reference to insert into struct field term_cable_type::WireCable::WireType(new_wire_type.clone()) } } else if let Some(cable_type_id) = &term_cable_types[k].cable { if self.cable_types.contains_key(cable_type_id) { term_cable_type::WireCable::CableType( self.cable_types[cable_type_id].clone()) } else { warn!{concat!{ "WireType: {} in TermCableType: ", "{} specified in datafile: {} is not ", "found in any library either read from ", "datafiles, or implemented in program ", "logic. Creating empty object for now"}, cable_type_id, k, datafile.file_path.display() } let new_cable_type = Rc::new(RefCell::new( cable_type::CableType::new())); new_cable_type.borrow_mut().id = cable_type_id.to_string(); // insert new_cable_type into library self.cable_types.insert(cable_type_id.to_string(), new_cable_type.clone()); // then return reference to insert into struct field term_cable_type::WireCable::CableType(new_cable_type.clone()) } } else { //TODO: fix this panic! {concat!{ "Neither wire or cable ", "values of TermCableType {} ", "are specified. Please correct this."}, k} } } }, nominal_length: term_cable_types[k].nominal_length, actual_length: term_cable_types[k].actual_length, end1: { let mut new_end1 = Vec::new(); for connector in &term_cable_types[k].end1 { let new_connector = term_cable_type::TermCableConnector { connector_type: { if self.connector_types.contains_key(&connector.connector_type) { self.connector_types[&connector.connector_type].clone() } else { warn! {concat!{ "End 1 of TermCableType: {} ", "in datafile: {}, contains ", "ConnectorType: {} that does ", "not exist in any library data, ", "either read from file, or ", "created via program logic. ", "Creating empty object for now."}, k, datafile.file_path.display(), &connector.connector_type} let new_connector_type = Rc::new(RefCell::new( connector_type::ConnectorType::new())); // insert new_connector_type into library self.connector_types.insert( connector.connector_type.to_string(), new_connector_type.clone()); // then return reference to insert into struct // field new_connector_type.clone() } }, terminations: { if let Some(terminations) = &connector.terminations { let mut new_terminations = Vec::new(); for termination in terminations { let new_termination = term_cable_type::TermCableConnectorTermination { core: termination.core, pin: termination.pin, }; new_terminations.push(new_termination); } Some(new_terminations) } else {None} }, }; new_end1.push(new_connector); } new_end1 }, end2: { let mut new_end2 = Vec::new(); for connector in &term_cable_types[k].end2 { let new_connector = term_cable_type::TermCableConnector { connector_type: { if self.connector_types.contains_key(&connector.connector_type) { self.connector_types[&connector.connector_type].clone() } else { warn! {concat!{ "End 2 of TermCableType: {} ", "in datafile: {}, contains ", "ConnectorType: {} that does ", "not exist in any library data, ", "either read from file, or ", "created via program logic. ", "Creating empty object for now."}, k, datafile.file_path.display(), &connector.connector_type} let new_connector_type = Rc::new(RefCell::new( connector_type::ConnectorType::new())); // insert new_connector_type into library self.connector_types.insert( connector.connector_type.to_string(), new_connector_type.clone()); // then return reference to insert into struct // field new_connector_type.clone() } }, terminations: { if let Some(terminations) = &connector.terminations { let mut new_terminations = Vec::new(); for termination in terminations { let new_termination = term_cable_type::TermCableConnectorTermination { core: termination.core, pin: termination.pin, }; new_terminations.push(new_termination); } Some(new_terminations) } else {None} }, }; new_end2.push(new_connector); } new_end2 }, }, ))); } } } // equipment_types if let Some(equipment_types) = datafile.equipment_types { for (k, v) in &equipment_types { if self.equipment_types.contains_key(k) { warn! {concat!{"EquipmentType : {} with ", "contents: {:#?} has already been loaded. ", "Found again in file {}. ", "Check this and merge if necessary"}, k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted EquipmentType: {}, value: {:#?} into main datastore.",k,v} self.equipment_types.insert(k.to_string(), Rc::new(RefCell::new(equipment_type::EquipmentType { id: k.to_string(), manufacturer: equipment_types[k].manufacturer.clone(), model: equipment_types[k].model.clone(), part_number: equipment_types[k].part_number.clone(), manufacturer_part_number: equipment_types[k].manufacturer_part_number.clone(), supplier: equipment_types[k].supplier.clone(), supplier_part_number: equipment_types[k].supplier_part_number.clone(), description: equipment_types[k].description.clone(), mount_type: equipment_types[k].mount_type.clone(), equip_type: equipment_types[k].equip_type.clone(), faces: { if let Some(faces) = &equipment_types[k].faces { let mut new_faces = Vec::new(); for face in faces { let new_face = equipment_type::EquipFace { name: face.name.to_string(), vis_rep: face.vis_rep.clone().map(Svg::from), connectors: { if let Some(connectors) = &face.connectors { let mut new_connectors = Vec::new(); for connector in connectors { let new_connector = equipment_type::EquipConnector { connector_type: { if self.connector_types.contains_key(&connector.connector_type) { self.connector_types[&connector.connector_type].clone() } else { warn! {concat!{ "ConnectorType: {} in Equipment: {} ", "from datafile: {}, not found ", "in any library data, ", "either read from file, or ", "created via program logic. ", "Creating empty object for now."}, &connector.connector_type, k, datafile.file_path.display() } let new_connector_type = Rc::new(RefCell::new( connector_type::ConnectorType::new())); // insert new_connector_type into library self.connector_types.insert( connector.connector_type.to_string(), new_connector_type.clone()); // then return reference to insert into struct // field new_connector_type.clone() } }, direction: connector.direction.clone(), x: connector.x, y: connector.y, }; new_connectors.push(new_connector); } Some(new_connectors) } else {None} }, }; new_faces.push(new_face); } Some(new_faces) } else { None } }, visual_rep: Svg::from(equipment_types[k].visual_rep.clone()), }, ))); } } } } } impl Project { ///Initializes an empty `Project` pub fn new() -> Self { Project { locations: HashMap::new(), equipment: HashMap::new(), pathways: HashMap::new(), wire_cables: HashMap::new(), } } /// `from_datafiles` converts between the textual representation of datafiles, and the struct /// object representation of the internal objects pub fn from_datafiles(&mut self, datafiles: Vec<DataFile>, library: &Library) { // parse all datafiles for datafile in datafiles { self.from_datafile(datafile, library) } for (_, location) in &self.locations { //TODO: check for empty objects } for (_, equipment) in &self.equipment { //TODO: check for empty objects } for (_, pathway) in &self.pathways { //TODO: check for empty objects } for (_, wire_cable) in &self.wire_cables { //TODO: check for empty objects } } /// `from_datafile` takes a `DataFile` and a `Library` and imports all Project data found /// within, into the `Project` struct this method is called on. It will check `Library` for /// defined types to assign as references within the various project data imported from /// `datafile` #[allow(clippy::wrong_self_convention)] // this is not a type conversion function so does not // need to follow the same rules // TODO: maybe rename this to something that doesn't // sound like a type conversion function fn from_datafile(&mut self, datafile: DataFile, library: &Library) { // pathway if let Some(pathways) = datafile.pathways { for (k, v) in &pathways { if self.pathways.contains_key(k) { warn! {"Pathway : {} with contents: {:#?} has already been loaded. Found again in file {}. Check this and merge if necessary", k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted Pathway: {}, value: {:#?} into main datastore.",k,v} self.pathways.insert(k.to_string(), Rc::new( RefCell::new( pathway::Pathway { id: k.to_string(), path_type: { if library.pathway_types.contains_key(&pathways[k].path_type) { library.pathway_types[&pathways[k].path_type].clone() } else { //TODO: handle this more intelligently panic! {"Failed to find PathwayType: {} used in Pathway: {} in file {}, in any imported library dictionary or file. Please check spelling, or add it, if this was not intentional.", pathways[k].path_type, &k, datafile.file_path.display() } } }, identifier: pathways[k].identifier.clone(), description: pathways[k].description.clone(), length: pathways[k].length, } ) ) ); } } } // wire_cables if let Some(wire_cables) = datafile.wire_cables { for (k, v) in &wire_cables { if self.wire_cables.contains_key(k) { warn! {concat!{ "WireCable: {} with contents: ", "{:#?} has already been loaded. ", "Found again in file {}. ", "Check this and merge if necessary"}, k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted WireCable: {}, value: {:#?} into main project.",k,v} self.wire_cables.insert( k.to_string(), Rc::new(RefCell::new(wire_cable::WireCable { id: k.to_string(), ctw_type: { // Checking to make sure only one of wire, cable, or term_cable are set if (wire_cables[k].wire.is_some() && wire_cables[k].cable.is_some() && wire_cables[k].term_cable.is_some()) || (wire_cables[k].wire.is_some() && wire_cables[k].cable.is_some()) || (wire_cables[k].cable.is_some() && wire_cables[k].term_cable.is_some()) || (wire_cables[k].wire.is_some() && wire_cables[k].term_cable.is_some()) { panic! {concat!{ "More than one of wire, ", "cable and term_cable of ", "WireCable {} are specified. ", "Please correct this."}, &k} } else if wire_cables[k].wire.is_none() && wire_cables[k].cable.is_none() && wire_cables[k].term_cable.is_none() { panic! {concat!{"Neither wire, cable ", "or term_cable values of WireCable {} ", "are specified. Please correct this."}, &k} } else { // at this point, only one of wire, cable and term_cable should // be set. // // clone string here to avoid moving value out of hashmap. if let Some(wire_type) = wire_cables[k].wire.clone() { if library.wire_types.contains_key(&wire_type) { wire_cable::WireCableType::WireType( library.wire_types[&wire_type].clone(), ) } else { // since this is project, not library, we want to error // for types not found in library, since they should // all have been parsed before parsing project. panic! {concat!{ "WireType: {} in ", "WireCable: {} specified in ", "datafile: {} is not found in ", "any library either read from ", "datafiles, or implemented in program ", "logic. Check your spelling"}, wire_type, k, datafile.file_path.display()} } // clone string here to avoid moving value out of hashmap. } else if let Some(cable_type) = wire_cables[k].cable.clone() { if library.cable_types.contains_key(&cable_type) { wire_cable::WireCableType::CableType( library.cable_types[&cable_type].clone(), ) } else { // since this is project, not library, we want to error // for types not found in library, since they should // all have been parsed before parsing project. panic! {concat!{ "CableType: {} in ", "WireCable: {} specified in ", "datafile: {} is not found in ", "any library either read from ", "datafiles, or implemented in program ", "logic. Check your spelling"}, cable_type, k, datafile.file_path.display()} } // clone string here to avoid moving value out of hashmap. } else if let Some(term_cable_type) = wire_cables[k].term_cable.clone() { if library.term_cable_types.contains_key(&term_cable_type) { wire_cable::WireCableType::TermCableType( library.term_cable_types[&term_cable_type].clone(), ) } else { // since this is project, not library, we want to error // for types not found in library, since they should // all have been parsed before parsing project. panic! {concat!{ "TermCableType: {} in ", "WireCable: {} specified in ", "datafile: {} is not found in ", "any library either read from ", "datafiles, or implemented in program ", "logic. Check your spelling"}, term_cable_type, k, datafile.file_path.display()} } } else { //TODO: fix this panic! {concat!{ "Neither wire, cable ", "or termcable type values ", "of WireCable {} are specified. ", "Please correct this."}, &k} } } }, identifier: wire_cables[k].identifier.clone(), description: wire_cables[k].description.clone(), length: wire_cables[k].length, pathway: { // clone string here to avoid moving value out of hashmap. if let Some(pathway) = wire_cables[k].pathway.clone() { if self.pathways.contains_key(k) { Some(self.pathways[k].clone()) } else { error! {concat!{ "WireCable: {} is assigned to ", "Pathway: {} in datafile: {}, ", "that doesn't exist in any ", "library either read in from ", "datafile, or added via program ", "logic. Not assigning pathway to ", "WireCable {}. Please check your spelling "}, k, pathway, datafile.file_path.display(), k} let new_pathway = Rc::new(RefCell::new(pathway::Pathway::new())); // insert new_pathway into Project self.pathways.insert(pathway, new_pathway.clone()); // then return reference for struct field Some(new_pathway) } } else { None } }, })), ); } } } // locations if let Some(locations) = datafile.locations { for (k, v) in &locations { if self.locations.contains_key(k) { warn! {concat!{"Location: {} with ", "contents: {:#?} has already been ", "loaded. Found again in file {}. ", "Check this and merge if necessary"}, k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted Location: {}, value: {:#?} into main project.",k,v} self.locations.insert( k.to_string(), Rc::new(RefCell::new(location::Location { id: k.to_string(), location_type: { if library .location_types .contains_key(&locations[k].location_type) { library.location_types[&locations[k].location_type].clone() } else { // since this is project, not library, we want to error // for types not found in library, since they should // all have been parsed before parsing project. panic! {concat!{ "Failed to find ", "LocationType: {} used in ", "Location: {} in file {}, ", "in any imported library dictionary ", "or file. Please check spelling, or ", "add it, if this was not intentional."}, locations[k].location_type, &k, datafile.file_path.display() } } }, identifier: locations[k].identifier.clone(), description: locations[k].description.clone(), physical_location: locations[k].physical_location.clone(), })), ); } } } // equipment if let Some(equipment) = datafile.equipment { for (k, v) in &equipment { if self.equipment.contains_key(k) { warn! {"Equipment: {} with contents: {:#?} has already been loaded. Found again in file {}. Check this and merge if necessary", k, v, datafile.file_path.display()} //TODO: do something: ignore dupe, prompt user for merge, try to merge //automatically } else { trace! {"Inserted Equipment: {}, value: {:#?} into main project.",k,v} self.equipment.insert( k.to_string(), Rc::new(RefCell::new(equipment::Equipment { id: k.to_string(), equip_type: { if library .equipment_types .contains_key(&equipment[k].equipment_type) { library.equipment_types[&equipment[k].equipment_type].clone() } else { // since this is project, not library, we want to error // for types not found in library, since they should // all have been parsed before parsing project. panic! {concat!{ "Failed to find ", "EquipmentType: {} used ", "in Equipment: {} in ", "file {}, in any imported ", "library dictionary or ", "file. Please check spelling, ", "or add it, if this was not intentional."}, equipment[k].equipment_type, &k, datafile.file_path.display() } } }, identifier: equipment[k].identifier.clone(), mounting_type: equipment[k].mounting_type.clone(), location: { // clone string here to avoid moving value out of hashmap. if let Some(file_location) = equipment[k].location.clone() { #[allow(clippy::map_entry)] // TODO: use entry mechanic to fix this, allowing for now if self.locations.contains_key(&file_location) { Some(self.locations[k].clone()) } else { error! {concat!{ "Location: {} is assigned to ", "Equipment: {} in datafile: {}, ", "that doesn't exist in any library ", "either read in from datafile, or ", "added via program logic. Check your spelling"}, k, file_location, datafile.file_path.display()} let new_location = Rc::new(RefCell::new(location::Location::new())); // add new_location to Project self.locations.insert(file_location, new_location.clone()); // then return reference to struct field Some(new_location.clone()) } } else { None } }, description: equipment[k].description.clone(), })), ); } } } } } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; #[test] fn new_library() { assert_eq!( Library::new(), Library { wire_types: HashMap::new(), cable_types: HashMap::new(), term_cable_types: HashMap::new(), location_types: HashMap::new(), connector_types: HashMap::new(), equipment_types: HashMap::new(), pathway_types: HashMap::new(), } ) } #[test] fn new_project() { assert_eq!( Project::new(), Project { locations: HashMap::new(), equipment: HashMap::new(), pathways: HashMap::new(), wire_cables: HashMap::new(), } ) } // TODO: testing ideas (for both project and library): // - test import of datafile containing each individual object // - test import of basic datafile, minimal amount of data necessary // - test import of full datafile, with multiple defined dictionary entries for each dictionary // - test failure of multiple of the top level dicts defined in one file // - test to make sure only one of wire, cable, termcable is set in project parsing, both // positive and negative // - test importing a cable/termcable type with a missing wiretype (also for equipment, etc) // - test complicated term_cable // - test all project datatypes with both present and absent library values // - test all panics // - test library types that refer to each other, make sure objects are always parsed in // correct order // - same with project types, except with both library and project assets #[test] fn read_datafile_library() {} #[test] fn read_datafile_project() {} }
true
348ee467114341334ab05f9b2f2b83429e4b15cf
Rust
ikfr/orz
/src/byteslice.rs
UTF-8
1,067
2.9375
3
[ "MIT" ]
permissive
pub trait ByteSliceExt { unsafe fn read<T>(&self, offset: usize) -> T; unsafe fn write<T>(&mut self, offset: usize, value: T); unsafe fn read_forward<T>(&self, offset: &mut usize) -> T; unsafe fn write_forward<T>(&mut self, offset: &mut usize, value: T); } impl ByteSliceExt for [u8] { unsafe fn read<T>(&self, offset: usize) -> T { return std::ptr::read_unaligned(self.as_ptr().add(offset) as *const T); } unsafe fn write<T>(&mut self, offset: usize, value: T) { std::ptr::write_unaligned(self.as_mut_ptr().add(offset) as *mut T, value); } unsafe fn read_forward<T>(&self, offset: &mut usize) -> T { let t = std::ptr::read_unaligned(self.as_ptr().add(*offset) as *const T); std::ptr::write(offset, *offset + std::mem::size_of::<T>()); return t; } unsafe fn write_forward<T>(&mut self, offset: &mut usize, value: T) { std::ptr::write_unaligned(self.as_mut_ptr().add(*offset) as *mut T, value); std::ptr::write(offset, *offset + std::mem::size_of::<T>()); } }
true
7a8fde05b2c5ea29a8d5af5dad7e31ba787e3a75
Rust
fanyangxi/erno-cube-solver-repo
/erno-cube-solver/src/models/cube.rs
UTF-8
2,312
3.578125
4
[]
no_license
use crate::models::face::Face; use std::fmt; pub struct Cube { pub front: Face, // Front pub back: Face, // Back pub left: Face, // Left pub right: Face, // Right pub up: Face, // Up pub down: Face, // Down } impl Cube { pub fn new(faces: [Face; 6]) -> Self { Cube { front: faces[0], back: faces[1], left: faces[2], right: faces[3], up: faces[4], down: faces[5], } } } impl fmt::Display for Cube { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Cube: {} {} {} {} {} {}", self.front, self.back, self.left, self.right, self.up, self.down) } } #[cfg(test)] mod cross_tests { use crate::models::cube::Cube; use crate::models::colors::Color; use crate::models::face::Face; #[test] fn it_works() { let face1 = Face::new([ [Color::Red,Color::Red,Color::Red], [Color::Red,Color::Red,Color::Red], [Color::Red,Color::Red,Color::Red], ]); let face2 = Face::new([ [Color::Green,Color::Green,Color::Green], [Color::Green,Color::Green,Color::Green], [Color::Green,Color::Green,Color::Green], ]); let face3 = Face::new([ [Color::Yellow,Color::Yellow,Color::Yellow], [Color::Yellow,Color::Yellow,Color::Yellow], [Color::Yellow,Color::Yellow,Color::Yellow], ]); let face4 = Face::new([ [Color::Blue,Color::Blue,Color::Blue], [Color::Blue,Color::Blue,Color::Blue], [Color::Blue,Color::Blue,Color::Blue], ]); let face5 = Face::new([ [Color::Orange,Color::Orange,Color::Orange], [Color::Orange,Color::Orange,Color::Orange], [Color::Orange,Color::Orange,Color::Orange], ]); let face6 = Face::new([ [Color::White,Color::White,Color::White], [Color::White,Color::White,Color::White], [Color::White,Color::White,Color::White], ]); let _cube = Cube::new([face1, face2, face3, face4, face5, face6]); println!("Cube fmt: [{}].", _cube); // assert_eq!("x", _cube); } }
true
195b5e4e0121d3581534f20c2d2be49a506d6d1b
Rust
Pwootage/os.rv
/kernel/src/peripherals/memory_size.rs
UTF-8
397
2.703125
3
[]
no_license
use volatile_register::RO; pub struct MemorySize { p: &'static mut MemorySizeRegisters } #[repr(C)] struct MemorySizeRegisters { pub size: RO<usize> } impl MemorySize { pub fn new() -> MemorySize { MemorySize { p: unsafe { &mut *(0x7FFF_0000 as *mut MemorySizeRegisters) } } } pub fn max_size(&self) -> usize { self.p.size.read() } }
true
145b2fc10cd99ff1bd5b1f3132e847fd22dcc1f9
Rust
bartosz-lipinski/solana-program-library
/examples/rust/cross-program-invocation/src/processor.rs
UTF-8
1,614
2.75
3
[ "Apache-2.0" ]
permissive
//! Program instruction processor use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint::ProgramResult, program::invoke_signed, program_error::ProgramError, pubkey::Pubkey, system_instruction, }; /// Amount of bytes of account data to allocate pub const SIZE: usize = 42; /// Instruction processor pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> ProgramResult { // Create in iterator to safety reference accounts in the slice let account_info_iter = &mut accounts.iter(); // Account info for the program being invoked let system_program_info = next_account_info(account_info_iter)?; // Account info to allocate let allocated_info = next_account_info(account_info_iter)?; let expected_allocated_key = Pubkey::create_program_address(&[b"You pass butter", &[instruction_data[0]]], program_id)?; if *allocated_info.key != expected_allocated_key { // allocated key does not match the derived address return Err(ProgramError::InvalidArgument); } // Invoke the system program to allocate account data invoke_signed( &system_instruction::allocate(allocated_info.key, SIZE as u64), // Order doesn't matter and this slice could include all the accounts and be: // `&accounts` &[ system_program_info.clone(), // program being invoked also needs to be included allocated_info.clone(), ], &[&[b"You pass butter", &[instruction_data[0]]]], )?; Ok(()) }
true
a31bca6802210b96d355eef962e016ea4b36de3e
Rust
kosslab-kr/rust
/src/test/compile-fail/issue-28992-empty.rs
UTF-8
805
2.59375
3
[ "MIT", "Apache-2.0", "NCSA", "ISC", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "BSD-2-Clause", "Unlicense", "LicenseRef-scancode-other-permissive" ]
permissive
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Can't use constants as tuple struct patterns #![feature(associated_consts)] const C1: i32 = 0; struct S; impl S { const C2: i32 = 0; } fn main() { if let C1(..) = 0 {} //~ ERROR expected variant or struct, found constant `C1` if let S::C2(..) = 0 {} //~ ERROR `S::C2` does not name a tuple variant or a tuple struct }
true
c586445d10cb77226604b521c5e748fadf87ff0a
Rust
alexkursell/subotai
/src/node/tests.rs
UTF-8
9,577
2.546875
3
[ "MIT" ]
permissive
use {node, routing, time, hash, storage}; use std::collections::VecDeque; use std::str::FromStr; use std::thread; use std::time::Duration as StdDuration; use std::net; use node::receptions; pub const POLL_FREQUENCY_MS: u64 = 50; pub const TRIES: u8 = 5; #[test] fn node_ping() { let alpha = node::Node::new().unwrap(); let beta = node::Node::new().unwrap(); let beta_seed = beta.resources.local_info().address; // Bootstrapping alpha: assert!(alpha.bootstrap(&beta_seed).is_ok()); match alpha.state() { node::State::OffGrid => (), _ => panic!("Should be off grid with this few nodes"), } // Alpha pings beta. assert!(alpha.resources.ping(&beta.local_info().address).is_ok()); } #[test] fn reception_iterator_times_out_correctly() { let alpha = node::Node::new().unwrap(); let span = time::Duration::seconds(1); let maximum = time::Duration::seconds(3); let receptions = alpha.receptions().during(span); let before = time::SteadyTime::now(); // nothing is happening, so this should time out in around a second (not necessarily precise) assert_eq!(0, receptions.count()); let after = time::SteadyTime::now(); assert!(after - before < maximum); } #[test] fn bootstrapping_and_finding_on_simulated_network() { let mut nodes = simulated_network(30); // Head finds tail in a few steps. let head = nodes.pop_front().unwrap(); let tail = nodes.pop_back().unwrap(); assert_eq!(head.resources.locate(tail.id()).unwrap().id, tail.resources.local_info().id); } #[test] fn finding_on_simulated_unresponsive_network() { let mut nodes = simulated_network(35); nodes.drain(10..20); assert_eq!(nodes.len(), 25); // Head finds tail in a few steps. let head = nodes.pop_front().unwrap(); let tail = nodes.pop_back().unwrap(); assert_eq!(head.resources.locate(tail.id()).unwrap().id, tail.resources.local_info().id); } #[test] fn finding_a_nonexisting_node_in_a_simulated_network_times_out() { let mut nodes = simulated_network(30); // Head finds tail in a few steps. let head = nodes.pop_front().unwrap(); let random_hash = hash::SubotaiHash::random(); assert!(head.resources.locate(&random_hash).is_err()); } fn simulated_network(network_size: usize) -> VecDeque<node::Node> { let cfg: node::Configuration = Default::default(); assert!(network_size > cfg.k_factor, "You can't build a network with so few nodes!"); let nodes: VecDeque<node::Node> = (0..network_size).map(|_| { node::Node::new().unwrap() }).collect(); { let origin = nodes.front().unwrap(); for node in nodes.iter().skip(1) { node.bootstrap(&origin.resources.local_info().address).unwrap(); } for node in nodes.iter() { node.wait_for_state(node::State::OnGrid); } } nodes } #[test] fn updating_table_with_full_bucket_starts_the_conflict_resolution_mechanism() { let node = node::Node::new().unwrap(); let cfg = &node.resources.configuration; node.resources.table.fill_bucket(8, cfg.k_factor as u8); // Bucket completely full let mut id = node.id().clone(); id.flip_bit(8); id.raw[0] = 0xFF; let info = node_info_no_net(id); node.resources.update_table(info); assert_eq!(node.resources.conflicts.lock().unwrap().len(), 1); } #[test] fn generating_a_conflict_causes_a_ping_to_the_evicted_node() { let alpha = node::Node::new().unwrap(); let beta = node::Node::new().unwrap(); let cfg = &alpha.resources.configuration; alpha.resources.update_table(beta.resources.local_info()); let index = alpha.resources.table.bucket_for_node(beta.id()); // We fill the bucket corresponding to Beta until we are ready to cause a conflict. alpha.resources.table.fill_bucket(index, (cfg.k_factor -1) as u8); // We expect a ping to beta let pings = beta.receptions() .of_kind(receptions::KindFilter::Ping) .during(time::Duration::seconds(2)); // Adding a new node causes a conflict. let mut id = beta.id().clone(); id.raw[0] = 0xFF; let info = node_info_no_net(id); alpha.resources.update_table(info); assert_eq!(pings.count(), 1); } #[test] fn generating_too_many_conflicts_causes_the_node_to_enter_defensive_state() { let node = node::Node::new().unwrap(); let cfg = &node.resources.configuration; for index in 0..(cfg.k_factor + cfg.max_conflicts) { let mut id = node.id().clone(); id.flip_bit(140); // Arbitrary bucket id.raw[0] = index as u8; let info = node_info_no_net(id); node.resources.update_table(info); } let state = node.state(); match state { node::State::Defensive => (), _ => panic!(), } // Trying to add new conflictive nodes while in defensive state will fail. let mut id = node.id().clone(); id.flip_bit(140); // Arbitrary bucket id.raw[0] = 0xFF; let info = node_info_no_net(id.clone()); node.resources.update_table(info); assert!(node.resources.table.specific_node(&id).is_none()); // However, if they would fall in a different bucket, it's ok. id.flip_bit(155); let info = node_info_no_net(id.clone()); node.resources.update_table(info); assert!(node.resources.table.specific_node(&id).is_some()); } #[test] fn node_probing_in_simulated_network() { let cfg: node::Configuration = Default::default(); let mut nodes = simulated_network(40); // We manually collect the info tags of all nodes. let mut info_nodes: Vec<routing::NodeInfo> = nodes .iter() .map(|ref node| node.resources.local_info()) .collect(); let head = nodes.pop_front().unwrap(); let tail = nodes.pop_back().unwrap(); let probe_results = head.resources.probe(tail.id(), cfg.k_factor).unwrap(); // We sort our manual collection by distance to the tail node. info_nodes.sort_by(|ref info_a, ref info_b| (&info_a.id ^ tail.id()).cmp(&(&info_b.id ^ tail.id()))); info_nodes.truncate(cfg.k_factor); // This guarantees us the closest ids to the tail assert_eq!(info_nodes.len(), probe_results.len()); for (a, b) in probe_results.iter().zip(info_nodes.iter()) { assert_eq!(a.id, b.id); } } #[test] fn node_probing_in_simulated_unresponsive_network() { let cfg: node::Configuration = Default::default(); let mut nodes = simulated_network(40); // We manually collect the info tags of all nodes. let mut info_nodes: Vec<routing::NodeInfo> = nodes .iter() .map(|ref node| node.resources.local_info()) .collect(); nodes.drain(10..20); let head = nodes.pop_front().unwrap(); let tail = nodes.pop_back().unwrap(); let probe_results = head.resources.probe(tail.id(), cfg.k_factor).unwrap(); // We sort our manual collection by distance to the tail node. info_nodes.sort_by(|ref info_a, ref info_b| (&info_a.id ^ tail.id()).cmp(&(&info_b.id ^ tail.id()))); info_nodes.truncate(cfg.k_factor); // This guarantees us the closest ids to the tail assert_eq!(info_nodes.len(), probe_results.len()); for (a, b) in probe_results.iter().zip(info_nodes.iter()) { assert_eq!(a.id, b.id); } } #[test] fn bucket_pruning_removes_dead_nodes() { let mut nodes = simulated_network(40); let head = nodes.pop_front().unwrap(); // let's find a bucket with nodes let index = (0..160).rev().find(|i| head.resources.table.nodes_from_bucket(*i).len() > 0).unwrap(); let initial_nodes = head.resources.table.nodes_from_bucket(index).len(); head.resources.prune_bucket(index).unwrap(); assert_eq!(initial_nodes, head.resources.table.nodes_from_bucket(index).len()); // Now when we kill the nodes, the pruning will work. nodes.clear(); head.resources.prune_bucket(index).unwrap(); assert_eq!(0, head.resources.table.nodes_from_bucket(index).len()); } #[test] fn store_retrieve_in_simulated_network() { let mut nodes = simulated_network(40); let key = hash::SubotaiHash::random(); let entry = storage::StorageEntry::Value(hash::SubotaiHash::random()); let head = nodes.pop_front().unwrap(); let tail = nodes.pop_back().unwrap(); head.store(key.clone(), entry.clone()).unwrap(); let retrieved_entries = tail.retrieve(&key).unwrap(); assert_eq!(entry, retrieved_entries[0]); let key = hash::SubotaiHash::random(); let blob: Vec<u8> = vec![0x00, 0x01, 0x02]; let entry = storage::StorageEntry::Blob(blob.clone()); head.store(key.clone(), entry.clone()).unwrap(); let retrieved_entries = tail.retrieve(&key).unwrap(); assert_eq!(entry, retrieved_entries[0]); // Now for mass storage let arbitrary_expiration = time::now() + time::Duration::minutes(30); let collection: Vec<_> = (0..10) .map(|_| (storage::StorageEntry::Value(hash::SubotaiHash::random()), arbitrary_expiration)).collect(); let collection_key = hash::SubotaiHash::random(); head.resources.mass_store(collection_key.clone(), collection.clone()).unwrap(); // We must sleep here to prevent asking a node for the entries as it's halfway through storing them. thread::sleep(StdDuration::new(5,0)); let retrieved_collection = tail.retrieve(&collection_key).unwrap(); let collection_entries: Vec<_> = collection.into_iter().map(|(entry, _)| entry).collect(); assert_eq!(collection_entries.len(), retrieved_collection.len()); assert_eq!(collection_entries, retrieved_collection); } fn node_info_no_net(id : hash::SubotaiHash) -> routing::NodeInfo { routing::NodeInfo { id : id, address : net::SocketAddr::from_str("0.0.0.0:0").unwrap(), } }
true
6f9542160fe3c64cd416089ed666f60f02f2d33e
Rust
xcaptain/rust-algorithms
/algorithms/src/misc/shortest_seq.rs
UTF-8
1,103
3.6875
4
[]
no_license
use std::cmp::min; /// 使用尺取法,计算最短连续子数组长度大于某个值 pub fn shortest_seq(arr: Vec<usize>, target: usize) -> (usize, usize, usize) { let mut sum = 0; let mut start = 0; let mut end = 0; let len = arr.len(); let mut ans = len + 1; loop { while sum < target && end < len { sum += arr[end]; end += 1; } if sum < target { break; } ans = min(ans, end - start); sum -= arr[start]; start += 1; } if ans > len { return (0, 0, 0); } (ans, start - 1, end - 1) } #[cfg(test)] mod tests { use super::*; #[test] fn test_1() { assert_eq!((3, 2, 4), shortest_seq(vec![1, 2, 3, 5, 6], 12)); } #[test] fn test_2() { assert_eq!((2, 3, 4), shortest_seq(vec![1, 2, 3, 5, 6], 11)); } #[test] fn test_3() { assert_eq!((2, 3, 4), shortest_seq(vec![1, 2, 3, 5, 6], 10)); } #[test] fn test_4() { assert_eq!((0, 0, 0), shortest_seq(vec![1, 2, 3, 5, 6], 20)); } }
true
56f40e3007637c45febed4717ecee7fab4fe78af
Rust
vinc/geodate
/src/moon_phase.rs
UTF-8
11,351
2.546875
3
[ "MIT" ]
permissive
use math::*; use julian::*; use delta_time::*; use core::ops::Rem; #[cfg(not(feature = "std"))] use num_traits::Float; #[repr(usize)] #[derive(Clone, Copy)] enum MoonPhase { NewMoon, FirstQuarterMoon, FullMoon, LastQuarterMoon } // From "Astronomical Algorithms" // By Jean Meeus fn get_time_of(phase: MoonPhase, lunation_number: f64) -> i64 { /* // TODO: use `lunation_number: i64` let k = match phase { MoonPhase::NewMoon => (lunation_number as f64) + 0.00; MoonPhase::FirstQuarterMoon => (lunation_number as f64) + 0.25; MoonPhase::FullMoon => (lunation_number as f64) + 0.50; MoonPhase::LastQuarterMoon => (lunation_number as f64) + 0.75; }; */ let k = lunation_number; let t = k / 1236.85; let e = 1.0 - 0.002_516 * t - 0.000_007_4 * t.powi(2); // Sun's mean anomaly at time JDE let s = 2.5534 + 29.105_356_7 * k - 0.000_001_4 * t.powi(2) - 0.000_000_11 * t.powi(3); // Moon's mean anomaly let m = 201.5643 + 385.816_935_28 * k + 0.010_758_2 * t.powi(2) + 0.000_012_38 * t.powi(3) - 0.000_000_058 * t.powi(4); // Moon's argument of latitude let f = 160.7108 + 390.670_502_84 * k - 0.001_611_8 * t.powi(2) - 0.000_002_27 * t.powi(3) + 0.000_000_011 * t.powi(4); // Longitude of the ascending node of the lunar orbit let o = 124.7746 - 1.563_755_88 * k + 0.002_0672 * t.powi(2) + 0.000_002_15 * t.powi(3); let e = (e.rem(360.0) + 360.0).rem(360.0); let s = (s.rem(360.0) + 360.0).rem(360.0); let m = (m.rem(360.0) + 360.0).rem(360.0); let f = (f.rem(360.0) + 360.0).rem(360.0); let o = (o.rem(360.0) + 360.0).rem(360.0); let jde = 2_451_550.097_660 + 29.530_588_861 * k + 0.000_154_370 * t.powi(2) - 0.000_000_150 * t.powi(3) + 0.000_000_000_730 * t.powi(4); // Correction to be added to JDE // [New Moon, First Quarter, Full Moon, Last Quarter] let num_cors = vec![ [-0.40720, -0.62801, -0.40614, -0.62801], [ 0.17241, 0.17172, 0.17302, 0.17172], [ 0.01608, -0.01183, 0.01614, -0.01183], [ 0.01039, 0.00862, 0.01043, 0.00862], [ 0.00739, 0.00804, 0.00734, 0.00804], [-0.00514, 0.00454, -0.00515, 0.00454], [ 0.00208, 0.00204, 0.00209, 0.00204], [-0.00111, -0.00180, -0.00111, -0.00180], [-0.00057, -0.00070, -0.00057, -0.00070], [ 0.00056, -0.00040, 0.00056, -0.00040], [-0.00042, -0.00034, -0.00042, -0.00034], [ 0.00042, 0.00032, 0.00042, 0.00032], [ 0.00038, 0.00032, 0.00038, 0.00032], [-0.00024, -0.00028, -0.00024, -0.00028], [-0.00017, 0.00027, -0.00017, 0.00027], [-0.00007, -0.00017, -0.00007, -0.00017], [ 0.00004, -0.00005, 0.00004, -0.00005], [ 0.00004, 0.00004, 0.00004, 0.00004], [ 0.00003, -0.00004, 0.00003, -0.00004], [ 0.00003, 0.00004, 0.00003, 0.00004], [-0.00003, 0.00003, -0.00003, 0.00003], [ 0.00003, 0.00003, 0.00003, 0.00003], [-0.00002, 0.00002, -0.00002, 0.00002], [-0.00002, 0.00002, -0.00002, 0.00002], [ 0.00002, -0.00002, 0.00002, -0.00002] ]; // Multiply each previous terms by E to a given power // [new moon, first quarter, full moon, last quarter] let pow_cors = vec![ [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 0, 1], [0, 0, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1], [2, 2, 2, 2], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 2, 1, 2], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]; // Sum the following terms multiplied a number of times // given in the next table, and multiply the sinus of the // result by the previously obtained number. let terms = [s, m, f, o]; // [new and full moon, first and last quarter] let mul_cors = vec![ [[ 0.0, 1.0, 0.0, 0.0], [ 0.0, 1.0, 0.0, 0.0]], [[ 1.0, 0.0, 0.0, 0.0], [ 1.0, 0.0, 0.0, 0.0]], [[ 0.0, 2.0, 0.0, 0.0], [ 1.0, 1.0, 0.0, 0.0]], [[ 0.0, 0.0, 2.0, 0.0], [ 0.0, 2.0, 0.0, 0.0]], [[-1.0, 1.0, 0.0, 0.0], [ 0.0, 0.0, 2.0, 0.0]], [[ 1.0, 1.0, 0.0, 0.0], [-1.0, 1.0, 0.0, 0.0]], [[ 2.0, 0.0, 0.0, 0.0], [ 2.0, 0.0, 0.0, 0.0]], [[ 0.0, 1.0, -2.0, 0.0], [ 0.0, 1.0, -2.0, 0.0]], [[ 0.0, 1.0, 2.0, 0.0], [ 0.0, 1.0, 2.0, 0.0]], [[ 1.0, 2.0, 0.0, 0.0], [ 0.0, 3.0, 0.0, 0.0]], [[ 0.0, 3.0, 0.0, 0.0], [-1.0, 2.0, 0.0, 0.0]], [[ 1.0, 0.0, 2.0, 0.0], [ 1.0, 0.0, 2.0, 0.0]], [[ 1.0, 0.0, -2.0, 0.0], [ 1.0, 0.0, -2.0, 0.0]], [[-1.0, 2.0, 0.0, 0.0], [ 2.0, 1.0, 0.0, 0.0]], [[ 0.0, 0.0, 0.0, 1.0], [ 1.0, 2.0, 0.0, 0.0]], [[ 2.0, 1.0, 0.0, 0.0], [ 0.0, 0.0, 0.0, 1.0]], [[ 0.0, 2.0, -2.0, 0.0], [-1.0, 1.0, -2.0, 0.0]], [[ 3.0, 0.0, 0.0, 0.0], [ 0.0, 2.0, 2.0, 0.0]], [[ 1.0, 1.0, -2.0, 0.0], [ 1.0, 1.0, 2.0, 0.0]], [[ 0.0, 2.0, 2.0, 0.0], [-2.0, 1.0, 0.0, 0.0]], [[ 1.0, 1.0, 2.0, 0.0], [ 1.0, 1.0, -2.0, 0.0]], [[-1.0, 1.0, 2.0, 0.0], [ 3.0, 0.0, 0.0, 0.0]], [[-1.0, 1.0, -2.0, 0.0], [ 0.0, 2.0, -2.0, 0.0]], [[ 1.0, 3.0, 0.0, 0.0], [-1.0, 1.0, 2.0, 0.0]], [[ 0.0, 4.0, 0.0, 0.0], [ 1.0, 3.0, 0.0, 0.0]] ]; let j = phase as usize; let cor = (0..25).fold(0.0, |acc, i| { let sin_cor = (0..4).fold(0.0, |sa, si| { sa + mul_cors[i][j % 2][si] * terms[si] }); acc + num_cors[i][j] * e.powi(pow_cors[i][j]) * sin_deg(sin_cor) }); // Additional corrections for quarters let w = 0.00306 - 0.00038 * e * cos_deg(s) + 0.00026 * cos_deg(m) - 0.00002 * cos_deg(m - s) + 0.00002 * cos_deg(m + s) + 0.00002 * cos_deg(2.0 * f); let cor = match phase { MoonPhase::FirstQuarterMoon => cor + w, MoonPhase::LastQuarterMoon => cor - w, _ => cor }; // Additional corrections for all phases let add = 0.0 + 0.000_325 * sin_deg(299.77 + 0.107_408 * k - 0.009_173 * t.powi(2)) + 0.000_165 * sin_deg(251.88 + 0.016_321 * k) + 0.000_164 * sin_deg(251.83 + 26.651_886 * k) + 0.000_126 * sin_deg(349.42 + 36.412_478 * k) + 0.000_110 * sin_deg( 84.66 + 18.206_239 * k) + 0.000_062 * sin_deg(141.74 + 53.303_771 * k) + 0.000_060 * sin_deg(207.14 + 2.453_732 * k) + 0.000_056 * sin_deg(154.84 + 7.306_860 * k) + 0.000_047 * sin_deg( 34.52 + 27.261_239 * k) + 0.000_042 * sin_deg(207.19 + 0.121_824 * k) + 0.000_040 * sin_deg(291.34 + 1.844_379 * k) + 0.000_037 * sin_deg(161.72 + 24.198_154 * k) + 0.000_035 * sin_deg(239.56 + 25.513_099 * k) + 0.000_023 * sin_deg(331.55 + 3.592_518 * k); let jde = jde + cor + add; terrestrial_to_universal_time(julian_to_unix(jde)) } pub fn get_new_moon(lunation_number: f64) -> i64 { get_time_of(MoonPhase::NewMoon, lunation_number) } pub fn get_first_quarter_moon(lunation_number: f64) -> i64 { get_time_of(MoonPhase::FirstQuarterMoon, lunation_number) } pub fn get_full_moon(lunation_number: f64) -> i64 { get_time_of(MoonPhase::FullMoon, lunation_number) } pub fn get_last_quarter_moon(lunation_number: f64) -> i64 { get_time_of(MoonPhase::LastQuarterMoon, lunation_number) } /* // TODO: get_lunation_number(timestamp: i64, numbering: LunationNumbering) // TODO: get_meeus_lunation_number(timestamp: i64) enum LunationNumbering { Islamic, Thai, Brown, Meeus } */ /// Computes the Lunation Number since the first new moon of 2000 pub fn get_lunation_number(timestamp: i64) -> f64 { ((unix_to_year(timestamp) - 2000.0) * 12.3685).floor() // TODO: `as i64` } pub fn get_next_new_moon(timestamp: i64) -> i64 { let new_moon = get_new_moon(get_lunation_number(timestamp)); if new_moon > timestamp { new_moon } else { get_new_moon(get_lunation_number(timestamp) + 1.0) } } #[cfg(test)] mod tests { use super::*; use utils::*; #[test] fn get_lunation_number_test() { // Example 49.a from "Astronomical Algoritms" // New Moon: 1977-02-18 03:37:42 TD let t = terrestrial_to_universal_time(parse_time("1977-02-18T03:37:42.00+00:00")); assert_eq!(-283.0, get_lunation_number(t)); // Later in the day let t = parse_time("1977-02-18T12:00:00.00+00:00"); assert_eq!(-283.0, get_lunation_number(t)); // Later in the month let t = parse_time("1977-02-28T12:00:00.00+00:00"); assert_eq!(-283.0, get_lunation_number(t)); // Earlier in the day let t = parse_time("1977-02-18T01:00:00.00+00:00"); assert_eq!(-283.0, get_lunation_number(t)); // A few days before let t = parse_time("1977-02-14T12:00:00.00+00:00"); assert_eq!(-283.0, get_lunation_number(t)); // FIXME: should be -284 // A week before let t = parse_time("1977-02-11T12:00:00.00+00:00"); assert_eq!(-284.0, get_lunation_number(t)); // Meeus Lunation 0 let t = parse_time("2000-01-06T18:14:00.00+00:00"); assert_eq!(0.0, get_lunation_number(t)); // Brown Lunation 1 let t = parse_time("1923-01-17T02:41:00.00+00:00"); assert_eq!(-952.0, get_lunation_number(t)); // Islamic Lunation 1 let t = parse_time("0622-07-16T00:00:00.00+00:00"); assert_eq!(-17037.0, get_lunation_number(t)); // Thai Lunation 0 let t = parse_time("0638-03-22T00:00:00.00+00:00"); assert_eq!(-16843.0, get_lunation_number(t)); // FIXME: should be -16842 } #[test] fn get_new_moon_test() { // Example 49.a from "Astronomical Algoritms" // New Moon: 1977-02-18 03:37:42 TD let lunation_number = -283.0; let t = terrestrial_to_universal_time(parse_time("1977-02-18T03:37:42.00+00:00")); assert_eq!(t, get_new_moon(lunation_number)); // First new moon of 1970 let t = parse_time("1970-01-07T20:35:27.00+00:00"); assert_eq!(t, get_new_moon(get_lunation_number(0) + 1.0)); } #[test] fn get_last_quarter_moon_test() { // Example 49.b from "Astronomical Algoritms" // Last Quarter Moon: 2044-01-21 23:48:17 TD let lunation_number = 544.75; let t = terrestrial_to_universal_time(parse_time("2044-01-21T23:48:17+00:00")); assert_eq!(t, get_last_quarter_moon(lunation_number)); } }
true
cf3a09868e3f3cb30f6234511e4fb445993b4aef
Rust
asciiu/blackjack
/src/blackjack.rs
UTF-8
4,947
3.515625
4
[]
no_license
pub mod shoe; use shoe::Shoe; use shoe::Card; use std::io; enum PlayerInput { Double, Hit, Stand, Split, Unknown, } struct Player { cards: Vec<Card> } impl Player { fn new() -> Player { Player{ cards: Vec::new() } } fn score(&mut self) -> i32 { let mut total = 0; for c in &self.cards { let v = match c.text() { 'K' | 'Q' | 'J' | 'T' => 10, 'A' => 0, _ => c.text().to_string().parse::<i32>().unwrap() }; total += v; } // add up all aces for c in &self.cards { if c.text() == 'A' { total += 11; if total > 31 { total -= 20; } else if total > 21 { total -= 10; } } } total } fn print_hand(&mut self, label: &str) { print!("{}: ", label); for c in self.cards.iter() { print!("{} ", c); } print!("[{}]\n", self.score()); } } fn read_input(can_double: bool) -> PlayerInput { if can_double { println!("\n(h)it (s)tand (d)ouble: "); } else { println!("\n(h)it (s)tand: "); } let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("Failed to read line"); println!(""); // trim trailing new line input = String::from(input.trim()); match (can_double, input.trim()) { (true, "d") => PlayerInput::Double, (_, "h") => PlayerInput::Hit, (_, "s") => PlayerInput::Stand, (_, "p") => PlayerInput::Split, _ => PlayerInput::Unknown, } } pub struct Blackjack { shoe: Shoe, player: Player, dealer: Player, } impl Blackjack { pub fn new() -> Blackjack { Blackjack{ shoe: Shoe::new(), player: Player::new(), dealer: Player::new() } } fn deal_card(&mut self) -> Card { match self.shoe.pop_card() { Some(card) => card, None => { self.shoe = Shoe::new(); self.shoe.pop_card().unwrap() } } } pub fn play_round(&mut self, balance: i32, mut wager: i32) -> i32 { let dealer_card: Card = self.deal_card(); self.dealer.cards.push(dealer_card); while self.player.cards.len() < 2 { let card: Card = self.deal_card(); self.player.cards.push(card); } let mut player_score = self.player.score(); let mut dealer_score = self.dealer.score(); let mut stand = false; self.player.print_hand("Player"); self.dealer.print_hand("Dealer"); while player_score < 21 && !stand { let can_double = self.player.cards.len() == 2 && (balance - wager) >= wager; let input = read_input(can_double); match input { PlayerInput::Double => { wager += wager; let player_card: Card = self.deal_card(); self.player.cards.push(player_card); self.player.print_hand("Player"); self.dealer.print_hand("Dealer"); player_score = self.player.score(); stand = true; } PlayerInput::Hit => { let player_card: Card = self.deal_card(); self.player.cards.push(player_card); self.player.print_hand("Player"); self.dealer.print_hand("Dealer"); player_score = self.player.score(); } PlayerInput::Stand => { stand = true; self.player.print_hand("Player"); } _ => () } } while dealer_score < 17 { let dealer_card: Card = self.deal_card(); self.dealer.cards.push(dealer_card); dealer_score = self.dealer.score(); } self.dealer.print_hand("Dealer"); self.player.cards.clear(); self.dealer.cards.clear(); if player_score > dealer_score && player_score <= 21 { println!("Player (win!)\n"); wager } else if player_score < dealer_score && dealer_score <= 21 { println!("Player (lose)\n"); -wager } else if player_score > 21 && dealer_score <= 21 { println!("Player (lose)\n"); -wager } else if dealer_score > 21 && player_score <= 21 { println!("Player (win!)\n"); wager } else if dealer_score == player_score { println!("push\n"); 0 } else { println!("push\n"); 0 } } }
true
34a07abc0a1488168980127397c1166b00e82c15
Rust
MingweiSamuel/Riven
/riven/src/consts/team.rs
UTF-8
669
2.59375
3
[ "MIT" ]
permissive
use num_enum::{IntoPrimitive, TryFromPrimitive}; use serde_repr::{Deserialize_repr, Serialize_repr}; /// League of Legends team. #[derive( Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize_repr, Deserialize_repr, IntoPrimitive, TryFromPrimitive, )] #[repr(u16)] pub enum Team { /// Team ID zero for 2v2v2v2 Arena `CHERRY` game mode. (TODO: SUBJECT TO CHANGE?) ZERO = 0, /// Blue team (bottom left on Summoner's Rift). BLUE = 100, /// Red team (top right on Summoner's Rift). RED = 200, /// "killerTeamId" when Baron Nashor spawns and kills Rift Herald. OTHER = 300, }
true
573d1089fa944ab3954efe3278b6139c58f71755
Rust
kyleburton/sandbox
/examples/rust/bin-with-lib/src/utils.rs
UTF-8
182
2.546875
3
[]
no_license
use time; pub fn say_hello() { println!("Hello, world at {}!", time::now().asctime()); } pub fn say_goodbye() { println!("Goodbye, world at {}!", time::now().asctime()); }
true
fc6c866276dbb0e0440feecb43f4d6f20969ed4e
Rust
ItiharaYuuko/file_crypto_base64
/src/main.rs
UTF-8
8,338
3
3
[]
no_license
use base64::{decode, encode}; use std::convert::AsRef; use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use std::path::Path; trait SplitAt { fn get_split_at(self, sep: &str, index: usize) -> String; } impl SplitAt for String { fn get_split_at(self, sep: &str, index: usize) -> String { format!("{}", self.split(sep).collect::<Vec<&str>>()[index]) } } impl SplitAt for &str { fn get_split_at(self, sep: &str, index: usize) -> String { format!("{}", self.split(sep).collect::<Vec<&str>>()[index]) } } fn entry_self_check(ent: &fs::DirEntry) -> bool { let flg_pa: bool; let app_self: Vec<String> = env::args().collect(); if ent .path() .file_name() .unwrap() .to_str() .unwrap() .contains(&app_self[0]) { flg_pa = true; } else { flg_pa = false; } flg_pa } fn entry_contians(ent: &fs::DirEntry, context: &str) -> bool { let flg_pa: bool; if ent .path() .file_name() .unwrap() .to_str() .unwrap() .contains(context) { flg_pa = true; } else { flg_pa = false; } flg_pa } fn entry_to_str(ent: &fs::DirEntry) -> String { let ent_str = String::from(ent.path().file_name().unwrap().to_str().unwrap()); ent_str } fn chunk_encode<T: Clone + AsRef<[u8]>>(input: T) -> String { encode(&input) } fn chunk_decode<T: Clone + AsRef<[u8]>>(input: T) -> Vec<u8> { decode(&input).unwrap() } fn genfile_data(f_name: &str) -> Vec<u8> { let insert_file = File::open(f_name).unwrap(); let mut copyx = insert_file.try_clone().unwrap(); let mut vexc: Vec<u8> = Vec::new(); copyx.read_to_end(&mut vexc).unwrap(); vexc } fn creat_crypto_file(f_name: &str) { let data_vec = genfile_data(&f_name); let crypto_context = chunk_encode(&data_vec); let out_file_name = file_name_reorganization(f_name, "Cryptod"); fs::write(out_file_name.as_str(), &crypto_context).unwrap(); } fn creat_decrypto_file(f_name: &str) { let data_vec = genfile_data(f_name); let crypto_context = chunk_decode(&data_vec); let out_file_name = file_name_reorganization(f_name, "Deryptod"); fs::write(out_file_name.as_str(), &crypto_context).unwrap(); } fn file_name_reorganization(f_name: &str, bet_flg: &str) -> String { let tmp_str: String; if f_name.contains("Cryptod") { tmp_str = format!("{}", f_name.get_split_at("%^%", 1)); } else { tmp_str = format!("{}%^%{}", bet_flg, f_name); } tmp_str } fn file_name_crypto(f_name: &String) -> String { let cry_name = chunk_encode(f_name); fs::rename(f_name, &cry_name).unwrap(); cry_name } fn file_name_decrypto(f_name: &String) -> String { let dec_name = String::from_utf8(chunk_decode(f_name)).unwrap(); fs::rename(f_name, &dec_name).unwrap(); dec_name } fn purge_mata_file(purge_flag: bool) { let ctr_pat = Path::new("."); for entry in ctr_pat.read_dir().unwrap() { if let Ok(entry) = entry { let mata_flag: bool; if purge_flag { mata_flag = !entry_contians(&entry, "%^%"); } else { mata_flag = entry_contians(&entry, "%^%"); } if mata_flag && !entry_self_check(&entry) { fs::remove_file(entry_to_str(&entry)).unwrap(); println!( "[-]{} was removed.", entry_to_str(&entry) ); } } } } fn major_progress() { let pleaseholder_information = " Wrong console argument after application.\n Please choise:\n user$ file_crypto_base64 -c [file names separated by blank] #Crypto selected files.\n user$ file_crypto_base64 -d [file names separated by blank] #Decrypto selected files.\n user$ file_crypto_base64 -lc #Crypto current folders all files.\n user$ file_crypto_base64 -ld #Decrypto current folders all files.\n user$ file_crypto_base64 -pm #Remove all meta files.\n user$ file_crypto_base64 -pc #Remove all cryptod files.\n user$ file_crypto_base64 -cn #Crypto current folders all files name.\n user$ file_crypto_base64 -dn #Decrypto current folders all files name.\n Note: square brackets was files list it doesnt contain thire self.\n"; let arg_flg_loc: usize = 1; let mut file_index: u32 = 1; let mut list_file_count: u32 = 1; let operation_flg = env::args().collect::<Vec<String>>(); if operation_flg.len() > 1 { let current_path = Path::new("."); if operation_flg[arg_flg_loc].as_str() == "-c" { for file_name in &operation_flg[2..] { creat_crypto_file(&file_name); println!( "[+]{} files cryptod, current file is {}", file_index, file_name ); file_index += 1 } } else if operation_flg[arg_flg_loc].as_str() == "-d" { for file_name in &operation_flg[2..] { creat_decrypto_file(&file_name); println!( "[+]{} files decryptod, current file is {}", file_index, file_name ); file_index += 1; } } else if operation_flg[arg_flg_loc].as_str() == "-lc" { for entry in current_path.read_dir().unwrap() { if let Ok(entry) = entry { if !entry_self_check(&entry) && !entry_contians(&entry, "%^%") { let out_name = file_name_reorganization( entry_to_str(&entry).as_str(), "Cryptod", ); creat_crypto_file(entry_to_str(&entry).as_str()); println!( "[+]{} files cryptod, current file is {}", &list_file_count, &out_name ); } } list_file_count += 1; } } else if operation_flg[arg_flg_loc].as_str() == "-ld" { for entry in current_path.read_dir().unwrap() { if let Ok(entry) = entry { if !entry_self_check(&entry) { let out_name = file_name_reorganization( entry_to_str(&entry).as_str(), "Deryptod", ); creat_decrypto_file(entry_to_str(&entry).as_str()); println!( "[+]{} files decryptod, current file is {}", &list_file_count, &out_name ); } } list_file_count += 1; } } else if operation_flg[arg_flg_loc].as_str() == "-cn" { for entry in current_path.read_dir().unwrap() { if let Ok(entry) = entry { if !entry_self_check(&entry) { let cryptoed_name = file_name_crypto(&entry_to_str(&entry)); println!( "[#]{} crytpod to {}", &entry_to_str(&entry), &cryptoed_name ); } } } } else if operation_flg[arg_flg_loc].as_str() == "-dn" { for entry in current_path.read_dir().unwrap() { if let Ok(entry) = entry { if !entry_self_check(&entry) { let mata_name = file_name_decrypto(&entry_to_str(&entry)); println!( "[#]{} decryptod to {}", &entry_to_str(&entry), &mata_name ); } } } } else if operation_flg[1].as_str() == "-pm" { purge_mata_file(true); } else if operation_flg[1].as_str() == "-pc" { purge_mata_file(false); } else { panic!("{}", &pleaseholder_information); } } else { panic!("{}", &pleaseholder_information); } } fn main() { major_progress(); }
true
8cb8b4a314a1865481975599133155b90ad56301
Rust
lpil/decksterity
/src/engine/dsp_node/player_node.rs
UTF-8
2,002
2.84375
3
[]
no_license
use std::mem; use super::super::{dsp, media}; use dsp::{Frame, Node}; use super::super::super::engine; #[derive(Debug)] pub struct PlayerNode { is_playing: bool, offset: f64, pitch: f64, buffer: Vec<engine::Frame>, } impl PlayerNode { pub fn new() -> Self { Self { is_playing: false, offset: 0.0, pitch: 1.0, buffer: vec![], } } pub fn toggle_play_pause(&mut self) -> bool { let Self { ref mut is_playing, .. } = *self; let new_value = !*is_playing; *is_playing = new_value; new_value } pub fn adjust_pitch(&mut self, delta: f64) -> f64 { let Self { ref mut pitch, .. } = *self; let new_pitch = *pitch + delta; *pitch = new_pitch; new_pitch } pub fn set_media(&mut self, media: media::Media) { let Self { ref mut offset, ref mut buffer, .. } = *self; mem::replace(buffer, media); *offset = 0.0; } // pub fn set_pitch(&mut self, new_pitch: f64) -> f64 { // let Self { ref mut pitch, .. } = *self; // *pitch = new_pitch; // new_pitch // } } impl Node<engine::Frame> for PlayerNode { fn audio_requested(&mut self, out_buffer: &mut [engine::Frame], _sample_hz: f64) { if !self.is_playing { return; // When not playing the Player does nothing. } let Self { ref mut offset, pitch, ref buffer, .. } = *self; dsp::slice::map_in_place(out_buffer, |_| { let frame = buffer.get(*offset as usize).unwrap_or_else(|| { *offset = 0.0; &buffer[0] }); // Why is the input audio SUPER loud? let quiet_frame = frame.map(|s| s * 0.00003); *offset += pitch; quiet_frame }) } }
true
5d0e5f4ae3cf4e90e8b4758de7c501b0488276e4
Rust
benruijl/reform
/src/poly/exponent.rs
UTF-8
629
3.015625
3
[ "MIT" ]
permissive
use std::ops::Sub; use num_traits::{CheckedAdd, One, Zero}; use num_traits::cast::{FromPrimitive, AsPrimitive}; use std::hash::Hash; use std::fmt::{Debug, Display}; /// Trait for exponents in polynomials. pub trait Exponent : Hash + Zero + Debug + Display + One + FromPrimitive + AsPrimitive<u32> + CheckedAdd + Sub<Output = Self> + Ord + Clone { } impl< T: Hash + Zero + Debug + Display + One + FromPrimitive + AsPrimitive<u32> + CheckedAdd + Sub<Output = Self> + Ord + Clone, > Exponent for T { }
true
3f10da46a3a36431b077292807da93bc8fd3243e
Rust
LDA111222/GraphScope
/interactive_engine/src/executor/Pegasus/src/common/mod.rs
UTF-8
13,194
3.046875
3
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-elastic-license-2018", "LicenseRef-scancode-other-permissive" ]
permissive
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. use std::iter::Iterator; use std::fmt; use std::sync::Arc; use std::any::Any; use std::ops::{Deref, DerefMut}; use std::cell::RefCell; use std::io; pub trait Paging: Send { type Item; fn next_page(&mut self) -> Option<Vec<Self::Item>>; } impl<D, T: Iterator<Item=Vec<D>> + Send> Paging for T { type Item = D; fn next_page(&mut self) -> Option<Vec<Self::Item>> { self.next() } } #[derive(Debug, Default)] pub struct OnePage<D> { inner: Option<Vec<D>> } impl<D: Send> OnePage<D> { #[inline] pub fn take(&mut self) -> Option<Vec<D>> { self.inner.take() } } impl<D> ::std::convert::From<Vec<D>> for OnePage<D> { #[inline] fn from(src: Vec<D>) -> Self { OnePage { inner: Some(src) } } } impl<D: Send> Paging for OnePage<D> { type Item = D; #[inline] fn next_page(&mut self) -> Option<Vec<Self::Item>> { self.take() } } /// Modify the origin vector, retain the elements whose `preicate` is true, /// return a new vector consist of elements whose `preicate` is false; /// This function is O(n); /// # Note: /// This function will change the order of elements in the origin vec; /// # Examples /// ``` /// use pegasus::common::retain; /// // create a new numeric list; /// let mut origin = (0..64).collect::<Vec<_>>(); /// // remove elements which is less than 32; /// let removed = retain(&mut origin, |item| *item > 31); /// /// assert_eq!(32, origin.len()); /// assert_eq!(32, removed.len()); /// assert!(origin.iter().all(|item| *item > 31)); /// assert!(removed.iter().all(|item| *item <= 31)); /// ``` #[inline] pub fn retain<T, F: Fn(&T) -> bool>(origin: &mut Vec<T>, predicate: F) -> Vec<T> { let mut target = Vec::new(); let mut index = origin.len(); while index > 0 { if !predicate(&origin[index - 1]) { let item = if index == origin.len() { origin.remove(index - 1) } else { origin.swap_remove(index - 1) }; target.push(item); } index -= 1; } target } #[derive(Copy, Clone, Hash, Eq, PartialEq)] pub struct Port { pub index: usize, pub port: usize, } impl Port { #[inline(always)] pub fn first(index: usize) -> Self { Port {index, port: 0} } #[inline(always)] pub fn second(index: usize) -> Self { Port {index, port: 1} } #[inline(always)] pub fn new(index: usize, port: usize) -> Self { Port {index, port} } } impl fmt::Debug for Port { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}.{})", self.index, self.port) } } #[derive(Copy,Clone)] struct Slice(pub *mut u8, pub usize); impl Slice { pub fn as_slice(&self) -> &[u8] { unsafe { ::std::slice::from_raw_parts(self.0, self.1) } } pub fn as_mut_slice(&mut self) -> &mut [u8] { unsafe { ::std::slice::from_raw_parts_mut(self.0, self.1) } } } pub struct Bytes { slice: Slice, backend: Arc<Box<dyn Any>> } impl Bytes { pub fn from<B>(bytes: B) -> Self where B: DerefMut<Target=[u8]> + 'static { let mut boxed = Box::new(bytes) as Box<dyn Any>; let ptr = boxed.downcast_mut::<B>().unwrap().as_mut_ptr(); let len = boxed.downcast_ref::<B>().unwrap().len(); let backend = Arc::new(boxed); let slice = Slice(ptr, len); Bytes { slice, backend } } pub fn extract_to(&mut self, index: usize) -> Bytes { assert!(index <= self.slice.1); let result = Bytes { slice: Slice(self.slice.0, index), backend: self.backend.clone(), }; unsafe { self.slice.0 = self.slice.0.offset(index as isize); } self.slice.1 -= index; result } pub fn try_recover<B>(self) -> Result<B, Bytes> where B: DerefMut<Target=[u8]>+'static { match Arc::try_unwrap(self.backend) { Ok(bytes) => Ok(*bytes.downcast::<B>().unwrap()), Err(arc) => Err(Bytes { slice: self.slice, backend: arc, }), } } pub fn try_regenerate<B>(&mut self) -> bool where B: DerefMut<Target=[u8]>+'static { if let Some(boxed) = Arc::get_mut(&mut self.backend) { let downcast = boxed.downcast_mut::<B>().expect("Downcast failed"); self.slice = Slice(downcast.as_mut_ptr(), downcast.len()); true } else { false } } } impl Deref for Bytes { type Target = [u8]; fn deref(&self) -> &[u8] { self.slice.as_slice() } } impl DerefMut for Bytes { fn deref_mut(&mut self) -> &mut [u8] { self.slice.as_mut_slice() } } impl AsRef<[u8]> for Bytes { #[inline] fn as_ref(&self) -> &[u8] { self.slice.as_slice() } } /// It is carefully managed to make sure that no overlap of byte range between threads; unsafe impl Send for Bytes { } /// All Bytes are only be transformed between threads through mpmc channel, no sync; // unsafe impl Sync for Bytes { } /// A large binary allocation for writing and sharing. /// /// A bytes slab wraps a `Bytes` and maintains a valid (written) length, and supports writing after /// this valid length, and extracting `Bytes` up to this valid length. Extracted bytes are enqueued /// and checked for uniqueness in order to recycle them (once all shared references are dropped). pub struct BytesSlab { buffer: Bytes, // current working buffer. in_progress: Vec<Option<Bytes>>, // buffers shared with workers. stash: Vec<Bytes>, // reclaimed and resuable buffers. shift: usize, // current buffer allocation size. valid: usize, // buffer[..valid] are valid bytes. } impl BytesSlab { /// Allocates a new `BytesSlab` with an initial size determined by a shift. pub fn new(shift: usize) -> Self { BytesSlab { buffer: Bytes::from(vec![0u8; 1 << shift].into_boxed_slice()), in_progress: Vec::new(), stash: Vec::new(), shift, valid: 0, } } /// The empty region of the slab. #[inline] pub fn empty(&mut self) -> &mut [u8] { &mut self.buffer[self.valid..] } /// The valid region of the slab. #[inline] pub fn valid(&mut self) -> &mut [u8] { &mut self.buffer[..self.valid] } #[inline] pub fn valid_len(&self) -> usize { self.valid } /// Marks the next `bytes` bytes as valid. pub fn make_valid(&mut self, bytes: usize) { self.valid += bytes; } /// Extracts the first `bytes` valid bytes. pub fn extract(&mut self, bytes: usize) -> Bytes { debug_assert!(bytes <= self.valid); self.valid -= bytes; self.buffer.extract_to(bytes) } pub fn extract_valid(&mut self) -> Option<Bytes> { if self.valid > 0 { Some(self.extract(self.valid)) } else { None } } /// Ensures that `self.empty().len()` is at least `capacity`. /// /// This method may retire the current buffer if it does not have enough space, in which case /// it will copy any remaining contents into a new buffer. If this would not create enough free /// space, the shift is increased until it is sufficient. pub fn ensure_capacity(&mut self, capacity: usize) { if self.empty().len() < capacity { let mut increased_shift = false; // Increase allocation if copy would be insufficient. while self.valid + capacity > (1 << self.shift) { self.shift += 1; self.stash.clear(); // clear wrongly sized buffers. self.in_progress.clear(); // clear wrongly sized buffers. increased_shift = true; } // Attempt to reclaim shared slices. if self.stash.is_empty() { for shared in self.in_progress.iter_mut() { if let Some(mut bytes) = shared.take() { if bytes.try_regenerate::<Box<[u8]>>() { // NOTE: Test should be redundant, but better safe... if bytes.len() == (1 << self.shift) { self.stash.push(bytes); } } else { *shared = Some(bytes); } } } self.in_progress.retain(|x| x.is_some()); } let new_buffer = self.stash.pop().unwrap_or_else(|| Bytes::from(vec![0; 1 << self.shift].into_boxed_slice())); let old_buffer = ::std::mem::replace(&mut self.buffer, new_buffer); self.buffer[.. self.valid].copy_from_slice(&old_buffer[.. self.valid]); if !increased_shift { self.in_progress.push(Some(old_buffer)); } } } } macro_rules! write_number { ($ty:ty, $n:expr, $slab:expr) => ({ let size = ::std::mem::size_of::<$ty>(); $slab.ensure_capacity(size); let dst = $slab.empty(); if dst.len() < size { return Err(io::Error::from(io::ErrorKind::WriteZero)); } else { unsafe { let src = *(&$n.to_le() as *const _ as *const [u8;::std::mem::size_of::<$ty>()]); ::std::ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), size); } $slab.make_valid(size); } }) } impl BytesSlab { pub fn write_u64(&mut self, v: u64) -> Result<(), io::Error> { write_number!(u64, v, self); Ok(()) } pub fn write_u32(&mut self, v: u32) -> Result<(), io::Error> { write_number!(u32, v, self); Ok(()) } pub fn write_u16(&mut self, v: u16) -> Result<(), io::Error> { write_number!(u16, v, self); Ok(()) } pub fn try_read(&mut self, length: usize) -> Option<Bytes> { if self.valid < length { None } else { Some(self.extract(length)) } } } impl io::Write for BytesSlab { fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> { let length = buf.len(); self.ensure_capacity(length); let empty = self.empty(); if empty.len() < length { Ok(0) } else { unsafe { ::std::ptr::copy_nonoverlapping(buf.as_ptr(), empty.as_mut_ptr(), length); } self.make_valid(length); Ok(length) } } #[inline(always)] fn flush(&mut self) -> Result<(), io::Error> { Ok(()) } } macro_rules! read_number { ($ty:ty, $src:expr) => ({ let size = ::std::mem::size_of::<$ty>(); if $src.len() < size { return Err(io::Error::from(io::ErrorKind::UnexpectedEof)); } let r = $src.extract_to(size); let mut tmp: $ty = 0; unsafe { ::std::ptr::copy_nonoverlapping( r.as_ptr(), &mut tmp as *mut $ty as *mut u8, size ) } tmp.to_le() }) } impl Bytes { pub fn read_u64(&mut self) -> Result<u64, io::Error> { let r = read_number!(u64, self); Ok(r) } pub fn read_u32(&mut self) -> Result<u32, io::Error> { let r = read_number!(u32, self); Ok(r) } pub fn read_u16(&mut self) -> Result<u16, io::Error> { let r = read_number!(u16, self); Ok(r) } } thread_local! { pub static SLAB: RefCell<BytesSlab> = RefCell::new(BytesSlab::new(20)); } #[cfg(test)] mod test { use crate::common::BytesSlab; #[test] fn test_write_read_number() { let mut slab = BytesSlab::new(10); slab.write_u64(0).unwrap(); slab.write_u64(1).unwrap(); slab.write_u32(2).unwrap(); slab.write_u32(3).unwrap(); assert_eq!(slab.valid_len(), 24); let mut valid = slab.extract_valid().expect("unreachable"); assert_eq!(valid.read_u64().unwrap(), 0); assert_eq!(valid.read_u64().unwrap(), 1); assert_eq!(valid.read_u32().unwrap(), 2); assert_eq!(valid.read_u32().unwrap(), 3); } }
true
9cf019513cb61c55403234e20863f0db2600328f
Rust
JCapucho/font-to-mif
/src/main.rs
UTF-8
4,166
2.890625
3
[]
no_license
use ab_glyph::{Font, FontVec}; use clap::{App, Arg}; use std::{ fs, io::{self, Write}, ops::Range, path::Path, }; const ABOUT: &str = r#" Converts true type fonts (.ttf) and Open type fonts (.otf) to intel quartus Memory Initialization File (.mif) "#; fn range_parser(range: &str) -> Result<Range<usize>, String> { let mut chars = range.chars(); if let Some(first) = chars.next() { if !first.is_digit(10) { return Err(String::from("First char must be an integer")); } let mut start_end = 1; let mut end_start = None; while let Some(c) = chars.next() { if c.is_digit(10) { start_end += 1 } else if c == '.' { if chars.next() != Some('.') { return Err(String::from("Expected '.'")); } if !chars.next().map(|c| c.is_digit(10)).unwrap_or(false) { return Err(String::from("Character after '.' must be a digit")); } end_start = Some(start_end + 2); while let Some(c) = chars.next() { if !c.is_digit(10) { return Err(String::from("Invalid char")); } } } else { return Err(String::from("Invalid char")); } } let start = range[..start_end].parse().unwrap(); Ok(if let Some(high_start) = end_start { let end = range[high_start..].parse().unwrap(); Range { start, end } } else { Range { start, end: start + 1, } }) } else { Err(String::from("Empty string is an invalid range")) } } fn main() -> io::Result<()> { let matches = App::new("font to intel quartus MIF converter") .version("0.1") .author("João Capucho <jcapucho7@gmail.com>") .about(ABOUT) .arg( Arg::with_name("FONT") .help("Sets the font file to use") .required(true) .index(1), ) .arg( Arg::with_name("output") .short("o") .long("out") .value_name("FILE") .default_value("./font.mif") .help("Sets the path to the output file"), ) .arg( Arg::with_name("range") .short("r") .long("range") .value_name("RANGE") .default_value("0..256") .validator(|value| range_parser(&value).map(|_| ())) .help("Sets the range of glyphs to process"), ) .get_matches(); let path = Path::new(matches.value_of("FONT").unwrap()); let range = range_parser(matches.value_of("range").unwrap()).unwrap(); let font_data = fs::read(path)?; let font = FontVec::try_from_vec(font_data).unwrap(); let depth = range.len() * 8; let mut data: Vec<u8> = vec![0; depth]; for i in range { let glyph = font.glyph_id(From::from(i as u8)).with_scale(8.0); if let Some(outlined) = font.outline_glyph(glyph) { outlined.draw(|x, y, coverage| { if coverage != 0.0 { data[i * 8 + y as usize] |= 1 << x; } }); } } let mut out = fs::OpenOptions::new() .write(true) .truncate(true) .create(true) .open(matches.value_of("output").unwrap())?; writeln!( &mut out, "-- {} \n", path.file_name().unwrap().to_str().unwrap() )?; writeln!(&mut out, "DEPTH = {};", depth)?; writeln!(&mut out, "WIDTH = 8;")?; writeln!(&mut out, "ADDRESS_RADIX = HEX;")?; writeln!(&mut out, "DATA_RADIX = HEX;\n")?; writeln!(&mut out, "CONTENT")?; writeln!(&mut out, "BEGIN")?; writeln!(&mut out)?; for (addr, byte) in data.into_iter().enumerate() { writeln!(&mut out, "{:04X} : {:02X};", addr * 8, byte)?; } writeln!(&mut out)?; writeln!(&mut out, "END;")?; Ok(()) }
true
1fb14e731d2361a4e84211cf236b51a664168748
Rust
Wojtechnology/chess
/src/main.rs
UTF-8
13,016
3.046875
3
[]
no_license
use std::collections::HashMap; use std::fmt; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use serde::Serialize; use serde_json::json; mod piece { use super::{Board, Location, WalkStrategy}; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum Type { Pawn, Bishop, Knight, Rook, Queen, King, } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum Color { White, Black, } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Piece { pub tpe: Type, pub color: Color, } impl Piece { pub fn new(tpe: Type, color: Color) -> Piece { Piece { tpe: tpe, color: color, } } pub fn new_opt(tpe: Type, color: Color) -> Option<Piece> { Some(Self::new(tpe, color)) } fn strategies_pawn(&self, from: Location) -> Vec<WalkStrategy> { match self.color { Color::White => { if from.y == 1 { vec![WalkStrategy::new(0, 1, 2)] } else { vec![WalkStrategy::new(0, 1, 1)] } } Color::Black => { if from.y == 6 { vec![WalkStrategy::new(0, -1, 2)] } else { vec![WalkStrategy::new(0, -1, 1)] } } } } pub fn valid_moves(&self, board: &Board, from: Location) -> Vec<Location> { let strategies = match self.tpe { Type::Pawn => self.strategies_pawn(from), Type::Bishop => vec![ WalkStrategy::new(-1, -1, 7), WalkStrategy::new(-1, 1, 7), WalkStrategy::new(1, -1, 7), WalkStrategy::new(1, 1, 7), ], Type::Knight => vec![ WalkStrategy::new(-2, -1, 1), WalkStrategy::new(-2, 1, 1), WalkStrategy::new(-1, -2, 1), WalkStrategy::new(-1, 2, 1), WalkStrategy::new(1, -2, 1), WalkStrategy::new(1, 2, 1), WalkStrategy::new(2, -1, 1), WalkStrategy::new(2, 1, 1), ], Type::Rook => vec![ WalkStrategy::new(-1, 0, 7), WalkStrategy::new(0, -1, 7), WalkStrategy::new(0, 1, 7), WalkStrategy::new(1, 0, 7), ], Type::Queen => vec![ WalkStrategy::new(-1, -1, 7), WalkStrategy::new(-1, 1, 7), WalkStrategy::new(1, -1, 7), WalkStrategy::new(1, 1, 7), WalkStrategy::new(-1, 0, 7), WalkStrategy::new(0, -1, 7), WalkStrategy::new(0, 1, 7), WalkStrategy::new(1, 0, 7), ], Type::King => vec![ WalkStrategy::new(-1, -1, 1), WalkStrategy::new(-1, 1, 1), WalkStrategy::new(1, -1, 1), WalkStrategy::new(1, 1, 1), WalkStrategy::new(-1, 0, 1), WalkStrategy::new(0, -1, 1), WalkStrategy::new(0, 1, 1), WalkStrategy::new(1, 0, 1), ], }; let mut moves = Vec::new(); for strategy in strategies { let walk = strategy.to_walk(from); for dest in walk { if let Some(piece) = board.0[dest.y as usize][dest.x as usize] { if piece.color == self.color { break; } } moves.push(dest) } } moves } } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] struct Location { x: u8, y: u8, } impl Location { pub fn to_string(&self) -> String { format!("{}{}", (self.x + 97) as char, self.y + 1) } } impl fmt::Display for Location { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } #[derive(Debug, Copy, Clone)] struct WalkStrategy { dx: i8, dy: i8, max_steps: u8, } impl WalkStrategy { pub fn new(dx: i8, dy: i8, max_steps: u8) -> WalkStrategy { WalkStrategy { dx: dx, dy: dy, max_steps: max_steps, } } pub fn to_walk(&self, start: Location) -> Walk { Walk { dx: self.dx, dy: self.dy, steps_left: self.max_steps, cur: start, } } } struct Walk { dx: i8, dy: i8, steps_left: u8, cur: Location, } impl Iterator for Walk { type Item = Location; fn next(&mut self) -> Option<Location> { if self.steps_left == 0 { None } else if self.dx < 0 && -self.dx as u8 > self.cur.x { None } else if self.dx > 0 && self.dx as u8 + self.cur.x >= 8 { None } else if self.dy < 0 && -self.dy as u8 > self.cur.y { None } else if self.dy > 0 && self.dy as u8 + self.cur.y >= 8 { None } else { self.steps_left -= 1; self.cur.x = (self.cur.x as i8 + self.dx) as u8; self.cur.y = (self.cur.y as i8 + self.dy) as u8; Some(self.cur) } } } struct Board([[Option<piece::Piece>; 8]; 8]); impl Board { pub fn new() -> Board { use piece::{Color, Piece, Type}; Board([ [ Piece::new_opt(Type::Rook, Color::White), Piece::new_opt(Type::Knight, Color::White), Piece::new_opt(Type::Bishop, Color::White), Piece::new_opt(Type::Queen, Color::White), Piece::new_opt(Type::King, Color::White), Piece::new_opt(Type::Bishop, Color::White), Piece::new_opt(Type::Knight, Color::White), Piece::new_opt(Type::Rook, Color::White), ], [ Piece::new_opt(Type::Pawn, Color::White), Piece::new_opt(Type::Pawn, Color::White), Piece::new_opt(Type::Pawn, Color::White), Piece::new_opt(Type::Pawn, Color::White), Piece::new_opt(Type::Pawn, Color::White), Piece::new_opt(Type::Pawn, Color::White), Piece::new_opt(Type::Pawn, Color::White), Piece::new_opt(Type::Pawn, Color::White), ], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [ Piece::new_opt(Type::Pawn, Color::Black), Piece::new_opt(Type::Pawn, Color::Black), Piece::new_opt(Type::Pawn, Color::Black), Piece::new_opt(Type::Pawn, Color::Black), Piece::new_opt(Type::Pawn, Color::Black), Piece::new_opt(Type::Pawn, Color::Black), Piece::new_opt(Type::Pawn, Color::Black), Piece::new_opt(Type::Pawn, Color::Black), ], [ Piece::new_opt(Type::Rook, Color::Black), Piece::new_opt(Type::Knight, Color::Black), Piece::new_opt(Type::Bishop, Color::Black), Piece::new_opt(Type::Queen, Color::Black), Piece::new_opt(Type::King, Color::Black), Piece::new_opt(Type::Bishop, Color::Black), Piece::new_opt(Type::Knight, Color::Black), Piece::new_opt(Type::Rook, Color::Black), ], ]) } pub fn step(&mut self, from: Location, to: Location) -> Result<(), String> { let piece = match self.0[from.y as usize][from.x as usize] { None => Err(format!("No piece at {}", from)), Some(p) => Ok(p), }?; let valid_moves = piece.valid_moves(self, from); let () = if valid_moves.iter().any(|&dest| dest == to) { Ok(()) } else { Err("Invalid move".to_string()) }?; self.0[from.y as usize][from.x as usize] = None; self.0[to.y as usize][to.x as usize] = Some(piece); Ok(()) } } fn cell_as_str(cell: &Option<piece::Piece>) -> String { use piece::{Color, Piece, Type}; match cell { None => "".to_string(), Some(Piece { tpe, color }) => { let c = match color { Color::White => "w", Color::Black => "b", }; let t = match tpe { Type::Pawn => "P", Type::Bishop => "B", Type::Knight => "N", Type::Rook => "R", Type::Queen => "Q", Type::King => "K", }; format!("{}{}", c, t) } } } fn board_as_str(board: &Board) -> String { let mut cells = Vec::with_capacity(64); for i in 0..8 { for j in 0..8 { cells.push(cell_as_str(&board.0[i][j])); } } cells.join(",") } fn get_path(mut stream: &TcpStream) -> (String, HashMap<String, String>) { let mut buffer = [0; 1024]; stream.read(&mut buffer).unwrap(); let req_str = String::from_utf8_lossy(&buffer[..]); let req_fst_line = req_str.split('\n').next().unwrap(); let mut req_fst_line_it = req_fst_line.split(' '); req_fst_line_it.next().unwrap(); // Method let full_path = req_fst_line_it.next().unwrap(); let mut full_path_it = full_path.split("?"); let path = full_path_it.next().unwrap().to_string(); let query_str_it = { match full_path_it.next() { Some(query_str) => query_str.split("&"), None => { // Make the split empty let mut split = "".split("&"); split.next().unwrap(); split } } }; let mut query_args = HashMap::new(); for query_arg_str in query_str_it { let mut query_arg_str_it = query_arg_str.split("="); query_args.insert( query_arg_str_it.next().unwrap().to_string(), query_arg_str_it.collect::<Vec<&str>>().join("="), ); } (path, query_args) } fn location_from_string(s: &String) -> Location { let i = s.parse::<u8>().unwrap(); Location { x: i % 8, y: i / 8 } } fn get_from_to(query_args: HashMap<String, String>) -> (Location, Location) { let from_raw = query_args.get("from").unwrap(); let to_raw = query_args.get("to").unwrap(); (location_from_string(from_raw), location_from_string(to_raw)) } #[derive(Serialize)] struct ResponseData { squares: String, } fn success_res(content: String) -> String { format!( "\ HTTP/1.1 200 OK\r\n\ Access-Control-Allow-Origin: *\r\n\ Content-Type: application/json\r\n\ Content-Length: {}\r\n\ \r\n\ {}", content.len(), content, ) } fn bad_request_res(err_msg: String) -> String { format!( "\ HTTP/1.1 400 Bad Request\r\n\ Access-Control-Allow-Origin: *\r\n\ Content-Type: text/plain\r\n\ Content-Length: {}\r\n\ \r\n\ {}", err_msg.len(), err_msg, ) } fn write_board(board: &Board, mut stream: &TcpStream) { let data = ResponseData { squares: board_as_str(board), }; let body = json!(data).to_string(); let response = success_res(body); stream.write(response.as_bytes()).unwrap(); } fn write_err(err_msg: String, mut stream: &TcpStream) { let response = bad_request_res(err_msg); stream.write(response.as_bytes()).unwrap(); } fn main() { let mut board = Board::new(); let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); for stream in listener.incoming() { let mut stream = stream.unwrap(); let (path, query_args) = get_path(&stream); println!("{}: {:?}", path, query_args); if path.eq("/game") { write_board(&board, &stream); } else if path.eq("/move") { let (from, to) = get_from_to(query_args); match board.step(from, to) { Ok(()) => write_board(&board, &stream), Err(e) => { println!("Error: {}", e); write_err(e, &stream) } }; } else { // TODO: 404 write_err("Unknown path".to_string(), &stream); } stream.flush().unwrap() } }
true
69dd6468553a85bcfa57706c7361bb3115801a6d
Rust
mdaffin/nuc
/src/bin/nuc.rs
UTF-8
811
2.984375
3
[ "MIT" ]
permissive
extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate nuc; use nuc::Number; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "nuc", about = "Converts numbers form one for to another")] struct Opt { /// Number to convert #[structopt(help = "Input numbers")] input: Vec<String>, } fn main() { let opt = Opt::from_args(); for arg in opt.input { let num: Number = match arg.parse() { Ok(i) => i, Err(e) => { println!("Failed to parse input '{}': {}", arg, e); std::process::exit(1); } }; print!("{:>8} ", num); print!("{:>8} ", num.fmt_signed()); print!("{:>#8x} ", num); print!("{:>#16b}", num); println!(); } }
true
ab6627ce58ec67aad32c2e9c59fadf1abbefaa83
Rust
wzhd/rotor
/src/util/cmd.rs
UTF-8
1,162
2.859375
3
[]
no_license
use super::super::host::UserAtHost; use std::str::FromStr; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "rotor", about = "Deploying properties to hosts.")] pub struct RotorMain { #[structopt(subcommand)] pub cmd: RotorSub, } #[derive(Debug, StructOpt)] pub enum RotorSub { #[structopt(name = "list")] /// List configured users at hosts List, /// Apply configurations for username@hostname locally #[structopt(name = "apply")] Apply { #[structopt(parse(try_from_str))] user: UserAtHost, }, /// Apply configurations to remote users or hosts via ssh #[structopt(name = "push")] Push { targets: Vec<PushTarget> }, } #[derive(Debug)] pub enum PushTarget { /// A single user on a single host User(UserAtHost), /// All users on a host Host(String), } impl FromStr for PushTarget { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { if !s.contains('@') { Ok(PushTarget::Host(s.to_string())) } else { let u = FromStr::from_str(s)?; Ok(PushTarget::User(u)) } } }
true
8d76920c11fedc2e7bb55e69be3df7b59a492e4b
Rust
kellerja/AoC2020
/src/day16/mod.rs
UTF-8
5,789
2.890625
3
[]
no_license
use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::ops::Range; use std::collections::HashSet; use regex::Regex; lazy_static! { static ref FIELD_RULE_PATTERN: Regex = Regex::new(r"(?P<name>.+): (?P<low_start>\d+)-(?P<low_end>\d+) or (?P<high_start>\d+)-(?P<high_end>\d+)").unwrap(); } struct TicketField { name: String, rules: Vec<Range<u64>> } impl TicketField { fn parse(input: &str) -> Option<Self> { FIELD_RULE_PATTERN.captures(input).and_then(|cap| { Some(Self { name: cap["name"].to_owned(), rules: vec![ Range {start: cap["low_start"].parse().unwrap(), end: cap["low_end"].parse::<u64>().unwrap() + 1}, Range {start: cap["high_start"].parse().unwrap(), end: cap["high_end"].parse::<u64>().unwrap() + 1} ] }) }) } fn is_valid(&self, number: u64) -> bool { for rule in &self.rules { if rule.contains(&number) { return true; } } false } } #[derive(Clone)] struct Ticket { fields: Vec<String>, values: Vec<u64> } impl Ticket { fn parse(input: &str) -> Option<Self> { let input = input.split(","); let mut values = Vec::new(); for s in input { if let Ok(value) = s.parse() { values.push(value); } else { return None; } } Some(Ticket { fields: Vec::with_capacity(values.len()), values }) } fn find_illegal_fields(&self, rules: &Vec<TicketField>) -> Vec<u64> { if rules.is_empty() { return Vec::new(); } self.values.iter() .filter(|&num| !rules.iter().map(|rule| rule.is_valid(*num)).fold(false, |acc, result| acc || result) ).map(|num| *num).collect() } } fn get_possible_fields_map(fields: &[TicketField]) -> Vec<Vec<&str>> { let field_names: Vec<&str> = fields.iter().map(|field| field.name.as_str()).collect(); vec![field_names.clone(); field_names.len()] } fn remove_invalid_possible_fields(possible_fields: &mut Vec<Vec<&str>>, valid_tickets: &[&Ticket], fields: &[TicketField]) { for ticket in valid_tickets { for (i, &value) in ticket.values.iter().enumerate() { for field in fields { if !field.is_valid(value) { possible_fields[i].retain(|&name| name != field.name); } } } } } fn remove_cerain_fields_from_uncertain_fields(possible_fields: &mut Vec<Vec<&str>>) { let mut handled_fields = HashSet::with_capacity(possible_fields.len()); loop { let certain_fields: HashSet<&str> = possible_fields.iter() .filter(|fields| fields.len() == 1) .map(|fields| fields.first().unwrap().to_owned()).collect(); let unhandled_field = certain_fields.difference(&handled_fields).next(); match unhandled_field { None => break, Some(unhandled_field) => { for fields in possible_fields.iter_mut() { if fields.len() == 1 { continue; } fields.retain(|field| field != unhandled_field); } let unhandled_field = unhandled_field.to_owned(); handled_fields.insert(unhandled_field); } } } } fn certain_field_map<'a>(possible_fields: &'a Vec<Vec<&str>>) -> Option<Vec<&'a str>> { if possible_fields.iter().any(|field| field.len() != 1) { return None } else { Some(possible_fields.iter().map(|field| field.first().unwrap().to_owned()).collect()) } } pub fn solve(input: &File) -> (Option<u64>, Option<u64>) { let input = parse_input(input); if let Some((fields, my_ticket, tickets)) = input { let mut valid_tickets: Vec<&Ticket> = tickets.iter().filter(|ticket| ticket.find_illegal_fields(&fields).is_empty()).collect(); valid_tickets.push(&my_ticket); let mut possible_field_map = get_possible_fields_map(&fields); remove_invalid_possible_fields(&mut possible_field_map, &valid_tickets, &fields); remove_cerain_fields_from_uncertain_fields(&mut possible_field_map); let field_map = certain_field_map(&possible_field_map); let departure_fields_product = field_map.and_then(|field_map| { let mut result = 1; for (i, field) in field_map.iter().enumerate() { if field.starts_with("departure") { result *= my_ticket.values[i]; } } Some(result) }); let invalid_ticket_fields_sum = tickets.iter().map(|ticket| ticket.find_illegal_fields(&fields).iter().sum::<u64>()).sum(); (Some(invalid_ticket_fields_sum), departure_fields_product) } else { (None, None) } } fn parse_input(input: &File) -> Option<(Vec<TicketField>, Ticket, Vec<Ticket>)> { let mut lines = BufReader::new(input).lines(); let mut fields = Vec::new(); loop { let line = lines.next(); let field = line.and_then(|line| TicketField::parse(&line.unwrap())); match field { Some(field) => fields.push(field), None => break } }; lines.next(); let my_ticket = lines.next().and_then(|line| Ticket::parse(&line.unwrap())); lines.next(); lines.next(); let tickets: Vec<Ticket> = lines.map(|line| Ticket::parse(&line.unwrap()).unwrap()).collect(); if fields.is_empty() || my_ticket.is_none() || tickets.is_empty() { None } else { Some((fields, my_ticket.unwrap(), tickets)) } }
true
9dfb91782b25f342c1f51f281268f46d66e7a741
Rust
whentze/loom
/src/futures/mod.rs
UTF-8
959
2.765625
3
[ "MIT" ]
permissive
//! Future related synchronization primitives. mod atomic_task; pub use self::atomic_task::AtomicTask; pub use self::rt::wait_future as block_on; use rt; /// Mock implementation of `futures::task`. pub mod task { use rt; /// Mock implementation of `futures::task::Task`. #[derive(Debug)] pub struct Task { thread: rt::thread::Id, } /// Mock implementation of `futures::task::current`. pub fn current() -> Task { Task { thread: rt::thread::Id::current(), } } impl Task { /// Indicate that the task should attempt to poll its future in a timely fashion. pub fn notify(&self) { self.thread.future_notify(); } /// This function is intended as a performance optimization for structures which store a Task internally. pub fn will_notify_current(&self) -> bool { self.thread == rt::thread::Id::current() } } }
true
2ee109a255b57bd9d9eb9296e8c17b945ac711e0
Rust
rm-hull/image-preview
/src/main.rs
UTF-8
1,825
3
3
[ "MIT" ]
permissive
use image::io::Reader as ImageReader; use image::GenericImageView; use std::io::{self, Write}; use structopt::StructOpt; extern crate image_preview; #[derive(StructOpt)] struct Cli { filename: String, #[structopt( long, help = "When supplied, renders the image in true colour (not supported on all terminals). The default is to use the nearest colour from the 255 indexed colours of the standard ANSI palette." )] true_color: bool, #[structopt( long, help = "Resize filter used when scaling for the terminal (allowed values: nearest, triangle, catmullrom, gaussian, lanczos3)", default_value = "lanczos3" )] filter_type: String, #[structopt( long, short, help = "When supplied, limits the image with to the number of columns, else probes the terminal to determine the displayable width." )] width: Option<u32>, } fn main() { let args = Cli::from_args(); let img = ImageReader::open(args.filename) .expect("File does not exist") .decode() .expect("Cannot decode image"); let filter_type = image_preview::from_str(&args.filter_type).expect("Unsupported filter type"); let (width, height) = image_preview::calc_size(&img, args.width).unwrap(); let resized_img = img.resize(width, height, filter_type); let pixel_renderer = match args.true_color { true => image_preview::true_color, false => image_preview::indexed, }; let mut buf = Vec::new(); for y in (0..resized_img.height() - 1).step_by(2) { for x in 0..resized_img.width() { buf.write_all(pixel_renderer(&resized_img, x, y).as_bytes()) .unwrap(); } buf.write_all(b"\x1b[m\n").unwrap(); } io::stdout().write_all(&buf).unwrap(); }
true
a20eb7b379ce61003e57c6fc12c171197e59b940
Rust
linuxdevops-34/aws-apigateway-lambda-authorizer-blueprints
/blueprints/rust/main.rs
UTF-8
6,162
2.65625
3
[ "Apache-2.0" ]
permissive
#![allow(dead_code)] #[macro_use] extern crate lambda_runtime as lambda; #[macro_use] extern crate serde_derive; #[macro_use] extern crate log; extern crate simple_logger; use lambda::error::HandlerError; use serde_json::json; use std::error::Error; static POLICY_VERSION: &str = "2012-10-17"; // override if necessary fn my_handler( event: APIGatewayCustomAuthorizerRequest, _ctx: lambda::Context, ) -> Result<APIGatewayCustomAuthorizerResponse, HandlerError> { info!("Client token: {}", event.authorization_token); info!("Method ARN: {}", event.method_arn); // validate the incoming token // and produce the principal user identifier associated with the token // this could be accomplished in a number of ways: // 1. Call out to OAuth provider // 2. Decode a JWT token inline // 3. Lookup in a self-managed DB let principal_id = "user|a1b2c3d4"; // you can send a 401 Unauthorized response to the client by failing like so: // Err(HandlerError{ msg: "Unauthorized".to_string(), backtrace: None }); // if the token is valid, a policy must be generated which will allow or deny access to the client // if access is denied, the client will recieve a 403 Access Denied response // if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called // this function must generate a policy that is associated with the recognized principal user identifier. // depending on your use case, you might store policies in a DB, or generate them on the fly // keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) // and will apply to subsequent calls to any method/resource in the RestApi // made with the same token //the example policy below denies access to all resources in the RestApi let tmp: Vec<&str> = event.method_arn.split(":").collect(); let api_gateway_arn_tmp: Vec<&str> = tmp[5].split("/").collect(); let aws_account_id = tmp[4]; let region = tmp[3]; let rest_api_id = api_gateway_arn_tmp[0]; let stage = api_gateway_arn_tmp[1]; let policy = APIGatewayPolicyBuilder::new(region, aws_account_id, rest_api_id, stage) .deny_all_methods() .build(); // new! -- add additional key-value pairs associated with the authenticated principal // these are made available by APIGW like so: $context.authorizer.<key> // additional context is cached Ok(APIGatewayCustomAuthorizerResponse { principal_id: principal_id.to_string(), policy_document: policy, context: json!({ "stringKey": "stringval", "numberKey": 123, "booleanKey": true }), }) } fn main() -> Result<(), Box<dyn Error>> { simple_logger::init_with_level(log::Level::Info)?; lambda!(my_handler); Ok(()) } #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct APIGatewayCustomAuthorizerRequest { #[serde(rename = "type")] _type: String, authorization_token: String, method_arn: String, } #[derive(Serialize, Deserialize)] #[allow(non_snake_case)] struct APIGatewayCustomAuthorizerPolicy { Version: String, Statement: Vec<IAMPolicyStatement>, } #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct APIGatewayCustomAuthorizerResponse { principal_id: String, policy_document: APIGatewayCustomAuthorizerPolicy, context: serde_json::Value, } #[derive(Serialize, Deserialize)] #[allow(non_snake_case)] struct IAMPolicyStatement { Action: Vec<String>, Effect: Effect, Resource: Vec<String>, } struct APIGatewayPolicyBuilder { region: String, aws_account_id: String, rest_api_id: String, stage: String, policy: APIGatewayCustomAuthorizerPolicy, } #[derive(Serialize, Deserialize)] enum Method { #[serde(rename = "GET")] Get, #[serde(rename = "POST")] Post, #[serde(rename = "*PUT")] Put, #[serde(rename = "DELETE")] Delete, #[serde(rename = "PATCH")] Patch, #[serde(rename = "HEAD")] Head, #[serde(rename = "OPTIONS")] Options, #[serde(rename = "*")] All, } #[derive(Serialize, Deserialize)] enum Effect { Allow, Deny, } impl APIGatewayPolicyBuilder { pub fn new( region: &str, account_id: &str, api_id: &str, stage: &str, ) -> APIGatewayPolicyBuilder { Self { region: region.to_string(), aws_account_id: account_id.to_string(), rest_api_id: api_id.to_string(), stage: stage.to_string(), policy: APIGatewayCustomAuthorizerPolicy { Version: POLICY_VERSION.to_string(), Statement: vec![], }, } } pub fn add_method<T: Into<String>>( mut self, effect: Effect, method: Method, resource: T, ) -> Self { let resource_arn = format!( "arn:aws:execute-api:{}:{}:{}/{}/{}/{}", &self.region, &self.aws_account_id, &self.rest_api_id, &self.stage, serde_json::to_string(&method).unwrap(), resource.into().trim_start_matches("/") ); let stmt = IAMPolicyStatement { Effect: effect, Action: vec!["execute-api:Invoke".to_string()], Resource: vec![resource_arn], }; self.policy.Statement.push(stmt); self } pub fn allow_all_methods(self) -> Self { self.add_method(Effect::Allow, Method::All, "*") } pub fn deny_all_methods(self) -> Self { self.add_method(Effect::Deny, Method::All, "*") } pub fn allow_method(self, method: Method, resource: String) -> Self { self.add_method(Effect::Allow, method, resource) } pub fn deny_method(self, method: Method, resource: String) -> Self { self.add_method(Effect::Deny, method, resource) } // Creates and executes a new child thread. pub fn build(self) -> APIGatewayCustomAuthorizerPolicy { self.policy } }
true
f1e4a0c0d05386f7ffb6f6296c7fae4770282033
Rust
CryZe/romhack-compiler
/backend/src/iso/reader.rs
UTF-8
4,139
2.734375
3
[ "MIT" ]
permissive
use super::virtual_file_system::{Directory, File, Node}; use super::{consts::*, FstEntry, FstNodeType}; use byteorder::{ByteOrder, BE}; use failure::{Error, ResultExt}; use std::fs; use std::io::{Read, Result as IOResult}; use std::path::Path; use std::str; pub fn load_iso_buf<P: AsRef<Path>>(path: P) -> IOResult<Vec<u8>> { let mut file = fs::File::open(path)?; let len = file.metadata()?.len(); let mut buf = Vec::with_capacity(len as usize + 1); file.read_to_end(&mut buf)?; Ok(buf) } pub fn load_iso<'a>(buf: &'a [u8]) -> Result<Directory<'a>, Error> { let fst_offset = BE::read_u32(&buf[OFFSET_FST_OFFSET..]) as usize; let mut pos = fst_offset; let num_entries = BE::read_u32(&buf[fst_offset + 8..]) as usize; let string_table_offset = num_entries * 0xC; let mut fst_entries = Vec::with_capacity(num_entries); for _ in 0..num_entries { let kind = if buf[pos] == 0 { FstNodeType::File } else { FstNodeType::Directory }; pos += 2; let cur_pos = pos; let string_offset = BE::read_u16(&buf[pos..]) as usize; pos = string_offset + string_table_offset + fst_offset; let mut end = pos; while buf[end] != 0 { end += 1; } let relative_file_name = str::from_utf8(&buf[pos..end]).context("Couldn't parse the relative file name")?; pos = cur_pos + 2; let file_offset_parent_dir = BE::read_u32(&buf[pos..]) as usize; let file_size_next_dir_index = BE::read_u32(&buf[pos + 4..]) as usize; pos += 8; fst_entries.push(FstEntry { kind, relative_file_name, file_offset_parent_dir, file_size_next_dir_index, file_name_offset: 0, }); } let mut root_dir = Directory::new("root"); let mut sys_data = Directory::new("&&systemdata"); sys_data .children .push(Node::File(File::new("iso.hdr", &buf[..HEADER_LENGTH]))); let dol_offset = BE::read_u32(&buf[OFFSET_DOL_OFFSET..]) as usize; sys_data.children.push(Node::File(File::new( "AppLoader.ldr", &buf[HEADER_LENGTH..dol_offset], ))); sys_data.children.push(Node::File(File::new( "Start.dol", &buf[dol_offset..fst_offset], ))); let fst_size = BE::read_u32(&buf[OFFSET_FST_SIZE..]) as usize; sys_data.children.push(Node::File(File::new( "Game.toc", &buf[fst_offset..][..fst_size], ))); root_dir.children.push(Node::Directory(Box::new(sys_data))); let mut count = 1; while count < num_entries { let entry = &fst_entries[count]; if fst_entries[count].kind == FstNodeType::Directory { let mut dir = Directory::new(entry.relative_file_name); while count < entry.file_size_next_dir_index - 1 { count = get_dir_structure_recursive(count + 1, &fst_entries, &mut dir, buf); } root_dir.children.push(Node::Directory(Box::new(dir))); } else { let file = get_file_data(&fst_entries[count], buf); root_dir.children.push(Node::File(file)); } count += 1; } Ok(root_dir) } fn get_dir_structure_recursive<'a>( mut cur_index: usize, fst: &[FstEntry<'a>], parent_dir: &mut Directory<'a>, buf: &'a [u8], ) -> usize { let entry = &fst[cur_index]; if entry.kind == FstNodeType::Directory { let mut dir = Directory::new(entry.relative_file_name); while cur_index < entry.file_size_next_dir_index - 1 { cur_index = get_dir_structure_recursive(cur_index + 1, fst, &mut dir, buf); } parent_dir.children.push(Node::Directory(Box::new(dir))); } else { let file = get_file_data(entry, buf); parent_dir.children.push(Node::File(file)); } cur_index } fn get_file_data<'a>(fst_data: &FstEntry<'a>, buf: &'a [u8]) -> File<'a> { let data = &buf[fst_data.file_offset_parent_dir..][..fst_data.file_size_next_dir_index]; File::new(fst_data.relative_file_name, data) }
true
0ec69a2129085d2ec0096ecb8a909d0af303a9eb
Rust
dollarkillerx/Re-learning-RUST
/demo12_1/src/main.rs
UTF-8
1,396
3.828125
4
[ "MIT" ]
permissive
// struct Handbag<T> { // article: Option<Box<T>>, // } // impl <T>Handbag<T> { // fn new() -> Handbag<T> { // Handbag{ // article:None, // } // } // fn put(&mut self,article: T) { // self.article = Some(Box::new(article)); // } // fn take(&mut self) -> Option<Box<T>> { // match &self.article { // Some(data) => { // data: &Box<T> // self.article = None; // return Some(*data) // }, // None => None, // } // } // } use std::mem::take; fn main() { // let mut handbag = Handbag::new(); // handbag.put(String::from("hello")); // if let Some(article) = handbag.take() { // println!("data: {}",article); // } let mut u = User::new(); u.set_name(String::from("acg")); println!("name: {}",u.get_name().unwrap()); println!("name: {}",u.get_name().unwrap()); println!("Hello, world!"); } struct User { name: Option<String>, } impl User { fn new() -> User { User{name:None} } fn set_name(&mut self,name: String) { self.name = Some(name); } fn get_name(&mut self) -> Option<String> { take(&mut self.name) // match &self.name { // None=>None, // Some(name) => { // take(name) // }, // } } }
true
cfe8ce67e3977c8ccb98f3e6db28184566e7f24a
Rust
lemunozm/ruscii
/examples/space_invaders.rs
UTF-8
7,365
2.671875
3
[ "Apache-2.0" ]
permissive
use ruscii::app::{App, State}; use ruscii::drawing::Pencil; use ruscii::gui::FPSCounter; use ruscii::keyboard::{Key, KeyEvent}; use ruscii::spatial::Vec2; use ruscii::terminal::{Color, Style, Window}; use rand::{self, prelude::*}; struct GameState { pub dimension: Vec2, pub spaceship: Vec2, pub spaceship_shots: Vec<Vec2>, pub last_shot_frame: usize, pub aliens: Vec<Vec2>, pub aliens_shots: Vec<Vec2>, pub aliens_movement: (i32, bool), //dir, just_down pub last_aliens_movement: usize, pub last_aliens_shots: usize, pub lives: usize, pub score: usize, } impl GameState { pub fn new(dimension: Vec2) -> GameState { let mut aliens = Vec::new(); for y in 2..7 { for x in 5..dimension.x - 5 { if x % 2 != 0 { aliens.push(Vec2::xy(x, y)); } } } GameState { dimension, spaceship: Vec2::xy(dimension.x / 2, dimension.y - 2), spaceship_shots: Vec::new(), last_shot_frame: 0, aliens, aliens_shots: Vec::new(), aliens_movement: (1, false), last_aliens_movement: 0, last_aliens_shots: 0, lives: 3, score: 0, } } pub fn spaceship_move_x(&mut self, displacement: i32) { if displacement < 0 && self.spaceship.x != 0 || displacement > 0 && self.spaceship.x != self.dimension.x { self.spaceship.x += displacement; } } pub fn spaceship_shot(&mut self, shot_frame: usize) { if self.last_shot_frame + 15 < shot_frame { self.spaceship_shots.push(self.spaceship); self.last_shot_frame = shot_frame; } } pub fn update(&mut self, frame: usize) { let mut partial_score = 0; let aliens = &mut self.aliens; self.spaceship_shots.retain(|shot| { if shot.y == 1 { return false; } let pre_len = aliens.len(); aliens.retain(|alien| alien != shot); let destroyed = aliens.len() != pre_len; if destroyed { partial_score += 5; } !destroyed }); self.score += partial_score; self.spaceship_shots.iter_mut().for_each(|shot| shot.y -= 1); if self.last_aliens_shots + 5 < frame { self.last_aliens_shots = frame; for alien in &self.aliens { let must_shot = thread_rng().gen_range(0..=200) == 0; if must_shot { self.aliens_shots.push(*alien); } } let bottom_shot_limit = self.dimension.y; self.aliens_shots.retain(|shot| shot.y < bottom_shot_limit); self.aliens_shots.iter_mut().for_each(|shot| shot.y += 1); } let mut damage = 0; let spaceship = &self.spaceship; self.aliens_shots.retain(|shot| { if shot.y == spaceship.y && (shot.x == spaceship.x || shot.x == spaceship.x + 1 || shot.x == spaceship.x - 1) { damage += 1; return false; } true }); self.aliens.iter().for_each(|alien| { if alien.y == spaceship.y && (alien.x == spaceship.x || alien.x == spaceship.x + 1 || alien.x == spaceship.x - 1) { damage = 1000; } }); self.lives = if damage >= self.lives { 0 } else { self.lives - damage }; if self.aliens.len() > 0 { let left = self.aliens.iter().min_by_key(|alien| alien.x).unwrap(); let right = self.aliens.iter().max_by_key(|alien| alien.x).unwrap(); if self.last_aliens_movement + 20 < frame { self.last_aliens_movement = frame; if left.x == 0 || right.x == self.dimension.x { if self.aliens_movement.1 { self.aliens_movement.0 = -self.aliens_movement.0; let dir = self.aliens_movement.0; self.aliens .iter_mut() .for_each(|alien| alien.x = alien.x + dir); self.aliens_movement.1 = false; } else { self.aliens.iter_mut().for_each(|alien| alien.y += 1); self.aliens_movement.1 = true; } } else { let dir = self.aliens_movement.0; self.aliens .iter_mut() .for_each(|alien| alien.x = alien.x + dir); } } } } } fn main() { let mut app = App::default(); let mut state = GameState::new(Vec2::xy(60, 22)); let mut fps_counter = FPSCounter::default(); app.run(|app_state: &mut State, window: &mut Window| { for key_event in app_state.keyboard().last_key_events() { match key_event { KeyEvent::Pressed(Key::Esc) => app_state.stop(), KeyEvent::Pressed(Key::Q) => app_state.stop(), _ => (), } } for key_down in app_state.keyboard().get_keys_down() { match key_down { Key::A | Key::H => state.spaceship_move_x(-1), Key::D | Key::L => state.spaceship_move_x(1), Key::Space => state.spaceship_shot(app_state.step()), _ => (), } } state.update(app_state.step()); fps_counter.update(); let win_size = window.size(); let mut pencil = Pencil::new(window.canvas_mut()); pencil.draw_text(&format!("FPS: {}", fps_counter.count()), Vec2::xy(1, 0)); if state.aliens.is_empty() || state.lives == 0 { let status_msg = if state.lives > 0 { "You win! :D" } else { "You lose :(" }; let msg = &format!("{} - score: {}", status_msg, state.score); pencil.set_origin(win_size / 2 - Vec2::x(msg.len() / 2)); pencil.draw_text(msg, Vec2::zero()); return (); } pencil.set_origin((win_size - state.dimension) / 2); pencil.draw_text( &format!("lives: {} - score: {}", state.lives, state.score), Vec2::xy(15, 0), ); pencil.set_foreground(Color::Cyan); pencil.draw_char('^', state.spaceship); pencil.draw_char('/', state.spaceship - Vec2::x(1)); pencil.draw_char('\\', state.spaceship + Vec2::x(1)); pencil.draw_char('\'', state.spaceship + Vec2::y(1)); pencil.set_foreground(Color::Red); for shot in &state.aliens_shots { pencil.draw_char('|', *shot); } pencil.set_foreground(Color::Green); for alien in &state.aliens { pencil.draw_char('W', *alien); } pencil.set_foreground(Color::Yellow); pencil.set_style(Style::Bold); for shot in &state.spaceship_shots { pencil.draw_char('|', *shot); } }); }
true
b15972d1044b1dc9f5d5f8453ffe6db81aaa46d3
Rust
goncalopalaio/raytracing_in_rust
/src/raytrace/camera.rs
UTF-8
2,027
3.0625
3
[]
no_license
use super::ray::Ray; use super::vec::Vec3; extern crate rand; use rand::Rng; pub fn drand48() -> f32 { let random_float: f32 = rand::thread_rng().gen(); random_float } pub struct Camera { origin: Vec3, lower_left_corner: Vec3, vertical: Vec3, horizontal: Vec3, u: Vec3, v: Vec3, w: Vec3, lens_radius: f32, } impl Camera { pub fn new( look_from: Vec3, look_at: Vec3, vup: Vec3, vfov: f32, aspect: f32, aperture: f32, focus_dist: f32, ) -> Self { let lens_radius = aperture / 2.0; let theta = vfov * std::f32::consts::PI / 180.0; let half_height = f32::tan(theta / 2.0); let half_width = aspect * half_height; let origin = look_from; let w = Vec3::make_unit_vector(look_from - look_at); let u = Vec3::make_unit_vector(Vec3::cross(vup, w)); let v = Vec3::cross(w, u); let mut lower_left_corner = Vec3::new(-half_width, -half_height, -1.0); lower_left_corner = origin - half_width * focus_dist * u - half_height * focus_dist * v - focus_dist * w; let horizontal = 2.0 * half_width * focus_dist * u; let vertical = 2.0 * half_height * focus_dist * v; Camera { origin, lower_left_corner, horizontal, vertical, u, v, w, lens_radius, } } pub fn get_ray(&self, u: f32, v: f32) -> Ray { let rd: Vec3 = self.lens_radius * random_in_unit_sphere(); let offset = self.u * rd.x() + self.v * rd.y(); Ray::new( self.origin + offset, self.lower_left_corner + u * self.horizontal + v * self.vertical - self.origin - offset, ) } } fn random_in_unit_sphere() -> Vec3 { let mut p: Vec3; while { p = 2.0 * Vec3::new(drand48(), drand48(), drand48()) - Vec3::new(1.0, 1.0, 1.0); p.squared_length() >= 1.0 } {} return p; }
true
3ad9cf2a4da9da9769e70303ba19564d0220c9e7
Rust
jps580393335/ThermalControl
/dbtest/src/main.rs
UTF-8
728
3.125
3
[]
no_license
use postgres::{Client, NoTls}; fn main() { let mut client = Client::connect("host=localhost user=postgres", NoTls).unwrap(); client.batch_execute(" CREATE TABLE person ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, data BYTEA ) ").unwrap(); let name = "Ferris"; let data = None::<&[u8]>; client.execute( "INSERT INTO person (name, data) VALUES ($1, $2)", &[&name, &data], ).unwrap(); for row in client.query("SELECT id, name, data FROM person", &[]).unwrap() { let id: i32 = row.get(0); let name: &str = row.get(1); let data: Option<&[u8]> = row.get(2); println!("found person: {} {} {:?}", id, name, data); } }
true
ec848088f9da108179f4675907a37d9d00bf0d13
Rust
Jaguar-515/foreman
/src/auth_store.rs
UTF-8
1,749
2.890625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::io; use serde::{Deserialize, Serialize}; use toml_edit::{value, Document}; use crate::{fs, paths}; pub static DEFAULT_AUTH_CONFIG: &str = include_str!("../resources/default-auth.toml"); /// Contains stored user tokens that Foreman can use to download tools. #[derive(Debug, Default, Serialize, Deserialize)] pub struct AuthStore { pub github: Option<String>, } impl AuthStore { pub fn load() -> io::Result<Self> { log::debug!("Loading auth store..."); match fs::read(paths::auth_store()) { Ok(contents) => { let store: AuthStore = toml::from_slice(&contents).unwrap(); if store.github.is_some() { log::debug!("Found GitHub credentials"); } else { log::debug!("Found no credentials"); } Ok(store) } Err(err) => { if err.kind() == io::ErrorKind::NotFound { return Ok(AuthStore::default()); } else { return Err(err); } } } } pub fn set_github_token(token: &str) -> io::Result<()> { let contents = match fs::read_to_string(paths::auth_store()) { Ok(contents) => contents, Err(err) => { if err.kind() == io::ErrorKind::NotFound { DEFAULT_AUTH_CONFIG.to_owned() } else { return Err(err); } } }; let mut store: Document = contents.parse().unwrap(); store["github"] = value(token); let serialized = store.to_string(); fs::write(paths::auth_store(), serialized) } }
true
37413ae2a19fdc2faf49581d7a4ee92cf3b5171d
Rust
Hizoul/tetris-link-research
/src/heuristics/tune.rs
UTF-8
1,924
2.59375
3
[]
no_license
use crate::game_logic::field::{GameField}; use crate::game_logic::field::helper_structs::{GameRules}; use crate::game_logic::field::rl::LearnHelper; use crate::game_logic::cache::ShapeCache; use std::sync::{Arc,RwLock}; use rayon::prelude::*; const SAMPLE_SIZE: u64 = 500; const EVALUATED_PLAYER_NUMBER: i8 = 0; const ENEMY_CONFIGS: [(f64, f64, f64, f64); 2] = [ (4.95238700733393,0.115980839099051,0.0603795891552745,19.0148438477953), (2.29754304265925,0.714950690441259,0.0203784890483687,4.26915982151196) ]; pub fn heuristic_evaluator(connectability_weight: f64, enemy_block_wheight: f64, touching_weight: f64, score_weight: f64) -> u64 { let mut final_score = 0; let shape_cache = Arc::new(ShapeCache::new()); let wins_per_config: Vec<u64> = ENEMY_CONFIGS.par_iter().map(|weight_configuration| { let wins: RwLock<u64> = RwLock::new(0); (0..SAMPLE_SIZE).into_par_iter().for_each(|_| { let mut field = GameField::new_with_cache(2, shape_cache.clone(), GameRules::deterministic()); while !field.game_over { let play_to_do = if field.current_player == EVALUATED_PLAYER_NUMBER { field.get_best_heuristic_play_for_params(connectability_weight, enemy_block_wheight, touching_weight, score_weight, true, 0) } else { field.get_best_heuristic_play_for_params(weight_configuration.0, weight_configuration.1, weight_configuration.2, weight_configuration.3, true, 0) }; field.place_block_using_play(play_to_do); } if field.get_winning_player() == EVALUATED_PLAYER_NUMBER { let mut writeable_wins = wins.write().unwrap(); *writeable_wins += 1; } }); let readable_wins = wins.read().unwrap(); *readable_wins }).collect(); for win_amount in wins_per_config { if win_amount > (SAMPLE_SIZE / 4) { final_score += win_amount; } } final_score }
true
de44602ccc26d48adaf913c73304cb953224bf19
Rust
iCodeIN/lin-rado-turing
/src/types.rs
UTF-8
8,278
3.25
3
[]
no_license
use crate::program::ProgramParseError; use std::{fmt::Debug, str::FromStr}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Direction { Left, Right, } impl FromStr for Direction { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "L" => Ok(Self::Left), "R" => Ok(Self::Right), s => Err(ProgramParseError::Error(format!( "Expected 'L' or 'R', found {}", s ))), } } } pub trait State: Ord + Eq + FromStr + Copy + Debug { const NUM_STATES: usize; fn initial_state() -> Self; fn iter_states() -> Box<dyn Iterator<Item = Self>>; fn halt() -> Self; } pub trait Symbol: Ord + Eq + FromStr + Copy + Debug + ToString { const NUM: usize; fn iter_symbols() -> Box<dyn Iterator<Item = Self>>; fn zero() -> Self; } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum TwoState { A, B, H, } impl FromStr for TwoState { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "A" => Ok(Self::A), "B" => Ok(Self::B), "H" => Ok(Self::H), a => Err(ProgramParseError::Error(format!( "Expected 'A', 'B', 'H' not {}", a ))), } } } impl State for TwoState { const NUM_STATES: usize = 2; fn initial_state() -> Self { Self::A } fn iter_states() -> Box<dyn Iterator<Item = Self>> { Box::new(vec![Self::A, Self::B].into_iter()) } fn halt() -> Self { Self::H } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum ThreeState { A, B, C, H, } impl FromStr for ThreeState { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "A" => Ok(Self::A), "B" => Ok(Self::B), "C" => Ok(Self::C), "H" => Ok(Self::H), a => Err(ProgramParseError::Error(format!( "Expected 'A', 'B', 'C', or 'H', found {}", a ))), } } } impl State for ThreeState { const NUM_STATES: usize = 3; fn initial_state() -> Self { Self::A } fn iter_states() -> Box<dyn Iterator<Item = Self>> { Box::new(vec![Self::A, Self::B, Self::C].into_iter()) } fn halt() -> Self { Self::H } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum FourState { A, B, C, D, H, } impl State for FourState { const NUM_STATES: usize = 4; fn initial_state() -> Self { Self::A } fn iter_states() -> Box<dyn Iterator<Item = Self>> { Box::new(vec![Self::A, Self::B, Self::C, Self::D].into_iter()) } fn halt() -> Self { Self::H } } impl FromStr for FourState { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "A" => Ok(Self::A), "B" => Ok(Self::B), "C" => Ok(Self::C), "D" => Ok(Self::D), "H" => Ok(Self::H), a => Err(ProgramParseError::Error(format!( "Expected 'A', 'B', 'C', 'D', 'H', found {}", a ))), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum TwoSymbol { Zero, One, } impl FromStr for TwoSymbol { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "0" => Ok(Self::Zero), "1" => Ok(Self::One), a => Err(ProgramParseError::Error(format!( "Expected '0' or '1', found {}", a ))), } } } impl Symbol for TwoSymbol { const NUM: usize = 2; fn iter_symbols() -> Box<dyn Iterator<Item = Self>> { Box::new(vec![Self::Zero, Self::One].into_iter()) } fn zero() -> Self { Self::Zero } } impl ToString for TwoSymbol { fn to_string(&self) -> String { match self { Self::One => "#", Self::Zero => "_", } .to_owned() } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum ThreeSymbol { Zero, One, Two, } impl Symbol for ThreeSymbol { const NUM: usize = 3; fn iter_symbols() -> Box<dyn Iterator<Item = Self>> { Box::new(vec![Self::Zero, Self::One, Self::Two].into_iter()) } fn zero() -> Self { Self::Zero } } impl ToString for ThreeSymbol { fn to_string(&self) -> String { match self { Self::Zero => "0", Self::One => "1", Self::Two => "2", } .to_owned() } } impl FromStr for ThreeSymbol { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "0" => Ok(Self::Zero), "1" => Ok(Self::One), "2" => Ok(Self::Two), a => Err(ProgramParseError::Error(format!( "Expected '0', '1', or '2', not {}", a ))), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum FiveState { A, B, C, D, E, H, } impl FromStr for FiveState { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "A" => Ok(Self::A), "B" => Ok(Self::B), "C" => Ok(Self::C), "D" => Ok(Self::D), "E" => Ok(Self::E), "H" => Ok(Self::H), a => Err(ProgramParseError::Error(format!( "Expecting 'A', 'B', 'C', 'D', 'E', or 'H', not {}", a ))), } } } impl State for FiveState { const NUM_STATES: usize = 5; fn initial_state() -> Self { Self::A } fn iter_states() -> Box<dyn Iterator<Item = Self>> { Box::new(vec![Self::A, Self::B, Self::C, Self::D, Self::E].into_iter()) } fn halt() -> Self { Self::H } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum SixState { A, B, C, D, E, F, H, } impl FromStr for SixState { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "A" => Ok(Self::A), "B" => Ok(Self::B), "C" => Ok(Self::C), "D" => Ok(Self::D), "E" => Ok(Self::E), "F" => Ok(Self::F), "H" => Ok(Self::H), a => Err(ProgramParseError::Error(format!( "Expecting 'A', 'B', 'C', 'D', 'E', or 'H', not {}", a ))), } } } impl State for SixState { const NUM_STATES: usize = 5; fn initial_state() -> Self { Self::A } fn iter_states() -> Box<dyn Iterator<Item = Self>> { Box::new(vec![Self::A, Self::B, Self::C, Self::D, Self::E, Self::F].into_iter()) } fn halt() -> Self { Self::H } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum FourSymbol { Zero, One, Two, Three, } impl Symbol for FourSymbol { const NUM: usize = 3; fn iter_symbols() -> Box<dyn Iterator<Item = Self>> { Box::new(vec![Self::Zero, Self::One, Self::Two, Self::Three].into_iter()) } fn zero() -> Self { Self::Zero } } impl FromStr for FourSymbol { type Err = ProgramParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "0" => Ok(Self::Zero), "1" => Ok(Self::One), "2" => Ok(Self::Two), "3" => Ok(Self::Three), a => Err(ProgramParseError::Error(format!( "Expected '0', '1', or '2', not {}", a ))), } } } impl ToString for FourSymbol { fn to_string(&self) -> String { match self { Self::Zero => "0", Self::One => "1", Self::Two => "2", Self::Three => "3", } .to_owned() } }
true
c7358a6987f53f4e0de4be0d849dbcd306104e2a
Rust
Connicpu/directx-rs
/dcommon/src/idltypes/bstr.rs
UTF-8
1,493
2.703125
3
[]
no_license
use winapi::shared::wtypes::BSTR; #[repr(transparent)] pub struct BStr { bstr: BSTR, } impl BStr { pub fn new(s: &str) -> BStr { let len = s.encode_utf16().count(); assert!(len <= std::u32::MAX as usize); unsafe { let bstr = SysAllocStringLen(0 as _, len as u32); let slice = std::slice::from_raw_parts_mut(bstr, len); for (dst, src) in slice.iter_mut().zip(s.encode_utf16()) { *dst = src; } BStr { bstr } } } pub unsafe fn from_raw(bstr: BSTR) -> Self { assert!(!bstr.is_null()); BStr { bstr } } pub unsafe fn get_raw(&self) -> BSTR { self.bstr } pub unsafe fn into_raw(self) -> BSTR { let bstr = self.get_raw(); std::mem::forget(self); bstr } pub fn len(&self) -> usize { unsafe { SysStringLen(self.bstr) as usize } } pub fn as_slice(&self) -> &[u16] { unsafe { std::slice::from_raw_parts(self.bstr, self.len()) } } } impl PartialEq for BStr { fn eq(&self, other: &BStr) -> bool { self.as_slice() == other.as_slice() } } impl Drop for BStr { fn drop(&mut self) { unsafe { let hr = SysFreeString(self.bstr); assert!(hr >= 0); } } } extern "system" { fn SysAllocStringLen(str_in: *const u16, ui: u32) -> BSTR; fn SysFreeString(b: BSTR) -> i32; fn SysStringLen(b: BSTR) -> u32; }
true
009cca9275888aadfbcf258960fc9adb127afe13
Rust
yayoc/leetcode
/src/longest_common_prefix.rs
UTF-8
1,771
3.78125
4
[]
no_license
// Write a function to find the longest common prefix string amongst an array of strings. // // If there is no common prefix, return an empty string "". // // Example 1: // // Input: ["flower","flow","flight"] // Output: "fl" // // Example 2: // // Input: ["dog","racecar","car"] // Output: "" // Explanation: There is no common prefix among the input strings. // // Note: // // All given inputs are in lowercase letters a-z. pub struct Solution1; pub trait Solution { fn longest_common_prefix(strs: Vec<String>) -> String; } impl Solution for Solution1 { fn longest_common_prefix(strs: Vec<String>) -> String { if strs.len() == 0 { return String::from(""); } let min_len = strs.iter().map(|s| s.len()).min().unwrap(); for i in 0..min_len { let ch = strs[0].chars().nth(i).unwrap(); for s in &strs { if s.chars().nth(i).unwrap() != ch { return s[0..i].to_string(); } } } strs[0][0..min_len].to_string() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_longest_common_prefix() { assert_eq!( "fl", Solution1::longest_common_prefix(vec!( String::from("flower"), String::from("flow"), String::from("flight") )) ); assert_eq!( "", Solution1::longest_common_prefix(vec!( String::from("dog"), String::from("racecar"), String::from("car") )) ); assert_eq!( "", Solution1::longest_common_prefix(vec!(String::from("aca"), String::from("cba"))) ) } }
true
08242f971d3f15e9763cc02f6269ceb5dbc2795c
Rust
poita66/lsd
/src/flags/color.rs
UTF-8
6,993
3.59375
4
[ "Apache-2.0" ]
permissive
//! This module defines the [Color]. To set it up from [ArgMatches], a [Yaml] and its [Default] //! value, use its [configure_from](Configurable::configure_from) method. use super::Configurable; use crate::config_file::Config; use clap::ArgMatches; use yaml_rust::Yaml; /// A collection of flags on how to use colors. #[derive(Clone, Debug, Copy, PartialEq, Eq, Default)] pub struct Color { /// When to use color. pub when: ColorOption, } impl Color { /// Get a `Color` struct from [ArgMatches], a [Config] or the [Default] values. /// /// The [ColorOption] is configured with their respective [Configurable] implementation. pub fn configure_from(matches: &ArgMatches, config: &Config) -> Self { let when = ColorOption::configure_from(matches, config); Self { when } } } /// The flag showing when to use colors in the output. #[derive(Clone, Debug, Copy, PartialEq, Eq)] pub enum ColorOption { Always, Auto, Never, } impl ColorOption { /// Get a Color value from a [Yaml] string. The [Config] is used to log warnings about wrong /// values in a Yaml. fn from_yaml_string(value: &str, config: &Config) -> Option<Self> { match value { "always" => Some(Self::Always), "auto" => Some(Self::Auto), "never" => Some(Self::Never), _ => { config.print_invalid_value_warning("color->when", &value); None } } } } impl Configurable<Self> for ColorOption { /// Get a potential `ColorOption` variant from [ArgMatches]. /// /// If the "classic" argument is passed, then this returns the [ColorOption::Never] variant in /// a [Some]. Otherwise if the argument is passed, this returns the variant corresponding to /// its parameter in a [Some]. Otherwise this returns [None]. fn from_arg_matches(matches: &ArgMatches) -> Option<Self> { if matches.is_present("classic") { Some(Self::Never) } else if matches.occurrences_of("color") > 0 { match matches.value_of("color") { Some("always") => Some(Self::Always), Some("auto") => Some(Self::Auto), Some("never") => Some(Self::Never), _ => panic!("This should not be reachable!"), } } else { None } } /// Get a potential `ColorOption` variant from a [Config]. /// /// If the Config's [Yaml] contains a [Boolean](Yaml::Boolean) value pointed to by "classic" /// and its value is `true`, then this returns the [ColorOption::Never] variant in a [Some]. /// Otherwise if the Yaml contains a [String](Yaml::String) value pointed to by "color" -> /// "when" and it is one of "always", "auto" or "never", this returns its corresponding variant /// in a [Some]. Otherwise this returns [None]. fn from_config(config: &Config) -> Option<Self> { if let Some(yaml) = &config.yaml { if let Yaml::Boolean(true) = &yaml["classic"] { Some(Self::Never) } else { match &yaml["color"]["when"] { Yaml::BadValue => None, Yaml::String(value) => Self::from_yaml_string(&value, &config), _ => { config.print_wrong_type_warning("color->when", "string"); None } } } } else { None } } } /// The default value for `ColorOption` is [ColorOption::Auto]. impl Default for ColorOption { fn default() -> Self { Self::Auto } } #[cfg(test)] mod test_color_option { use super::ColorOption; use crate::app; use crate::config_file::Config; use crate::flags::Configurable; use yaml_rust::YamlLoader; #[test] fn test_from_arg_matches_none() { let argv = vec!["lsd"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!(None, ColorOption::from_arg_matches(&matches)); } #[test] fn test_from_arg_matches_always() { let argv = vec!["lsd", "--color", "always"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(ColorOption::Always), ColorOption::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_autp() { let argv = vec!["lsd", "--color", "auto"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(ColorOption::Auto), ColorOption::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_never() { let argv = vec!["lsd", "--color", "never"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(ColorOption::Never), ColorOption::from_arg_matches(&matches) ); } #[test] fn test_from_arg_matches_classic_mode() { let argv = vec!["lsd", "--color", "always", "--classic"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(ColorOption::Never), ColorOption::from_arg_matches(&matches) ); } #[test] fn test_from_config_none() { assert_eq!(None, ColorOption::from_config(&Config::with_none())); } #[test] fn test_from_config_empty() { let yaml_string = "---"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!(None, ColorOption::from_config(&Config::with_yaml(yaml))); } #[test] fn test_from_config_always() { let yaml_string = "color:\n when: always"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(ColorOption::Always), ColorOption::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_auto() { let yaml_string = "color:\n when: auto"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(ColorOption::Auto), ColorOption::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_never() { let yaml_string = "color:\n when: never"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(ColorOption::Never), ColorOption::from_config(&Config::with_yaml(yaml)) ); } #[test] fn test_from_config_classic_mode() { let yaml_string = "classic: true\ncolor:\n when: always"; let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone(); assert_eq!( Some(ColorOption::Never), ColorOption::from_config(&Config::with_yaml(yaml)) ); } }
true
395be840d336975394316e79b1ca4fd08ee596a4
Rust
iCodeIN/srv
/src/ui/info.rs
UTF-8
20,612
2.59375
3
[ "MIT" ]
permissive
use std::{collections::HashMap, fmt, fmt::Write, sync::Arc}; use screeps_api::websocket::{ objects::{ ConstructionSite, Creep, KnownRoomObject, Mineral, Resource, Source, StructureContainer, StructureController, StructureExtension, StructureExtractor, StructureKeeperLair, StructureLab, StructureLink, StructureNuker, StructureObserver, StructurePortal, StructurePowerBank, StructurePowerSpawn, StructureRampart, StructureRoad, StructureSpawn, StructureStorage, StructureTerminal, StructureTower, StructureWall, Tombstone, }, resources::ResourceType, RoomUserInfo, }; use crate::room::{RoomObjectType, VisualObject}; pub fn info<T: Info + ?Sized>(thing: &T, state: &InfoInfo) -> String { let mut res = String::new(); thing .fmt(&mut res, state) .expect("formatting to string should not fail"); res } #[derive(Copy, Clone)] pub struct InfoInfo<'a> { game_time: u32, users: &'a HashMap<String, Arc<RoomUserInfo>>, } impl<'a> InfoInfo<'a> { pub fn new(game_time: u32, users: &'a HashMap<String, Arc<RoomUserInfo>>) -> Self { InfoInfo { game_time, users } } fn username(&self, id: &str) -> Option<&'a str> { self.users .get(id) .and_then(|i| i.username.as_ref()) .map(AsRef::as_ref) } fn username_or_fallback<'b>(&self, id: &'b str) -> OptionalUser<'b, 'a> { OptionalUser { id, username: self.username(id), } } } struct OptionalUser<'a, 'b> { id: &'a str, username: Option<&'b str>, } impl fmt::Display for OptionalUser<'_, '_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.username { Some(u) => write!(f, "{}", u), None => write!(f, "user {}", self.id), } } } pub trait Info { /// Formats self, including a trailing newline fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result; } impl<T: Info> Info for [T] { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { for obj in self { obj.fmt(out, state)?; } Ok(()) } } impl<T: Info> Info for Vec<T> { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { // defer to [T] self[..].fmt(out, state) } } impl Info for VisualObject { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { match self { VisualObject::InterestingTerrain { ty, .. } => writeln!(out, "terrain: {}", ty), VisualObject::Flag(f) => writeln!(out, "flag {}", f.name), VisualObject::RoomObject(obj) => obj.fmt(out, state), } } } impl Info for KnownRoomObject { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { match self { KnownRoomObject::Source(o) => o.fmt(out, state), KnownRoomObject::Mineral(o) => o.fmt(out, state), KnownRoomObject::Spawn(o) => o.fmt(out, state), KnownRoomObject::Extension(o) => o.fmt(out, state), KnownRoomObject::Extractor(o) => o.fmt(out, state), KnownRoomObject::Wall(o) => o.fmt(out, state), KnownRoomObject::Road(o) => o.fmt(out, state), KnownRoomObject::Rampart(o) => o.fmt(out, state), KnownRoomObject::KeeperLair(o) => o.fmt(out, state), KnownRoomObject::Controller(o) => o.fmt(out, state), KnownRoomObject::Portal(o) => o.fmt(out, state), KnownRoomObject::Link(o) => o.fmt(out, state), KnownRoomObject::Storage(o) => o.fmt(out, state), KnownRoomObject::Tower(o) => o.fmt(out, state), KnownRoomObject::Observer(o) => o.fmt(out, state), KnownRoomObject::PowerBank(o) => o.fmt(out, state), KnownRoomObject::PowerSpawn(o) => o.fmt(out, state), KnownRoomObject::Lab(o) => o.fmt(out, state), KnownRoomObject::Terminal(o) => o.fmt(out, state), KnownRoomObject::Container(o) => o.fmt(out, state), KnownRoomObject::Nuker(o) => o.fmt(out, state), KnownRoomObject::Tombstone(o) => o.fmt(out, state), KnownRoomObject::Creep(o) => o.fmt(out, state), KnownRoomObject::Resource(o) => o.fmt(out, state), KnownRoomObject::ConstructionSite(o) => o.fmt(out, state), other => { let ty = RoomObjectType::of(&other); let ty = string_morph::to_kebab_case(&format!("{:?}", ty)); writeln!(out, "{} {}", ty, other.id())?; Ok(()) } } } } impl Info for Source { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { writeln!(out, "source:")?; fmt_id(out, &self.id)?; fmt_energy(out, self.energy, self.energy_capacity as i32)?; if self.energy != self.energy_capacity { if let Some(gen_time) = self.next_regeneration_time { writeln!(out, " regen in: {}", gen_time - state.game_time)?; } } Ok(()) } } impl Info for Mineral { fn fmt<W: Write>(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result { writeln!( out, "mineral: {} {}", self.mineral_amount, kebab_of_debug(self.mineral_type) )?; fmt_id(out, &self.id)?; Ok(()) } } impl Info for StructureSpawn { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "spawn {}:", self.room)?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; fmt_energy(out, self.energy, self.energy_capacity)?; Ok(()) } } impl Info for StructureExtension { fn fmt<W: Write>(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result { writeln!(out, "extension:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; fmt_energy(out, self.energy, self.energy_capacity)?; Ok(()) } } impl Info for StructureExtractor { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_optional_user_prefix(out, &self.user, state)?; writeln!(out, "extractor:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; Ok(()) } } impl Info for StructureWall { fn fmt<W: Write>(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result { writeln!(out, "wall:")?; fmt_id(out, &self.id)?; fmt_hits_inf(out, self.hits, self.hits_max)?; Ok(()) } } impl Info for StructureRoad { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { writeln!(out, "road:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; writeln!(out, " decay in: {}", self.next_decay_time - state.game_time)?; Ok(()) } } impl Info for StructureRampart { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "rampart:")?; fmt_id(out, &self.id)?; fmt_hits_inf(out, self.hits, self.hits_max)?; writeln!(out, " decay in: {}", self.next_decay_time - state.game_time)?; if self.public { writeln!(out, " --public--")?; } else { writeln!(out, " --private--")?; } Ok(()) } } impl Info for StructureKeeperLair { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { writeln!(out, "keeper lair:")?; fmt_id(out, &self.id)?; if let Some(spawn_time) = self.next_spawn_time { writeln!(out, " spawning in: {}", spawn_time - state.game_time)?; } Ok(()) } } impl Info for StructureController { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_optional_user_prefix(out, &self.user, state)?; writeln!(out, "controller:")?; fmt_id(out, &self.id)?; if let Some(sign) = &self.sign { write!( out, "{}", textwrap::indent(&textwrap::fill(&sign.text, 30), " ") )?; // TODO: real time? writeln!( out, " - {} ({} ticks ago)", state.username_or_fallback(&sign.user_id), i64::from(state.game_time) - i64::from(sign.game_time_set) )?; } if self.user.is_some() { writeln!(out, " level: {}", self.level)?; if let Some(required) = self.progress_required() { let progress_percent = (required as f64 - self.progress as f64) / required as f64 * 100.0; writeln!(out, " progress: %{:.2}", progress_percent)?; } // TODO: red text for almost downgraded if let Some(time) = self.downgrade_time { // TODO: see what this data looks like? writeln!(out, " downgrade time: {}", time)?; } // TODO: only apply this to owned controllers, maybe? writeln!(out, " safemode:")?; if let Some(end_time) = self.safe_mode { if state.game_time < end_time { writeln!(out, " --safe mode active--")?; writeln!(out, " ends in: {}", end_time - state.game_time)?; } } writeln!(out, " available: {}", self.safe_mode_available)?; if self.safe_mode_cooldown > state.game_time { writeln!( out, " activation cooldown: {}", self.safe_mode_cooldown - state.game_time )?; } } if let Some(reservation) = &self.reservation { if reservation.end_time > state.game_time { writeln!( out, " reserved by {}", state.username_or_fallback(&reservation.user) )?; writeln!(out, " ends in {}", reservation.end_time - state.game_time)?; } } Ok(()) } } impl Info for StructurePortal { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_id(out, &self.id)?; writeln!( out, "portal -> {},{} in {}", self.destination.x, self.destination.y, self.destination.room )?; if let Some(_date) = self.unstable_date { // TODO: figure out time formatting writeln!(out, " stable (decay time is in days)")?; writeln!(out, " (time formatting unimplemented)")?; } if let Some(time) = self.decay_time { writeln!(out, " decays in {} ticks", time - state.game_time)?; } Ok(()) } } impl Info for StructureLink { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "link:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; fmt_energy(out, self.energy, self.energy_capacity)?; if self.cooldown != 0 { writeln!(out, " cooldown: {}", self.cooldown)?; } Ok(()) } } impl Info for StructureStorage { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "storage:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; writeln!( out, " capacity: {}/{}", self.resources().map(|(_, amt)| amt).sum::<i32>(), self.capacity )?; format_object_contents(out, self.resources())?; Ok(()) } } impl Info for StructureTower { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "tower:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; fmt_energy(out, self.energy, self.energy_capacity)?; Ok(()) } } impl Info for StructureObserver { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "observer:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; if let Some(name) = self.observed { writeln!(out, " observing {}", name)?; } Ok(()) } } impl Info for StructurePowerBank { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { writeln!(out, "power bank:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; writeln!(out, " power: {}", self.power)?; writeln!(out, " decay in: {}", self.decay_time - state.game_time)?; Ok(()) } } impl Info for StructurePowerSpawn { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "power spawn:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; fmt_energy(out, self.energy, self.energy_capacity)?; writeln!(out, " power: {}/{}", self.power, self.power_capacity)?; Ok(()) } } impl Info for StructureLab { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "lab:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; fmt_energy(out, self.energy, self.energy_capacity)?; match self.mineral_type { Some(ty) => { writeln!( out, " {}: {}/{}", kebab_of_debug(ty), self.mineral_amount, self.mineral_capacity )?; } None => { writeln!( out, " minerals: {}/{}", self.mineral_amount, self.mineral_capacity )?; } } if self.cooldown != 0 { writeln!(out, " cooldown: {}", self.cooldown)?; } Ok(()) } } impl Info for StructureTerminal { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "terminal:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; writeln!( out, " capacity: {}/{}", self.resources().map(|(_, amt)| amt).sum::<i32>(), self.capacity )?; format_object_contents(out, self.resources())?; Ok(()) } } impl Info for StructureContainer { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { writeln!(out, "container:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; writeln!(out, " decay in: {}", self.next_decay_time - state.game_time)?; writeln!( out, " capacity: {}/{}", self.resources().map(|(_, amt)| amt).sum::<i32>(), self.capacity )?; format_object_contents(out, self.resources())?; Ok(()) } } impl Info for StructureNuker { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "nuker:")?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; fmt_disabled(out, self.disabled)?; fmt_energy(out, self.energy, self.energy_capacity as i32)?; writeln!(out, " ghodium: {}/{}", self.ghodium, self.ghodium_capacity)?; if self.cooldown_time < state.game_time { writeln!(out, " --ready--")?; } else { writeln!(out, " cooldown: {}", self.cooldown_time - state.game_time)?; } Ok(()) } } impl Info for Tombstone { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "tombstone:")?; fmt_id(out, &self.id)?; writeln!(out, " died: {}", state.game_time - self.death_time)?; writeln!(out, " decay: {}", self.decay_time - state.game_time)?; writeln!(out, " creep:")?; writeln!(out, " id: {}", self.creep_id)?; writeln!(out, " name: {}", self.creep_name)?; writeln!(out, " ttl: {}", self.creep_ticks_to_live)?; format_object_contents(out, self.resources())?; Ok(()) } } impl Info for Creep { fn fmt<W: Write>(&self, out: &mut W, state: &InfoInfo) -> fmt::Result { fmt_user_prefix(out, &self.user, state)?; writeln!(out, "creep {}:", self.name)?; fmt_id(out, &self.id)?; fmt_hits(out, self.hits, self.hits_max)?; if self.fatigue != 0 { writeln!(out, " fatigue: {}", self.fatigue)?; } if let Some(age_time) = self.age_time { writeln!(out, " life: {}", age_time - state.game_time)?; } if self.capacity > 0 { writeln!( out, " capacity: {}/{}", self.carry_contents().map(|(_, amt)| amt).sum::<i32>(), self.capacity )?; format_object_contents(out, self.carry_contents())?; } Ok(()) } } impl Info for Resource { fn fmt<W: Write>(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result { writeln!( out, "dropped: {} {}", self.amount, kebab_of_debug(self.resource_type) )?; Ok(()) } } impl Info for ConstructionSite { fn fmt<W: Write>(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result { writeln!( out, "constructing {}:", kebab_of_debug(&self.structure_type) )?; writeln!(out, " progress: {}/{}", self.progress, self.progress_total)?; if let Some(name) = &self.name { writeln!(out, " name: {}", name)?; } Ok(()) } } fn fmt_optional_user_prefix<W: Write>( out: &mut W, user_id: &Option<String>, state: &InfoInfo, ) -> fmt::Result { if let Some(user_id) = user_id { fmt_user_prefix(out, user_id, state)?; } Ok(()) } fn fmt_user_prefix<W: Write>(out: &mut W, user_id: &str, state: &InfoInfo) -> fmt::Result { write!(out, "[{}] ", state.username_or_fallback(user_id)) } fn fmt_id<W: Write>(out: &mut W, id: &str) -> fmt::Result { writeln!(out, " id: {}", id) } fn fmt_hits<W: Write>(out: &mut W, hits: i32, hits_max: i32) -> fmt::Result { writeln!(out, " hits: {}/{}", hits, hits_max) } fn fmt_hits_inf<W: Write>(out: &mut W, hits: i32, hits_max: i32) -> fmt::Result { if f64::from(hits) > f64::from(hits_max) * 0.9 { fmt_hits(out, hits, hits_max) } else { writeln!(out, "hits: {}", hits) } } fn fmt_energy<W: Write>(out: &mut W, energy: i32, energy_capacity: i32) -> fmt::Result { writeln!(out, " energy: {}/{}", energy, energy_capacity) } fn fmt_disabled<W: Write>(out: &mut W, disabled: bool) -> fmt::Result { if disabled { writeln!(out, " --disabled--")?; } Ok(()) } fn kebab_of_debug<T: fmt::Debug>(item: T) -> String { string_morph::to_kebab_case(&format!("{:?}", item)) } fn format_object_contents<W, T>(out: &mut W, contents: T) -> fmt::Result where W: fmt::Write, T: Iterator<Item = (ResourceType, i32)>, { for (ty, amount) in contents { if amount > 0 { writeln!(out, " {}: {}", kebab_of_debug(ty), amount)?; } } Ok(()) }
true
c03883aed6f89bf5c0a12751f54b21648fe4ce27
Rust
TurkeyMcMac/vec-rac
/src/main.rs
UTF-8
7,676
2.5625
3
[ "MIT" ]
permissive
extern crate getopts; extern crate rayon; use getopts::Options; use rayon::{prelude::*, ThreadPoolBuilder}; use std::env; use std::iter; use std::process; use std::str::FromStr; use std::sync::mpsc; use std::thread; use std::time::{Duration, SystemTime}; use vec_rac::brain::Brain; use vec_rac::racetrack::Racetrack; use vec_rac::rng::Rng; use vec_rac::vector::Vector; fn options() -> Options { let mut opts = Options::new(); opts.optflag("h", "help", "Print this help information."); opts.optflag("v", "version", "Print version information."); opts.optopt( "", "view-dist", "Set how far a racer can see in each cardinal direction. This is a positive integer. The default is 20. This cannot be more than display-dist.", "DISTANCE", ); opts.optopt( "", "display-dist", "Set how far you can see in each cardinal direction. This is a positive integer. The default is 20. This cannot be less than view-dist.", "DISTANCE", ); opts.optopt( "", "path-radius", "Set track path radius. This is a positive integer. The default is 4.", "RADIUS", ); opts.optopt( "", "seed", "Set random seed to use. This is a positive integer. The default is decided randomly.", "SEED", ); opts.optopt( "", "population", "Set genome population size. This is a positive integer. It may be rounded a bit. The default is 10.", "SIZE", ); opts.optopt( "", "mutation", "Set mutation rate, a positive decimal. The default is 0.05.", "RATE", ); opts.optopt( "", "testing-threads", "Set the number of threads to use to continuously test AIs. This is a positive integer. The default is probably the number of cores the computer has.", "COUNT", ); opts } fn print_help(opts: &Options) -> String { let name = env::args().nth(0).unwrap_or("(anonymous)".to_string()); format!( "{}\n\n{}\n", opts.short_usage(&name), opts.usage("Simulate vector racers.") ) } fn main() { let opts = options(); let matches = opts.parse(env::args()).unwrap_or_else(|err| { eprint!("{}\n\n{}", err, print_help(&opts)); process::exit(1) }); if matches.opt_present("help") { print!("{}", print_help(&opts)); process::exit(0); } else if matches.opt_present("version") { println!("vec-rac version 0.4.2"); process::exit(0); } let view_dist = matches .opt_str("view-dist") .and_then(|arg| i32::from_str(&arg).ok()); let display_dist = matches .opt_str("display-dist") .and_then(|arg| i32::from_str(&arg).ok()); let (view_dist, display_dist) = match (view_dist, display_dist) { (Some(v), Some(d)) => (v, i32::max(v, d)), (Some(v), None) => (v, v), (None, Some(d)) => (d, d), (None, None) => (20, 20), }; let view_dist = i32::max(1, view_dist); let display_dist = i32::max(1, display_dist); let path_radius = matches .opt_str("path-radius") .and_then(|arg| i32::from_str(&arg).ok()) .unwrap_or(4); let seed = matches .opt_str("seed") .and_then(|arg| u64::from_str(&arg).ok()) .unwrap_or_else(|| { // Seed the RNG from the system time now. SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) }); let population = matches .opt_str("population") .and_then(|arg| usize::from_str(&arg).ok()) .map(|pop| { if pop == 0 { 2 } else if pop & 1 == 1 { pop + 1 } else { pop } }) .unwrap_or(10); let mutation = matches .opt_str("mutation") .and_then(|arg| f64::from_str(&arg).ok()) .unwrap_or(0.05); matches .opt_str("testing-threads") .and_then(|arg| usize::from_str(&arg).ok()) .map(|count| { ThreadPoolBuilder::new() .num_threads(count) .build_global() .unwrap() }); let mut rng = Rng::with_seed(seed + 17); let track_builder = Racetrack::builder().path_radius(path_radius).seed(seed); let track = track_builder.clone().view_dist(view_dist).build(); let mut brains = iter::repeat_with(|| Brain::random(view_dist, &mut rng)) .take(population) .collect::<Vec<_>>(); let mut max_max_score = 0; let (tx, rx) = mpsc::channel(); thread::spawn(move || { let displayed_track = track_builder.view_dist(display_dist).build(); for brain in rx { print!("\x07"); test_brain(&brain, &displayed_track, true); } }); loop { let mut results = brains .par_iter() .map(|brain| (brain.clone(), test_brain(brain, &track, false))) .collect::<Vec<_>>(); results.sort_by(|(_, (score_a, time_a)), (_, (score_b, time_b))| { score_b.cmp(&score_a).then(time_b.cmp(&time_a)) }); results.truncate(population / 2); let max_score = (results[0].1).0; if max_score > max_max_score { max_max_score = max_score; tx.send(results[0].0.clone()).unwrap(); } brains.clear(); for (brain, _) in results.into_iter() { brains.push(brain.mutant(&mut rng, mutation)); brains.push(brain); } } } fn clear_terminal() { print!("\x1b[H\x1b[J"); } fn draw_track(track: &Racetrack) { let view_dist = track.view_dist(); clear_terminal(); for y in (-view_dist..=view_dist).rev() { for x in -view_dist..=view_dist { let pos = Vector::new(x, y); let c = if pos == Vector::ORIGIN { '@' } else if let Some(true) = track.get(pos) { '.' } else { ' ' }; print!("{}", c); } print!("\n"); } } fn test_brain(brain: &Brain, track: &Racetrack, show: bool) -> (i32, usize) { let mut track = track.clone(); let mut time = 0usize; let mut vel = Vector::ORIGIN; let mut pos = Vector::ORIGIN; let mut max_score = 0; let mut since_improved = 0; track.translate(Vector::ORIGIN); 'tick_loop: loop { vel = vel + brain.compute_accel(vel, &track); for pt in Vector::ORIGIN.segment_pts(vel) { if let Some(false) = track.get(pt) { if show { track.translate(pt); } else { pos = pos + pt; } break 'tick_loop; } } pos = pos + vel; if pos.y > max_score { max_score = pos.y; since_improved = 0; } else if since_improved > 50 { break 'tick_loop; } else { since_improved += 1; } track.translate(vel); time = time.saturating_add(1); if show { draw_track(&track); println!("score: {} velocity: {}", pos.y, vel); thread::sleep(Duration::from_millis(50)); } if let Some(false) = track.get(Vector::ORIGIN) { break 'tick_loop; } } if show { draw_track(&track); println!("max score: {}", pos.y); thread::sleep(Duration::from_millis(150)); } (pos.y, time) }
true
4bda801613f5e4aa62d7f43f0c75007b81e18038
Rust
sergey-melnychuk/parsed
/src/parser.rs
UTF-8
11,103
2.84375
3
[ "MIT" ]
permissive
pub use crate::matcher::{Matcher, MatchError, unit}; use crate::stream::ByteStream; use std::marker::PhantomData; pub struct Save<M, T, U, F> { matcher: M, func: F, phantom: PhantomData<(T, U)>, } impl<M, T, U, F> Matcher<T> for Save<M, T, U, F> where M: Matcher<(T, U)>, F: Fn(&mut T, U), { fn do_match(&self, bs: &mut ByteStream) -> Result<T, MatchError> { let (mut t, u) = self.matcher.do_match(bs)?; (self.func)(&mut t, u); Ok(t) } } pub struct Skip<M, T, U> { matcher: M, phantom: PhantomData<(T, U)>, } impl<M, T, U> Matcher<T> for Skip<M, T, U> where M: Matcher<(T, U)>, { fn do_match(&self, bs: &mut ByteStream) -> Result<T, MatchError> { let (t, _u) = self.matcher.do_match(bs)?; Ok(t) } } pub trait ParserExt<T, U>: Sized { fn save<F: Fn(&mut T, U) + 'static>(self, f: F) -> Save<Self, T, U, F>; fn skip(self) -> Skip<Self, T, U>; } impl<M, T, U> ParserExt<T, U> for M where M: Matcher<(T, U)> + Sized { fn save<F: Fn(&mut T, U) + 'static>(self, f: F) -> Save<Self, T, U, F> { Save { matcher: self, func: f, phantom: PhantomData::<(T, U)>, } } fn skip(self) -> Skip<Self, T, U> { Skip { matcher: self, phantom: PhantomData::<(T, U)>, } } } pub fn one(b: u8) -> impl Matcher<u8> { move |bs: &mut ByteStream| { let pos = bs.pos(); bs.next().filter(|x| *x == b).ok_or(MatchError::unexpected( pos, "EOF".to_string(), format!("byte {}", b), )) } } pub fn single(chr: char) -> impl Matcher<char> { move |bs: &mut ByteStream| { let pos = bs.pos(); bs.next() .map(|b| b as char) .filter(|c| *c == chr) .ok_or(MatchError::unexpected( pos, "EOF".to_string(), format!("char '{}'", chr), )) } } pub fn repeat<T: 'static>(this: impl Matcher<T>) -> impl Matcher<Vec<T>> { move |bs: &mut ByteStream| { let mut acc: Vec<T> = vec![]; loop { let mark = bs.mark(); match this.do_match(bs) { Err(_) => { bs.reset(mark); return Ok(acc); } Ok(t) => acc.push(t), } } } } pub fn times<T: 'static>(count: usize, this: impl Matcher<T>) -> impl Matcher<Vec<T>> { move |bs: &mut ByteStream| { let mut acc: Vec<T> = vec![]; let mark = bs.mark(); loop { match this.do_match(bs) { Ok(item) => { acc.push(item); }, err => { bs.reset(mark); return err.map(|_| vec![]); } } if acc.len() >= count { return Ok(acc); } } } } pub fn maybe<T: 'static>(this: impl Matcher<T>) -> impl Matcher<Option<T>> { move |bs: &mut ByteStream| { let mark = bs.mark(); match this.do_match(bs) { Ok(m) => Ok(Some(m)), Err(_) => { bs.reset(mark); Ok(None) } } } } pub fn until<F: Fn(u8) -> bool + 'static>(f: F) -> impl Matcher<Vec<u8>> { move |bs: &mut ByteStream| { let mut acc = vec![]; loop { let mark = bs.mark(); match bs.next() { Some(b) if f(b) => acc.push(b), Some(_) => { bs.reset(mark); return Ok(acc); }, _ => return Err(MatchError::over_capacity( bs.pos(), bs.len(), 1)) } } } } pub fn before(chr: char) -> impl Matcher<Vec<u8>> { move |bs: &mut ByteStream| { let pos = bs.pos(); bs.find_single(|c| *c == chr as u8) .map(|idx| idx - pos) .and_then(|len| bs.get(len)) .ok_or(MatchError::over_capacity(pos, bs.len(), 1)) } } pub fn token() -> impl Matcher<String> { before(' ').map(|vec| vec.into_iter().map(|b| b as char).collect::<String>()) } pub fn exact(slice: &'static [u8]) -> impl Matcher<Vec<u8>> { move |bs: &mut ByteStream| { let mark = bs.mark(); let mut acc = vec![]; for i in 0..slice.len() { let b = slice[i]; let s = single(b as char); match s.do_match(bs) { Ok(b) => acc.push(b), Err(e) => { bs.reset(mark); return Err(e); } } } Ok(acc.into_iter().map(|c| c as u8).collect()) } } pub fn string(s: &'static str) -> impl Matcher<String> { move |bs: &mut ByteStream| { let m = exact(s.as_bytes()); let mark = bs.mark(); match m.do_match(bs) { Ok(vec) => Ok(String::from_utf8(vec).unwrap()), Err(e) => { bs.reset(mark); return Err(e); } } } } pub fn space() -> impl Matcher<Vec<char>> { move |bs: &mut ByteStream| { let f: fn(u8) -> bool = |b| (b as char).is_whitespace(); match until(f).do_match(bs) { Ok(vec) => Ok(vec.into_iter().map(|b| b as char).collect()), Err(e) => Err(e), } } } pub fn bytes(len: usize) -> impl Matcher<Vec<u8>> { move |bs: &mut ByteStream| { bs.get(len) .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), len)) } } pub fn get_u8() -> impl Matcher<u8> { move |bs: &mut ByteStream| { bs.get_u8() .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 1)) } } pub fn get_u16() -> impl Matcher<u16> { move |bs: &mut ByteStream| { bs.get_u16() .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 2)) } } pub fn get_u32() -> impl Matcher<u32> { move |bs: &mut ByteStream| { bs.get_u32() .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 4)) } } pub fn get_u64() -> impl Matcher<u64> { move |bs: &mut ByteStream| { bs.get_u64() .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 8)) } } pub fn get_16() -> impl Matcher<[u8; 16]> { move |bs: &mut ByteStream| { bs.get_16() .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 16)) } } pub fn get_32() -> impl Matcher<[u8; 32]> { move |bs: &mut ByteStream| { bs.get_32() .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 32)) } } pub trait Applicator { fn apply<T>(&mut self, parser: impl Matcher<T>) -> Result<T, MatchError>; } impl Applicator for ByteStream { fn apply<T>(&mut self, parser: impl Matcher<T>) -> Result<T, MatchError> { parser.do_match(self) } } #[cfg(test)] mod tests { use super::*; #[test] fn simple() { #[derive(Debug, Eq, PartialEq)] enum Token { KV { k: char, v: char }, } struct TokenBuilder { k: Option<char>, v: Option<char>, } impl TokenBuilder { fn zero() -> TokenBuilder { TokenBuilder { k: None, v: None } } } let mut bs: ByteStream = "abc".to_string().into(); let m = unit(|| TokenBuilder::zero()) .then_map(single('a'), |(tb, a)| TokenBuilder { k: Some(a), ..tb }) .then_map(single('b'), |(tb, b)| TokenBuilder { v: Some(b), ..tb }) .map(|tb| Token::KV { k: tb.k.unwrap(), v: tb.v.unwrap(), }); assert_eq!(bs.apply(m).unwrap(), Token::KV { k: 'a', v: 'b' }); assert_eq!(bs.pos(), 2); } #[test] fn list() { let mut bs: ByteStream = "abccc".to_string().into(); let c = single('c'); let abccc = unit(|| vec![]) .then_map(single('a'), |(acc, a)| { let mut copy = acc.clone(); copy.push(a); copy }) .then_map(single('b'), |(acc, b)| { let mut copy = acc.clone(); copy.push(b); copy }) .then_map(repeat(c), |(acc, vec)| { let mut copy = acc; for item in vec { copy.push(item); } copy }); assert_eq!(bs.apply(abccc).unwrap(), vec!['a', 'b', 'c', 'c', 'c']); assert_eq!(bs.pos(), 5); } #[test] fn until() { let mut bs: ByteStream = "asdasdasdasd1".to_string().into(); let until1 = unit(|| ()) .then_map(before('1'), |(_, vec)| { vec.into_iter().map(|b| b as char).collect::<String>() }) .then_map(single('1'), |(vec, one)| (vec, one)); assert_eq!(bs.apply(until1).unwrap(), ("asdasdasdasd".to_string(), '1')); } #[test] fn chunks() { let mut bs: ByteStream = "asdasdqqq123123token1 token2\n".to_string().into(); let m = unit(|| vec![]) .then(exact("asd".as_bytes())) .map(|(mut vec, bs)| { vec.push(bs.into_iter().map(|b| b as char).collect::<String>()); vec }) .then(exact("asdqqq".as_bytes())) .map(|(mut vec, bs)| { vec.push(bs.into_iter().map(|b| b as char).collect::<String>()); vec }) .then(exact("123123".as_bytes())) .map(|(mut vec, bs)| { vec.push(bs.into_iter().map(|b| b as char).collect::<String>()); vec }) .then(token()) .map(|(mut vec, bs)| { vec.push(bs); vec }) .then(before('\n')) .map(|(mut vec, bs)| { vec.push(bs.into_iter().map(|b| b as char).collect::<String>()); vec }); assert_eq!( bs.apply(m).unwrap(), vec![ "asd".to_string(), "asdqqq".to_string(), "123123".to_string(), "token1".to_string(), " token2".to_string(), ] ); } #[test] fn test_times_ok() { let mut bs = ByteStream::wrap(b"012301230123".to_vec()); let m = unit(|| ()) .then(times(3, exact(b"0123"))) .map(|(_, times)| times); assert_eq!( bs.apply(m).unwrap(), vec![ b"0123", b"0123", b"0123", ] ); } #[test] fn test_times_mismatch() { let mut bs = ByteStream::wrap(b"0123012301AA".to_vec()); let m = unit(|| vec![]) .then(times(3, exact(b"0123"))) .save(|vec, times| *vec = times); assert!(bs.apply(m).is_err()); } }
true
5943c3238ac29ff213eae55862ed5f0474247217
Rust
pedantic79/Exercism
/rust/atbash-cipher/src/lib.rs
UTF-8
1,917
3.21875
3
[]
no_license
use std::iter::{from_fn, once}; /// "Encipher" with the Atbash cipher. pub fn encode(plain: &str) -> String { split_from_fn(at_bash(plain)) } /// "Decipher" with the Atbash cipher. pub fn decode(cipher: &str) -> String { at_bash(cipher).collect() } fn at_bash(s: &str) -> impl Iterator<Item = char> + '_ { s.bytes().filter(|c| c.is_ascii_alphanumeric()).map(|c| { if c.is_ascii_digit() { c } else { b'a' + b'z' - c.to_ascii_lowercase() } .into() }) } /// split_flat_map is public so I can run benchmarks /// flat_map 12: 224ns (R²=1.000, 4685942 iterations in 136 samples) /// flat_map 48: 625ns (R²=0.994, 1806626 iterations in 126 samples) /// flat_map 252: 1us 888ns (R²=0.995, 575638 iterations in 114 samples) /// flat_map 1024: 5us 739ns (R²=0.999, 183408 iterations in 102 samples) pub fn split_flat_map(itr: impl Iterator<Item = char>) -> String { itr.enumerate() .flat_map(|(idx, c)| { if idx % 5 == 0 && idx > 0 { Some(' ') } else { None } .into_iter() .chain(once(c)) }) .collect() } /// split_from_fn is public so I can run benchmarks /// from_fn 12: 188ns (R²=1.000, 5669992 iterations in 138 samples) /// from_fn 48: 441ns (R²=0.996, 2404623 iterations in 129 samples) /// from_fn 252: 965ns (R²=1.000, 1121768 iterations in 121 samples) /// from_fn 1024: 2us 444ns (R²=1.000, 432483 iterations in 111 samples) pub fn split_from_fn(iter: impl Iterator<Item = char>) -> String { let mut count = 0; let mut iter = iter.peekable(); from_fn(|| { if count == 5 && iter.peek().is_some() { count = 0; Some(' ') } else { count += 1; iter.next() } }) .collect() }
true
3dad82b1b1d08c14f2acd7005d1239265e57863f
Rust
yangqiong/leetcode
/rust/src/e118_pascals_triangle.rs
UTF-8
926
3.359375
3
[]
no_license
// https://leetcode.cn/problems/pascals-triangle/ // 给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。 use std::result; struct Solution {} impl Solution { pub fn generate(num_rows: i32) -> Vec<Vec<i32>> { let mut result: Vec<Vec<i32>> = vec![]; for i in 0..num_rows { match i { 0 => { result.push(vec![1]); } 1 => { result.push(vec![1, 1]); } _ => { let mut nums = vec![1]; let last_nums = &result[(i - 1) as usize]; for j in 0..(last_nums.len() - 1) { nums.push(last_nums[j] + last_nums[j + 1]); } nums.push(1); result.push(nums) } } } result } }
true
01ce4c055791e08e3e16a0295b69620e39552df5
Rust
krak3n/Rust101
/constants/src/main.rs
UTF-8
526
3.109375
3
[]
no_license
// must give it a type - no fixed memory address // const cannot be muteable const FOO: u8 = 42; // another way - fixed memory address static BAR: u8 = 123; // mutable constants !? static mut FIZZ: i32 = 345; fn main() { println!("{}", FOO); println!("{}", BAR); // must be unsafe to use FIZZ because FIZZ is not thread // safe since anything at anytime could be reading // and writting from it unsafe { println!("{}", FIZZ); FIZZ = 678; // eep println!("{}", FIZZ); } }
true
57cdd5339a003dc8f4b153c4f3fb680cb4069e5f
Rust
divvun/kbdgen
/src/build/windows/klc/ligature.rs
UTF-8
810
2.875
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::fmt::Display; pub struct KlcLigature { pub rows: Vec<KlcLigatureRow>, } impl Display for KlcLigature { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.rows.is_empty() { return Ok(()); } f.write_str("LIGATURE\n\n")?; for ligature in &self.rows { f.write_fmt(format_args!( "{}\t{}", ligature.virtual_key, ligature.shift_state ))?; for utf16 in &ligature.utf16s { f.write_fmt(format_args!("\t{:04x}", utf16))?; } f.write_str("\n")?; } f.write_str("\n")?; Ok(()) } } pub struct KlcLigatureRow { pub virtual_key: String, pub shift_state: String, pub utf16s: Vec<u16>, }
true
67d5f79816429a7a2590e5d6776005d1df656372
Rust
kotlin2018/learn_rust
/tests/chapter_collection.rs
UTF-8
1,684
4.3125
4
[]
no_license
#[cfg(test)] mod test{ #[derive(Debug,Default)] struct Student{ pub name: Option<String>, pub age: Option<i32>, pub gender: Option<bool>, } /// 在循环中使用 Vector (动态数组) #[test] fn test_vec_mut(){ let mut students = Vec::<Student>::new(); let mut student_vec = Vec::<Student>::new(); students.push(Student{ name: Some("小明".to_string()), age: Some(18), gender: Some(true), }); students.push(Student{ name: Some("小红".to_string()), age: Some(20), gender: Some(false), }); /// 这个循环要 消费掉 每个遍历到的元素 for mut student in students{ student.name = Some("韩信".to_string()); student.age = Some(25); student.gender = Some(true); student_vec.push(student) }; println!("student_vec = {:?}",student_vec); } /// 只有对象的实例是可变的,才能定义它的引用是可变的。(只能获取可变对象的可变引用,不能获取不可变对象的可变引用) #[test] fn test_borrow_and_borrow_mut(){ /// 只有对象的实例是可变的,才能定义它的引用是可变的。(只能获取可变对象的可变引用,不能获取不可变对象的可变引用) //let student = Student::default(); //let student_borrow_mut = &mut student;// Error: 只有 Student 的实例 student 是 mut(可变的),才能定义它的引用是可变的 let mut student = Student::default(); let student_mut = &mut student; } }
true
e80934404a36404e9a431797fae3a96618c0bd20
Rust
ShadowJonathan/utils
/pkcs8/src/private_key_info.rs
UTF-8
4,126
2.8125
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! PKCS#8 `PrivateKeyInfo`. use core::{convert::TryFrom, fmt}; use der::{Decodable, Encodable, Message}; #[cfg(feature = "pem")] use {crate::pem, zeroize::Zeroizing}; #[cfg(feature = "encryption")] use { crate::EncryptedPrivateKeyDocument, rand_core::{CryptoRng, RngCore}, }; #[cfg(feature = "alloc")] use crate::PrivateKeyDocument; use crate::{AlgorithmIdentifier, Error, Result}; /// RFC 5208 designates `0` as the only valid version for PKCS#8 documents const VERSION: u8 = 0; /// PKCS#8 `PrivateKeyInfo`. /// /// ASN.1 structure containing an [`AlgorithmIdentifier`] and private key /// data in an algorithm specific format. /// /// Described in [RFC 5208 Section 5]: /// /// ```text /// PrivateKeyInfo ::= SEQUENCE { /// version Version, /// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, /// privateKey PrivateKey, /// attributes [0] IMPLICIT Attributes OPTIONAL } /// /// Version ::= INTEGER /// /// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier /// /// PrivateKey ::= OCTET STRING /// /// Attributes ::= SET OF Attribute /// ``` /// /// [RFC 5208 Section 5]: https://tools.ietf.org/html/rfc5208#section-5 #[derive(Clone)] pub struct PrivateKeyInfo<'a> { /// X.509 [`AlgorithmIdentifier`] for the private key type pub algorithm: AlgorithmIdentifier<'a>, /// Private key data pub private_key: &'a [u8], // TODO(tarcieri): support for `Attributes` (are they used in practice?) // PKCS#9 describes the possible attributes: https://tools.ietf.org/html/rfc2985 // Workaround for stripping attributes: https://stackoverflow.com/a/48039151 } impl<'a> PrivateKeyInfo<'a> { /// Encrypt this private key using a symmetric encryption key derived /// from the provided password. #[cfg(feature = "encryption")] #[cfg_attr(docsrs, doc(cfg(feature = "encryption")))] pub fn encrypt( &self, rng: impl CryptoRng + RngCore, password: impl AsRef<[u8]>, ) -> Result<EncryptedPrivateKeyDocument> { PrivateKeyDocument::from(self).encrypt(rng, password) } /// Encode this [`PrivateKeyInfo`] as ASN.1 DER. #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub fn to_der(&self) -> PrivateKeyDocument { self.into() } /// Encode this [`PrivateKeyInfo`] as PEM-encoded ASN.1 DER. #[cfg(feature = "pem")] #[cfg_attr(docsrs, doc(cfg(feature = "pem")))] pub fn to_pem(&self) -> Zeroizing<alloc::string::String> { Zeroizing::new(pem::encode( self.to_der().as_ref(), pem::PRIVATE_KEY_BOUNDARY, )) } } impl<'a> TryFrom<&'a [u8]> for PrivateKeyInfo<'a> { type Error = Error; fn try_from(bytes: &'a [u8]) -> Result<Self> { Ok(Self::from_der(bytes)?) } } impl<'a> TryFrom<der::Any<'a>> for PrivateKeyInfo<'a> { type Error = der::Error; fn try_from(any: der::Any<'a>) -> der::Result<PrivateKeyInfo<'a>> { any.sequence(|decoder| { // Parse and validate `version` INTEGER. if u8::decode(decoder)? != VERSION { return Err(der::ErrorKind::Value { tag: der::Tag::Integer, } .into()); } let algorithm = decoder.decode()?; let private_key = decoder.octet_string()?.into(); Ok(Self { algorithm, private_key, }) }) } } impl<'a> Message<'a> for PrivateKeyInfo<'a> { fn fields<F, T>(&self, f: F) -> der::Result<T> where F: FnOnce(&[&dyn Encodable]) -> der::Result<T>, { f(&[ &VERSION, &self.algorithm, &der::OctetString::new(self.private_key)?, ]) } } impl<'a> fmt::Debug for PrivateKeyInfo<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PrivateKeyInfo") .field("algorithm", &self.algorithm) .finish() // TODO(tarcieri): use `finish_non_exhaustive` when stable } }
true
28676fefadc8748b3ef84e26b99ab01d966f0c77
Rust
Tarv3/gc_dynamic
/src/evec.rs
UTF-8
3,030
3.875
4
[]
no_license
use std::mem; use std::ops::{Index, IndexMut}; #[derive(Debug, Clone)] pub struct Evec<T> { pub values: Vec<Option<T>>, pub available: Vec<usize>, } impl<T> Evec<T> { pub fn new() -> Evec<T> { Evec { values: Vec::new(), available: Vec::new(), } } pub fn from(vec: Vec<T>) -> Evec<T> { let capacity = vec.capacity(); let mut values = Vec::with_capacity(capacity); for value in vec { values.push(Some(value)); } Evec { values, available: Vec::with_capacity(capacity), } } pub fn from_option_vec(vec: Vec<Option<T>>) -> Evec<T> { let mut available = Vec::with_capacity(vec.capacity()); for (i, value) in vec.iter().enumerate() { if value.is_none() { available.push(i); } } Evec { values: vec, available, } } pub fn next_available(&self) -> usize { match self.available.last() { Some(index) => *index, None => self.values.len() } } pub fn with_capacity(capacity: usize) -> Evec<T> { Evec { values: Vec::with_capacity(capacity), available: Vec::with_capacity(capacity), } } pub fn push(&mut self, value: T) -> usize { match self.available.pop() { Some(index) => { self.values[index] = Some(value); index } None => { let index = self.values.len(); self.values.push(Some(value)); index } } } pub fn remove(&mut self, index: usize) { assert!(index < self.values.len()); if self.values[index].is_some() { self.values[index] = None; self.available.push(index); } } pub fn remove_unused(&mut self) { self.available.clear(); let mut values = Vec::with_capacity(self.values.capacity()); mem::swap(&mut self.values, &mut values); for item in values.into_iter().filter(|item| item.is_some()) { self.values.push(item); } } } impl<T> Index<usize> for Evec<T> { type Output = Option<T>; fn index(&self, index: usize) -> &Option<T> { &self.values[index] } } impl<T> IndexMut<usize> for Evec<T> { fn index_mut(&mut self, index: usize) -> &mut Option<T> { &mut self.values[index] } } #[cfg(test)] mod tests { use evec::Evec; #[test] fn first_tests() { let mut evec = Evec::from(vec![1, 2, 3, 4]); evec.remove(2); evec.push(10); evec.push(5); assert_eq!(evec[2], Some(10)); assert_eq!(evec[4], Some(5)); } #[test] fn remove_test() { let mut evec = Evec::from_option_vec(vec![Some(1), Some(2), None, None, Some(5)]); evec.remove_unused(); assert_eq!(evec[2], Some(5)); } }
true
1fad11f86c29e96781dda8a238d2b59e4f7f4e40
Rust
jordansissel/experiments
/aoc/aoc2022/1/for_loop.rs
UTF-8
732
3.5
4
[]
no_license
use std::io; fn main() { let mut elves = vec![]; let mut count = 0; for line in io::stdin().lines() { if let Err(e) = line { println!("Error reading line: {}", e); return; } let text = line.unwrap(); if text.is_empty() { elves.push(count); count = 0; continue; } let calories = text.parse::<u32>().unwrap(); count += calories; } if count > 0 { elves.push(count); } // Part 1 let max = elves.iter().max(); println!("Highest single elf: {}", max.unwrap()); // Part 2 elves.sort(); elves.reverse(); println!("Sum of top 3: {}", elves[0..3].iter().sum::<u32>()); }
true
f4402fc0e9891d79dc0d1e3d0355738e2fd6b85a
Rust
mosbasik/advent-of-code-2018
/src/bin/day04a.rs
UTF-8
6,210
3.421875
3
[]
no_license
use std::collections::HashMap; use std::io::{self, BufRead}; use std::iter::Iterator; extern crate chrono; use chrono::NaiveDateTime; extern crate unicode_segmentation; use unicode_segmentation::UnicodeSegmentation; fn main() { // make a handle to the standard input of the current process let stdin = io::stdin(); // read all of the input into a vector of strings (Vec<String>) let input = stdin.lock().lines().map(|line| line.unwrap()).collect(); // feed the Vec<String> into the main logic and print the result println!("{:}", answer(input)); } fn answer(input: Vec<String>) -> usize { // create vector to hold our Log structs let mut logs = Vec::new(); // parse a Log struct out of every line of the input for line in input.iter() { logs.push(parse_log(line)); } // sort the Logs from earliest to latest by datetime logs.sort_unstable_by(|a, b| a.dt.cmp(&b.dt)); // "indices" of a sort to track the current state as we walk through the logs let mut guard = None; let mut first_sleep_min: Option<usize> = None; let mut first_wake_min: Option<usize>; // a map of guard IDs to [a map of minutes to counts, where count is the // number of times this guard was asleep during this minute] let mut asleep = HashMap::new(); // loop over every log entry, choosing a set of operations to perform based // on which one of three possible actions this log entry represents for log in logs.iter() { match log.action { // if a guard comes on duty, record his ID Action::Start => { guard = log.guard; } // if a guard goes to sleep, record the minute Action::Sleep => { first_sleep_min = Some(log.dt.format("%M").to_string().parse().unwrap()); } // if a guard wakes up, record the minute. then, for each minute // between the time they went to sleep and the time they woke up, // increment the appropriate minute counter in the "asleep" HashMap Action::Wake => { first_wake_min = Some(log.dt.format("%M").to_string().parse().unwrap()); for min in first_sleep_min.unwrap()..first_wake_min.unwrap() { let slot = asleep .entry(guard.unwrap()) .or_insert(HashMap::new()) .entry(min) .or_insert(0 as usize); *slot += 1; } // unset the "going to sleep" minute for sanity first_sleep_min = None; } } } // find the guard who sleeps the most let guard = sleepiest_guard(&asleep); // find the minute of the night that guard sleeps the most let minute = sleepiest_minute(&asleep, guard); // multiply the two together and return the result guard * minute } fn sleepiest_guard(asleep: &HashMap<usize, HashMap<usize, usize>>) -> usize { asleep // make hashmap into an iterator over (k, v) tuples .iter() // convert to an iterator over (guard, total minutes asleep) tuples .map(|(guard, minute_counts)| (*guard, minute_counts.values().sum::<usize>())) // find the tuple with the highest total minutes asleep .max_by_key(|v| v.1) .unwrap() // return the guard ID of that tuple .0 } fn sleepiest_minute(asleep: &HashMap<usize, HashMap<usize, usize>>, guard: usize) -> usize { match asleep.get(&guard) { Some(m) => *(m.iter().max_by_key(|x| x.1).unwrap().0), None => panic!(), } } #[derive(Debug)] enum Action { Start, Sleep, Wake, } #[derive(Debug)] struct Log { dt: NaiveDateTime, guard: Option<usize>, action: Action, } fn parse_log(input: &str) -> Log { // split input into (roughly) a datetime string and an action string let input_tokens = input.split(|c| c == '[' || c == ']').collect::<Vec<&str>>(); // parse the datetime string into a NaiveDateTime object let dt = NaiveDateTime::parse_from_str(input_tokens[1], "%Y-%m-%d %H:%M").unwrap(); // split the action string on the unicode word boundaries let action_tokens = UnicodeSegmentation::unicode_words(input_tokens[2]).collect::<Vec<&str>>(); // use the first word to determine what Action is being taken let action = match action_tokens[0] { "Guard" => Action::Start, "falls" => Action::Sleep, "wakes" => Action::Wake, _ => panic!(), }; // if the Action is that of a guard starting their shift, get their ID // number from the next word let guard = match action { Action::Start => Some(action_tokens[1].parse().unwrap()), _ => None, }; // create and return the Log struct Log { dt, guard, action } } #[cfg(test)] mod tests { use super::*; #[test] fn test_1() { assert_eq!( answer(vec![ String::from("[1518-11-01 00:05] falls asleep"), String::from("[1518-11-01 00:25] wakes up"), String::from("[1518-11-01 00:30] falls asleep"), String::from("[1518-11-01 00:55] wakes up"), String::from("[1518-11-01 00:00] Guard #10 begins shift"), String::from("[1518-11-01 23:58] Guard #99 begins shift"), String::from("[1518-11-02 00:40] falls asleep"), String::from("[1518-11-02 00:50] wakes up"), String::from("[1518-11-03 00:05] Guard #10 begins shift"), String::from("[1518-11-03 00:24] falls asleep"), String::from("[1518-11-03 00:29] wakes up"), String::from("[1518-11-04 00:02] Guard #99 begins shift"), String::from("[1518-11-04 00:36] falls asleep"), String::from("[1518-11-04 00:46] wakes up"), String::from("[1518-11-05 00:03] Guard #99 begins shift"), String::from("[1518-11-05 00:45] falls asleep"), String::from("[1518-11-05 00:55] wakes up"), ]), 240 ); } }
true
57291ad6d9558d1f9a3745a8900075f56fe0a46e
Rust
Picahoo/ciruela
/src/client/keys.rs
UTF-8
3,146
2.78125
3
[ "MIT", "Apache-2.0" ]
permissive
use std::io::{self, Read}; use std::env::{self, home_dir}; use std::path::Path; use std::fs::File; use failure::{Error, ResultExt}; use ssh_keys::PrivateKey; use ssh_keys::openssh::parse_private_key; fn keys_from_file(filename: &Path, allow_non_existent: bool, res: &mut Vec<PrivateKey>) -> Result<(), Error> { let mut f = match File::open(filename) { Ok(f) => f, Err(ref e) if e.kind() == io::ErrorKind::NotFound && allow_non_existent => { return Ok(()); } Err(e) => return Err(e.into()), }; let mut keybuf = String::with_capacity(1024); f.read_to_string(&mut keybuf)?; let keys = parse_private_key(&keybuf)?; res.extend(keys); Ok(()) } fn keys_from_env(name: &str, allow_non_existent: bool, res: &mut Vec<PrivateKey>) -> Result<(), Error> { let value = match env::var(name) { Ok(x) => x, Err(ref e) if matches!(e, &env::VarError::NotPresent) && allow_non_existent => { return Ok(()); } Err(e) => return Err(e.into()), }; let keys = parse_private_key(&value)?; res.extend(keys); Ok(()) } pub fn read_keys(identities: &Vec<String>, key_vars: &Vec<String>) -> Result<Vec<PrivateKey>, Error> { let mut private_keys = Vec::new(); let no_default = identities.len() == 0 && key_vars.len() == 0; if no_default { keys_from_env("CIRUELA_KEY", true, &mut private_keys) .context(format!("Can't read env key CIRUELA_KEY"))?; match home_dir() { Some(home) => { let path = home.join(".ssh/id_ed25519"); keys_from_file(&path, true, &mut private_keys) .context(format!("Can't read key file {:?}", path))?; let path = home.join(".ssh/id_ciruela"); keys_from_file(&path, true, &mut private_keys) .context(format!("Can't read key file {:?}", path))?; let path = home.join(".ciruela/id_ed25519"); keys_from_file(&path, true, &mut private_keys) .context(format!("Can't read key file {:?}", path))?; } None if private_keys.len() == 0 => { warn!("Cannot find home dir. \ Use `-i` or `-k` options to specify \ identity (private key) explicitly."); } None => {} // fine if there is some key, say from env variable } } else { for ident in identities { keys_from_file(&Path::new(&ident), false, &mut private_keys) .context(format!("Can't read key file {:?}", ident))?; } for name in key_vars { keys_from_env(&name, false, &mut private_keys) .context(format!("Can't read env key {:?}", name))?; } }; eprintln!("Ciruela {}: read {} private keys, listing public:", env!("CARGO_PKG_VERSION"), private_keys.len()); for key in &private_keys { eprintln!(" {}", key.public_key().to_string()); } return Ok(private_keys) }
true
38b3211d94766707ae9c5d880ef1c74695d93402
Rust
OpenTechSchool-Leipzig/volunteero
/heart/src/opportunity.rs
UTF-8
6,951
3.09375
3
[]
no_license
use std::convert::TryFrom; use std::convert::TryInto; use serde::Serialize; use crate::contact::Contact; use crate::contact::ContactOption; use crate::dto::DTO; use crate::geocoder::geocode; use crate::label::Label; use crate::location::{Address, Location}; use crate::organisation::Organisation; use crate::repository::Repository; #[derive(Debug, PartialEq, Serialize, Clone)] pub struct Opportunity { pub job_description: String, pub organisation: Organisation, pub locations: Vec<Location>, pub contact: Contact, pub labels: Vec<Label>, } impl Opportunity { fn get_labels_for_key(&self, key: &str) -> Vec<String> { self.labels .clone() .into_iter() .find(|label| label.key == key) .map(|label| label.values) .unwrap_or_else(Vec::new) } } // TODO: DTO mit Stadtteil // TODO: Beispieldaten ins Repository als HashMap und bei fetch_all ausliefern pub enum OpportunityFilter { LabelFilter(Label), } #[derive(Debug, PartialEq)] pub struct OpportunityRepository { pub data: Vec<Opportunity>, } impl Repository<Opportunity> for OpportunityRepository { fn fetch_all(&self) -> Vec<Opportunity> { self.data.clone() } } impl OpportunityRepository { pub fn find(&self, filters: &[OpportunityFilter]) -> Vec<Opportunity> { self.data .clone() .into_iter() .filter(|opportunity| { filters.iter().all(|filter| match filter { OpportunityFilter::LabelFilter(filter_label) => { self.filter_by_labels(opportunity, filter_label) } }) }) .collect() } fn filter_by_labels(&self, opportunity: &Opportunity, filter_label: &Label) -> bool { let values = &filter_label.values; values.iter().any(|l| { opportunity .get_labels_for_key(&filter_label.key) .contains(&l) }) } } #[cfg(test)] mod tests { use super::*; use crate::sample_data::OPPORTUNITIES; #[test] fn filter_opportunities_by_single_label() { let repository = OpportunityRepository { data: OPPORTUNITIES.clone(), }; let filter = vec![OpportunityFilter::LabelFilter(Label { key: "Sportart".to_string(), values: vec!["Fußball".to_string()], })]; let actual = repository.find(&filter); assert_eq!(actual, OPPORTUNITIES.clone()) } #[test] fn filter_opportunities_by_multiple_labels() { let repository = OpportunityRepository { data: OPPORTUNITIES.clone(), }; let filter = vec![OpportunityFilter::LabelFilter(Label { key: "Aufgabenfeld".to_string(), values: vec!["Vereinsleben".to_string(), "Trainigsbetrieb".to_string()], })]; let actual = repository.find(&filter); assert_eq!(actual, OPPORTUNITIES.clone()) } #[test] fn filter_opportunities_by_none_partially_existing_label() { let repository = OpportunityRepository { data: OPPORTUNITIES.clone(), }; let filter = vec![OpportunityFilter::LabelFilter(Label { key: "Sportart".to_string(), values: vec!["Eishockey".to_string(), "Fußball".to_string()], })]; let actual = repository.find(&filter); assert_eq!(actual, OPPORTUNITIES.clone()) } #[test] fn filter_opportunities_by_none_existing_label() { let repository = OpportunityRepository { data: OPPORTUNITIES.clone(), }; let filter = vec![OpportunityFilter::LabelFilter(Label { key: "Sportart".to_string(), values: vec!["Eishockey".to_string()], })]; let actual = repository.find(&filter); assert_eq!(actual, vec![]) } } impl TryFrom<DTO> for Opportunity { type Error = String; fn try_from(raw_data: DTO) -> Result<Self, Self::Error> { let address = Address { name: raw_data.address_1_name.trim().to_string(), street: raw_data.address_1_street.trim().to_string(), house_number: raw_data.address_1_housenr.trim().to_string(), postcode: raw_data.address_1_postcode.trim().to_string(), city: raw_data.address_1_city.trim().to_string(), }; // TODO: validate Ok(Self { job_description: raw_data.job_description.trim().to_string(), organisation: Organisation { id: raw_data.organisation_id, name: raw_data.organisation_name.trim().to_string(), }, locations: vec![Location { coordinates: geocode(&address).ok(), address, }], contact: Contact { name: raw_data.contact_name, options: extract_options( raw_data.contact_email.trim().to_string(), raw_data.contact_phone.trim().to_string(), raw_data.contact_mobile.trim().to_string(), ), }, labels: extract_labels( raw_data.label_1, raw_data.label_2, raw_data.label_3, raw_data.label_4, ), }) } } // TODO should return all addresses || now only returns one adress fn extract_options(email: String, phone: String, _mobile: String) -> Vec<ContactOption> { use ContactOption::*; let results = vec![ (email, "".into()).try_into().map(EMail), (phone, "".into()).try_into().map(Phone), ]; results.iter().filter_map(|r| r.clone().ok()).collect() } fn extract_labels( label_1: String, label_2: String, label_3: String, label_4: String, ) -> Vec<Label> { let mut my_vector: Vec<Label> = vec![]; if label_1.split('=').next().unwrap() != "" { my_vector.push(Label { key: label_1.split('=').next().unwrap().trim().to_string(), values: vec![label_1.split('=').nth(1).unwrap().to_string()], }) } if label_2.split('=').next().unwrap() != "" { my_vector.push(Label { key: label_2.split('=').next().unwrap().trim().to_string(), values: vec![label_2.split('=').nth(1).unwrap().to_string()], }) } if label_3.split('=').next().unwrap() != "" { my_vector.push(Label { key: label_3.split('=').next().unwrap().trim().to_string(), values: vec![label_3.split('=').nth(1).unwrap().to_string()], }) } if label_4.split('=').next().unwrap() != "" { my_vector.push(Label { key: label_4.split('=').next().unwrap().trim().to_string(), values: vec![label_4.split('=').nth(1).unwrap().to_string()], }) } my_vector }
true
5c73384ef6fd66d1d1d04e0cffd3a4b4ac46e07d
Rust
samueltangz/rust-etcd
/src/kv/put.rs
UTF-8
1,858
2.765625
3
[ "MIT" ]
permissive
use crate::kv::KeyValue; use crate::proto::rpc; use crate::ResponseHeader; pub struct PutRequest { key: Vec<u8>, value: Vec<u8>, lease: Option<i64>, prev_kv: bool, ignore_value: bool, ignore_lease: bool, } impl PutRequest { pub fn new(key: &[u8], value: &[u8]) -> Self { Self { key: key.to_vec(), value: value.to_vec(), lease: None, prev_kv: false, ignore_lease: false, ignore_value: false, } } pub fn with_lease(mut self, lease_id: i64) -> Self { self.lease = Some(lease_id); self } pub fn with_prev_kv(mut self) -> Self { self.prev_kv = true; self } pub fn with_ignore_value(mut self) -> Self { self.ignore_value = true; self } pub fn with_ignore_lease(mut self) -> Self { self.ignore_lease = true; self } } impl Into<rpc::PutRequest> for PutRequest { fn into(self) -> rpc::PutRequest { let mut req = rpc::PutRequest::new(); req.set_key(self.key.to_vec()); req.set_value(self.value.to_vec()); req.set_ignore_lease(self.ignore_lease); req.set_ignore_value(self.ignore_value); req.set_prev_kv(self.prev_kv); if let Some(lease) = self.lease { req.set_lease(lease); } req } } #[derive(Debug)] pub struct PutResponse { resp: rpc::PutResponse, } impl PutResponse { pub fn prev_kv(&self) -> KeyValue { // FIXME perf From::from(self.resp.get_prev_kv().clone()) } pub fn header(&self) -> ResponseHeader { // FIXME perf From::from(self.resp.get_header().clone()) } } impl From<rpc::PutResponse> for PutResponse { fn from(resp: rpc::PutResponse) -> Self { Self { resp } } }
true
1e8291aa9fed2e992891b9062432905d8d4f3e2e
Rust
mgill25/delta-rs
/rust/src/delta_config.rs
UTF-8
8,883
3.140625
3
[ "Apache-2.0" ]
permissive
//! Delta Table configuration use crate::{DeltaDataTypeInt, DeltaDataTypeLong, DeltaTableMetaData}; use lazy_static::lazy_static; use std::time::Duration; lazy_static! { /// How often to checkpoint the delta log. pub static ref CHECKPOINT_INTERVAL: DeltaConfig = DeltaConfig::new("checkpointInterval", "10"); /// The shortest duration we have to keep logically deleted data files around before deleting /// them physically. /// Note: this value should be large enough: /// - It should be larger than the longest possible duration of a job if you decide to run "VACUUM" /// when there are concurrent readers or writers accessing the table. ///- If you are running a streaming query reading from the table, you should make sure the query /// doesn't stop longer than this value. Otherwise, the query may not be able to restart as it /// still needs to read old files. pub static ref TOMBSTONE_RETENTION: DeltaConfig = DeltaConfig::new("deletedFileRetentionDuration", "interval 1 week"); } /// Delta configuration error #[derive(thiserror::Error, Debug, PartialEq)] pub enum DeltaConfigError { /// Error returned when configuration validation failed. #[error("Validation failed - {0}")] Validation(String), } /// Delta table's `metadata.configuration` entry. #[derive(Debug)] pub struct DeltaConfig { /// The configuration name pub key: String, /// The default value if `key` is not set in `metadata.configuration`. pub default: String, } impl DeltaConfig { fn new(key: &str, default: &str) -> Self { Self { key: key.to_string(), default: default.to_string(), } } /// Returns the value from `metadata.configuration` for `self.key` as DeltaDataTypeInt. /// If it's missing in metadata then the `self.default` is used. #[allow(dead_code)] pub fn get_int_from_metadata( &self, metadata: &DeltaTableMetaData, ) -> Result<DeltaDataTypeInt, DeltaConfigError> { Ok(parse_int(&self.get_raw_from_metadata(metadata))? as i32) } /// Returns the value from `metadata.configuration` for `self.key` as DeltaDataTypeLong. /// If it's missing in metadata then the `self.default` is used. #[allow(dead_code)] pub fn get_long_from_metadata( &self, metadata: &DeltaTableMetaData, ) -> Result<DeltaDataTypeLong, DeltaConfigError> { parse_int(&self.get_raw_from_metadata(metadata)) } /// Returns the value from `metadata.configuration` for `self.key` as Duration type for the interval. /// The string value of this config has to have the following format: interval <number> <unit>. /// Where <unit> is either week, day, hour, second, millisecond, microsecond or nanosecond. /// If it's missing in metadata then the `self.default` is used. pub fn get_interval_from_metadata( &self, metadata: &DeltaTableMetaData, ) -> Result<Duration, DeltaConfigError> { parse_interval(&self.get_raw_from_metadata(metadata)) } fn get_raw_from_metadata(&self, metadata: &DeltaTableMetaData) -> String { metadata .configuration .get(&self.key) .and_then(|opt| opt.as_deref()) .unwrap_or_else(|| self.default.as_str()) .to_string() } } const SECONDS_PER_MINUTE: u64 = 60; const SECONDS_PER_HOUR: u64 = 60 * SECONDS_PER_MINUTE; const SECONDS_PER_DAY: u64 = 24 * SECONDS_PER_HOUR; const SECONDS_PER_WEEK: u64 = 7 * SECONDS_PER_DAY; fn parse_interval(value: &str) -> Result<Duration, DeltaConfigError> { let not_an_interval = || DeltaConfigError::Validation(format!("'{}' is not an interval", value)); if !value.starts_with("interval ") { return Err(not_an_interval()); } let mut it = value.split_whitespace(); let _ = it.next(); // skip "interval" let number = parse_int(it.next().ok_or_else(not_an_interval)?)?; if number < 0 { return Err(DeltaConfigError::Validation(format!( "interval '{}' cannot be negative", value ))); } let number = number as u64; let duration = match it.next().ok_or_else(not_an_interval)? { "nanosecond" => Duration::from_nanos(number), "microsecond" => Duration::from_micros(number), "millisecond" => Duration::from_millis(number), "second" => Duration::from_secs(number), "minute" => Duration::from_secs(number * SECONDS_PER_MINUTE), "hour" => Duration::from_secs(number * SECONDS_PER_HOUR), "day" => Duration::from_secs(number * SECONDS_PER_DAY), "week" => Duration::from_secs(number * SECONDS_PER_WEEK), unit => { return Err(DeltaConfigError::Validation(format!( "Unknown unit '{}'", unit ))); } }; Ok(duration) } fn parse_int(value: &str) -> Result<i64, DeltaConfigError> { value.parse().map_err(|e| { DeltaConfigError::Validation(format!("Cannot parse '{}' as integer: {}", value, e)) }) } #[cfg(test)] mod tests { use super::*; use crate::Schema; use std::collections::HashMap; fn dummy_metadata() -> DeltaTableMetaData { let schema = Schema::new(Vec::new()); DeltaTableMetaData::new(None, None, None, schema, Vec::new(), HashMap::new()) } #[test] fn get_interval_from_metadata_test() { let mut md = dummy_metadata(); // default 1 week assert_eq!( TOMBSTONE_RETENTION .get_interval_from_metadata(&md) .unwrap() .as_secs(), 1 * SECONDS_PER_WEEK, ); // change to 2 day md.configuration.insert( TOMBSTONE_RETENTION.key.to_string(), Some("interval 2 day".to_string()), ); assert_eq!( TOMBSTONE_RETENTION .get_interval_from_metadata(&md) .unwrap() .as_secs(), 2 * SECONDS_PER_DAY, ); } #[test] fn get_long_from_metadata_test() { assert_eq!( CHECKPOINT_INTERVAL .get_long_from_metadata(&dummy_metadata()) .unwrap(), 10, ) } #[test] fn get_int_from_metadata_test() { assert_eq!( CHECKPOINT_INTERVAL .get_int_from_metadata(&dummy_metadata()) .unwrap(), 10, ) } #[test] fn parse_interval_test() { assert_eq!( parse_interval("interval 123 nanosecond").unwrap(), Duration::from_nanos(123) ); assert_eq!( parse_interval("interval 123 microsecond").unwrap(), Duration::from_micros(123) ); assert_eq!( parse_interval("interval 123 millisecond").unwrap(), Duration::from_millis(123) ); assert_eq!( parse_interval("interval 123 second").unwrap(), Duration::from_secs(123) ); assert_eq!( parse_interval("interval 123 minute").unwrap(), Duration::from_secs(123 * 60) ); assert_eq!( parse_interval("interval 123 hour").unwrap(), Duration::from_secs(123 * 3600) ); assert_eq!( parse_interval("interval 123 day").unwrap(), Duration::from_secs(123 * 86400) ); assert_eq!( parse_interval("interval 123 week").unwrap(), Duration::from_secs(123 * 604800) ); } #[test] fn parse_interval_invalid_test() { assert_eq!( parse_interval("whatever").err().unwrap(), DeltaConfigError::Validation("'whatever' is not an interval".to_string()) ); assert_eq!( parse_interval("interval").err().unwrap(), DeltaConfigError::Validation("'interval' is not an interval".to_string()) ); assert_eq!( parse_interval("interval 2").err().unwrap(), DeltaConfigError::Validation("'interval 2' is not an interval".to_string()) ); assert_eq!( parse_interval("interval 2 years").err().unwrap(), DeltaConfigError::Validation("Unknown unit 'years'".to_string()) ); assert_eq!( parse_interval("interval two years").err().unwrap(), DeltaConfigError::Validation( "Cannot parse 'two' as integer: invalid digit found in string".to_string() ) ); assert_eq!( parse_interval("interval -25 hours").err().unwrap(), DeltaConfigError::Validation( "interval 'interval -25 hours' cannot be negative".to_string() ) ); } }
true
06e071e0c61d7d5e5975564e0ab268afe672f663
Rust
akovaski/AdventOfCode
/2020/22/aoc2020_22a.rs
UTF-8
2,050
3.40625
3
[]
no_license
use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::io::Result; use std::collections::VecDeque; fn main() -> Result<()> { let lines: Vec<String> = BufReader::new(File::open("input.txt")?).lines().map(|l| l.unwrap()).collect(); let (mut deck1, mut deck2) = parse_input(&lines); // simulate a game of Combat while deck1.len() > 0 && deck2.len() > 0 { let card1 = deck1.pop_front().unwrap(); let card2 = deck2.pop_front().unwrap(); if card1 > card2 { deck1.push_back(card1); deck1.push_back(card2); } else if card1 < card2 { deck2.push_back(card2); deck2.push_back(card1); } else { unreachable!(); } } let winning_deck = if deck1.len() > 0 { deck1 } else if deck2.len() > 0 { deck2 } else { unreachable!() }; // calculate score let score: i64 = winning_deck.iter().rev().enumerate().map(|(i, card)| card * (i as i64 + 1)).sum(); println!("Score: {}", score); Ok(()) } type Deck = VecDeque<i64>; fn parse_input(lines: &[String]) -> (Deck, Deck) { enum ParseState { Player1Label, Player1Card, Player2Label, Player2Card, } let mut state = ParseState::Player1Label; let mut player1_cards: Deck = Deck::new(); let mut player2_cards: Deck = Deck::new(); for line in lines { match state { ParseState::Player1Label => state = ParseState::Player1Card, ParseState::Player1Card => if line == "" { state = ParseState::Player2Label; } else { player1_cards.push_back(line.parse().unwrap()); } ParseState::Player2Label => state = ParseState::Player2Card, ParseState::Player2Card => if line == "" { unreachable!(); } else { player2_cards.push_back(line.parse().unwrap()); } } } (player1_cards, player2_cards) }
true
31ac3677a02c0a42579ed4dfbef9d7b390bbd431
Rust
manuel-rhdt/font_parse
/src/glyph_accessor.rs
UTF-8
1,736
2.53125
3
[ "Apache-2.0" ]
permissive
// Copyright 2018 Manuel Reinhardt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::cff::{Glyph as CffGlyph, GlyphAccessor as CffGlyphAccessor}; use crate::ttf_glyph_accessor::{Glyph as TtfGlyph, GlyphAccessor as TtfGlyphAccessor}; use crate::error::ParserError; #[derive(Debug)] pub enum Glyph<'font> { Cff(CffGlyph<'font>), Ttf(TtfGlyph<'font>), } #[derive(Debug, Clone)] pub(crate) enum _GlyphAccessor<'font> { Cff(CffGlyphAccessor<'font>), Ttf(TtfGlyphAccessor<'font>), } #[derive(Debug, Clone, From)] pub struct GlyphAccessor<'font>(pub(crate) _GlyphAccessor<'font>); impl<'font> GlyphAccessor<'font> { pub fn num_glyphs(&self) -> u32 { match self.0 { _GlyphAccessor::Cff(ref accessor) => accessor.num_glyphs(), _GlyphAccessor::Ttf(ref accessor) => accessor.num_glyphs(), } } pub fn index(&mut self, index: u32) -> Result<Option<Glyph<'_>>, ParserError> { let glyph = match self.0 { _GlyphAccessor::Cff(ref mut accessor) => accessor.index(index).map(Glyph::Cff), _GlyphAccessor::Ttf(ref accessor) => accessor.index(index as u16)?.map(Glyph::Ttf), }; Ok(glyph) } }
true
bbf6d8ba56a6fc0559ddd00658cdab8db4051f8e
Rust
Alexei-Kornienko/zmq.rs
/examples/message_broker.rs
UTF-8
1,133
2.609375
3
[ "MIT" ]
permissive
use std::convert::TryInto; use std::error::Error; use std::time::Duration; use zeromq::{Socket, ZmqError}; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let mut frontend = zeromq::RouterSocket::new(); frontend .bind("tcp://127.0.0.1:5559") .await .expect("Failed to bind"); // let mut backend = zmq_rs::DealerSocket::bind("tcp://127.0.0.1:5560") // .await // .expect("Failed to bind"); // // zmq_rs::proxy(Box::new(frontend), Box::new(backend)).await?; loop { let mess = frontend.recv_multipart().await; match mess { Ok(mut message) => { dbg!(&message); let request: String = message.remove(2).try_into()?; message.push(format!("{} Reply", request).into()); frontend.send_multipart(message).await?; } Err(ZmqError::NoMessage) => { println!("No messages"); } Err(e) => { dbg!(e); } } tokio::time::delay_for(Duration::from_millis(500)).await; } }
true
e2316ee39e8f635c66402a5d343d925f4ca3c1f2
Rust
sugyan/atcoder
/agc007/src/bin/a.rs
UTF-8
310
2.6875
3
[]
no_license
use proconio::marker::Chars; use proconio::{fastout, input}; #[fastout] fn main() { input! { h: usize, w: usize, a: [Chars; h], } if a.iter().flatten().filter(|&c| *c == '#').count() == h + w - 1 { println!("Possible"); } else { println!("Impossible"); } }
true
67addb6c8d96931bb4f3cb885ad441030f3e9210
Rust
watterso/languages
/rust/geolocation.rs
UTF-8
1,302
3.734375
4
[]
no_license
pub type Course = f64; #[derive(Debug)] pub struct GeoLocation { latitude: f64, longitude: f64 } #[derive(Debug)] pub struct GeoLocationInRadians { pub latitude: f64, pub longitude: f64 } impl GeoLocation { pub fn to_radians(&self) -> GeoLocationInRadians { GeoLocationInRadians{ latitude: self.latitude.to_radians(), longitude: self.longitude.to_radians() } } } pub struct GeoLocationBuilder{ lat: f64, long: f64 } fn valid_latitude(angle: f64) -> bool { angle >= -90.0f64 && angle <= 90.0f64 } fn valid_longitude(angle: f64) -> bool { angle >= -180.0f64 && angle <= 180.0f64 } impl GeoLocationBuilder { pub fn new() -> GeoLocationBuilder { GeoLocationBuilder { lat: 0.0, long: 0.0 } } pub fn lat(&mut self, new_lat: f64) -> &mut GeoLocationBuilder { self.lat = new_lat; self } pub fn long(&mut self, new_long: f64) -> &mut GeoLocationBuilder { self.long = new_long; self } pub fn finalize(&self) -> GeoLocation { if valid_latitude(self.lat) && valid_longitude(self.long){ GeoLocation{ latitude: self.lat, longitude: self.long } } else{ panic!("invalid lat-long: {}, {}", self.lat, self.long); } } }
true
4824cb93fe2844babfac8ff34aaeb2ba4d94da95
Rust
fzerocentral/fzgx-image2emblem-rs
/src/gamecube/memcard.rs
UTF-8
1,223
2.59375
3
[]
no_license
extern crate byteorder; use self::byteorder::{BigEndian, ByteOrder}; use super::super::emblem::make_bytes; pub enum Region { NTSC, PAL, } pub struct Memcard { pub gamecode: [u8; 4], // GFZE pub company: [u8; 2], // 8P pub reserved01: u8, // 0xFF pub banner_fmt: u8, // 0x02 pub filename: [u8; 32], pub timestamp: [u8; 4], pub icon_addr: [u8; 4], // 0x00 0x00 0x00 0x60 pub icon_fmt: [u8; 2], // 0x00 0x02 pub icon_speed: [u8; 2], // 0x00 0x03 pub permission: u8, pub copy_counter: u8, pub index: [u8; 2], pub filesize8: [u8; 2], // 0x00 0x03 pub reserved02: [u8; 2], // 0xFF 0xFF pub comment_addr: [u8; 4], // 0x00 0x00 0x00 0x04 } impl Memcard { pub fn set_region(&mut self, region: Region) { match region { Region::NTSC => self.gamecode = *b"GFZP", Region::PAL => self.gamecode = *b"GFZE", } } pub fn set_filename(&mut self, filename: String) { make_bytes(&mut self.filename, &filename.as_bytes()); } pub fn set_timestamp(&mut self, time: u32) { let mut buf = [0x00; 4]; BigEndian::write_u32(&mut buf, time); self.timestamp = buf; } }
true
dbe82b2027c6666345b2db1af69e8a987ab0de20
Rust
markrepedersen/netparser
/lib/netparse/src/layer3/ip/ipv4.rs
UTF-8
3,163
2.671875
3
[]
no_license
use crate::{ core::{ parse::{self, BitParsable}, ux::*, }, layer3::{ icmp, ip::{ip::*, tcp, udp}, }, }; use custom_debug_derive::*; use nom::{ bits::bits, bytes::complete::take, combinator::map, error::context, number::complete::{be_u16, be_u8}, sequence::tuple, }; use serde::{Deserialize, Serialize}; use std::fmt; #[derive(Serialize, Deserialize, CustomDebug)] pub struct Packet { #[debug(format = "{:02x}")] pub version: u4, #[debug(format = "{:02x}")] pub ihl: u4, #[debug(format = "{:02x}")] pub dscp: u6, #[debug(format = "{:b}")] pub ecn: u2, #[debug(format = "{}")] pub length: u16, #[debug(format = "{:04x}")] pub identification: u16, #[debug(format = "{:b}")] pub flags: u3, #[debug(format = "{}")] pub fragment_offset: u13, #[debug(format = "{}")] pub ttl: u8, pub src: Addr, pub dst: Addr, #[debug(skip)] pub checksum: u16, pub protocol: Option<Protocol>, pub payload: Payload, } impl Packet { pub fn parse(i: parse::Input) -> parse::ParseResult<Self> { context("IPv4 frame", |i| { let (i, (version, ihl)) = bits(tuple((u4::parse, u4::parse)))(i)?; let (i, (dscp, ecn)) = bits(tuple((u6::parse, u2::parse)))(i)?; let (i, length) = be_u16(i)?; let (i, identification) = be_u16(i)?; let (i, (flags, fragment_offset)) = bits(tuple((u3::parse, u13::parse)))(i)?; let (i, ttl) = be_u8(i)?; let (i, protocol) = Protocol::parse(i)?; let (i, checksum) = be_u16(i)?; let (i, (src, dst)) = tuple((Addr::parse, Addr::parse))(i)?; let (i, payload) = match protocol { Some(Protocol::TCP) => map(tcp::Packet::parse, Payload::TCP)(i)?, Some(Protocol::UDP) => map(udp::Datagram::parse, Payload::UDP)(i)?, Some(Protocol::ICMP) => map(icmp::Packet::parse, Payload::ICMP)(i)?, _ => (i, Payload::Unknown), }; let res = Self { version, ihl, dscp, ecn, length, identification, flags, fragment_offset, ttl, protocol, checksum, src, dst, payload, }; Ok((i, res)) })(i) } } #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy)] pub struct Addr(pub [u8; 4]); impl Addr { pub fn parse(i: parse::Input) -> parse::ParseResult<Self> { let (i, slice) = context("IPv4 address", take(4_usize))(i)?; let mut res = Self([0, 0, 0, 0]); res.0.copy_from_slice(slice); Ok((i, res)) } } impl fmt::Display for Addr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let [a, b, c, d] = self.0; write!(f, "{}.{}.{}.{}", a, b, c, d) } } impl fmt::Debug for Addr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self) } }
true
06ae54a801ad572c7d4cdc8882aa3b537e778729
Rust
Durpler/rusty_pong
/src/main.rs
UTF-8
6,367
2.828125
3
[]
no_license
use ggez::{self, Context, ContextBuilder, GameResult}; use ggez::graphics::{self, Color, Text, Font, Scale}; use ggez::event::{self, EventHandler}; use ggez::nalgebra as na; use ggez::input::keyboard::{self, KeyCode}; use rand::{self, thread_rng, Rng}; /// /// CONSTANT VALUES /// const PLAYER_SPEED: f32 = 350.0; const RACKET_HEIGHT: f32 = 100.0; const RACKET_WIDTH: f32 = 20.0; const RACKET_WIDTH_HALF:f32 = RACKET_WIDTH * 0.5; const RACKET_HEIGHT_HALF:f32 = RACKET_HEIGHT * 0.5; const BALL_SIZE:f32 = 30.0; const BALL_SIZE_HALF:f32 = BALL_SIZE * 0.5; const BALL_SPEED : f32 = 150.0; // clamp function to hold players in screen fn clamp(value: &mut f32, low: f32, high: f32){ if *value < low{ *value = low; } else if *value > high{ *value = high; } } fn poll_movement_racket(pos : &mut na::Point2<f32>, keycode: KeyCode, y_dir : f32, ctx : &mut Context){ let screen_h = graphics::drawable_size(ctx).1; let dt = ggez::timer::delta(ctx).as_secs_f32(); if keyboard::is_key_pressed(ctx, keycode){ pos.y += y_dir * PLAYER_SPEED * dt; } clamp(&mut pos.y, RACKET_HEIGHT_HALF, screen_h - RACKET_HEIGHT_HALF); } // set ball to middle of the screen and randomize velocity fn reset_ball (ball_pos :&mut na::Point2<f32>, ball_velocity : &mut na::Vector2<f32>, ctx : &mut Context){ let (screen_w, screen_h) = graphics::drawable_size(ctx); ball_pos.x = screen_w * 0.5; ball_pos.y = screen_h * 0.5; randomize_vector(ball_velocity, BALL_SPEED, BALL_SPEED); } fn randomize_vector(vec : &mut na::Vector2<f32>, x : f32, y : f32){ let mut rng = thread_rng(); vec.x = match rng.gen_bool(0.5){ true => x, false => -y, }; vec.y = match rng.gen_bool(0.5){ true => y, false => -y, }; } struct MainState{ player_1_pos: na::Point2<f32>, player_2_pos: na::Point2<f32>, ball_pos: na::Point2<f32>, ball_velocity : na::Vector2<f32>, player_1_score : i32, player_2_score : i32, } impl MainState{ // constructor / new-operator pub fn new(ctx: &mut Context) -> MainState{ let (screen_w, screen_h) = graphics::drawable_size(ctx); let (screen_w_half, screen_h_half) = (screen_w * 0.5, screen_h * 0.5); let mut ball_velocity = na::Vector2::new(0.0, 0.0); randomize_vector(&mut ball_velocity, 50.0, 50.0); MainState{ player_1_pos : na::Point2::new(RACKET_WIDTH_HALF, screen_h_half), player_2_pos : na::Point2::new(screen_w - RACKET_WIDTH_HALF, screen_h_half), ball_pos : na::Point2::new(screen_w_half, screen_h_half), ball_velocity, player_1_score : 0, player_2_score : 0, } } } impl EventHandler for MainState{ fn update(&mut self, ctx: &mut Context) -> GameResult<()>{ // poll racket movement poll_movement_racket(&mut self.player_1_pos,KeyCode::W, -1.0, ctx); poll_movement_racket(&mut self.player_1_pos,KeyCode::S, 1.0, ctx); poll_movement_racket(&mut self.player_2_pos,KeyCode::Up, -1.0, ctx); poll_movement_racket(&mut self.player_2_pos,KeyCode::Down, 1.0, ctx); // update ball let dt = ggez::timer::delta(ctx).as_secs_f32(); self.ball_pos += self.ball_velocity * dt; let (screen_w, screen_h) = graphics::drawable_size(ctx); // ball check for score if self.ball_pos.x < 0.0 { reset_ball(&mut self.ball_pos, &mut self.ball_velocity, ctx); self.player_2_score += 1; } if self.ball_pos.x > screen_w{ reset_ball(&mut self.ball_pos, &mut self.ball_velocity, ctx); self.player_1_score +=1; } //ball bounce if self.ball_pos.y < 0.0 { self.ball_velocity = self.ball_velocity.abs(); } else if self.ball_pos.y > screen_h{ self.ball_velocity = -self.ball_velocity.abs(); } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()>{ // define color white, since it can't be found? What the heck?! let white : Color = Color::new(1.0,1.0,1.0,1.0); let black : Color = Color::new(0.0,0.0,0.0,0.0); graphics::clear(ctx, black); //create player rect let racket_rect = graphics::Rect::new(-RACKET_WIDTH_HALF, -RACKET_HEIGHT_HALF, RACKET_WIDTH, RACKET_HEIGHT); let racket_mesh = graphics::Mesh::new_rectangle(ctx, graphics::DrawMode::fill(), racket_rect, white)?; //create ball rect let ball_rect = graphics::Rect::new(-BALL_SIZE_HALF,-BALL_SIZE_HALF, BALL_SIZE_HALF, BALL_SIZE_HALF); let ball_mesh = graphics::Mesh::new_rectangle(ctx, graphics::DrawMode::fill(), ball_rect, white)?; let mut draw_params = graphics::DrawParam::default(); draw_params.dest = self.player_1_pos.into(); graphics::draw(ctx, &racket_mesh, draw_params)?; // Draw Player 2 draw_params.dest = self.player_2_pos.into(); graphics::draw(ctx, &racket_mesh, draw_params)?; // Draw Ball draw_params.dest = self.ball_pos.into(); graphics::draw(ctx,&ball_mesh, draw_params)?; // draw scoreboard let mut score_text = graphics::Text::new(format!("{} : {}", self.player_1_score, self.player_2_score)); score_text.set_font(Font::default(), Scale::uniform(100.0)); let (screen_w, screen_h) = graphics::drawable_size(ctx); let (screen_w_half, screen_h_half) = (screen_w * 0.5, screen_h * 0.5); let score_pos = na::Point2::new(screen_w_half - (score_text.width(ctx)/2) as f32, screen_h_half * 0.25 - (score_text.height(ctx)/2) as f32); draw_params.dest = score_pos.into(); graphics::draw(ctx, &score_text, draw_params)?; // finalize drawing graphics::present(ctx)?; Ok(()) } } fn main() -> GameResult<()> { // create a context let (mut ctx,mut event_loop) = ContextBuilder::new("MyPong", "Durpler") .build() .expect("Could not initialize the game : geez"); graphics::set_window_title(&ctx, "My Pong!"); let mut game = MainState::new(&mut ctx); event::run(&mut ctx,&mut event_loop, &mut game) .expect("Could not run main loop"); Ok(()) }
true
05cb6a24550baf4e0b4317bc9048cd422609e8a9
Rust
dtolnay-contrib/odbc2parquet
/src/query/binary.rs
UTF-8
2,874
2.703125
3
[ "MIT" ]
permissive
use std::{convert::TryInto, marker::PhantomData}; use anyhow::Error; use odbc_api::buffers::{AnyColumnView, BufferDescription, BufferKind}; use parquet::{ basic::{Repetition, Type as PhysicalType}, column::writer::{get_typed_column_writer_mut, ColumnWriter}, data_type::{ByteArray, DataType}, schema::types::Type, }; use crate::parquet_buffer::{BufferedDataType, ParquetBuffer}; use super::strategy::ColumnFetchStrategy; pub struct Binary<Pdt> { repetition: Repetition, length: usize, _phantom: PhantomData<Pdt>, } impl<Pdt> Binary<Pdt> { pub fn new(repetition: Repetition, length: usize) -> Self { Self { repetition, length, _phantom: PhantomData, } } } impl<Pdt> ColumnFetchStrategy for Binary<Pdt> where Pdt: DataType, Pdt::T: BufferedDataType + From<ByteArray>, { fn parquet_type(&self, name: &str) -> Type { let physical_type = Pdt::get_physical_type(); match physical_type { PhysicalType::BYTE_ARRAY => Type::primitive_type_builder(name, physical_type) .with_repetition(self.repetition) .build() .unwrap(), PhysicalType::FIXED_LEN_BYTE_ARRAY => Type::primitive_type_builder(name, physical_type) .with_repetition(self.repetition) .with_length(self.length.try_into().unwrap()) .build() .unwrap(), _ => { panic!("Only ByteArray and FixedLenByteArray are allowed to instantiate Binary<_>") } } } fn buffer_description(&self) -> BufferDescription { BufferDescription { kind: BufferKind::Binary { length: self.length, }, nullable: true, } } fn copy_odbc_to_parquet( &self, parquet_buffer: &mut ParquetBuffer, column_writer: &mut ColumnWriter, column_view: AnyColumnView, ) -> Result<(), Error> { let cw = get_typed_column_writer_mut::<Pdt>(column_writer); if let AnyColumnView::Binary(it) = column_view { parquet_buffer.write_optional( cw, it.map(|maybe_bytes| { maybe_bytes.map(|bytes| { let byte_array: ByteArray = bytes.to_owned().into(); // Transforms ByteArray into FixedLenByteArray or does nothing depending `Pdt`. let out: Pdt::T = byte_array.into(); out }) }), )? } else { panic!( "Invalid Column view type. This is not supposed to happen. Please open a Bug at \ https://github.com/pacman82/odbc2parquet/issues." ) } Ok(()) } }
true
0caa702255c6defe23f7a254e8d5459e3db54867
Rust
stackcats/leetcode
/algorithms/easy/sort_array_by_increasing_frequency.rs
UTF-8
444
3.046875
3
[ "MIT" ]
permissive
use std::cmp::Ordering; use std::collections::HashMap; impl Solution { pub fn frequency_sort(mut nums: Vec<i32>) -> Vec<i32> { let mut map = HashMap::new(); for n in &nums { *map.entry(*n).or_insert(0) += 1; } nums.sort_by(|a, b| { if map[a] == map[b] { b.cmp(a) } else { map[a].cmp(&map[b]) } }); nums } }
true
199cb4aab5f88a62d280b4b830f3d4c604aad014
Rust
jazzfool/reclutch
/reclutch/examples/image_viewer/main.rs
UTF-8
15,804
2.578125
3
[ "MIT", "Apache-2.0" ]
permissive
use { glium::glutin::{ self, event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, }, reclutch::{ display::{ self, Color, CommandGroup, DisplayCommand, DisplayListBuilder, Filter, FontInfo, GraphicsDisplay, GraphicsDisplayPaint, GraphicsDisplayStroke, ImageData, Point, Rect, ResourceData, ResourceDescriptor, ResourceReference, SharedData, Size, TextDisplayItem, Vector, }, event::{merge::Merge, RcEventListener, RcEventQueue}, gl, prelude::*, WidgetChildren, }, }; #[derive(Clone)] struct ConsumableEvent<T>(std::rc::Rc<std::cell::RefCell<Option<T>>>); impl<T> ConsumableEvent<T> { fn new(val: T) -> Self { ConsumableEvent(std::rc::Rc::new(std::cell::RefCell::new(Some(val)))) } fn with<P: FnMut(&T) -> bool>(&self, mut pred: P) -> Option<T> { if self.0.borrow().is_some() { if pred(self.0.borrow().as_ref().unwrap()) { return self.0.replace(None); } } None } } #[derive(Clone)] enum GlobalEvent { MouseClick(ConsumableEvent<Point>), MouseRelease(Point), MouseMove(Point), WindowResize, } struct Globals { cursor: Point, size: Size, } #[derive(Debug, Clone, Copy)] enum TitlebarEvent { BeginClick(Point), Move(Vector), EndClick, } #[derive(WidgetChildren)] struct Titlebar { pub move_event: RcEventQueue<TitlebarEvent>, position: Point, cursor_anchor: Option<Point>, global_listener: RcEventListener<GlobalEvent>, command_group: CommandGroup, width: f32, text: String, font: FontInfo, font_resource: Option<ResourceReference>, } impl Titlebar { fn new( position: Point, width: f32, text: String, global: &mut RcEventQueue<GlobalEvent>, ) -> Self { Titlebar { move_event: RcEventQueue::default(), position, cursor_anchor: None, global_listener: global.listen(), command_group: CommandGroup::new(), width, text, font: FontInfo::from_name("Segoe UI", &["SF Display", "Arial"], None).unwrap(), font_resource: None, } } fn set_position(&mut self, position: Point) { self.position = position; self.command_group.repaint(); } } impl Widget for Titlebar { type UpdateAux = Globals; type GraphicalAux = (); type DisplayObject = DisplayCommand; fn bounds(&self) -> Rect { Rect::new(self.position, Size::new(self.width, 30.0)) } fn update(&mut self, _aux: &mut Globals) { for event in self.global_listener.peek() { match event { GlobalEvent::MouseClick(click) => { if let Some(ref position) = click.with(|pos| self.bounds().contains(pos.clone())) { self.cursor_anchor = Some(position.clone()); self.move_event.emit_owned(TitlebarEvent::BeginClick(position.clone())); } } GlobalEvent::MouseRelease(_) => { if self.cursor_anchor.is_some() { self.cursor_anchor = None; self.move_event.emit_owned(TitlebarEvent::EndClick); } } GlobalEvent::MouseMove(pos) => { if let Some(ref cursor_anchor) = self.cursor_anchor { self.move_event.emit_owned(TitlebarEvent::Move(pos - *cursor_anchor)); } } _ => (), } } } fn draw(&mut self, display: &mut dyn GraphicsDisplay, _aux: &mut ()) { if self.font_resource.is_none() { self.font_resource = display .new_resource(ResourceDescriptor::Font(ResourceData::Data(SharedData::RefCount( std::sync::Arc::new(self.font.data().unwrap()), )))) .ok(); } let bounds = self.bounds(); let mut builder = DisplayListBuilder::new(); builder.push_rectangle_backdrop(bounds, true, Filter::Blur(10.0, 10.0)); builder.push_rectangle( bounds, GraphicsDisplayPaint::Fill(Color::new(1.0, 1.0, 1.0, 0.6).into()), None, ); builder.push_line( Point::new(bounds.origin.x, bounds.origin.y + bounds.size.height), Point::new(bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height), GraphicsDisplayStroke { thickness: 1.0, antialias: false, ..Default::default() }, None, ); builder.push_text( TextDisplayItem { text: self.text.clone().into(), font: self.font_resource.as_ref().unwrap().clone(), font_info: self.font.clone(), size: 22.0, bottom_left: bounds.origin + Size::new(5.0, 22.0), color: Color::new(0.0, 0.0, 0.0, 1.0).into(), }, None, ); self.command_group.push(display, &builder.build(), Default::default(), None, None).unwrap(); } } #[derive(WidgetChildren)] struct Panel { pub on_click: RcEventQueue<*const Panel>, #[widget_child] titlebar: Titlebar, position_anchor: Option<Point>, position: Point, size: Size, global_listener: RcEventListener<GlobalEvent>, titlebar_move_listener: RcEventListener<TitlebarEvent>, command_group: CommandGroup, image_data: &'static [u8], image: Option<ResourceReference>, } impl Panel { fn new( position: Point, size: Size, text: String, image_data: &'static [u8], global: &mut RcEventQueue<GlobalEvent>, ) -> Self { let titlebar = Titlebar::new(position.clone(), size.width - 1.0, text, global); let titlebar_move_listener = titlebar.move_event.listen(); Panel { on_click: RcEventQueue::default(), titlebar, position_anchor: None, position, size, global_listener: global.listen(), titlebar_move_listener, command_group: CommandGroup::new(), image_data, image: None, } } fn fit_in_window(&mut self, size: &Size) { let window_rect = Rect::new(Point::default(), size.clone()); let bounds = self.bounds(); let vert = if bounds.min_y() < window_rect.min_y() { window_rect.min_y() - bounds.min_y() } else if bounds.max_y() > window_rect.max_y() { window_rect.max_y() - bounds.max_y() } else { 0.0 }; let horiz = if bounds.min_x() < window_rect.min_x() { window_rect.min_x() - bounds.min_x() } else if bounds.max_x() > window_rect.max_x() { window_rect.max_x() - bounds.max_x() } else { 0.0 }; self.position += Vector::new(horiz, vert); } } impl Widget for Panel { type UpdateAux = Globals; type GraphicalAux = (); type DisplayObject = DisplayCommand; fn bounds(&self) -> Rect { Rect::new(self.position, self.size) } fn update(&mut self, aux: &mut Globals) { for child in self.children_mut() { child.update(aux); } for event in self.titlebar_move_listener.peek() { match event { TitlebarEvent::BeginClick(_) => { self.position_anchor = Some(self.position); self.on_click.emit_owned(self as _); } TitlebarEvent::Move(delta) => { if let Some(position_anchor) = self.position_anchor { self.position = position_anchor + delta; self.fit_in_window(&aux.size); self.titlebar.set_position(self.position.clone()); self.command_group.repaint(); } } TitlebarEvent::EndClick => { self.position_anchor = None; } } } for event in self.global_listener.peek() { match event { GlobalEvent::MouseClick(click) => { if let Some(_) = click.with(|pos| self.bounds().contains(pos.clone())) { self.on_click.emit_owned(self as _); self.command_group.repaint(); self.titlebar.command_group.repaint(); } } GlobalEvent::WindowResize => { self.fit_in_window(&aux.size); self.titlebar.set_position(self.position.clone()); self.command_group.repaint(); } _ => (), } } } fn draw(&mut self, display: &mut dyn GraphicsDisplay, aux: &mut ()) { if self.image.is_none() { self.image = display .new_resource(ResourceDescriptor::Image(ImageData::Encoded(ResourceData::Data( SharedData::Static(self.image_data), )))) .ok(); } let bounds = self.bounds(); let mut builder = DisplayListBuilder::new(); builder.push_rectangle_backdrop(bounds, true, Filter::Blur(5.0, 5.0)); builder.push_rectangle( bounds, GraphicsDisplayPaint::Fill(Color::new(0.9, 0.9, 0.9, 0.5).into()), None, ); builder.push_image(None, bounds, self.image.clone().unwrap(), None); builder.push_rectangle( bounds.inflate(0.0, 0.5), GraphicsDisplayPaint::Stroke(GraphicsDisplayStroke { color: Color::new(0.0, 0.0, 0.0, 1.0).into(), thickness: 1.0, antialias: false, ..Default::default() }), None, ); self.command_group.push(display, &builder.build(), Default::default(), None, None).unwrap(); for child in self.children_mut() { child.draw(display, aux); } } } #[derive(WidgetChildren)] struct PanelContainer { #[vec_widget_child] panels: Vec<Panel>, listeners: Vec<RcEventListener<*const Panel>>, } impl PanelContainer { fn new() -> Self { PanelContainer { panels: Vec::new(), listeners: Vec::new() } } fn add_panel(&mut self, panel: Panel) { let on_click_listener = panel.on_click.listen(); self.panels.push(panel); self.listeners.push(on_click_listener); } } impl Widget for PanelContainer { type UpdateAux = Globals; type GraphicalAux = (); type DisplayObject = DisplayCommand; fn update(&mut self, globals: &mut Globals) { // propagate back to front so that panels rendered front-most get events first. for child in self.children_mut().iter_mut().rev() { child.update(globals); } { // collect all the panel events into a single vec let mut panel_events = Vec::new(); for listener in &self.listeners { listener.extend_other(&mut panel_events); } for event in panel_events { if let Some(panel_idx) = self.panels.iter().position(|p| p as *const Panel == event) { let last = self.panels.len() - 1; self.panels.swap(panel_idx, last); } } } } fn draw(&mut self, display: &mut dyn GraphicsDisplay, aux: &mut ()) { for child in self.children_mut() { child.draw(display, aux); } } } fn main() { let window_size = (500u32, 500u32); let event_loop = EventLoop::new(); let wb = glutin::window::WindowBuilder::new() .with_title("Image Viewer with Reclutch") .with_inner_size(glutin::dpi::PhysicalSize::new(window_size.0 as f64, window_size.1 as f64)) .with_min_inner_size(glutin::dpi::PhysicalSize::new(400.0, 200.0)); let context = glutin::ContextBuilder::new() .with_vsync(true) // fast dragging motion at the cost of high GPU usage .build_windowed(wb, &event_loop) .unwrap(); let context = unsafe { context.make_current().unwrap() }; gl::load_with(|s| context.get_proc_address(s)); let mut fboid = 0; unsafe { gl::GetIntegerv(gl::FRAMEBUFFER_BINDING, &mut fboid) }; let mut display = display::skia::SkiaGraphicsDisplay::new_gl_framebuffer( |s| context.get_proc_address(s), &display::skia::SkiaOpenGlFramebuffer { framebuffer_id: fboid as _, size: (window_size.0 as _, window_size.1 as _), }, ) .unwrap(); display .push_command_group( &[DisplayCommand::Clear(Color::new(1.0, 1.0, 1.0, 1.0))], Default::default(), None, Some(false), ) .unwrap(); let mut global_q = RcEventQueue::default(); let mut globals = Globals { cursor: Point::default(), size: Size::new(window_size.0 as _, window_size.1 as _), }; let mut panel_container = PanelContainer::new(); panel_container.add_panel(Panel::new( Point::new(10.0, 10.0), Size::new(288.0, 180.15), "Ferris".into(), include_bytes!("ferris.png"), &mut global_q, )); panel_container.add_panel(Panel::new( Point::new(30.0, 30.0), Size::new(300.0, 200.0), "Forest".into(), include_bytes!("image.jpg"), &mut global_q, )); event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Wait; match event { Event::RedrawRequested { .. } => { panel_container.draw(&mut display, &mut ()); display.present(None).unwrap(); context.swap_buffers().unwrap(); } Event::WindowEvent { event: WindowEvent::CursorMoved { position, .. }, .. } => { globals.cursor = Point::new(position.x as _, position.y as _); global_q.emit_owned(GlobalEvent::MouseMove(globals.cursor.clone())); } Event::WindowEvent { event: WindowEvent::MouseInput { button: glutin::event::MouseButton::Left, state, .. }, .. } => match state { glutin::event::ElementState::Pressed => { global_q.emit_owned(GlobalEvent::MouseClick(ConsumableEvent::new( globals.cursor.clone(), ))); } glutin::event::ElementState::Released => { global_q.emit_owned(GlobalEvent::MouseRelease(globals.cursor.clone())); } }, Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { *control_flow = ControlFlow::Exit; } Event::WindowEvent { event: WindowEvent::Resized(size), .. } => { display.resize((size.width as _, size.height as _)).unwrap(); context.resize(size); globals.size.width = size.width as _; globals.size.height = size.height as _; global_q.emit_owned(GlobalEvent::WindowResize); } _ => return, } panel_container.update(&mut globals); context.window().request_redraw(); }); }
true
37507dfbd9cb719d7c1e8573f0c48593a0409094
Rust
fmeringdal/RANN
/src/math.rs
UTF-8
4,092
3.5
4
[]
no_license
use std::cmp::Ordering; pub fn dot(vec1: &Vec<f32>, vec2: &Vec<f32>) -> f32 { vec1.iter().zip(vec2.iter()).map(|(x, y)| x * y).sum() } pub fn matrix_multiply_vec(mat: &Vec<Vec<f32>>, vec: &Vec<f32>) -> Vec<f32> { let mut res = vec![]; for row in mat.iter() { res.push(dot(row, vec)); } res } pub fn mat_multiply_mat(vec: &Vec<Vec<f32>>, mat: &Vec<Vec<f32>>) -> Vec<Vec<f32>> { let mut res = vec![vec![0.; mat[0].len()]; vec.len()]; for i in 0..res.len() { for j in 0..res[0].len() { let col_mat_2 = mat.iter().map(|row| row[j]); res[i][j] = vec[i] .iter() .zip(col_mat_2) .map(|(x, y)| x * y) .sum::<f32>(); } } res } pub fn cut_val(val: f32, max: f32) -> f32 { if val > max { max } else if -max < val { -max } else { val } } pub fn one_hot_encode(i: usize, size: usize) -> Vec<usize> { let mut one_hot_encoded = vec![0; size]; one_hot_encoded[i] = 1; one_hot_encoded } pub fn mean_squared_error(vec1: &Vec<f32>, vec2: &Vec<f32>) -> f32 { let size = vec1.len(); if size == 0 { return 0.; } let error: f32 = vec1 .iter() .zip(vec2.iter()) .map(|(x, y)| (x - y).powi(2)) .sum(); error / size as f32 } pub fn softmax(vals: &Vec<f32>) -> Vec<f32> { let e = 2.71828_f32; let max_val = vals .iter() .max_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)) .unwrap_or(&0.); let vals = vals.iter().map(|val| e.powf(*val - max_val)); let denominator: f32 = vals.clone().sum(); vals.map(|val| val / denominator).collect() } pub fn softmax_derivative(vals: &Vec<f32>) -> Vec<f32> { let e = 2.71828_f32; let vals: Vec<f32> = vals.iter().map(|val| e.powf(*val)).collect(); let mut dervs = vec![0.; vals.len()]; let total: f32 = vals.iter().sum(); let total_square = total.powi(2); for i in 0..vals.len() { dervs[i] = vals[i] * (total - vals[i]) / total_square; } dervs } #[cfg(test)] mod test { use super::*; #[test] fn dot_product() { assert_eq!(dot(&vec![1.0], &vec![1.0]), 1.0); assert_eq!(dot(&vec![1.0, 2.0], &vec![1.0, 2.0]), 5.0); assert_eq!(dot(&vec![], &vec![]), 0.); assert_eq!(dot(&vec![-1.], &vec![-1.]), 1.); assert_eq!(dot(&vec![-1., 1., 2.], &vec![-1., 1., 2.]), 6.); } #[test] fn mean_squared() { assert_eq!(mean_squared_error(&vec![], &vec![]), 0.); assert_eq!(mean_squared_error(&vec![1., -4.], &vec![1., -4.]), 0.); assert_eq!(mean_squared_error(&vec![1., -1.], &vec![0., -5.]), 8.5); } #[test] fn vec_mult_mat() { let res = mat_multiply_mat(&vec![vec![4.], vec![6.]], &vec![vec![-2., 5.]]); assert_eq!(res[0], vec![-8., 20.]); assert_eq!(res[1], vec![-12., 30.]); let res = mat_multiply_mat( &vec![vec![4., -2., 2.], vec![1., 5., -9.]], &vec![vec![12., -5.], vec![-3., -2.], vec![4., 2.]], ); assert_eq!(res[0], vec![62., -12.]); assert_eq!(res[1], vec![-39., -33.]); } #[test] fn softmax_test() { let test1 = vec![1.]; let res1 = softmax(&test1); assert_eq!(res1, vec![1.]); let test2 = vec![1., 1.]; let res2 = softmax(&test2); assert_eq!(res2, vec![0.5, 0.5]); let test2 = vec![1., 1., 2.]; let res2 = softmax(&test2); let expected = vec![0.2119, 0.2119, 0.5761]; for (r, t) in res2.iter().zip(expected) { assert!(r - t < 0.01); } } #[test] fn softmax_der_test() { let test1 = vec![1.]; let res1 = softmax_derivative(&test1); assert_eq!(res1, vec![0.]); let test2 = vec![1., 2.]; let res2 = softmax_derivative(&test2); let expected = vec![0.19661, 0.19661]; for (r, t) in res2.iter().zip(expected) { assert!(r - t < 0.01); } } }
true
af606f6bb818b5659e325df335af63c0cad22168
Rust
mydotey/lang-extension
/rust/src/any/key.rs
UTF-8
4,586
3
3
[ "Apache-2.0" ]
permissive
use std::hash::{ Hash, Hasher }; use std::collections::hash_map::DefaultHasher; use super::*; pub trait KeyConstraint: ValueConstraint + Hash { } impl<T: ?Sized + ValueConstraint + Hash> KeyConstraint for T { } pub trait Key: Value { fn hashcode(&self) -> u64 { self.memory_address() as u64 } as_trait!(Key); as_boxed!(Key); } impl<T: ?Sized + KeyConstraint> Key for T { fn hashcode(&self) -> u64 { let mut hasher = DefaultHasher::default(); self.hash(&mut hasher); hasher.finish() } as_trait!(impl Key); as_boxed!(impl Key); } #[macro_export] macro_rules! boxed_key_trait { ($trait:tt) => { as_boxed!(impl Hash for $trait); boxed_value_trait!($trait); }; ($trait:tt<$($param:tt), *>) => { as_boxed!(impl Hash for $trait<$($param), *>); boxed_value_trait!($trait<$($param), *>); }; ($trait:tt<$($param:tt: $constraint0:tt $(+ $constraint:tt)*), *>) => { as_boxed!(impl Hash for $trait<$($param: $constraint0 $(+ $constraint)*), *>); boxed_value_trait!($trait<$($param: $constraint0 $(+ $constraint)*), *>); }; ($trait:tt<$($param:tt: ?Sized + $constraint0:tt $(+ $constraint:tt)*), *>) => { as_boxed!(impl Hash for $trait<$($param: ?Sized + $constraint0 $(+ $constraint)*), *>); boxed_value_trait!($trait<$($param: ?Sized + $constraint0 $(+ $constraint)*), *>); }; ($trait:tt<$($param:tt: 'static + $constraint0:tt $(+ $constraint:tt)*), *>) => { as_boxed!(impl Hash for $trait<$($param: 'static + $constraint0 $(+ $constraint)*), *>); boxed_value_trait!($trait<$($param: 'static + $constraint0 $(+ $constraint)*), *>); }; ($trait:tt<$($param:tt: 'static + ?Sized + $constraint0:tt $(+ $constraint:tt)*), *>) => { as_boxed!(impl Hash for $trait<$($param: 'static + ?Sized + $constraint0 $(+ $constraint)*), *>); boxed_value_trait!($trait<$($param: 'static + ?Sized + $constraint0 $(+ $constraint)*), *>); }; } boxed_key_trait!(Key); #[cfg(test)] mod tests { use crate::*; use super::*; use std::collections::HashMap; use std::fmt::Debug; trait K1<K: KeyConstraint>: Key { fn say(&self, _k: K) { } as_boxed!(K1<K>); } #[derive(Hash, PartialEq, Eq, Debug, Clone)] struct S1 { a: i32, b: u32 } impl<K: KeyConstraint> K1<K> for S1 { as_boxed!(impl K1<K>); } boxed_key_trait!(K1<K: KeyConstraint>); #[test] fn hashcode() { let s = S1 { a: 1, b: 2 }; assert_eq!(s.hashcode(), s.clone().hashcode()); let bs: Box<dyn Key> = Box::new(s); assert_eq!(bs.hashcode(), bs.clone().hashcode()); let mut hasher = DefaultHasher::new(); bs.hash(&mut hasher); hasher.finish(); } #[test] fn hashmap() { let k = S1 { a: 1, b: 2 }; let v = S1 { a: 11, b: 22 }; let key: Box<dyn Key> = Box::new(k.clone()); let value: Box<dyn Value> = Box::new(v.clone()); let mut map = HashMap::<Box<dyn Key>, Box<dyn Value>>::new(); map.insert(key.clone(), value.clone()); assert_eq!(&value, map.get(&key).unwrap()); } trait SomeType0<K: KeyConstraint, V: ValueConstraint>: Key { fn say(&self, k: K, v: V); as_boxed!(SomeType0<K, V>); as_trait!(SomeType0<K, V>); } boxed_key_trait!(SomeType0<K: KeyConstraint, V: ValueConstraint>); trait SomeType1<K: KeyConstraint + Debug, V: ValueConstraint>: Key { fn say(&self, k: K, v: V); as_boxed!(SomeType1<K, V>); as_trait!(SomeType1<K, V>); } boxed_key_trait!(SomeType1<K: KeyConstraint + Debug, V: ValueConstraint>); trait SomeType2<K: ?Sized + KeyConstraint, V: ?Sized + ValueConstraint>: Key { fn say(&self, k: K, v: V); as_boxed!(SomeType2<K, V>); as_trait!(SomeType2<K, V>); } boxed_key_trait!(SomeType2<K: ?Sized + KeyConstraint, V: ?Sized + ValueConstraint>); trait SomeType3<K: 'static + KeyConstraint, V: 'static + ValueConstraint>: Key { fn say(&self, k: K, v: V); as_boxed!(SomeType3<K, V>); as_trait!(SomeType3<K, V>); } boxed_key_trait!(SomeType3<K: 'static + KeyConstraint, V: 'static + ValueConstraint>); trait SomeType4<K: 'static + ?Sized + KeyConstraint, V: 'static + ?Sized + ValueConstraint>: Key { fn say(&self, k: K, v: V); as_boxed!(SomeType4<K, V>); as_trait!(SomeType4<K, V>); } boxed_key_trait!(SomeType4<K: 'static + ?Sized + KeyConstraint, V: 'static + ?Sized + ValueConstraint>); }
true