text
stringlengths
8
4.13M
use serde::de::{DeserializeSeed, SeqAccess}; use crate::{Element, Value}; use crate::error::TychoError; use crate::serde::de::TychoDeserializer; pub struct SeqArrayDeserializer { array: Vec<Value>, } impl SeqArrayDeserializer { pub fn new(x: Vec<Value>) -> Self { Self { array: x } } } impl<'de> ...
pub mod button; pub mod container; pub mod event; pub mod font; pub mod layout; pub mod layout_builder; pub mod listener; pub mod text; pub mod quad; pub mod renderer; use std::any::Any; use std::cell::Cell; use slotmap::{new_key_type, Key, SecondaryMap}; use gristmill::geometry2d::*; use gristmill::util::forest::Fo...
#![allow(dead_code)] #[derive(RustcEncodable, RustcDecodable, Clone, Debug, Default)] pub struct MemMap { pub idt: ::interrupt::Idt, pub keyboard: ::keyboard::Keyboard, pub ram: ::memory::Ram, pub serial: ::serial::Serial, pub vram: ::video::Vram, } impl ::memory::Memory for MemMap { fn read_...
use std::sync::Arc; use std::cell::Cell; //immutability:is the variable trully safe in case the variable is pointed by two reference struct Point { x:i32, y:i32, } struct PointByCell { x:i32, y:Cell<i32>, } struct Inches(i32); fn main() { let mut x = 6; let y = &mut x; //reference ...
use crate::{Config, Error, Result}; use tokio::process::Command; const ALREADY_MASTER_ERR: &'static str = "pg_ctl: cannot promote server; server is not in standby mode"; pub async fn promote(config: &Config) -> Result<()> { let child = Command::new("pg_ctlcluster") .arg(format!("{}", config.cluster.ve...
extern crate proc_macro; extern crate quote; extern crate syn; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, DeriveInput}; /// This generates an implementation of shader inputs like /// /// ``` /// impl Vertex { /// fn vertex_attrib_pointers(gl: &gl::Gl) { /// let stride = 6 ...
use std::collections::{HashMap, HashSet, LinkedList}; // probably not the most optimal way of solving those tasks // but I don't have better idea at the moment // TODO(pixsll): optimize it! pub fn solve_v1() -> i32 { let data = super::load_file("day7.txt"); let mut bags_capable: HashSet<&str> = HashSet::new(...
fn main() {} #[cfg(test)] mod tests { #[test] fn you_can_assert() { assert!(true); } }
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct ExtendedIdentifiers { ext: Option<ExtendedIdentifiersExt>, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct ExtendedIdentifiersExt {}
use amethyst::{ core::timing::Time, ecs::prelude::{Read, System}, input::InputHandler, renderer::VirtualKeyCode, }; #[derive(Default)] pub struct ShadowDummySystem { pub counter: u64, } impl<'a,> System<'a,> for ShadowDummySystem { type SystemData = (Read<'a, Time,>, Read<'a, InputHandler<Stri...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] Blob_StartUpload(#[from] blob::start_...
use rascam::*; use std::{thread, time}; pub fn setup_camera(resolution_divider: u32) -> Result<SimpleCamera, CameraError> { let info = info().unwrap(); if info.cameras.len() < 1 { panic!("QR Scanner found 0 cameras"); } // Raspberry Pi HQ Cam resolution / resolution_divider let width: u32 ...
use serde_derive::Deserialize; mod differences; #[derive(Debug, Deserialize, PartialEq)] #[serde(untagged)] pub enum Encoding { Predefined(PredefinedEncoding), Dictionary(EncodingDictionary), } impl Encoding { pub fn lookup(&self, char_code: u8) -> Option<&GlyphName> { match self { En...
use std::str::FromStr; enum Operand { Position(usize), Immediate(i32), } impl Operand { fn new(mode: char, value: i32) -> CPUResult<Operand> { match mode { '0' => Ok(Operand::Position(value as usize)), '1' => Ok(Operand::Immediate(value)), _ => Err(CPUException:...
#[macro_use] pub mod terminal; pub mod cfg; pub mod commands; pub mod error; mod selected_envs; pub mod settings;
#[doc = "Register `MACFCR` reader"] pub type R = crate::R<MACFCR_SPEC>; #[doc = "Register `MACFCR` writer"] pub type W = crate::W<MACFCR_SPEC>; #[doc = "Field `FCB` reader - Flow control busy/back pressure activate"] pub type FCB_R = crate::BitReader<FCB_A>; #[doc = "Flow control busy/back pressure activate\n\nValue on...
pub mod collision; pub mod death; pub mod gravity; pub mod movement; pub mod plates;
use super::super::messages::WriteGTP; use super::*; use std::io; // TODO: Convert to and from tuples. #[derive(Clone, Debug, PartialEq)] pub enum Value { Empty, Collection(simple_entity::Value, Box<Value>), } impl Value { fn new(head: simple_entity::Value, tail: Value) -> Value { Value::Collection(head, Box::new...
#[cfg(test)] mod tests { use bae_utils::*; use bae_types::*; use std::fs::File; const SAMPLE_RATE: usize = 48_000; const INV_SAMPLE_RATE: AccurateMath = 1.0 / SAMPLE_RATE as AccurateMath; #[test] fn test_write_wav() -> Result<(), ()> { let mut t = SampleTrack::new(); for ...
mod check; mod definition; mod result; mod store; mod validation; mod value; pub use definition::{ValueDef, VariableDef}; pub use result::{ValueError, ValueResult}; pub use store::ValueStore; pub use validation::Validator; pub use value::Value; use crate::{qjs, Map, Mut, Ref, Result, Weak, WeakElement, WeakKey, WeakS...
use std::fmt; #[derive(Debug, PartialEq, Clone)] pub enum Token { Lparen, Rparen, Lbrace, Rbrace, Lsquare, Rsquare, Dot, Comma, Semicolon, Colon, Ref, Pipe, Arrow, OpMul, OpDiv, OpAdd, OpSub, OpRem, CompEqual, CompInEqual, CompGreaterEqual, CompGreater, CompLessEqual, CompLess, CompAnd, Co...
#![no_std] #![no_main] const SHOOT_SOUND: &'static [u8] = include_bytes!("../sfx/shoot.raw"); const EXPLODE_SOUND: &'static [u8] = include_bytes!("../sfx/explode.raw"); const BACKGROUND_MUSIC: &'static [u8] = include_bytes!("../sfx/background_music.raw"); use agb::display::tiled0::Background; use agb::display::{ ...
use super::Block; use super::Content as BlockContent; use crate::config::*; use crate::crypto::hash::{Hashable, H256}; use crate::crypto::merkle::MerkleTree; use crate::experiment::performance_counter::PayloadSize; /// The content of a voter block. #[derive(Serialize, Deserialize, Debug, Default, Clone)] pub struct Co...
#[doc = "Register `ETH_MACL4A1R` reader"] pub type R = crate::R<ETH_MACL4A1R_SPEC>; #[doc = "Register `ETH_MACL4A1R` writer"] pub type W = crate::W<ETH_MACL4A1R_SPEC>; #[doc = "Field `L4SP1` reader - L4SP1"] pub type L4SP1_R = crate::FieldReader<u16>; #[doc = "Field `L4SP1` writer - L4SP1"] pub type L4SP1_W<'a, REG, co...
use std::os; use std::io::File; fn main() { let args: ~[~str] = os::args(); if args.len() != 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let current_dir = std::os::getcwd(); let share1fname = args[1].clone(); let share2fname = args[2].clone(); ...
// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except accordin...
use super::*; use crate::agent::{agent_config::*, agent_vnet_test::*, *}; use crate::candidate::*; use crate::errors::*; use crate::network_type::*; use regex::Regex; use tokio::sync::{mpsc, Mutex}; #[tokio::test] async fn test_multicast_dns_only_connection() -> Result<(), Error> { let cfg0 = AgentConfig { ...
#[macro_use] extern crate lazy_static; extern crate cfg_if; extern crate wasm_bindgen; mod utils; use cfg_if::cfg_if; use wasm_bindgen::prelude::*; use std::collections::HashMap; cfg_if! { // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. if #[cfg(feature = "wee_all...
/** * $ sudo apt-get install pkg-config libssl-dev * * [dependencies] reqwest = "0.10" serde_json = "1.0" tokio = { version = "0.2", features = ["full"] } * */ // URL呼び出し #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let url = "http://openccpm.com/blog/" ; println!("call {}",...
use apllodb_shared_components::{ ApllodbResult, DatabaseName, Session, SessionWithDb, SessionWithTx, SessionWithoutDb, }; use apllodb_storage_engine_interface::{StorageEngine, WithDbMethods, WithoutDbMethods}; use super::sqlite_database_cleaner::SqliteDatabaseCleaner; pub async fn session_with_db<Engine: StorageE...
use crate::common::params::InnerHashParameters; use franklin_crypto::bellman::pairing::ff::{PrimeFieldRepr, ScalarEngine}; use franklin_crypto::bellman::pairing::Engine; extern crate num_bigint; extern crate num_integer; extern crate num_traits; use crate::common::utils::biguint_to_u64_array; use crate::traits::{Custom...
use crate::primes::find_prime_factors; pub fn phi(n: u64) -> u64 { let prime_map = find_prime_factors(n); let mut res = n; for (p, pow) in prime_map { res = res / p; res = res * (p - 1); } res }
use boxcars::{self, ParserBuilder}; #[test] fn test_sample1() { let data = include_bytes!("../assets/3d07e.replay"); let replay = ParserBuilder::new(&data[..]) .always_check_crc() .must_parse_network_data() .parse() .unwrap(); let frames = replay.network_frames.unwrap().fra...
use crate::schema::auth_requests; use crate::{db_conn, Error}; use common::{ chrono::{DateTime, Utc}, uuid::Uuid, }; use diesel::prelude::*; #[derive(Queryable, AsChangeset, Insertable, Debug, Clone)] #[table_name = "auth_requests"] pub struct AuthRequest { pub id: i64, pub created_at: DateTime<Utc>, ...
use super::input; use super::search; use std::process; pub fn run_cmd_query() { let cmd_input = input::get_cmd_input().unwrap_or_else(|err| { print!("Issue with receiving use arguments: {}\n", err); process::exit(1); }); let is_in_file = search::search_for_query(&cmd_input).unwrap_or_else(...
use std::collections::{HashMap, HashSet}; #[aoc_generator(day1)] pub fn to_vec_of_int(input: &str) -> Vec<i32> { input .split('\n') .collect::<Vec<_>>() .iter() .map(|line| line.parse::<i32>().unwrap()) .collect::<Vec<i32>>() } #[aoc(day1, part1)] pub fn day1_part1_solve(i...
use std::net::{IpAddr, Ipv6Addr, SocketAddr}; /// The capabilities a UDP socket supports on a certain platform. #[derive(Clone, Copy, Debug)] pub struct UdpCapabilities { /// The maximum amount of segments which can be transmitted if a platform /// supports Generic Send Offload (GSO). /// This is 1 if the ...
mod combat_data; mod content; mod def; mod simulation; mod vars; #[macro_use] extern crate serde_derive; use wasm_bindgen::prelude::*; use combat_data::{CombatSetup, HeroSetup}; use simulation::Simulation; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_a...
mod macros; pub fn is_lines_equal(s: &str, width: usize) -> bool { string_width_multiline(s) == width } fn string_width_multiline(text: &str) -> usize { #[cfg(not(feature = "color"))] { text.lines() .map(unicode_width::UnicodeWidthStr::width) .max() .unwrap_or(0...
//! Minimalist Thread Pool in Rust //! //! Glanceable source code for prototypes seeking brevity with transparency. use std::thread; use std::time::Instant; use crossbeam::channel::{ Sender, Receiver, unbounded }; use uuid::Uuid; use std::ops::Sub; type Job = Box<dyn FnOnce() + Send + 'static>; enum Mes...
use quote::quote_spanned; use syn::parse_quote; use super::{ FlowProperties, FlowPropertyVal, OperatorCategory, OperatorConstraints, OperatorWriteOutput, WriteContextArgs, RANGE_0, RANGE_1, }; /// > 1 input stream of pair tuples `(A, B)`, 2 output streams /// /// Takes the input stream of pairs and unzips eac...
use tcod::input::{ Key, Mouse}; use tcod::map::{ Map as FovMap}; use super::data::{ Object, Game, Tcod, PlayerAction, MessageLog }; use super::movement; use super::items; use super::menu; use super::mapping; use crate::{PLAYER, LEVEL_UP_BASE, LEVEL_UP_FACTOR, CHARACTER_SCREEN_WIDTH}; pub fn handle_keys( key: Key,...
use azure_core::headers::CommonStorageResponseHeaders; use bytes::Bytes; use http::response::Response; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct SetQueueMetadataResponse { pub common_storage_response_headers: CommonStorageResponseHeaders, } impl std::convert::TryFrom<&Response<Bytes>> for SetQ...
pub mod backend; pub mod widget; pub mod window; use backend::{Backend, BackendImpl}; use window::WindowBuilder; pub use window::Window; pub fn start<F>(init_fn: F) where F: FnOnce() -> WindowBuilder { BackendImpl::start(init_fn()); } #[macro_export] macro_rules! builder { ($builder_name:ident($ty:ide...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Clock control register"] pub cr: CR, #[doc = "0x04 - Clock configuration register (RCC_CFGR)"] pub cfgr: CFGR, #[doc = "0x08 - Clock interrupt register (RCC_CIR)"] pub cir: CIR, #[doc = "0x0c - APB2 peripheral r...
#[derive(Debug, Copy, Clone, PartialEq)] pub struct Action(u8); impl Action { pub fn new(pos: u8) -> Self { Action(pos) } pub fn position(&self) -> u8 { self.0 } }
//! Fraction is a lossless float type implementation that can be used for matching, ordering and hashing. //! //! The main goal of the project is to keep precision that floats cannot do. //! //! Base arithmetic implemented upon the [num](https://crates.io/crates/num) crate (in particular its [rational](https://crates.i...
// Copyright (c) 2019 Jason Holm // This program is licensed under the "MIT License". Please // see the file `LICENSE` for license terms. // Code adapted from the yew examples page // https://github.com/yewstack/yew/tree/master/examples/two_apps mod markdown; use markdown::*; use yew::html::Scope; use yew::App; us...
use common::Result; use harvest::Harvest; use structopt::StructOpt; #[derive(Debug, StructOpt)] pub struct ServerOptions { // short and long flags (-n, --namespace) will be deduced from the field's name #[structopt(short, long)] namespace: String, // // short and long flags (-o, --ouput) will be deduc...
use std::io; fn solve(x: isize, y: isize, s: String) -> isize { let s = s.replace("?", ""); let mut cost: isize = 0; let mut ahead = s.chars(); ahead.next(); for (fst, snd) in s.chars().zip(ahead) { if fst == 'C' && snd == 'J' { cost += x; } else if fst == 'J' && snd ...
mod parser; mod sexp; mod tokenizer; pub use crate::sexp::Sexp; use parser::{parse_many_tokens, ParseError}; use std::ops::Range; use tokenizer::{tokenize, TokenizationError}; #[derive(Debug, PartialEq, Eq)] pub enum Error { UnclosedParen(usize), ExtraCloseParen(usize), UnclosedString(usize), UnknownE...
use std::path::Path; use std::fs; mod lib_image; use crate::lib_image::image::*; mod lib_pixel; use crate::lib_pixel::pixel::*; fn new_with_file(filename: &str)->Image{ //creation struct image avec ouverture fichier println!("In file {}", filename); let content = fs::read_to_string(filename) .expect("Som...
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use crate::signature::BLS_SIG_LEN; use encoding::{blake2b_256, serde_bytes}; use serde::{Deserialize, Serialize}; /// The output from running a VRF #[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Default, Serialize, Deserialize)] #...
use std; #[derive(Debug)] pub enum Error { InvalidTypeCode(u8), InvalidEmoCode(u8), IOError(std::io::Error) }
// Vicfred // https://codeforces.com/problemset/problem/550/A // greedy use std::io; fn main() { let mut s = String::new(); io::stdin() .read_line(&mut s) .unwrap(); let s = s.trim(); let s: Vec<char> = s.chars().collect(); let mut fin: usize = s.len(); let mut found = false...
#[doc = "Register `CSR` reader"] pub type R = crate::R<CSR_SPEC>; #[doc = "Field `ADRDY_MST` reader - Master ADC ready This bit is a copy of the ADRDY bit in the corresponding ADC_ISR register."] pub type ADRDY_MST_R = crate::BitReader; #[doc = "Field `EOSMP_MST` reader - End of Sampling phase flag of the master ADC Th...
extern crate ctrlc; extern crate e2d2; extern crate tcp_proxy; extern crate time; #[macro_use] extern crate log; extern crate env_logger; extern crate ipnet; extern crate netfcts; extern crate separator; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use std::thread; use st...
use nom::multispace; use std::str; use common::{column_identifier_no_alias, integer_literal, Literal}; use column::Column; #[derive(Debug, Clone, Deserialize, Eq, Hash, PartialEq, Serialize)] pub enum ArithmeticOperator { Add, Subtract, Multiply, Divide, } #[derive(Debug, Clone, Deserialize, Eq, Hash...
struct Solution; impl Solution { pub fn search(nums: Vec<i32>, target: i32) -> i32 { if nums.is_empty() { return -1; } let (mut l, mut r) = (0, nums.len() - 1); let mut m; while l <= r { m = (l + r) / 2; if nums[m] == target { ...
// Copyright © 2019 Bart Massey // [This program is licensed under the "MIT License"] // Please see the file LICENSE in the source // distribution of this software for license terms. // Synthesizer demo example using synthkit-rs. use synthkit::*; fn main() { // Get a signal from a WAV file. let signal = get_s...
use crate::{ backend::QueryBuilder, expr::*, prepare::*, query::{condition::*, OrderedStatement}, types::*, value::*, Query, QueryStatementBuilder, SelectExpr, SelectStatement, }; #[cfg(feature = "with-json")] use serde_json::Value as JsonValue; /// Update existing rows in the table /// ///...
use std::fmt; const DAY: i32 = 24 * 60; #[derive(Debug, Eq, PartialEq)] pub struct Clock { minutes: i32, } impl Clock { pub fn new(hh: i32, mm: i32) -> Self { let mut minutes = (hh*60 + mm) % DAY; if minutes < 0 { minutes += DAY; } Clock { minutes, ...
#![allow(non_snake_case)] #![allow(dead_code)] use core::marker::Sized; use core::mem::{size_of, transmute}; use core::slice::*; use crate::usb::constants; //use crate::usb::macros; //use macros::show_streams; #[derive(Debug, Copy, Clone)] #[repr(C, packed)] //#[show_streams] pub struct Device { bLength: u8, ...
#![feature(test)] extern crate test; use std::mem::size_of; use std::mem::transmute; use std::sync::atomic::{AtomicUsize, Ordering}; use test::{black_box, Bencher}; // 64 Byte <- size of cache line #[repr(align(64))] struct Align64<T>(T); trait Atom { fn new() -> Self; fn get_ref(&self, ith: usize) -> &Ato...
#![feature(box_into_raw_non_null)] #![allow(unused)] use std::fs::File; use std::io::Read; use scan_fmt::*; use std::ptr::NonNull; #[derive(Debug, Clone, Copy)] struct Node<T> { prev: NonNull<Node<T>>, val: T, next: NonNull<Node<T>>, } impl<T> Node<T> { fn new(val: T) -> NonNull<Node<T>> { le...
use std::fs::File; use std::io::Write; use std::time::{SystemTime, UNIX_EPOCH}; fn main() { let mut f = File::create("src/inc.rs").unwrap(); writeln!(f, "const TIME: u64 = {};", SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()).unwrap(); println!("cargo:rerun-if-changed=build.rs"); prin...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ocamlrep::from; use ocamlrep::Allocator; use ocamlrep::FromError; use ocamlrep::FromOcamlRep; use ocamlrep::ToOcamlRep; use ocamlrep:...
mod cursesrenderer; pub use self::cursesrenderer::*;
// SPDX-FileCopyrightText: 2020-2021 HH Partners // // SPDX-License-Identifier: MIT use crate::CreationInfo; use super::ExternalDocumentReference; use serde::{Deserialize, Serialize}; /// ## Document Creation Information /// /// SPDX's [Document Creation Information](https://spdx.github.io/spdx-spec/2-document-creat...
use super::{Error, TagsConfiguration, TagsContext}; use std::collections::HashMap; use std::ffi::CStr; use std::os::raw::c_char; use std::process::abort; use std::sync::atomic::AtomicUsize; use std::{fmt, slice, str}; use tree_sitter::Language; const BUFFER_TAGS_RESERVE_CAPACITY: usize = 100; const BUFFER_DOCS_RESERVE...
#[derive(RustcDecodable,Debug,RustcEncodable)] pub struct SubscriptionList { object: String, has_more: bool, url: String, data: Vec<Subscription> } #[derive(RustcDecodable,Debug,RustcEncodable)] pub struct Subscription;
use std::cell::RefCell; use std::rc::Rc; struct Codec {} impl Codec { fn new() -> Self { Self {} } fn serialize(&self, root: Option<Rc<RefCell<TreeNode>>>) -> String { if let Some(root) = root { format!("{}({})({})", root.borrow().val, self.serialize(root.borrow().left.clone()...
use crate::common::types::VariableName; use ordered_float::OrderedFloat; use std::fmt; use std::result; use std::str::FromStr; #[derive(Debug, PartialEq, Eq, Clone)] pub(crate) struct SelectStatement { pub(crate) select_clause: SelectClause, pub(crate) table_references: Vec<TableReference>, pub(crate) wher...
use std::fmt; pub struct DisplayBandwidth { pub bandwidth: f64, pub as_rate: bool, } impl fmt::Display for DisplayBandwidth { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let suffix = if self.as_rate { "ps" } else { "" }; if self.bandwidth > 999_999_999_999.0 { //...
use rand::{Rng, RngCore}; use crate::color::RGB; pub trait Palette { fn generate(&self, n_colors: u32, rng: &mut dyn RngCore) -> Vec<RGB>; } #[derive(Copy, Clone)] pub struct UniformPalette; impl Palette for UniformPalette { fn generate(&self, n_colors: u32, _: &mut dyn RngCore) -> Vec<RGB> { let mu...
fn main() { // vector case_create_new_vector_1(); case_create_new_vector_2(); case_update_vector(); case_drop_vector(); case_read_elements_of_vectors(); case_ownership_in_vector(); case_iterate_vector(); case_use_enum_to_store_multiple_types(); // HashMap create_new_hash...
use std::rc::{Rc, Weak}; use std::cell::RefCell; use std::cmp::Ordering; use cpu::Cpu; use request::Request; #[derive(Debug)] pub enum EventType { Arrival(Rc<RefCell<Request>>), CtxSwitched(Rc<RefCell<Cpu>>), Departure(Rc<RefCell<Request>>), QuantumOver(Rc<RefCell<Cpu>>), Timeout(Weak<RefCell<Requ...
use futures::{SinkExt, StreamExt}; use reqwasm::websocket::*; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); const ECHO_SERVER_URL: &str = env!("ECHO_SERVER_URL"); #[wasm_bindgen_test] async fn websocket_works() { let ws = WebSocket::open(ECHO_SERVER_URL).unwrap(); let (mut sender, ...
use std::env; use std::fs; pub mod lexer; pub mod parser; pub mod typechecker; pub mod assembler; pub mod evaluator; fn main() { let args = env::args().collect::<Vec<_>>(); if args.len() == 2 { let path = &args[1]; let input = fs::read_to_string(path).expect("cant read file"); let tokens = lexer::t...
#[doc = "Register `CR2` reader"] pub type R = crate::R<CR2_SPEC>; #[doc = "Register `CR2` writer"] pub type W = crate::W<CR2_SPEC>; #[doc = "Field `PVDE` reader - Power voltage detector enable"] pub type PVDE_R = crate::BitReader<PVDE_A>; #[doc = "Power voltage detector enable\n\nValue on reset: 0"] #[derive(Clone, Cop...
use super::Control; use callback_helpers::{from_void_ptr, to_heap_ptr}; use std::ffi::{CStr, CString}; use std::mem; use std::os::raw::c_void; use ui::UI; use ui_sys::{self, uiButton, uiControl}; define_control! { /// A textual button which users can click on, causing a callback to run. rust_type: Button, ...
use futures::prelude::*; use runtime::fs::File; fn main() { let f = file::open("foo.txt").await?; let mut buffer = Vec::new(); let contents = f.read_to_end(&mut buffer).await?; println!("{:?}", contents); }
// High-level Internal Representation of GObject artifacts // // Here we provide a view of the world in terms of what GObject knows: // classes, interfaces, signals, etc. // // We construct this view of the world from the raw Abstract Syntax // Tree (AST) from the previous stage. use std::collections::HashMap; use pr...
use planpoker_common::{RoomMessage, RoomRequest}; use yew::prelude::*; use yew_router::push_route; use crate::{agents::RoomAgent, route::Route}; #[derive(Debug, Clone)] pub enum Msg { CreateRoom, RoomMessage(RoomMessage), } #[derive(PartialEq, Eq)] enum LobbyState { Loading, Idle, ...
//! A runtime implementation that runs everything on the current thread. mod arbiter; mod builder; mod runtime; mod system; pub use self::arbiter::Arbiter; pub use self::builder::{Builder, SystemRunner}; pub use self::runtime::Runtime; pub use self::system::System; /// Spawns a future on the current arbiter. /// ///...
use crate::utils::{sleep, wait_until}; use crate::{Net, Spec}; use ckb_app_config::CKBAppConfig; use log::info; use std::collections::HashSet; pub struct WhitelistOnSessionLimit; impl Spec for WhitelistOnSessionLimit { crate::name!("whitelist_on_session_limit"); crate::setup!(num_nodes: 5, connect_all: false...
extern crate libc; extern crate picohttpparser_sys; use libc::{c_char, c_int, size_t}; use std::mem; use std::slice; use picohttpparser_sys::*; fn slice_from_raw<'a>(pointer: *const c_char, len: size_t) -> &'a [u8] { unsafe { mem::transmute(slice::from_raw_parts(pointer, len)) } } struct ParsedHeaders { head...
//! # The XML `<obj>` format (character data) //! //! This module contains reader and writer and datastructures for //! the character data as serialized to XML. use serde::{Deserialize, Serialize}; use self::{ char::Character, dest::Destructible, flag::Flags, inv::Inventory, lvl::Level, mf::Minifig, mis::Miss...
mod basic_server; mod builder; mod raft_server; mod server; pub use basic_server::KvsBasicServer; pub use builder::KvsServerBuilder; pub use raft_server::KvRaftServer; pub use server::KvsServer; pub(crate) use server::ServerKind;
#![allow(dead_code)] // trait 约束和继承 // Rust 的 trait 的另外一个大用处是,作为泛型约束使用 use std::fmt::Debug; // 冒号后面加 trait 名字,就是这个泛型参数的约束条件 // 它要求这个 T 类型实现 Debug 这个 trait。这是因为 // 我们在函数体内,用到了 println! 格式化打印,而且用了 // {:?} 这样的格式控制符,它要求类型满足 Debug 的约束, // 否则编译不过。 // 泛型约束既是对实现部分的约束,也是对调用部分的约束 fn my_print<T: Debug>(x: T) { println!("The...
pub mod string_functions { /// Starting and index position take a slice of a string for x characterts /// /// # Examples /// /// ``` /// let alpha = "abcdefg"; /// let def = string_functions::sub_string(alpha, 4, 3); /// /// assert_eq!(def, "def"); /// ``` pub fn sub_string...
use std::task::{Context, Poll}; use actix_service::{Service, Transform}; use actix_web::{ dev::ServiceRequest, dev::ServiceResponse, http, Error, HttpMessage, HttpResponse, }; use futures_util::future::{ok, Either, Ready}; use crate::models::Session; use super::authenticate_token; pub struct Authentication; imp...
use itertools::Itertools; use std::cmp::{min, max}; // (hp, damage, armor) const BOSS: (i32, i32, i32) = (100, 8, 2); const PLAYER_HP: i32 = 100; // (cost, damage, armor) const WEAPONS: [(i32, i32, i32); 5] = [ (8, 4, 0), (10, 5, 0), (25, 6, 0), (40, 7, 0), (78, 8, 0), ]; // (cost, damage, armor...
use crate::types::affiliated_keywords::AffiliatedKeywords; use crate::types::{Element, GreaterElement, HasAffiliatedKeywords, Parent, Spanned}; use std::fmt; /// A special block. /// /// # Semantics /// /// Any block with name that is not recognized as another block is a special block. /// /// # Syntax /// /// ```text...
use std::collections::hash_map::RandomState; use std::collections::hash_set::Intersection; use std::collections::{HashMap, HashSet}; #[cfg(test)] mod tests { use super::*; #[test] fn it_maps_points() { let input = vec!["R8", "U5", "L5", "D3"] .into_iter() .map(String::from)...
use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use syntax::ast; use syntax::parse::{parser, DirectoryOwnership}; use syntax::source_map; use syntax::symbol::sym; use syntax_pos::symbol::Symbol; use crate::config::FileName; use crate::items::is_mod_decl; use crate::utils::contains_skip; type FileModM...
#![feature(advanced_slice_patterns, slice_patterns)] pub mod message_parsing; pub mod game_state;
use std::marker::PhantomData; use xtra_productivity::xtra_productivity; struct ActorWithParam<C> { ty: PhantomData<C>, } struct DummyMessage<C, D> { ty: PhantomData<(C, D)>, } struct DummyMessage2<A> { ty: PhantomData<A>, } trait Foo {} #[async_trait::async_trait] impl<C: 'static + Send> xtra::Actor fo...
/// An enum to represent all characters in the Mahajani block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Mahajani { /// \u{11150}: '𑅐' LetterA, /// \u{11151}: '𑅑' LetterI, /// \u{11152}: '𑅒' LetterU, /// \u{11153}: '𑅓' LetterE, /// \u{11154}: '𑅔' LetterO, ...
use crate::commands::wallet::wallet_query; use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use clap::Clap; use ic_types::Principal; /// List the wallet's controllers. #[derive(Clap)] pub struct ControllersOpts {} pub async fn exec(env: &dyn Environment, _opts: ControllersOpts) -> DfxResul...