text
stringlengths
8
4.13M
use serde::Deserialize; use std::path::PathBuf; #[derive(Debug, Copy, Clone, Deserialize)] pub(crate) enum TiledMapOrientation { #[serde(alias = "orthogonal")] Orthogonal, #[serde(alias = "isometric")] Isometric, #[serde(alias = "staggered")] Staggered, #[serde(alias = "hexagonal")] Hex...
use crate::indices::{EntityId, WorldPosition}; use crate::profile; use crate::storage::views::{DeferredDeleteEntityView, UnsafeView, View}; use crate::tables::JoinIterator; use crate::{components as comp, join}; use crate::{geometry::Axial, terrain::TileTerrainType}; use rand::Rng; use tracing::{debug, error, trace}; ...
use crate::utils::asserts::block::test_block_array; use crate::utils::asserts::delegate::{assert_delegate_data, test_delegate_array}; use crate::utils::asserts::meta::assert_meta; use crate::utils::asserts::wallet::test_wallet_array; use crate::utils::mockito_helpers::{mock_client, mock_http_request, mock_post_request}...
// // 0 1 0 Mnemosyne: a functional systems programming language. // 0 0 1 (c) 2015 Hawk Weisman // 1 1 1 hi@hawkweisman.me // // Mnemosyne is released under the MIT License. Please refer to // the LICENSE file at the top-level directory of this distribution // or at https://github.com/hawkw/mnemosyne/. // //!...
#![no_std] #![feature(generic_associated_types)] #![feature(asm)] #![feature(min_type_alias_impl_trait)] #![feature(impl_trait_in_bindings)] #![feature(type_alias_impl_trait)] #![allow(incomplete_features)] pub(crate) use stm32_metapac as pac; // This must go FIRST so that all the other modules see its macros. pub mo...
use json::JsonValue; pub trait SelectionLens { fn select<'a>(&self, input: Option<&'a JsonValue>) -> Option<&'a JsonValue>; } pub trait SelectionLensParser { fn try_parse<'a>( &self, lens_pattern: Option<&'a str>, ) -> Result<(Box<dyn SelectionLens>, Option<&'a str>), Option<&'a str>>; } ...
use std::f32::INFINITY; use crate::consts::EPSILON; use crate::types::{Vec3}; use crate::range::Range; use crate::collider::{ColliderType, InternalCollider}; use crate::sphere_collider::{InternalSphereCollider}; use crate::plane_collider::{InternalPlaneCollider}; use crate::mesh_collider::{InternalMeshCollider}; use c...
use std::time::Instant; extern crate mylib; use mylib::run; fn main() { let now = Instant::now(); let dist = String::from("C:/Users/zhangshiyang/.vscode/extensions"); let src = String::from("C:/Users/zhangshiyang/Desktop/test/extensions"); // let dist = String::from("C:\\Users\\zhangshiyang...
use tests_build::tokio; #[tokio::main] async fn missing_semicolon_or_return_type() { Ok(()) } #[tokio::main] async fn missing_return_type() { return Ok(()); } #[tokio::main] async fn extra_semicolon() -> Result<(), ()> { Ok(()); } fn main() {}
// 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,...
use rusqlite::{params, Connection, Result}; #[derive(Debug)] struct User { id: i32, name: String, age: i32, } fn main() -> Result<()> { // パラメータで分岐 let args = std::env::args().collect::<Vec<String>>(); let cn = Connection::open("sample.db")?; if args.len() <= 1 { // 一覧を表示 l...
use super::linear::{ Vector }; /// Returns the arithmetic mean of the values contained in a mathematical /// vector. /// /// # Examples /// ``` /// use ml_rust_cuda::math::{ /// f32_eq, /// linear::Vector, /// stats::mean /// }; /// /// let vec = Vector::new(vec![9_f32, 5_f32, 8_f32, 3_f32, 4_f32, 0_f32]); /// ...
#[macro_use] extern crate lazy_static; extern crate regex; use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; use std::cmp::max; use std::cmp::Ordering; use std::collections::HashMap; use regex::Regex; fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>...
// This file is part of Substrate. // Copyright (C) 2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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://w...
#[macro_use] extern crate smelter; #[derive(PartialEq, Debug, Builder, Default)] struct Point { x: u32, #[smelter(field_name="y_axis")] y: u32, } #[derive(PartialEq, Debug, Builder, Default)] struct Container<T> where T: PartialEq + Default { item: T, } #[test] fn can_generate_builder_methods()...
extern crate tantivy; use tantivy::collector::TopDocs; use tantivy::query::QueryParser; use tantivy::schema::*; use tantivy::{doc, Index, ReloadPolicy}; use tempfile::TempDir; pub fn create_index(src: &str, des: &str) { let index_path = TempDir::new().expect("temp dir"); let mut schema_builder = Schema::bui...
use crate::*; pub trait QueryBuilder: QuotedBuilder { /// The type of placeholder the builder uses for values, and whether it is numbered. fn placeholder(&self) -> (&str, bool) { ("?", false) } /// Translate [`InsertStatement`] into SQL statement. fn prepare_insert_statement( &self...
#![feature(inclusive_range_syntax)] #[macro_use] extern crate nom; use std::str; use nom::{digit, space}; use std::fs::File; use std::io::Read; use std::collections::HashMap; named!( depth<i32>, map_res!(map_res!(digit, str::from_utf8), str::parse) ); named!( range<i32>, map_res!(map_res!(digit, str:...
use std::collections::HashMap; use std::convert::TryFrom; use std::io; use std::path::Path; use std::path::PathBuf; use chrono::DateTime; use chrono::Utc; use failure::err_msg; use failure::Error; use md5::digest::FixedOutput; use md5::digest::Input; use tokio::fs; use tokio::io::AsyncWriteExt as _; use tokio::sync::M...
mod cli; mod icore; mod logger; use clap::{load_yaml, App}; use cli::{parser::parse_input, typer}; use icore::arg::{Arg, SendArg, RecvArg}; use icore::{message::send_msg, message::Message, receiver, sender}; #[async_std::main] async fn main() { // Init communication between UI and model. typer::launch(); ...
#![feature(box_syntax)] #![feature(proc_macro)] extern crate rise; extern crate rise_stylesheet; use rise::{App, Layout, NodeContext, WindowOptions, WindowPosition}; use rise_stylesheet::styles::prelude::Stylesheet; use std::boxed::Box; use rise_stylesheet::yoga::Node; use rise_stylesheet::yoga::NodeContextExt; fn ...
#[doc = "Register `FA1R` reader"] pub type R = crate::R<FA1R_SPEC>; #[doc = "Register `FA1R` writer"] pub type W = crate::W<FA1R_SPEC>; #[doc = "Field `FACT0` reader - Filter active"] pub type FACT0_R = crate::BitReader; #[doc = "Field `FACT0` writer - Filter active"] pub type FACT0_W<'a, REG, const O: u8> = crate::Bit...
use super::prelude::*; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Null(); impl Display for Null { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "null") } }
use std::marker::PhantomData; use std::any::{Any}; use std::rc::Rc; use std::sync::atomic::AtomicIsize; use observable::*; use subscriber::*; use unsub_ref::UnsubRef; use std::sync::Arc; use std::sync::atomic::Ordering; pub struct TakeOp<Src, V> where Src : Observable<V> { source: Src, total: isize, Phant...
#[multiversion::multiversion(targets = "simd")] #[allow(dead_code)] fn simd() {}
use crate::test_utils::*; use std::net::TcpStream; use vndb_rs::sync::client::Client; #[test] fn get_dbstats() { let expected = br###"dbstats { "releases":68258, "producers":9896, "users":0, "tags":2558, ...
extern crate regex; #[macro_use] extern crate lazy_static; extern crate utils; use std::env; use std::iter::FromIterator; use std::collections::HashSet; use std::collections::HashMap; use std::collections::VecDeque; use std::str::FromStr; use std::num::ParseIntError; use std::io::{self, BufReader}; use std::io::prelud...
pub use self::attack::AttackSystem; pub use self::bomber::BomberSystem; pub use self::camera::CameraSystem; pub use self::collision::{CollisionEvent, CollisionSystem}; pub use self::despawn::DespawnSystem; pub use self::enemy_spawn::EnemySpawnSystem; pub use self::motion::MotionSystem; pub use self::pickup::PickupSyste...
#![deny(clippy::all)] fn main() { println!("Hello, world!"); } #[test] fn test_your_face() { assert_eq!(1, 1); }
pub fn raindrops(n: i32) -> String { let mut res = String::new(); if has_factor(n, 3) { res += "Pling"; } if has_factor(n, 5) { res += "Plang"; } if has_factor(n, 7) { res += "Plong"; } if res.is_empty() { n.to_string() } else { res } } fn has_factor(n: i32, f: ...
use crate::custom_var::{downcast_var, CustomVar}; use crate::method::{NativeMethod, StdMethod}; use crate::name::Name; use crate::operator::Operator; use crate::runtime::Runtime; use crate::std_type::Type; use crate::string_var::StringVar; use crate::variable::{FnResult, Variable}; use crate::{first, first_n}; use std:...
use ndarray::prelude::*; use std::cmp::min; #[derive(Debug)] pub struct Levenshtein<T: Eq + Clone> { matrix: Array2<u32>, a: Vec<T>, b: Vec<T>, dim_a: usize, dim_b: usize, } impl<T: Eq + Clone> Levenshtein<T> { pub fn new(a: &Vec<T>, b: &Vec<T>) -> Levenshtein<T> { let vec_a = a.clone...
use std::thread; struct Hamster { name: String, age: u32, size: u16 } fn main() { let h = Hamster { name: "Bruce Lee".to_string(), age: 2, size: 1 }; println!("My Hamster's name is: {}",h.name); let handle = thread::spawn(|| { "Hello from a thread!" }); println!("{}", handle.join().unwrap()); }
fn print(n: i32) -> Option<String> { if n <= 0 || n % 2 == 0 { return None; } let mut s: String = String::new(); let mut i = 1; let mut j = n/2 ; while i <= n { s.push_str( &" ".repeat(( j )as usize)); s.push_str( &"*".repeat(( i )as usize)); s.push_str( &"\n" ); ...
//! Tests auto-converted from "sass-spec/spec/non_conformant/errors/import/miss/loop" #[allow(unused)] use super::rsass; // From "sass-spec/spec/non_conformant/errors/import/miss/loop/each.hrx" // Ignoring "each", error tests are not supported yet. // From "sass-spec/spec/non_conformant/errors/import/miss/loop/for.h...
use super::super::SQLiteDatabase; use nu_engine::CallExt; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Spanned, SyntaxShape, Type, }; use std::path::PathBuf; #[derive(Clone)] pub struct OpenDb; impl Comma...
use crate::ray::Ray; use crate::vector::Vec3; use rand::Rng; use std::f64::consts::PI; #[derive(Debug)] pub struct Camera { lover_left_corner: Vec3, horizontal: Vec3, vertical: Vec3, lens_radius: f64, pub origin: Vec3, u: Vec3, v: Vec3, w: Vec3, t0: f64, t1: f64 } impl Camera {...
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub(super) mod mask_32; #[cfg(target_arch = "x86_64")] pub(super) mod mask_64; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub(super) mod vector_128; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub(super) mod vector_256; #[allow(unused_...
use super::*; use crate::message::name::*; use crate::message::packer::*; // An MXResource is an mx Resource record. #[derive(Default, Debug, Clone, PartialEq)] pub struct MxResource { pub pref: u16, pub mx: Name, } impl fmt::Display for MxResource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Resul...
use anyhow::{Context, Result}; use cargo_metadata::Package; use semver::Version; use std::time::Duration; /// Fetches the current version from crates.io pub async fn get_published_version(name: &str) -> Result<Version> { let client = crates_io_api::AsyncClient::new("cargo-mono (kdy1997.dev@gmail.com)", Dur...
use super::super::prelude::DialogBoxCommand; pub static OnlyOk : DialogBoxCommand = 1 ; pub static Cancel : DialogBoxCommand = 2 ; pub static Abort : DialogBoxCommand = 3 ; pub static Retry : DialogBoxCommand = 4 ; pub static Ignore : DialogBoxCommand = 5 ; pub static Yes : DialogBoxCommand = 6 ...
use crate::prelude::*; use std::path::PathBuf; /// Input source. Can be an Image, Video or Cam. /// /// `Source` implements iterator, so you can easy loop /// over the source and receive a new frame in each iteration. /// /// ``` /// use airhobot::prelude::*; /// let source = Source::cam(0); /// for frame in source { ...
pub mod antidote; pub mod awakening; pub mod big_pearl; pub mod black_flute; pub mod blue_flute; pub mod blue_shard; pub struct Currency<'a> { name: &'a str, plural: &'a str, symbol: &'a str, } pub struct Item<'a> { code: &'a str, description: &'a str, name: &'a str, price_buy: u16, } pub...
use tokio_postgres; use tokio::process::{Command}; use khadga::pgdb; /// Creates a connection to our postgres database pub async fn establish_connection_test() -> Result<ConnectReturn, Error> { dotenv().ok(); let config = format!( "host=localhost user={} password={} dbname={}", env::var("DB_USER_TEST...
use std::mem; use std::cell::RefCell; use std::rc::Rc; use std::rt::task::{BlockedTask, Task}; use std::rt::local::Local; use green::{Callback, PausableIdleCallback}; use rustuv::Idle; type Chan = Rc<RefCell<(Option<BlockedTask>, uint)>>; struct MyCallback(Rc<RefCell<(Option<BlockedTask>, uint)>>, uint); impl Callba...
use std::env; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::collections::HashSet; fn main() { let filename = env::args().nth(1).expect("a filename"); let mut file = File::open(filename).expect("a input file"); let mut acc: i64 = 0; let mut frequencies = HashSet::new();...
// This will work on any meta.json file located in the directory use std::path::Path; use tantivy::query::QueryParser; use tantivy::schema::Field; use tantivy::Index; fn main() -> tantivy::Result<()> { let directory = Path::new("/tmp/tantivy/idxbs"); let dir_exists = directory.exists(); if dir_exists { ...
use crate::{ expr::Expression }; #[derive(Debug, Clone)] pub struct ObjectLifetime<'a>{ pub stages: Vec<LifetimeStage<'a>> } #[derive(Debug, Clone)] pub struct LifetimeStage<'a>{ pub references: Vec<Reference<'a>>, } #[derive(Debug, Clone)] pub struct Reference<'a>{ pub reference: &'a Expression, ...
#[allow(unused_imports)] use compute::EdgePreprocess; use crossbeam::atomic::AtomicCell; use gfaestus::context::{debug_context_action, pan_to_node_action, ContextMgr}; use gfaestus::quad_tree::QuadTree; use gfaestus::reactor::{ModalError, ModalHandler, ModalSuccess, Reactor}; use gfaestus::script::plugins::colors::{has...
use crate::{ArgsWeechat, Weechat}; use libc::c_int; pub trait WeechatPlugin: Sized { fn init(weechat: Weechat, args: ArgsWeechat) -> WeechatResult<Self>; } pub struct Error(c_int); pub type WeechatResult<T> = Result<T, Error>;
fn main() { const N: usize = 20; let _ = [0; N]; }
use std::collections::HashMap; use std::time::{Duration, Instant}; pub struct Span { start: Instant, end: Option<Instant>, } impl Span { pub fn new() -> Self { Self { start: Instant::now(), end: None, } } pub fn evaluate(&self) -> Duration { self.en...
pub mod grid; pub mod utils; pub mod physics; pub mod physical_modules; pub mod math_modules;
use crate::{ping_result_processors::ping_result_processor_factory, PingResult, PingResultProcessor, PingResultProcessorConfig}; use contracts::requires; use futures_intrusive::sync::ManualResetEvent; use std::sync::Arc; use tokio::{sync::mpsc, task, task::JoinHandle}; pub struct PingResultProcessingWorker { stop_e...
use serde::de::IntoDeserializer; use serde::de::{self, MapAccess, Visitor}; use serde::{Deserialize, Deserializer}; use std::fmt; use std::marker::PhantomData; pub(crate) fn default_for_null<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: Deserializer<'de>, T: Deserialize<'de> + Default, { Ok(O...
#[doc = "Reader of register DIV_16_5_CTL[%s]"] pub type R = crate::R<u32, super::DIV_16_5_CTL>; #[doc = "Writer for register DIV_16_5_CTL[%s]"] pub type W = crate::W<u32, super::DIV_16_5_CTL>; #[doc = "Register DIV_16_5_CTL[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::DIV_16_5_CTL { type Type = ...
// This file is part of Substrate. // Copyright (C) 2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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://w...
// Copyright 2019, 2020 Wingchain // // 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...
tonic::include_proto!("as/integration");
mod repository; pub use repository::*; use common::event::Event; use common::model::{AggregateRoot, StringId}; use common::result::Result; pub type AuthorId = StringId; #[derive(Debug, Clone)] pub struct Author { base: AggregateRoot<AuthorId, Event>, username: String, name: String, lastname: String, ...
#![cfg_attr(feature = "strict", deny(warnings))] #![allow(dead_code)] use borsh::{BorshDeserialize, BorshSchema, BorshSerialize}; use serum_common::pack::*; use solana_client_gen::prelude::*; pub mod accounts; pub mod error; #[cfg_attr(feature = "client", solana_client_gen)] pub mod instruction { use super::*; ...
/// Operation Codes for the Cybermaster pub enum OpCodes { Alive, PlaySound(u8), UnlockFirmware, } /// Generate the Message for the given OP Code and data pub fn gen_msg(op: OpCodes, toggle: bool) -> Vec<u8> { //Generate the Payload let payload = gen_payload(op, toggle); let payload_iter = payload.iter(); //...
use crate::*; pub fn init_error(globals: &mut Globals) -> Value { let id = globals.get_ident_id("RuntimeError"); let class = ClassRef::from(id, globals.builtins.object); Value::class(globals, class) }
use stdweb::unstable::TryInto; use stdweb::web::{document, Element, IElement, IParentNode}; pub fn set_title(title: &str) { let title = format!("{} - EOS Straw Poll", title); document().set_title(&title); set_attributes("meta[property='og:title']", "content", &title); } pub fn set_url(url: &str) { set...
//! Sync client implementation use serde::de::DeserializeOwned; use std::io::{BufRead, BufReader, Read, Write}; use crate::common::{ dbstats::DbStatsResponse, error::{VndbError, VndbResult}, get::{ character::GetCharacterResults, producer::GetProducerResults, release::GetReleaseResults, st...
#[doc = "Register `C2IMR1` reader"] pub type R = crate::R<C2IMR1_SPEC>; #[doc = "Register `C2IMR1` writer"] pub type W = crate::W<C2IMR1_SPEC>; #[doc = "Field `IM` reader - wakeup with interrupt Mask on Event input"] pub type IM_R = crate::FieldReader<IM_A>; #[doc = "wakeup with interrupt Mask on Event input\n\nValue o...
extern crate cargo_readme; use std::{fs, io::Write, path}; fn main() { // Generate README.md with cargo_readme. let mut f = fs::File::open("src/lib.rs").unwrap(); let mut template = fs::File::open("README.tpl").unwrap(); let mut content = cargo_readme::generate_readme(&path::PathBuf::from("./"), ...
use serial::{ReadU8, WriteU8}; pub struct SerialMock; impl ReadU8 for SerialMock { fn read(&mut self) -> Option<u8> { None } } impl WriteU8 for SerialMock { fn write(&mut self, v: u8) { } }
pub fn is_sum(x: usize, y: usize, sum: usize) -> bool { x + y == sum } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
//! Sensors and reports telemetry from the proxy. use std::sync::Arc; use std::time::Duration; use futures_mpsc_lossy; use ctx; mod control; pub mod event; mod metrics; pub mod sensor; pub mod tap; pub use self::control::{Control, MakeControl}; pub use self::event::Event; pub use self::sensor::Sensors; /// Create...
use std::collections::HashMap; use near_sdk::json_types::U128; use near_sdk::AccountId; use near_sdk::{env, PendingContractTx}; use near_sdk_sim::{ call, deploy, init_simulator, lazy_static_include::syn::token::Use, to_yocto, view, ContractAccount, UserAccount, DEFAULT_GAS, STORAGE_AMOUNT, }; extern crate nea...
#![allow(unused_must_use)] use json5; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use std::collections::HashMap; use crate::db; use actix_web::web; use std::sync::{Arc, Mutex}; use crate::Test; /// 执行测试后端接口 pub async fn run_test(conf: Test, db_data: web::Data<Mutex<db::Database>>) { ...
use std::{ cmp::{max, min}, fmt, slice::Iter, }; #[derive(Copy, Clone, Debug)] pub struct Range { pub start: usize, pub length: usize, } impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[{}, {}]", self.start, self.start + self.length -...
pub mod segment; use std::cmp::max; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::iter::Iterator; use byteorder::{BigEndian, ReadBytesExt}; use ::{ extract_section, format_u64, format_usize, NumberStyle, }; use self::segment::{Segment, SegmentType}; use sections::Section; const TEXT_S...
fn main() { proconio::input! { h: usize, w: usize, hw: [[i32; w]; h] } }
mod code; pub use code::*; #[cfg(test)] mod code_test;
use crate::schema::products; use crate::models::user::User; use diesel::prelude::*; #[derive(Identifiable, Queryable, Associations)] #[belongs_to(User)] pub struct Product { pub id: i32, pub name: String, pub user_id: Option<i32> } #[derive(Insertable, AsChangeset)] #[table_name = "products"] pub struct ...
#![no_std] #![allow(non_camel_case_types)] extern crate bare_metal; extern crate cast; extern crate cortex_m; pub extern crate embedded_hal as hal; pub extern crate void; pub use void::Void; #[macro_use(block)] pub extern crate nb; pub use nb::block; pub extern crate stm32f0; pub use stm32f0::interrupt; pub use stm...
pub mod sendgrid_webhook; pub mod emails;
use std::sync::Arc; use std::net::IpAddr; use futures::{future, Future}; use maxminddb::geoip2::City; use ip::IpAsnDatabase; use asn::AutonomousSystemNumber; use maxmind::MaxmindDatabase; use dns::{DnsResolverHandle, DnsLookupResult, DnsLookupResultMx, DnsLookupResultSoa}; pub fn create_lookup_handler(ip_asn_databas...
//! Link: https://adventofcode.com/2019/day/12 //! Day 12: The N-Body Problem //! //! The space near Jupiter is not a very safe place; //! you need to be careful of a big distracting red spot, //! extreme radiation, and a whole lot of moons swirling around. //! You decide to start by tracking the four largest moons...
use wasmer::{imports, wat2wasm, Instance, Module, Store}; fn main() -> Result<(), Box<dyn std::error::Error>>{ let wasm_bytes = wat2wasm( br#" (module (type $add_one_t (func (param i32) (result i32))) (func $add_one_f (type $add_one_t) (param $value i32) (result i32) ...
///// chapter 4 "structuring data and matching patterns" ///// program section: // fn main() { let thor = ("thor", true, 3500u32); let (name, _, power) = thor; let gained = increase_power(name, power); println!("{:?}", gained); } fn increase_power(name: &str, power: u32) -> (&str, u32) { if power > ...
use std::fmt::Display; use std::io::prelude::*; use std::io; use std::fs::{OpenOptions, File}; use std::os::unix::io::{RawFd, FromRawFd, AsRawFd}; use mio; use mio::{Evented, Token, EventSet, PollOpt}; #[derive(Debug)] pub struct Selector { sys: File } impl Selector { fn readable() -> OpenOptions { le...
use std::f64::NAN; use std::f64::consts::PI; use {BKCoord, PoincareCoord, angle}; use vecmath::{Vector2, vec2_len}; #[derive(Clone, Copy)] pub struct PolarCoord { pub radius: f64, pub angle: f64, } impl PolarCoord { pub fn origin() -> PolarCoord { PolarCoord::new(0.0, 0.0) } pub fn null() -> PolarCoord { Po...
/// Word size in bits for a given target. pub fn target_word_size_bits(target: &str) -> Result<u8, String> { // Targets from cakeml/compiler/compilerScript.sml match target { "ag32" => Ok(32), "arm6" => Ok(32), "arm8" => Ok(64), "x64" => Ok(64), "mips" => Ok(64), ...
/// A line data structure. #[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)] pub struct Line<T> { /// A horizontal/vertical character. pub main: T, /// A horizontal/vertical intersection. pub intersection: Option<T>, /// A horizontal left / vertical top intersection. pub connect1: Op...
use totsu::totsu_core::{ConeRPos, ConeSOC}; use totsu::totsu_core::solver::Cone; use super::La; // pub struct ProbCone { x_sz: usize, t_sz: usize, rpos: ConeRPos<La>, soc: ConeSOC<La>, } impl ProbCone { pub fn new(width: usize, height: usize) -> Self { ProbCone { ...
use std::path::Path; use anyhow::Result; #[cfg(feature = "async-std-runtime")] use async_std::{ fs::{self, OpenOptions}, io::{ self, prelude::{BufReadExt, WriteExt}, }, }; use futures::stream::Stream; #[cfg(feature = "tokio-runtime")] use tokio::{ fs::{self, OpenOptions}, io::{self,...
// Copyright 2019 Pierre Krieger // Copyright (c) 2019 Tokio Contributors // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights...
use std::collections::HashMap; use std::slice::Iter; use std::ops::Index; use node::StoryNode; pub struct StoryFeed { nodes: Vec<StoryNode>, /// Maps Node ids to vector indeces for quicker lookup. node_index: HashMap<String, usize>, } impl StoryFeed { pub fn new(story: Vec<StoryNode>) -> Self { ...
/*! ```rudra-poc [target] crate = "autorand" version = "0.2.2" [report] issue_url = "https://github.com/mersinvald/autorand-rs/issues/5" issue_date = 2020-12-31 rustsec_url = "https://github.com/RustSec/advisory-db/pull/612" rustsec_id = "RUSTSEC-2020-0103" [[bugs]] analyzer = "UnsafeDataflow" bug_class = "PanicSafet...
//! Module provides initialization of global application logger use std::error::Error; use chrono::{Local, SecondsFormat}; use log::LevelFilter; use log4rs::append::console::ConsoleAppender; use log4rs::append::file::FileAppender; use log4rs::config::{Appender, Config, Root}; use log4rs::encode::pattern::PatternEncod...
use std::env; use std::path::PathBuf; extern crate encryptfile; use encryptfile as ef; fn main() { let args: Vec<_> = env::args().collect(); if args.len() != 3 { println!("Usage: {} <encrypt|decrypt> filename", args[0]); return; } let in_mode = args[1].to_owned(); let in_file = ar...
#[derive(Copy, Clone, PartialEq, Debug)] pub struct RGB { r: f32, g: f32, b: f32 } pub trait ToRGB { fn to_rgb(&self) -> RGB; } impl RGB { pub fn from_rgb(r: f32, g: f32, b: f32) -> RGB { RGB { r: r, g: g, b: b } } pub fn get_values(&self) -> (f32, f32, f32) { (self.r, sel...
//! An example control gallery: a port of the same `ui` example. extern crate ui; use ui::prelude::*; use ui::controls::*; use ui::menus::{Menu, MenuItem}; fn run(ui: Rc<UI>) { let menu = Menu::new("File"); menu.append_item("Open").on_clicked(Box::new(open_clicked)); menu.append_item("Save").on_clicked(B...
use bytemuck::{Pod, Zeroable}; #[repr(C)] #[derive(Clone, Copy)] pub struct Vertex { pub pos: [f32; 2], pub uv: [f32; 2], pub color: [f32; 4], } unsafe impl Pod for Vertex {} unsafe impl Zeroable for Vertex {} impl Vertex { pub fn ptc<P, T>(pos: P, uv: T, color: &[f32; 4]) -> Self where P: Into<mint::Point2<f...
use super::spa; use super::zfs; pub struct DslPool { // Immutable root_dir_obj: u64, pub dp_dirty_total: u32, } impl DslPool { pub fn init(spa: &mut spa::Spa, txg: u64) -> zfs::Result<Self> { Self::open_impl(spa, txg) } fn open_impl(spa: &mut spa::Spa, txg: u64) -> zfs::Result<Self> {...
mod point; mod vector; mod line; use point::point::Point; use vector::vector::Vector; use line::line::Line; fn main() { unimplemented!(); } #[test] fn test_basic() { let v1 = Vector::new(1.0, 1.0, 1.0); let v2 = Vector::new(2.0, 2.0, 2.0); let p1 = Point::new(1.0, 1.0, 1.0); let p2 = Point::new(...
#[doc = "Register `DDRPHYC_DX1DQSTR` reader"] pub type R = crate::R<DDRPHYC_DX1DQSTR_SPEC>; #[doc = "Register `DDRPHYC_DX1DQSTR` writer"] pub type W = crate::W<DDRPHYC_DX1DQSTR_SPEC>; #[doc = "Field `R0DGSL` reader - R0DGSL"] pub type R0DGSL_R = crate::FieldReader; #[doc = "Field `R0DGSL` writer - R0DGSL"] pub type R0D...