text
stringlengths
8
4.13M
use noise::{NoiseFn, Seedable}; use rand::RngCore; fn main() { let make_noise = || { noise::OpenSimplex::new().set_seed(rand::thread_rng().next_u32()) }; let noises = [make_noise(), make_noise(),make_noise(), make_noise(),make_noise(), make_noise(),]; let f = |i| { i as f64 / 10.0 }; for y in (-40..=...
struct Error { message: str }
use std::error::Error; use std::fmt; #[derive(Debug, Clone)] pub enum CmdError { UnknownError, } impl fmt::Display for CmdError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { Self::UnknownError => "unknown erro...
// Copyright 2016 The Grin Developers // // 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 agree...
// Copyright 2020 <盏一 w@hidva.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,...
//! Carryless multiplication over GF(2^64) based on the PCLMULQDQ CPU intrinsics //! on `x86` and `x86_64` target architectures. use super::GfElement; use aead::{consts::U8, generic_array::GenericArray}; #[cfg(target_arch = "x86")] use core::arch::x86::*; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::*; typ...
fn unformatted_function( param : bool) -> bool { return param } fn main() { unformatted_function( false ); let x = 1; }
//! This is merged into a default manifest in order to form the full package manifest: //! //! ```cargo //! [dependencies] //! boolinator = "=0.1.0" //! tokio = { version = "1", features = ["full"] } //! ``` use boolinator::Boolinator; #[tokio::main] async fn main() { println!("--output--"); println!("{:?}", t...
use std::slice::Iter; enum Color { White, Yellow, Green, Blue, Orange, Red, } impl Color { fn iterator() -> Iter<'static, Color> { static COLORS: [Color; 6] = [Color::White, Color::Yellow, Color::Green, Color::Blue, Color::Orange, Color::Red]; COLORS.iter() ...
use cssparser::{Color as CSSColor, Parser, ParserInput, RGBA}; use crate::error::SkError; use crate::gradient::CanvasGradient; use crate::sk::ImagePattern; #[derive(Debug, Clone)] pub enum Pattern { Color(RGBA, String), Gradient(CanvasGradient), ImagePattern(ImagePattern), } impl Pattern { #[inline(always)] ...
//! Module contains structs and traits, required for proper interaction with Telegram server. #[doc(hidden)] mod observer; /// TDlib API methods. pub mod api; #[allow(clippy::module_inception)] /// Handlers for all incoming data pub mod client; pub mod errors; pub use client::{AuthStateHandler, Client, ClientBuilder,...
mod higherlower; pub use higherlower::*; use crate::commands::MyCommandOption; fn hl_options() -> Vec<MyCommandOption> { vec![] }
use crate::{ node::{Node, Tickable}, status::Status, }; /// A node whose status is determined by running a function on its child's /// status. /// /// This node will tick its child and then run the supplied function on the /// child's return status. /// /// # State /// /// **Initialized:** Depends on function....
use crate::input::script_update; use crate::protos::cao_common; use crate::protos::cao_script; use caolo_sim::{components::CaoIrComponent, indices::ScriptId}; use std::convert::TryInto; use tonic::{Response, Status}; use tracing::debug; #[derive(Clone)] pub struct ScriptingService { world: crate::WorldContainer, }...
#[macro_use] extern crate lazy_static; use std::env; mod stage1; mod stage2; fn ident(mul: usize, len: usize) -> String { format!("{: <1$}", "", len*mul) } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { println!("Not enough arguments, specify input file!"); ...
//! Implemented an [Object-Oriented Design Pattern] //! //! Type based state machine. //! //! [object-oriented design pattern]: https://doc.rust-lang.org/book/ch17-03-oo-design-patterns.html use std::error::Error; use the_book::ch17::sec03::Post; fn main() -> Result<(), Box<dyn Error>> { let mut post = Post::new(...
use openssl::symm::{encrypt, decrypt, Cipher}; use std::cell::RefCell; use crate::util::KtStd; use std::io::{stdin, Write}; use std::str::from_utf8; use web_view::*; mod util; use regex::Regex; use std::fs::File; #[macro_use] extern crate lazy_static; lazy_static! { static ref CIPHER: Cipher = Cipher::aes_256_cbc...
use std::os; fn fib(n: i32) -> i32{ if n==0 { return 0; } if n==1 { return 1; } return fib(n-1)+fib(n-2); } fn main(){ let mut n : i32 = 0; if os::args().len()>1 { let arg1 = os::args()[1].trim().parse::<i32>(); n = match arg1{ Some(arg1) => arg1, None => { ...
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod sse { #[cfg(target_arch = "x86")] use std::arch::x86::*; #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use std::i32::MAX; /// Skiplist will hold 16 keys internally pub const SKIP_LEN: usize = 16; #[derive(Debug, Cl...
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * file at the top-level directory of this distribution. * * Licensed u...
#[doc = "Register `VMSR` reader"] pub type R = crate::R<VMSR_SPEC>; #[doc = "Field `AVDO` reader - analog voltage detector output on V&lt;sub>DDA&lt;/sub> This bit is set and cleared by hardware. It is valid only if AVD on VDDA is enabled by the AVDEN bit. Note: Since the AVD is disabled in Standby mode, this bit is eq...
//! This module implements the worker of the master-worker parallel implementation of the search. //! A worker goes into idle state immediately after being spawned. Before becoming idle, a worker //! checks if it is the last thread to become idle and sends a `Result(None)` to the master to //! indicate that a new sear...
use std::collections::HashMap; use std::error::Error; use std::fs::File; use crate::account::Account; use crate::amount::Amount; use crate::transaction::{Transaction, TransactionStatus, TransactionType}; use crate::transaction_row::TransactionRow; #[derive(Debug)] pub struct PaymentEngine { tx_by_txid: HashMap<u3...
use serde::{Deserialize, Serialize}; use tracing::warn; use crate::errors::*; use crate::request::{FilterOptions, ModelRequest, RequestDetails, RequestParameters}; use crate::serializers::from_str; use std::collections::HashMap; pub(crate) fn model_path( portal: impl std::fmt::Display, project: impl std::fmt:...
//! The Trace trait must be implemented by every type that can be GC managed. use heap::TraceStack; /// Trace trait. Every type that can be managed by the GC must implement this trait. /// This trait is unsafe in that incorrectly implementing it can cause Undefined Behavior. pub unsafe trait Trace { /// If the ...
//! Async I2C API //! //! This API supports 7-bit and 10-bit addresses. Traits feature an `AddressMode` //! marker type parameter. Two implementation of the `AddressMode` exist: //! `SevenBitAddress` and `TenBitAddress`. //! //! Through this marker types it is possible to implement each address mode for //! the traits ...
//! Starting and maintaining processes, and the main entry point use super::{sub_process::launch_python, Command, Handle, SharedReceiver, SubProcessEvent}; use anyhow::Context; use std::path::PathBuf; use std::sync::Arc; use tokio::sync::{broadcast, mpsc, Mutex}; use tracing::Instrument; use tracing::{info, trace, war...
use crate::todo; #[derive(Debug)] pub enum Command { Add(todo::Todo), Delete(todo::Todo), // ShowAll, // Update(Todo), } impl From<Vec<String>> for Command { fn from(args: Vec<String>) -> Command { // TODO: length of needed arguments differs for commands. The error handling should reflect ...
use std::fs; use std::collections::HashSet; fn part1(input: &[Vec<&str>]) { let sum: usize = input.iter() .map(|group| { group.iter().flat_map(|answers| answers.chars()).collect::<HashSet<char>>() }) .map(|answers| answers.len()) .sum(); println!("{}", sum); } fn pa...
use std::collections::HashMap; use std::net::SocketAddr; use std::num::NonZeroUsize; use std::sync::Arc; use std::time::Duration; use capnp::message::{Builder, ReaderOptions}; use slog::{debug, error, info, o, warn, Logger}; use thiserror::Error; use futures3::channel::mpsc::Sender; use futures3::channel::oneshot; us...
/*! ```rudra-poc [target] crate = "beef" version = "0.4.4" [[target.peer]] crate = "crossbeam-utils" version = "0.8.0" [report] issue_url = "https://github.com/maciejhirsz/beef/issues/37" issue_date = 2020-10-28 rustsec_url = "https://github.com/RustSec/advisory-db/pull/696" rustsec_id = "RUSTSEC-2020-0122" [[bugs]]...
use quick_xml::{XmlReader, XmlWriter, Element, Event}; use quick_xml::error::Error as XmlError; use fromxml::{self, FromXml}; use toxml::{ToXml, XmlWriterExt}; use error::Error; use category::Category; use guid::Guid; use enclosure::Enclosure; use source::Source; use extension::ExtensionMap; use extension::itunes::ITu...
#![no_std] #![no_main] use apa102_spi::Apa102; use embedded_hal::blocking::delay::DelayMs; use panic_halt as _; use smart_leds::hsv::{hsv2rgb, Hsv}; use smart_leds::SmartLedsWrite; use trinket_m0 as hal; use trinket_m0::bindings as asf; #[no_mangle] pub unsafe extern "C" fn main() { asf::system_init(); /* ma...
use std::path::Path; use std::sync::Arc; use std::{fs::File, path::PathBuf}; use fehler::throws; use serde::Deserialize; use stable_eyre::eyre::{self, Error, WrapErr}; use toml::value::Datetime; use crate::metrics::Consumer; use crate::metrics::{self, Graphql}; mod high_contributor; mod issue_closure; mod repo_info;...
#[doc = "Register `OUTAR` reader"] pub type R = crate::R<OUTAR_SPEC>; #[doc = "Register `OUTAR` writer"] pub type W = crate::W<OUTAR_SPEC>; #[doc = "Field `POL1` reader - Output 1 polarity"] pub type POL1_R = crate::BitReader; #[doc = "Field `POL1` writer - Output 1 polarity"] pub type POL1_W<'a, REG, const O: u8> = cr...
mod ptrace; extern crate getopts; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); use std::env; use getopts::Options; use std::io; use std::io::Write; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} PATCH [options]", program); print!("{}", opts.usage(&brief)); } #[de...
use std::fmt; use std::fmt::{Display, Formatter}; pub(crate) struct MetricsConfig { pub(crate) print_only: bool, pub(crate) metrics_url: String, } impl MetricsConfig { pub(crate) fn new(metrics_url: String) -> MetricsConfig { MetricsConfig { print_only: metrics_url.eq("default"), ...
extern crate serde; #[macro_use] extern crate serde_json; extern crate serde_yaml; #[macro_use] extern crate serde_derive; extern crate csv; extern crate envy; #[macro_use] extern crate prettytable; extern crate handlebars; extern crate indicatif; extern crate chrono; #[macro_use] extern crate clap; #[macro_use] exter...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { super::results, failure::{bail, Error, ResultExt}, fidl_test_inspect_validate as validate, fuchsia_component::client as fclient, ...
use crate::{qjs, Error, Result, Set}; use nom::{ branch::alt, bytes::complete::{tag, take_while1}, character::complete::{char, line_ending, not_line_ending, space0, space1}, combinator::{all_consuming, eof, iterator, map, not, opt, value}, multi::separated_list1, sequence::{delimited, terminated...
pub mod eventsourcing; pub mod aggregate; pub mod usecase; pub mod inmemory_eventstore; pub mod snapshotter; pub mod dao; pub mod projector; use aggregate::{BankAccountEvent, BankAccount}; use eventsourcing::{EventStream, EventStore, EventPublisher}; pub type BankAccountEventStore = dyn EventStore<Event = BankAccount...
//! Read and write [ASPRS LAS](https://www.asprs.org/committee-general/laser-las-file-format-exchange-activities.html) //! point cloud data. //! //! # Reading //! //! Create a `Reader` from a `Path`: //! //! ``` //! use las::Reader; //! let reader = Reader::from_path("tests/data/autzen.las").unwrap(); //! ``` //! //! O...
#![deny(clippy::pedantic)] #![feature(never_type)] #[macro_use] extern crate serde_derive_state; mod arguments; pub mod classical; pub mod gillespie; pub mod skipping_gillespie;
use std::fs::File; use std::io::prelude::*; use crate::display::{ FONT_SET, CHIP8_HEIGHT, CHIP8_WIDTH }; use rand::Rng; pub struct CPU { pub opcode: u16, pub memory: [u8; 4096], pub v: [u8; 16], pub i: usize, pub pc: usize, pub delay_timer: u8, pub sound_timer: u8, pub stack: [u16; 16...
pub fn apple() { }
use crate::bool_to_option; use std::borrow::Cow; use wasm_bindgen::prelude::*; use yew::prelude::*; #[wasm_bindgen(module = "/build/mwc-formfield.js")] extern "C" { #[derive(Debug)] type Formfield; #[wasm_bindgen(getter, static_method_of = Formfield)] fn _dummy_loader() -> JsValue; } loader_hack!(For...
use std::env; use std::path::PathBuf; fn main() { let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); tonic_build::configure() .out_dir(out_dir) .compile(&["proto/kvs.proto"], &["proto"]) .unwrap(); let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); tonic_build::c...
use std::{ ops::{Add, Deref, Sub}, time::Duration, }; #[derive(Debug, Default)] pub struct Animate<T> { current: T, target: T, speed: f32, } impl<T> Animate<T> { pub fn new(start: T, target: T, speed: f32) -> Self { Self { current: start, target, spe...
//! # youchoose //! //! A simple, easy to use command line menu for Rust. //! //! //! //! ## Usage //! //! There are two methods you need to be familiar with to get started: //! `Menu::new` which takes an `Iterator` as an argument, and `Menu::show` //! which initializes `ncurses` and displays the menu. //! //! Here is ...
use futures::{future, Future}; use log::{debug, warn}; use rmp_rpc::{Client, ServiceWithClient, Value}; use std::collections::HashMap; enum Request<'a> { Poll, Specs, Function(&'a str), Autocmd(&'a str, &'a str), Command(&'a str), Unknown(&'a str), } impl<'a> From<&'a str> for Request<'a> { ...
extern crate diesel; #[macro_use] extern crate diesel_migrations; use std::path::Path; use std::{env, fs}; use clap::{crate_authors, crate_description, crate_version, App as CliApp, Arg, ArgMatches}; use config::TomlConfig; use failure::ResultExt; use log::{error, info, warn}; use pahkat_common::ProgressOutput; use s...
mod front_of_house { pub mod hosting { pub fn add_to_waitlist() { println!("add_to_waitlist: {:?}", "add_to_waitlist") } } } use front_of_house::hosting; // 从相对路径引入 pub fn eat_at_restaurant() { hosting::add_to_waitlist(); hosting::add_to_waitlist(); hosting::add_to_wait...
use std::fs::*; use std::path::*; use std::process; use ini::Ini; fn home_config_file() -> String { let config_dir = match dirs::config_dir() { Some(d) => d, None => { error!("no home directory available"); process::exit(1) }, }; let cache_dir = match dirs::cache_dir() { Some(d) => ...
use crate::requestlist::RequestList; use crate::input::{ Input }; use crate::proxy::{ Proxy }; use crate::extractor::{ Extractor }; use std::{ convert::{ TryFrom } }; use crate::storage::Storage; use futures::prelude::*; use futures::{ stream::{ StreamExt } }; pub struct Crawler { input: Inpu...
#[macro_use] extern crate diesel_migrations; embed_migrations!(); #[actix_web::main] async fn main() -> anyhow::Result<()> { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); let configuration = group_expenses::Settings::new()?; let db_pool = group_expenses::get_...
//! blsmsk /// Get mask up to lowest set bit. pub trait Blsmsk { /// Get mask up to lowest set bit. /// /// Sets all the bits of the result to `1` up to and including the lowest /// set bit of `self`. /// /// If `self` is zero, all the bits of the result are set. /// /// # Instructions ...
use std::io::{self, BufRead}; use std::convert::TryInto; use regex::Regex; fn main() { let mut valid_count_a = 0; let mut valid_count_b = 0; let re = Regex::new(r"^(\d*)-(\d*) ([a-z]): ([a-z]*)$").unwrap(); for wrapped_line in io::stdin().lock().lines() { let line = wrapped_line.unwrap(); ...
use futures::Future; use hyper::{Client, Error as HyperError, StatusCode, Uri}; use hyper::client::HttpConnector; use hyper_tls::HttpsConnector; use tokio_core::reactor::Core; use model::SubscriptionConfirmation; #[derive(Debug)] #[allow(unused)] pub(crate) enum SubscriptionConfirmationError { BadStatus(StatusCod...
use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("guessing game"); let randnum=rand::thread_rng().gen_range(1,101); let mut count=1; loop{ println!("please input a number"); let mut guess=String::new(); io::stdin().read_line(&mut guess) ...
use super::common::SyncBackend; use super::error::{MogError, MogResult}; use super::storage::Storage; pub use self::message::{Command, Request, Response}; pub mod evented; pub mod message; pub mod threaded; /// The tracker object. pub struct Tracker { backend: SyncBackend, storage: Storage, } impl Tracker {...
fn main() { let x = 2.1; let y: f32 = 3.1; let z: f64 = (x + y).into(); println!("z={}", z); let sum = 5 + 10; let difference = 95.5 - 4.3; let product = 4 * 30; let quotient = 56.7; let remainder = 43 % 5; let s = 1; let s = s + 1; let c : char = 'a'; let tup =...
//! Initialization code #![no_std] #[allow(unused_extern_crates)] // NOTE(allow) bug rust-lang/rust53964 extern crate panic_itm; // panic handler pub use cortex_m::{asm::bkpt, iprint, iprintln, peripheral::ITM}; pub use cortex_m_rt::entry; //pub use stm32f3_discovery::stm32f3xx_hal; use stm32f3xx_hal::prelude::*; p...
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::env; use std::sync::{Mutex, Arc}; use std::thread; struct Table { forks: Vec<Mutex<()>>, } fn for_x_secs(max: u32) -> u32 { let secs = rand::thread_rng().gen_range(1, max + 1); return secs; } struct Philosopher { name: String, born...
use std::{ cmp::{Ordering, Reverse}, sync::Arc, }; use chrono::{DateTime, Utc}; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{GameMode, User, Username}; use twilight_model::{ application::interaction::{ application_command::{CommandDataOption, CommandOptionValue}, Applica...
#[macro_use] extern crate lazy_static; mod ecdsa; mod eddsa; mod error; mod handles; mod rsa; mod signature; mod signature_keypair; mod signature_op; mod signature_publickey; use handles::*; use signature::*; use signature_keypair::*; use signature_op::*; use signature_publickey::*; pub use error::{CryptoError, Wasi...
#[doc = "Register `APB2LPENR` reader"] pub type R = crate::R<APB2LPENR_SPEC>; #[doc = "Register `APB2LPENR` writer"] pub type W = crate::W<APB2LPENR_SPEC>; #[doc = "Field `TIM1LPEN` reader - TIM1 clock enable during sleep mode Set and reset by software."] pub type TIM1LPEN_R = crate::BitReader; #[doc = "Field `TIM1LPEN...
extern crate rand; use rand::{thread_rng, Rng}; use std::{thread, time}; use std::fmt; #[derive(Clone)] struct Memento { money: u32, fruits: Vec<String>, } impl Memento { fn new(money: u32) -> Memento { Memento { money: money, fruits: Vec::new(), } } fn ge...
#[doc = "Register `SMPR` reader"] pub type R = crate::R<SMPR_SPEC>; #[doc = "Register `SMPR` writer"] pub type W = crate::W<SMPR_SPEC>; #[doc = "Field `SMP` reader - Sampling time selection"] pub type SMP_R = crate::FieldReader<SMP_A>; #[doc = "Sampling time selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug,...
use std::fmt::Display; use std::net::SocketAddr; use regex::Regex; use serde::Serialize; use serde_json::json; use tokio_util::codec::LinesCodecError; pub fn serialize_msg<T>(msg: T) -> String where T: Serialize + serde::de::DeserializeOwned, { json!(msg).to_string() } pub fn deserialize_msg<T>(msg: Result<(...
use crate::geometry::Point; use nalgebra_glm as glm; #[rustfmt::skip] #[inline] pub fn viewport_scale(width: f32, height: f32) -> glm::Mat4 { let w = width; let h = height; glm::mat4(2.0 / w, 0.0, 0.0, 0.0, 0.0, 2.0 / h, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, ...
#![no_std] use zoon::*; mod app; #[wasm_bindgen(start)] pub fn start() { start!(app) }
use byteorder::{ByteOrder, NativeEndian}; use crate::{ traits::{Emitable, Parseable}, DecodeError, Field, }; /// Generic queue statistics #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct TcStats { /// Number of enqueued bytes pub bytes: u64, /// Number of enqueued packets pub packets: u...
use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::{ Attribute, DataEnum, DataStruct, Error, Fields, FieldsNamed, FieldsUnnamed, GenericParam, Generics, Ident, Index, Meta, NestedMeta, Type, TypeParamBound, }; type Str = &'static str; type FieldFindResult<T> = Result<T, FieldFindError...
use crate::output::ElasticsearchOutput; use glob::glob; use log::{info, warn}; use rayon::prelude::*; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; pub struct Loader<'a> { input_dir: &'a str, config_file: &'a str, } impl<'a> Loader<'a> { pub fn new(input_dir: &'a str, config_f...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod job_collections { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub as...
#![no_std] extern crate spin; extern crate x86_64; use x86_64::instructions::interrupts; use core::ops::{Deref, DerefMut}; pub struct Mutex<T: ?Sized>(spin::Mutex<T>); pub struct MutexGuard<'a, T: ?Sized + 'a>{ guard: spin::MutexGuard<'a, T>, enable_interrupts: bool, } impl<T> Mutex<T> { pub const fn new...
#[derive(Default, PartialEq, Debug)] struct Vec2(i32, i32); impl Vec2 { fn rot_right90(&mut self) { // Apply right rotation matrix. // | 0 1 | // | -1 0 | *self = Vec2(self.1, -self.0); } fn rot_left90(&mut self) { // Apply left rotation matrix. // | 0 -1 |...
use std::collections::HashMap; use std::str::FromStr; use crate::util::lines_from_file; pub fn day21() { println!("== Day 21 =="); let input = lines_from_file("src/day21/input.txt"); let a = part_a(&input); println!("Part A: {}", a); let b = part_b(&input); println!("Part B: {}", b); } fn par...
mod helpers; mod tokens; use crate::vecpointer::VecPointerRef; pub use tokens::Token; use thiserror::Error; #[derive(Error, Debug)] pub enum LexError {} /// Tokenize an Xpath string to symbols for used in parsing later. pub fn lex(text: &str) -> Result<Vec<Token>, LexError> { let mut symbols: Vec<Token> = Vec::n...
use std::fmt; use std::sync::atomic::{AtomicIsize, Ordering}; use std::sync::Arc; use std::time::Duration; use super::blocking::SyncBlocker; use crate::cancel::trigger_cancel_panic; use crate::park::ParkError; use crossbeam::queue::SegQueue; /// Semphore primitive /// /// semaphores allow threads and coroutines to sy...
use std::path::{Component, Path, PathBuf}; #[inline] fn decode_percents(string: &str) -> String { percent_encoding::percent_decode_str(string) .decode_utf8_lossy() .into_owned() } fn normalize_path(path: &Path) -> PathBuf { path.components() .fold(PathBuf::new(), |mut result, p| match ...
use serde::{Deserialize, Serialize}; use crate::response::common::{AggsWrapper, HitsWrapper, Shards}; #[derive(Serialize, Deserialize, Debug)] pub struct ScrollResponse<T> { #[serde(rename = "_scroll_id")] pub scroll_id: String, pub took: u64, pub timed_out: bool, #[serde(rename = "_shards")] ...
use anyhow::Result; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use structopt::StructOpt; use taskpaper::Database; #[derive(Debug, Serialize, Deserialize)] struct Formats { formats: HashMap<String, taskpaper::FormatOptions>, } #[derive(StructOpt, Debug)] pub struct CommandLineArguments {} ...
use serde_json; use serde_yaml; use toml; use std::io; error_chain!{ types { Error, ErrorKind, ResultExt, Result; } links { } foreign_links { Io(io::Error); Json(serde_json::Error); Yaml(serde_yaml::Error); Toml(toml::de::Error); } errors { } ...
#![no_std] #[cfg(feature = "std")] extern crate std; pub mod palette; #[cfg(feature = "std")] pub mod stopwatch; #[cfg(all(feature = "std"))] pub mod io;
mod client; mod server; use std::net::SocketAddr; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use bytes::{Buf, BufMut}; pub use client::QuicClientEndpoint; use futures::{pin_mut, Future, Stream, StreamExt}; use messagebus::error::GenericError; use messagebus::{ Action, Bus, Event, EventBoxed...
use std::borrow::Borrow; use std::collections::btree_map::*; use std::collections::BTreeMap; use std::hash::Hash; use std::iter::{FromIterator, IntoIterator}; use std::ops::{Index, IndexMut}; /// A `BTreeMap` that returns a default when keys are accessed that are not present. #[derive(PartialEq, Eq, Clone, Debug)] pub...
use conrod_core::{ self, widget, widget_ids, Colorable, Labelable, Point, Positionable, Widget, Borderable, {position::Relative} }; use std::iter::once; use crate::support; use crate::gui::tile; #[derive(WidgetCommon)] pub struct Board<'a> { #[conrod(common_builder)] common: widget::CommonBuilder, sty...
//! An asynchronous implementation of [STUN][RFC 5389] server and client. //! //! # Examples //! //! An example that issues a `BINDING` request: //! //! ``` //! # extern crate fibers_global; //! # extern crate fibers_transport; //! # extern crate futures; //! # extern crate rustun; //! # extern crate stun_codec; //! # ...
//! This crates contains the code necessary to solve Advent of Code day 21, //! all written in Rust. use std::fs::File; use std::io::prelude::*; use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; /// Read the day's input data from a file. /// /// Returns a [Result<String>](std::io::Result). /// /// # A...
use std::any::{Any, TypeId}; pub mod component_store; pub mod components_lib; pub mod entity_store; pub mod system; //ENTITY #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Entity { pub id: u32, } //COMPONENT pub trait Component: Any {} impl<T: Any> Component for T {} //TODO: Clean & implement pub...
/* * Copyright (c) 2013, David Renshaw (dwrenshaw@gmail.com) * * See the LICENSE file in the capnproto-rust root directory. */ use std; use common::*; use endian::*; use message::*; pub mod InputStreamMessageReader { use std; use endian::*; use message::*; pub fn new<T>(inputStream : @ std::io::...
//! # Reading MSSQL sysdiagrams #[macro_use] extern crate nom; pub mod core; pub mod io; pub mod parser;
/* Given a list of integers, use a vector and return the mean (average), median (when sorted, the value in the middle position), and mode (the value that occurs most often; a hash map will be helpful here) of the list. */ use std::collections::HashMap; #[derive(Debug)] pub struct Properties { vector: Vec<i32>, ...
#[doc = "Register `DMACCATxDR` reader"] pub type R = crate::R<DMACCATX_DR_SPEC>; #[doc = "Register `DMACCATxDR` writer"] pub type W = crate::W<DMACCATX_DR_SPEC>; #[doc = "Field `CURTDESAPTR` reader - Application Transmit Descriptor Address Pointer"] pub type CURTDESAPTR_R = crate::FieldReader<u32>; #[doc = "Field `CURT...
//! Building blocks for a recursive descent LL(1) parsing method. //! //! The general idea is that a grammar (without left recursion) is translated to a series of //! conditional and unconditional 'acceptance' methods. //! //! For example, assuming we have a parser for integers: //! //! sum = integer | integer + sum //...
//! `FromCast` and `IntoCast` implementations for portable 64-bit wide vectors #![rustfmt::skip] use crate::*; impl_from_cast!( i8x8[test_v64]: u8x8, m8x8, i16x8, u16x8, m16x8, i32x8, u32x8, f32x8, m32x8, i64x8, u64x8, f64x8, m64x8, isizex8, usizex8, msizex8 ); impl_from_cast!( u8x8[test_v64]: i8x8, m8x8,...
pub type EFI_HANDLE = *const (); pub type EFI_RUNTIME_SERVICES = *const (); pub type EFI_CONFIGURATION_TABLE= *const (); pub type EFI_PHYSICAL_ADDRESS = usize; //EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID \ // {0x9042a9de,0x23dc,0x4a38,0x96,0xfb,0x7a,0xde,\ // 0xd0,0x80,0x51,0x6a} pub struct EFI_TABLE_HEADER { pub Signa...
use crate::action::*; use crate::time::*; use slog::debug; use std::rc::Rc; #[derive(Clone, Debug)] pub struct Cast { /// When we'll have finished casting. pub finish: Timestamp, /// Whatever we're currently casting. pub action: Action, } /// The `Player` stores MP, TP, buffs, and statuses (buffs/debu...
use log::debug; use css_in_rust::Style; use yew::{html, Component, Properties, ComponentLink, Html, ShouldRender}; pub struct Scene { link: ComponentLink<Self>, style: Style, } impl Component for Scene { type Message = (); type Properties = (); fn create(_props: Self::Properties, link: ComponentL...