text
stringlengths
8
4.13M
/// Like mem::epoch::AtomicPtr, but provides an ll/sc based api on x86, powerpc, arm, aarch64 use std::mem; use std::marker::PhantomData; use std::sync::atomic::{Ordering, AtomicUsize}; use std::sync::atomic::Ordering::*; #[cfg(target_arch = "aarch64")] mod multi_arch { #[inline(awlays)] unsafe fn load_exc(...
pub mod constants; pub mod exits;
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate sync15_adapter as sync; extern crate libc; extern crate serde_json; extern crate failure; use std::...
#[doc = "Reader of register DOUTR6"] pub type R = crate::R<u32, super::DOUTR6>; #[doc = "Writer for register DOUTR6"] pub type W = crate::W<u32, super::DOUTR6>; #[doc = "Register DOUTR6 `reset()`'s with value 0"] impl crate::ResetValue for super::DOUTR6 { type Type = u32; #[inline(always)] fn reset_value() ...
use serde::Serialize; #[derive(Clone, Debug, Serialize)] pub struct GoogleId(String); impl GoogleId { pub fn new(id: String) -> Self { GoogleId(id) } } use std::fmt; impl fmt::Display for GoogleId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } }...
use anyhow::{anyhow, Result}; use clap::{AppSettings, Clap}; use reqwest::{Url, header, Client, Response}; use std::str::FromStr; use std::collections::HashMap; use colored::*; use mime::{Mime, APPLICATION_JSON}; // 定义 HTTPie 的 CLI 的主入口,它包含若干个子命令 // 下面 /// 的注释是文档,clap 会将其作为 CLI 的帮助 /// A naive httpie implementation w...
use std::net::{TcpListener, TcpStream}; pub fn init(port: &String) ->Result<TcpListener, String>{ let addr = String::from("127.0.0.1:"); match TcpListener::bind(addr + port) { Ok(listener) => Ok(listener), Err(_) => Err(String::from("fail to bind")), } } use std::fs::File; pub struct HttpResponse { pub fi...
// FeLEO // // bencode.rs // imports here pub fn be_decode(data: &str, data_len: i64) -> &str { let mut ret = ""; if data_len == 0 { return ret; } // match is similar to a switch statement match data { // integers "i" => { // indexing string by characte...
pub use VkAccelerationStructureTypeNV::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkAccelerationStructureTypeNV { VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV = 0, VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV = 1, }
use std::sync::Arc; use crate::buffer::VkBufferSlice; use crate::rt::VkAccelerationStructure; use crate::texture::{ VkSampler, VkTextureView, }; use crate::{ VkCommandBufferSubmission, VkFrameBuffer, VkPipeline, VkRenderPass, VkTexture, VkTimelineSemaphore, }; pub struct VkLifetimeTrackers...
use chrono::{DateTime, TimeZone, Utc}; use rust_decimal::Decimal; use sqlx::postgres::PgRow; use sqlx::{Done, Row}; use super::Db; #[derive(Debug, serde::Serialize)] pub struct Transaction { pub id: String, pub account_id: String, pub timestamp: DateTime<Utc>, pub amount: Decimal, pub currency: St...
use datastore::{key::Key, Batch, Txn}; use matches::matches; use rand::{self, Rng}; use std::collections::HashMap; use tempfile::TempDir; use super::*; macro_rules! map ( { $($key:expr => $value:expr),+ } => { { let mut m = ::std::collections::HashMap::new(); $( m.i...
fn main() { let x = 1; let y = 4; let z = 5; let Point { x, .. } = new_point(x, y, z); println!("x: {}", x); } struct Point { x: i64, y: i64, z: i64, } fn new_point(x: i64, y: i64, z: i64) -> Point { Point { x, y, z } }
#![feature(io, std_misc)] mod format_strings; mod chat_server; mod connection; fn main() { chat_server::start(); }
use std::io; use std::fs; use std::iter; use std::path::Path; use crate::Battery; use crate::platform::traits::BatteryIterator; use super::SysFsDevice; #[derive(Debug)] pub struct SysFsIterator { // TODO: It is not cool to store all results at once, should keep iterator instead entries: Vec<io::Result<fs::Dir...
use serde::{Deserialize, Serialize}; /// Denotes the intended role of the module. /// /// This type is used as part of the [`Registration`](guest::Registration) process. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[repr(C)] pub enum Role { /// A transform. Transform = 0, /// A sou...
//! Listener and connections. //! //! This module implements the RTR listener socket and the high-level //! connection handling. use std::mem; use std::net::SocketAddr; use std::time::SystemTime; use futures::future; use futures::{Async, Future, IntoFuture, Stream}; use tokio; use tokio::io::{AsyncRead, ReadHalf, Writ...
use crate::audio::AudioEngine; use crate::robot::{send_robot_to_label, update_robot, BuiltInLabel, RobotId, Robots}; use crate::{ adjust_coordinate, bullet_from_param, Board, ByteString, CardinalDirection, Coordinate, Counters, Explosion, ExplosionResult, ExtendedColorValue, ExtendedParam, KeyPress, Message...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct HingeState(pub i32); impl HingeState { pub const Unknown: Self = Self(0i32); pub const Closed: Self = Self(1i32); pu...
use std::path::Path; use deck_core::FilesystemId; use super::path::{DirectoryPath, LockedPath}; use super::Directory; #[derive(Debug)] pub struct State<D> { directory: D, } impl<D> State<D> where D: Directory + 'static, D::Id: 'static, D::Input: 'static, D::Output: 'static, { pub fn new(dire...
/* Copyright 2020 Timo Saarinen 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 d...
// Copyright 2018 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ executor::Executor, mock_executor::{get_signed_txn, MockExecutor}, TransactionExecutor, }; use anyhow::Result; use compiler::Compiler; use crypto::keygen::KeyGen; use logger::prelude::*; use starcoin_config:...
use core::convert::TryFrom; use crate::util::{ bytes::{DeserializeError, SerializeError}, DebugByte, }; /// Unit represents a single unit of input for DFA based regex engines. /// /// **NOTE:** It is not expected for consumers of this crate to need to use /// this type unless they are implementing their own D...
//! Sx128x Radio Driver // Copyright 2018 Ryan Kurte #![no_std] use core::marker::PhantomData; use core::convert::TryFrom; extern crate libc; #[macro_use] extern crate log; #[cfg(any(test, feature = "util"))] #[macro_use] extern crate std; #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "util")] #[...
// 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 { serde_derive::{Deserialize, Serialize}, std::slice::Iter, }; /// The type of operations that can be performed using odu. Not all targets may...
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // /* Vikram Bhasin vb8nd and Justin Ingram jci5kb */ extern mod extra; use std::{io, run, os}; use std::io::buffered::BufferedReader; use std::io::stdin; use std...
#![feature(decl_macro, proc_macro_hygiene, custom_attribute)] #![allow(proc_macro_derive_resolution_fallback)] extern crate bcrypt; extern crate dotenv; extern crate rocket_contrib; extern crate serde; extern crate serde_json; extern crate validator; #[macro_use] extern crate rocket; #[macro_use] extern crate diesel;...
use syntex_syntax::ast::*; use syntex_syntax::visit::*; use syntex_pos::Span; use syntex_syntax::print::pprust; use gtk::prelude::*; use gtk::{ListStore, TreeStore, TreeIter}; use ast_model_extensions::{AstModelExt, AstStoreExt, AstPropertiesStoreExt}; pub(crate) struct TreeVisitor { pub tree: TreeStore, pub i...
#![allow(clippy::unused_unit)] #[macro_use] extern crate enum_primitive; #[macro_use] extern crate serde_derive; extern crate slog; #[macro_use] extern crate slog_scope; mod context; mod controller; mod diagnostics; mod editor_transport; mod general; mod language_features; mod language_server_transport; mod position;...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; extern crate serde_derive; #[macro_use] extern crate lazy_static; mod store; mod routes; fn main() { rocket::ignite().mount("/", routes![ ...
pub mod amd; pub mod core; pub mod ext; pub mod khr; pub mod nv; pub mod prelude; pub trait PNext<T> { fn chain(&mut self, p_next: &T); } #[macro_export] macro_rules! impl_pnext { ($implementor: ty, $struct_name: ident) => { impl PNext<$struct_name> for $implementor { fn chain(&mut self, ...
use super::*; pub struct BinaryPushBuilder; impl BinaryPushBuilder { pub fn build<'f, 'o>( builder: &mut ScopedFunctionBuilder<'f, 'o>, op: BinaryPush, ) -> Result<Option<Value>> { todo!("build binary push {:#?}", op); } }
use trybuild::TestCases; #[test] #[cfg_attr(miri, ignore)] fn compile_fail() { let cases = TestCases::new(); cases.compile_fail("tests/compile_fail/runtime/*.rs"); cases.compile_fail("tests/compile_fail/scoped/*.rs"); cases.compile_fail("tests/compile_fail/immovable/*.rs"); cases.compile_fail("tes...
use crate::value::Value; use parser::types::{ProgramError, SourceCodeLocation, Statement}; use std::cell::RefCell; use std::collections::HashMap; use std::fmt::{Debug, Error, Formatter}; use std::rc::Rc; use crate::interpreter::Interpreter; #[derive(Clone, PartialEq)] pub struct LoxFunction<'a> { pub arguments: Ve...
//! Scripting runtime types and helpers for interacting with it. mod runtime; mod value; pub use self::runtime::{ScriptRuntime}; pub use self::value::{ScriptTable, ScriptValue};
/* The math was taken and adapted from various places on the internet Specifically, from gl-matrix and the gltf-rs crate (which in turn took from cg_math) The idea is that we have a very minimal math lib with no dependencies for small projects Currently there's a ton of stuff missing */ mod aliases; mod matrix4; mod ...
#![no_std] #![feature(link_cfg)] #![feature(c_unwind)] #![cfg_attr(not(target_env = "msvc"), feature(libc))] cfg_if::cfg_if! { if #[cfg(target_env = "msvc")] { // no extra unwinder support needed } else if #[cfg(any( target_os = "l4re", target_os = "none", ))] { // These "un...
use serde::{Deserialize, Serialize}; use crate::domain::code_function::CodeFunction; use crate::domain::CodePoint; #[repr(C)] #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CodeClass { pub name: String, pub package: String, pub extends: Vec<String>, pub implements: Vec<String>, pub con...
use bintree::Tree; use std::fmt; pub fn leaf_list<T: Copy + fmt::Display>(tree: &Tree<T>) -> Vec<T> { match tree { Tree::Node { value, left, right } => match (left.as_ref(), right.as_ref()) { (Tree::End, Tree::End) => vec![*value], _ => { let mut leaves = leaf_list(l...
#![deny(missing_debug_implementations)] #![feature(async_await, await_macro, futures_api)] #![forbid(unsafe_code)] pub extern crate deck_core as core; #[cfg(feature = "local")] pub use self::local::LocalCache; #[cfg(feature = "s3")] pub use self::s3::S3Cache; use std::fmt::Debug; use std::future::Future; use std::pi...
#![feature(test)] // FIXME: `get_test_addresses` doesn't work on macos. #![cfg(not(target_os = "macos"))] extern crate addr2line; extern crate memmap; extern crate object; extern crate test; use std::env; use std::path::{self, PathBuf}; use std::process; fn release_fixture_path() -> PathBuf { let mut path = Path...
extern crate graph_layout; use graph_layout::layout::*; use graph_layout::compression::*; #[test] fn encode_decode_byte() { let hilbert = Hilbert::new(); for i in 0 .. (1 << 20) { assert_eq!(hilbert.entangle(hilbert.detangle(i)), i); } } #[test] fn compress_decompress() { let source = vec![0,1...
use bytes::Bytes; use futures::SinkExt; use serde::{Deserialize, Serialize}; use std::panic; use std::{time}; use tokio::net::TcpStream; use tokio::stream::StreamExt; use tokio_util::codec::{Framed, LengthDelimitedCodec}; mod common; static LOCAL_REMITS: &str = "localhost:4243"; static OK_RESP: &[u8] = &[0x62, 0x6F,...
use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use obj::*; #[test] fn load() { let mut expected = ObjData::new(); expected.vertices = vec![(1.,-1.,-1.,1.), (1.,-1.,1.,1.), (-1.,-1.,1.,1.), (-1.,-1.,-1.,1.), (1.,1.,-1.,1.), (1.,1.,1.,1.), (-1.,1.,1.,1.), (-1.,1.,-...
use bevy::{pbr::AmbientLight, prelude::*}; mod camera; mod city; mod connect_ui; mod info; mod screenspace; mod units; mod world; #[derive(Clone, Eq, PartialEq, Debug, Hash)] pub enum GameState { Loading, Account, Playing, } fn main() { App::new() .add_state(GameState::Loading) .insert_resource(WindowDescript...
// Copyright 2022 Datafuse Labs. // // 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 ...
#[doc = "Reader of register ISR"] pub type R = crate::R<u32, super::ISR>; #[doc = "Channel x transfer error flag (x = 1 ..7)\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TEIF7_A { #[doc = "0: No transfer error"] NOERROR = 0, #[doc = "1: A transfer error has occured"] ERROR = ...
#[cfg(test)] mod tests { use super::connection_lib::*; #[test] fn test() { macro_rules! assert_message_code { ($msg:expr, $res:expr) => {{ let msg = $msg; let res = $res; assert_eq!(msg.code(), res); assert_eq!(Message::from_code(&res).code(), res); }}; } // from the protocol assert...
fn dfs(i: usize, p: usize, g: &[Vec<usize>], par: &mut Vec<usize>) { par[i] = p; for &j in &g[i] { if j != p { dfs(j, i, g, par); } } } fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let ab: Vec<(...
//! Handles configuration use serde::Deserialize; use std::{collections::HashMap, fs::read_to_string, path::PathBuf}; use crate::IronCarrierError; fn default_port() -> u32 { 8090 } fn default_enable_watcher() -> bool { true } fn default_watcher_debounce() -> u64 { 10 } // Represents file names and paths...
// Copyright 2020-2021, The Tremor Team // // 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 agr...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn ActivateActCtx(hactctx: super::super::Foundation::HANDLE, lpcookie: *mut usize) -> super::super::Foundation::...
use prelude::*; mod clump; mod kmer; mod nucl; mod prelude; pub use clump::clumps; pub use kmer::Kmer; pub use nucl::Nucl; pub fn frequency_table(text: &[Nucl], k: usize) -> BTreeMap<usize, usize> { let mut table = BTreeMap::new(); for w in text.windows(k) { let kmer = Kmer::new(w); table ...
// Copyright (c) 2021 Quark Container Authors. // // 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...
use crate::{InputValueResult, Value}; /// A GraphQL scalar. /// /// You can implement the trait to create a custom scalar. /// /// # Examples /// /// ```rust /// use async_graphql::*; /// /// struct MyInt(i32); /// /// #[Scalar] /// impl ScalarType for MyInt { /// fn parse(value: Value) -> InputValueResult<Self> {...
use super::*; #[test] fn with_positive_index_greater_than_length_errors_badarg() { run!( |arc_process| { ( Just(arc_process.clone()), (1_usize..3_usize), strategy::term(arc_process.clone()), (1_usize..3_usize), stra...
//use std::fs::File; //use std::io::Write; //use std::path::Path; //use std::env; //use std::process::Command; fn main() { // let out_dir = env::var("OUT_DIR").unwrap(); // // Command::new("upx").args(&["src/hello.c", "-c", "-fPIC", "-o"]) // .arg(&format!("{}/hello.o", out_dir)); }
use std::time::Duration; use crate::{ HistogramObservation, MakeMetricObserver, MetricKind, MetricObserver, Observation, ObservationBucket, U64Counter, U64Gauge, U64Histogram, }; use std::convert::TryInto; /// The maximum duration that can be stored in the duration measurements pub const DURATION_MAX: Durati...
use log::LevelFilter; use rraw::auth::AnonymousAuthenticator; use rraw::Client; fn init() { if let Err(error) = env_logger::builder() .is_test(true) .filter_level(LevelFilter::Debug) .try_init() { println!("Logger Failed to Init Error: {}", error); } } #[ignore] #[tokio::te...
use std::fs::File; use std::io::prelude::*; // --- file read fn read_file(filename: &str) -> std::io::Result<String> { let mut file = File::open(filename)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } fn exec_line(program_code: String, pc:usize, counter: i32)-...
//! This file contains an operator which internally uses an arena allocator //! for all local allocations. use arcon::prelude::*; use arcon_macros::Arcon; use arcon_state::Backend; use bumpalo::boxed::Box; use bumpalo::collections::String; use bumpalo::collections::Vec; use kompact::prelude::ComponentDefinition; pub(...
use super::is_transient_error; use crate::listener::Listener; use crate::{log, Server}; use std::fmt::{self, Display, Formatter}; use async_std::os::unix::net::{self, SocketAddr, UnixStream}; use async_std::prelude::*; use async_std::{io, path::PathBuf, task}; /// This represents a tide [Listener](crate::listener::...
fn main() { let vec = Vec::new(); work_on_bytes(&vec); let arr = [0; 10]; work_on_bytes(&arr); let slice = &[1, 2, 3]; work_on_bytes(slice); } fn work_on_bytes(slice: &[u8]) { }
//! Buffer usage, creation-info and wrappers. mod usage; pub use { self::usage::{Usage, *}, gfx_hal::buffer::*, }; use crate::{ escape::{Escape, KeepAlive, Terminal}, memory::{Block, MappedRange, MemoryBlock}, }; /// Buffer info. #[derive(Clone, Copy, Debug)] pub struct Info { /// Buffer size. ...
use crate::domain; use near_sdk::{ json_types::U64, serde::{Deserialize, Serialize}, }; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(crate = "near_sdk::serde")] pub struct Gas(pub U64); impl From<domain::Gas> for Gas { fn from(value: domain::Gas) -> Self { value.0.into() ...
#![no_std] extern crate wfe_executor; extern crate nrf51; extern crate nrf51_hal; extern crate nrf51_blinker; use wfe_executor::Executor; use nrf51_hal::{timer::Timer, gpio::GpioExt}; pub fn main() { let core = nrf51::CorePeripherals::take().unwrap(); let peripherals = nrf51::Peripherals::take().unwrap(); ...
#![allow(dead_code)] extern crate cgmath; extern crate embree; extern crate support; use cgmath::{Vector3, Vector4}; use embree::{Device, Geometry, IntersectContext, QuadMesh, Ray, RayHit, Scene, TriangleMesh}; use support::Camera; fn make_cube<'a>(device: &'a Device) -> Geometry<'a> { let mut mesh = TriangleMes...
use std::io::Read; fn main() { let mut buf = String::new(); // 標準入力から全部bufに読み込む std::io::stdin().read_to_string(&mut buf).unwrap(); // 行ごとのiterが取れる let mut iter = buf.split_whitespace(); let problem_counts: usize = iter.next().unwrap().parse().unwrap(); let target_score: usize = iter.next...
use actix::prelude::*; use serde::Serialize; // use chrono::prelude::*; // use std::time::Duration; #[derive(Message)] pub struct StatusUpdate { pub status: ControllerState } // #[derive(Message)] pub enum WorkerCommand { Create, Render, Halt, Destroy } impl Message for WorkerCommand { // ty...
#[macro_use] extern crate nom; use nom::{IResult, digit}; use std::collections::BTreeSet; use std::io::{self, Read}; use std::str; use std::str::FromStr; #[derive(Debug)] enum Dir { Left, Right } #[derive(Debug)] struct Step { dir: Dir, dist: u16 } named!(dir<Dir>, alt_complete!(value!(Dir::Left, ch...
#[macro_use] extern crate lazy_static; use regex::Regex; use std::collections::HashMap; fn as_fuddy(content: &mut String, reg: &Regex, replace: &str) { let result = reg.replace_all(content, replace).to_string(); content.clear(); content.push_str(&result); } fn get_expressions() -> HashMap<&'static str, &'...
use crate::schema::atendimentos; use chrono::{NaiveDateTime, NaiveTime}; #[derive(Serialize, Deserialize, Queryable)] pub struct Atendimentos { pub id: i32, pub id_professor: i32, pub dia: String, pub hora_inicio: NaiveTime, pub hora_fim: NaiveTime, pub created_at: NaiveDateTime, pub update...
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg}; use clippy_utils::is_lint_allowed; use clippy_utils::source::{indent_of, reindent_multiline, snippet}; use rustc_errors::Applicability; use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor}; use rustc_hir::{Block, BlockCheckMode, Expr,...
mod args; mod dependencies; mod irust; mod utils; use crate::irust::IRust; use crate::{ args::{handle_args, ArgsResult}, irust::options::Options, }; use crossterm::{style::Stylize, tty::IsTty}; use dependencies::{check_required_deps, warn_about_opt_deps}; use irust_repl::CompileMode; use std::process::exit; fn...
use gli; pub trait Generator: gli::Generate { type Object: gli::IntoObject<Self::Object>; fn gen_one(&self) -> Self::Object { debug!("gen, size = one"); let id = <Self as gli::Generate>::gl_gen(1)[0]; debug!("[{}]: generated", id); <Self::Object as gli::IntoObject<Self::Obje...
use crate::group::*; use crate::key::PublicKey; use crate::keypackage::{self as kp, KeyPackage, MLS10_128_DHKEMP256_AES128GCM_SHA256_P256}; use crate::message::*; use crate::utils::{decode_option, encode_option, encode_vec_u32, read_vec_u32}; use rustls::internal::msgs::codec::{self, Codec, Reader}; #[derive(Debug, Cl...
use super::io::*; #[test] fn can_inject_answer_to_prompt_into_test_io() { let question = "some question".to_string(); let io = TestIo::new("answer".to_string()); assert_eq!("answer", io.prompt(question).as_slice()); }
// Copyright 2022 Datafuse Labs. // // 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 ...
#[derive(Debug)] pub struct Error { inner: Option<Box<dyn std::error::Error>>, desc: Option<&'static str>, } impl Error { pub fn from_err(inner: Box<dyn std::error::Error>) -> Error { Error { inner: Some(inner), desc: None } } pub fn from_str(s: &'static str) -> Error { Error { inner: None, desc: Some(s) } ...
const DRAM_BASE: u64 = 0x80000000; pub struct Memory { data: Vec<u8> } impl Memory { pub fn new() -> Self { Memory { data: vec![] } } pub fn init(&mut self, capacity: u64) { for _i in 0..capacity { self.data.push(0); } } pub fn read_byte(&self, address: u64) -> u8 { if address < DRAM_BASE { ...
use {Async, Future, IntoFuture, Poll}; use stream::Stream; /// A stream combinator which executes a unit closure over each item on a /// stream. /// /// This structure is returned by the `Stream::for_each` method. #[derive(Debug)] #[must_use = "streams do nothing unless polled"] pub struct ForEach<S, F, U> where U: In...
use std::collections::HashMap; use std::env; use std::fs::File; use std::io::BufRead; use std::io::BufReader; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let file = File::open(filename).expect("Could not read file"); let lines: Vec<String> = BufReader::new(file) ...
use fontsource::BuiltinFont; use std::collections::BTreeMap; use std::fs::File; use std::io::{BufRead, BufReader, Result}; /// Relevant data that can be loaded from an AFM (Adobe Font Metrics) file. A /// FontMetrics object is specific to a given encoding. #[derive(Debug, Hash, PartialEq, Eq, Clone)] pub struct FontMe...
// Copyright (c) 2014 Guillaume Pinot <texitoi(a)texitoi.eu> // // This work is free. You can redistribute it and/or modify it under // the terms of the Do What The Fuck You Want To Public License, // Version 2, as published by Sam Hocevar. See the COPYING file for // more details. #[macro_use] extern crate mdo; fn m...
use projecteuler::helper; use projecteuler::modulo; fn main() { helper::check_bench(|| { solve(); }); assert_eq!(solve(), 8739992577); dbg!(solve()); } fn solve() -> usize { let m = 10_000_000_000; let exp = 7830457; let mut t = modulo::modulo_power(2u128, exp, m); t *= 28433; ...
#![cfg(test)] extern crate sudoku_solver; use sudoku_solver::board; use sudoku_solver::solver; use sudoku_solver::board_serialize; #[test] fn display_empty_board() { let a_board = sudoku_solver::board::new_empty(); a_board.display(); } #[test] fn test_solution () { let mut a_board = Box::new(board::new_...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::MSTCTL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mu...
extern crate num; use std::io::prelude::*; use std::fs::File; use num::complex::*; fn main() { let mut f = File::open("input.txt").unwrap(); let mut s = String::new(); f.read_to_string(&mut s).unwrap(); let left = Complex::new(0, 1); let right = Complex::new(0, -1); let result = s.split("...
#[doc = "Reader of register AF2"] pub type R = crate::R<u32, super::AF2>; #[doc = "Writer for register AF2"] pub type W = crate::W<u32, super::AF2>; #[doc = "Register AF2 `reset()`'s with value 0"] impl crate::ResetValue for super::AF2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
use crate::probe::{Pin, PinConfig, PinMode, Probe}; use std::thread::sleep; use std::time::Duration; mod probe; fn main() { let mut pins = PinConfig::new(); pins.pin_mode(Pin::D12, PinMode::Digital); pins.pin_mode(Pin::D4, PinMode::Digital); pins.pin_mode(Pin::D6, PinMode::Digital); pins.pin_mode(...
//! Varisat is a [CDCL][cdcl] based SAT solver written in rust. Given a boolean formula in //! [conjunctive normal form][cnf], it either finds a variable assignment that makes the formula //! true or finds a proof that this is impossible. //! //! In addition to this API documentation, Varisat comes with a [user manual]...
/// Compute the value of the counter can take depending on the values the increments can take. pub fn compute_counter({{>choice.arg_defs ../this}} ir_instance: &ir::Function, store: &DomainStore, diff: &DomainDiff) -> {{~#if half}} HalfRange {...
use std::error::Error as StdError; use std::fmt; use std::io; use std::result::Result as StdResult; use serde; pub type Result<T> = StdResult<T, Error>; #[derive(Debug)] pub enum Error { IoError(io::Error), Serde(String), NBTError(nbt::Error), UnsupportedType(&'static str), } impl fmt::Display for ...
use paho_mqtt as mqtt; use std::time::Duration; const BROKER_URI: &str = "tcp://localhost:1883"; const TOPIC: &str = "sample"; const QOS: i32 = 1; fn main() { let client = mqtt::AsyncClient::new(BROKER_URI).unwrap(); let con_opts = mqtt::ConnectOptionsBuilder::new() //.mqtt_version(5) // ERROR: Wrong...
use errors::*; use libsodacon::net::endpoint::Endpoint; use rmp_serde; use std::collections::HashMap; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct DiscoveryReq { pub discover: HashMap<Vec<u8>, Vec<Endpoint>>, } impl DiscoveryReq { pub fn new(discover: HashMap<Vec<u8>, Vec<Endpoint>>) ...
use self::TokenType::*; /// /// The type of a token. /// #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] pub enum TokenType { EndOfFile, Identifier, Whitespace, NewLine, // LITERALS: __LiteralBegin, IntegerLiteral, DecimalLiteral, BooleanLiteral, __LiteralEnd, // KEYW...
// Copyright 2018 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 ...
// Copyright 2022 Datafuse Labs. // // 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 ...
pub mod label; pub mod text;