text
stringlengths
8
4.13M
extern crate bytes; use bytes::{Buf, Bytes, BytesMut}; use std::io::Cursor; const LONG: &'static [u8] = b"mary had a little lamb, little lamb, little lamb"; const SHORT: &'static [u8] = b"hello world"; #[test] fn collect_to_vec() { let buf: Vec<u8> = Cursor::new(SHORT).collect(); assert_eq!(buf, SHORT); ...
use legion::*; use rapier2d::{dynamics::{BodyStatus, RigidBodyBuilder, RigidBodySet, JointSet}, geometry::{ColliderBuilder, ColliderSet}}; use crate::{ static_data::{DataAccessor, Component, RigidBodyStatus, Shape}, asset::Assets, hierarchy::{Parent, Children}, transform::{Transform2D, LocalTransform, G...
use llvm_sys::LLVMLinkage; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Linkage { Private, Internal, External, Weak, } impl Default for Linkage { fn default() -> Self { Self::External } } impl Into<LLVMLinkage> for Linkage { fn into(self) -> LLVMLinkage { match self...
use super::Transform; use crate::{ event::discriminant::Discriminant, event::merge_state::LogEventMergeState, event::{self, Event}, topology::config::{DataType, TransformConfig, TransformContext, TransformDescription}, }; use serde::{Deserialize, Serialize}; use std::collections::{hash_map, HashMap}; us...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const COMPOSITIONOBJECT_READ: i32 = 1i32; pub const COMPOSITIONOBJECT_WRITE: i32 = 2i32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: ...
//! Mutators for tuple-like types //! //! This module contains the following traits and types: //! - [`RefTypes`] is a trait which essentially holds the types of a destructured tuple or structure. //! //! - `TupleN` is a marker type which implements [`RefTypes`] for tuples and structures of N elements. //! //! In th...
// A trait object points to both an instance of a type implementing our specified trait as well // as a table used to look up trait methods on that type at runtime. We create a trait object by // specifying some sort of pointer, such as a & reference or a Box<T> smart pointer, then the "dyn" // keyword, and then speci...
use proconio::input; use mod_int::ModInt998244353; type Mint = ModInt998244353; fn main() { input! { n: usize, m: usize, k: usize, }; let mut dp = vec![Mint::new(0); n + 1]; dp[0] = Mint::new(1); let mut ans = Mint::new(0); for _ in 0..k { let mut next = vec![M...
/* origin: FreeBSD /usr/src/lib/msun/src/e_lgammaf_r.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc....
#[cfg(feature = "border_cells")] mod border_cells; #[cfg(feature = "border_cells")] pub use border_cells::*;
use std::rc::Rc; use sdl2::surface; use sdl2::rect; use graphics; use game::TILE_SIZE; pub struct Sprite { sprite_sheet: Rc<~surface::Surface>, source_rect: rect::Rect } impl Sprite { pub fn new(p: ~str, x: i32, y: i32, display: &mut graphics::Graphics) -> Sprite { let source_rect = rect::Rect::n...
// 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 ...
use std::convert::TryInto; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::erlang::cancel_timer; use crate::timer; #[native_implemented::function(erlang:cancel_timer/2)] pub fn result(process: &Process, timer_reference: Term, ...
use crate::{Block, Hashlife}; use crate::leaf::LG_LEAF_SIZE; use crate::util::try_make_2x2; use super::build_rle::block_from_matrix; use super::parse::{State, MCLine, MCLeaf, MCNode}; pub fn build_mc<'a>(hl: &Hashlife<'a>, mclines: &[MCLine]) -> Result<Block<'a>, ()> { let mut table = Vec::new(); for li...
/// A simple map based on a vector for small integer keys. Space requirements /// are O(highest integer key). import option::none; import option::some; // FIXME: Should not be @; there's a bug somewhere in rustc that requires this // to be. type smallintmap[T] = @{mutable v: (option::t[T])[mutable ]}; fn mk[@T]() -...
pub fn is_valid(s: &str) -> bool { let mut sum = 0; let mut digits = 0; for (c, i) in s.chars().filter(|c| !c.is_whitespace()).rev().zip(1..) { match c.to_digit(10) { Some(n) => { digits += 1; sum += update_value(i, n) } _ => retur...
extern crate libc; extern crate serde; #[macro_use] extern crate serde_derive; #[derive(Serialize, Deserialize, Clone)] pub struct PirQuery { pub query: Vec<u8>, pub num: u32, } #[derive(Serialize, Deserialize, Clone)] pub struct PirReply { pub reply: Vec<u8>, pub num: u32, } pub mod client; pub mod ...
#![feature(test)] extern crate test; #[path = "../examples/jfb/src/lib.rs"] #[allow(dead_code)] mod jfb; use draco::Application; #[bench] fn bench_create_1000(b: &mut test::Bencher) { b.iter(|| { let mut jfb = jfb::Jfb::new(true); let mailbox = draco::Mailbox::new(|_| {}); jfb.update(jfb...
use std::error; use std::fmt; use std::io; use std::time::Duration; use std::{env, sync::Arc}; use rustls::{ Certificate, ClientConfig, RootCertStore, ServerCertVerified, ServerCertVerifier, TLSError, }; use ureq; use webpki::DNSNameRef; #[derive(Debug)] struct StringError(String); impl error::Error for StringEr...
use axum::{ body::{boxed, Body, BoxBody}, http, http::{HeaderValue, Response}, response::IntoResponse, }; /// Responder for a GraphQL response. /// /// This contains a batch response, but since regular responses are a type of /// batch response it works for both. pub struct GraphQLResponse(pub async_gr...
//! Compute dominance frontiers for a control flow graph. See the comments for `DomInfo` for more //! information. use std::mem; use crate::common::{Graph, NodeIx, NumTy}; use hashbrown::HashSet; use petgraph::Direction; use smallvec::SmallVec; pub(crate) type Tree = Vec<SmallVec<[NumTy; 2]>>; pub(crate) type Frontie...
use std::{panic::Location, time::Instant}; pub(crate) use as_derive_utils::utils::{ dummy_ident, expr_from_ident, expr_from_int, join_spans, type_from_ident, //take_manuallydrop, uint_lit, LinearResult, SynResultExt, }; #[allow(dead_code)] pub struct PrintDurationOnDrop { start...
use crate::lexer::*; use crate::parsers::expression::assignment::multiple::left_hand_side; use crate::parsers::expression::assignment::multiple::multiple_assignment_statement; use crate::parsers::expression::operator_expression; pub(crate) mod abbreviated; pub(crate) mod multiple; pub(crate) mod single; /// *single_a...
extern crate iovec; extern crate mio; extern crate tempdir; extern crate mio_uds; use std::io::prelude::*; use std::time::Duration; use iovec::IoVec; use mio::*; use mio_uds::*; use tempdir::TempDir; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with {}", strin...
extern crate redis; use actix_cors::Cors; use actix_web::{get, http, post, web, App, Error, HttpResponse, HttpServer, Responder}; use log::{debug, info, trace}; use redis::Commands; use reqwest::Client; use serde::Deserialize; use std::collections::HashMap; use std::iter::FromIterator; use std::str::from_utf8; use std...
// Copyright 2018 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. //! AccountHandler manages the state of a single Fuchsia account and its personae on a Fuchsia //! device, and provides access to authentication tokens for...
extern crate rand; mod semi_oo; mod func; use semi_oo::run as oo_run; use func::run as fn_run; fn main(){ oo_run(); fn_run(); }
use pecan_utils::codec; use std::fmt::{self, Display, Formatter}; use std::{error, result}; #[derive(Debug)] pub enum Error { ExceedRecursiveLimit(usize), InvalidData { wire: u8, index: u8, reason: codec::Error, }, OutOfSpace, } impl Error { pub(crate) fn truncated() -> Err...
use std::env; pub fn cmd_args() -> env::Args { let mut args = env::args(); args.next(); // kill command name args } pub fn util_args() -> env::Args { let mut args = cmd_args(); if let Some(n) = args.next() { if n.starts_with("-") { while let Some(_) = args.next() {} } ...
use super::*; use std::convert::TryFrom; use frame_metadata::RuntimeMetadataPrefixed; use node_metadata::Metadata; pub struct ChainHelper { metadata: Metadata, event_decode: EventsDecoder, runtime_version: u32, tx_version: u32, decimal: u32, genesis_hash: Hash, } impl ChainHelper { pub fn ...
pub struct Solution; impl Solution { pub fn get_sum(a: i32, b: i32) -> i32 { if b == 0 { a } else { Solution::get_sum(a ^ b, (a & b) << 1) } } } #[test] fn test0371() { fn case(a: i32, b: i32, want: i32) { let got = Solution::get_sum(a, b); a...
use sys::*; use bezier_curve; use bspline_curve; use catmull_rom_curve; use hermite_curve; use instance; use linear_curve; use quad_mesh; use triangle_mesh; pub enum Geometry<'a> { Triangle(triangle_mesh::TriangleMesh<'a>), Quad(quad_mesh::QuadMesh<'a>), Instance(instance::Instance<'a>), LinearCurve(l...
#[macro_use] extern crate serde_derive; extern crate serde; extern crate libloading as lib_load; extern crate handlebars; #[macro_use] extern crate serde_json; extern crate failure; extern crate rand; mod config; mod licensor; mod error; mod nalperion; use config::LicensesCfg; fn main() { let client = licensor::C...
use log::info; use rust_grpc_sample::asset::Asset; use rust_grpc_sample::grpc_stub::rust_grpc_sample::api::hello_rpc_service_server::{ HelloRpcService, HelloRpcServiceServer, }; use rust_grpc_sample::grpc_stub::rust_grpc_sample::api::hello_stream_service_server::{ HelloStreamService, HelloStreamServiceServer, }...
use kiss3d::light::Light; use kiss3d::window::Window; use nalgebra::Point2; use floc; fn main() { let mut window = Window::new("Steering"); window.set_light(Light::StickToCamera); let mut sm = floc::SteeringManager::new(); for i in 0..50 { sm.add_agent(floc::Agent::new(&mut window, i)); }...
use bevy::{core::FixedTimestep, prelude::*, render::camera::Camera}; use rand::seq::SliceRandom; use rand::Rng; struct Cell { term: String, } struct ScoreText; struct TermText { row: usize, col: usize, } #[derive(Default)] struct Cruncher { entity: Option<Entity>, row: usize, col: usize, } ...
#[link(name = "mongrel2", vers = "0.3", uuid = "f1bdda2b-0db7-42df-a40e-0decd4d56bb0")]; #[crate_type = "lib"]; extern mod extra; extern mod zmq; extern mod tnetstring; use std::hashmap::HashMap; use std::{cast, io, str, uint}; use extra::json; use extra::json::ToStr; pub struct Connection { sender...
fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() < 2 { panic!("USAGE: aoc [day] [data_file]") } let day = &args[1]; match day.as_ref() { "1" => aoc::day_1::run(&args[2]), "2" => aoc::day_2::run(&args[2]), "3" => aoc::day_3::run(&args[2...
//! A crate used for IPC between two processes. //! This crate allows one side to do a request for some post-quantum operation //! and then the other side will perform this post-quantum operation and //! send the result back. //! One should take care that the IPC channel used is not readable by everyone //! as cryptogr...
use super::{PineRef, PineStaticType, PineType, RefData, RuntimeErr}; use std::cell::RefCell; use std::fmt::Debug; use std::rc::Rc; pub fn downcast_pf<'a, T>(item: PineRef<'a>) -> Result<RefData<T>, RuntimeErr> where T: PineStaticType + PartialEq + Debug + 'a, { match item { PineRef::Box(item) => Ok(Ref...
pub use packages::{ patches::{ Id, Patch, decompress::Oodle, files::FileInfo, }, Package, }; use std::{ collections::HashMap, fs::read_dir, io::Result, path::{ Path, PathBuf, }, }; pub mod packages; fn create_package_map(package_dir: Path...
#[doc = "Reader of register DLLCR"] pub type R = crate::R<u32, super::DLLCR>; #[doc = "Writer for register DLLCR"] pub type W = crate::W<u32, super::DLLCR>; #[doc = "Register DLLCR `reset()`'s with value 0"] impl crate::ResetValue for super::DLLCR { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
use crate::constants::{ COLOR_PAIR_BLACK, COLOR_PAIR_BLUE, COLOR_PAIR_CYAN, COLOR_PAIR_GREEN, COLOR_PAIR_MAGENTA, COLOR_PAIR_RED, COLOR_PAIR_WHITE, COLOR_PAIR_YELLOW, }; use pancurses::{ init_pair, start_color, COLOR_BLACK, COLOR_BLUE, COLOR_CYAN, COLOR_GREEN, COLOR_MAGENTA, COLOR_RED, COLOR_WHITE, COLO...
use askama::Template; use serde::Serialize; use crate::database as db; use deadpool_postgres::Pool; #[derive(Template)] #[template(path = "channel.html")] struct ChannelTemplate { title: String, preload_images: Vec<String>, group_id: db::GroupID, channel_id: db::ChannelID, user_id: db::UserID, ...
use crate::image::Image; use actix_web::{get, web, HttpResponse, Responder}; #[get("/api/v1/find/{id}")] async fn find(path: web::Path<(i32,)>) -> impl Responder { let id = path.0; HttpResponse::Ok().json({ Image { id: id, file_name: String::from("yeet"), } }) } pu...
use std::collections::HashMap; use std::fmt; use text_io::read; use serde::{Deserialize, Serialize}; use crate::card_deck::{Card, CardGroup, CardRank, CardValue}; use crate::game_state::GameState; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CardGroupOwner { // TODO: Allow player lookup by...
// 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 ...
mod bonus_matcher; mod exact_matcher; mod fuzzy_matcher; mod inverse_matcher; mod word_matcher; pub use self::bonus_matcher::{Bonus, BonusMatcher}; pub use self::exact_matcher::ExactMatcher; pub use self::fuzzy_matcher::FuzzyMatcher; pub use self::inverse_matcher::InverseMatcher; pub use self::word_matcher::WordMatche...
use crate::attribute::Attribute; use crate::handler::{Handler, HandlerResult}; pub type CancelFN = fn(&Attribute) -> bool; /// Implements the Handler trait that will cancel the parse if the provided /// Cancel function returns true or forward/proxy all functions to another /// Handler implementation. Some use cases ...
fn main() { windows::core::build_legacy! {Windows::Win32::Graphics::Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC, Windows::Win32::System::IO::OVERLAPPED}; }
use crate::headers::authorization::{Basic, Bearer}; use crate::headers::Authorization; use crate::headers::WWWAuthenticate; use crate::http::{ok, response, Error, Request, Result, StatusCode}; use serde_derive::Deserialize; pub(crate) const REALM: &str = "User Visible Realm"; fn unauthorized_authenticate() -> Error ...
//! The "default" theme. //! //! This module describes two themes: //! - a `BinaryColor` theme with `Off` background color and `On` foreground color //! - an `Rgb555`, `Rgb565` and `Rgb888` version with a light color scheme with a blue-ish primary accent color. //! use core::ops::RangeInclusive; use crate::themes::...
use libc::c_int; use curses; use {Error, Result}; use super::Screen; #[allow(dead_code)] pub struct Line<'a> { screen: &'a mut Screen, } impl<'a> Line<'a> { #[inline] pub unsafe fn wrap(screen: &mut Screen) -> Line { Line { screen: screen } } } impl<'a> Line<'a> { #[inline] pub fn delete(&mut self) -> Resul...
extern crate rier; extern crate cgmath; use rier::transform::Transform; use cgmath::{Matrix4, One}; #[test] fn new_transform() { let trans = Transform::new(); assert!(trans.matrix == Matrix4::one()); }
#[macro_use] extern crate clap; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; pub mod badges; pub mod cli; pub mod web;
use super::*; #[derive(Debug, PartialEq)] pub struct Ranged { pub from: Box<Node>, pub to: Box<Node>, pub exclusive: bool, }
use crate::{Vector2, Vector3, ObjectData, GenericObject}; use crate::{math, DrawCall}; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct Bullet { pub data: ObjectData, duration: f64, speed: f64, } impl Bullet { pub fn new(pos: Vector3, size: Vector3, rotation: f64, additional_speed: f64, m...
// // mod.rs // Copyright (C) 2019 Malcolm Ramsay <malramsay64@gmail.com> // Distributed under terms of the MIT license. // pub mod packed; pub mod potential; pub use packed::*; pub use potential::*;
use sha1::{Digest, Sha1}; /// returns the hash digest of msg || PB || ext /// where PB is padding block, ext is extension msg fn extension_attack(msg: &[u8], ext: &[u8]) -> Vec<u8> { let padding = get_md_padding(&msg); let mut h = Sha1::new(); h.input(&[msg, &padding].concat()); h.input(ext); h.res...
use std::collections::VecDeque; use std::mem; use std::path::Path; use btmgmt::packet::{IdentityResolvingKey, LongTermKey}; use tokio::fs::{File, OpenOptions}; use tokio::io::{self, AsyncSeekExt, AsyncWriteExt, BufStream, SeekFrom}; use crate::serde::Wrapper; #[derive(Debug, serde::Serialize, serde::Deserialize)] pu...
use std::collections::HashMap; use std::hash::Hash; use tokio::sync::Mutex; #[derive(Default)] pub struct ConcurrentMap<K, V> where K: Eq + Hash, V: Clone, { data: Mutex<HashMap<K, V>>, } impl<K, V> ConcurrentMap<K, V> where K: Eq + Hash, V: Clone, { pub fn new() -> Self { Self { ...
//! Builds code for micro benchmarks. use std::sync::Arc; use crate::characterize::Table; use crate::{Context, Gpu, Kernel, PerfCounterSet}; use itertools::Itertools; use log::*; use num::Zero; use telamon::codegen; use telamon::device::{ArgMapExt, Device, ScalarArgument}; use telamon::explorer; use telamon::helper::t...
pub struct Solution; impl Solution { pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 { let n = nums.len(); let mut cnt = 0; for i in 0..n { if nums[i] != val { nums[cnt] = nums[i]; cnt += 1; } } nums.resize(...
pub mod ray; pub mod intersection; pub mod model; pub mod world; pub mod light; pub mod material; pub mod color; pub mod view; pub mod propagation; pub mod worldview; pub mod execution; pub mod scene; pub use self::model::*; pub use self::ray::*; pub use self::intersection::*; pub use self::model::*; pub use self::wor...
extern crate failure; extern crate openssl; extern crate base64; use failure::Error; use std::collections::HashMap; use std::fs; use openssl::rsa::{Rsa, Padding}; use std::sync::Arc; use openssl::pkey::Private; use failure::_core::num::ParseIntError; use std::path::Path; pub type TallyResult = HashMap<String, i32>; ...
use std::collections::VecDeque; use std::fs::File; use std::io; use std::io::Write; use structopt::StructOpt; use intcode::intcode; #[derive(StructOpt)] struct Cli { /// Input program #[structopt(parse(from_os_str))] path: std::path::PathBuf, #[structopt( name = "initial-input", short = "I", long = "input...
use std::any::TypeId; use std::collections::hash_map::{Entry, HashMap}; use std::ffi::CString; use std::fs::File; use std::path::{Path, PathBuf}; use std::sync::{Arc, RwLock}; use std::time::Duration; use std::{io, ptr, sync}; #[cfg(windows)] use std::ffi::OsStr; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; use once...
use std; use hyper::{self, Client}; use hyper::header; use hyper::mime; use hyper::net::HttpsConnector; use hyper_native_tls::NativeTlsClient; use serde_json; use consts; #[derive(Clone, Debug)] pub enum CloudflareError { InvalidArg, HttpRequestError, ApiError(String), NoResult, } header! { (XAuth...
pub enum Message { DROP, PUSH, }
extern crate gaussian; extern crate rand; use rand::Rng; #[test] pub fn gen() { let mut rng = rand::thread_rng(); for _ in 0..1_000_000 { let f: f64 = rng.gen(); let r: f64 = rng.gen(); let v = gaussian::gen(&mut rng, f, r); assert!(v >= 0.0 && v < 1.0); } }
use tokio::net::TcpListener; use tokio::prelude::*; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let mut listener = TcpListener::bind("0.0.0.0:8084").await?; loop { let (mut socket, _) = listener.accept().await?; tokio::spawn(async move { let mut buf ...
/* * Module: gost * Autor: Piotr Pszczółkowski (piotr@beesoft.pl) * Date: 5/05/2019 * * Copyright (c) 2019, Piotr Pszczółkowski * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributi...
#![warn(clippy::all)] #![warn(clippy::pedantic)] fn main() { run(); } fn run() { let start = std::time::Instant::now(); // code goes here let res: u64 = (3..=2_177_280) .filter(|&i| { digits(i) .iter() .map(|&i| factorial(i)) .sum::<u64>() == i }) .sum(); ...
use std::collections::HashMap; // ------------------------------- mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } use crate::front_of_house::hosting; pub fn eat_at_restaurant() { hosting::add_to_waitlist(); hosting::add_to_waitlist(); hosting::add_to_waitlist(); } /...
mod round; mod game; mod engine; fn main() { let mut obj_engine = engine::Engine { game: game::Game { controller : round::Controller { input_num: 0, round: 1, user: 1, points: [0; 9] }, } }; obj_engine.init(); obj_engine.start(); obj_engine.r...
// 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; use serde_derive::Serialize; use serde_json::Map; use serde_json::Value; use std::collections::HashMap; use std::error::Err...
use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000000007; fn alphabet2idx(c: char) -> usize { if c.is_ascii_lowercase() { c as u8 as usize - 'a' as u8 as usize } else if c.is_ascii_uppercase() { c a...
use egui::{epaint::Color32, plot::Plot, Frame}; use glam::{vec2, Vec2}; use crate::{rendering::Display, simulation::Simulation}; #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] pub struct GridApp { pub visible: bool, } impl Default for GridApp { fn default() -> Self { ...
#[doc = "Reader of register LCRH"] pub type R = crate::R<u32, super::LCRH>; #[doc = "Writer for register LCRH"] pub type W = crate::W<u32, super::LCRH>; #[doc = "Register LCRH `reset()`'s with value 0"] impl crate::ResetValue for super::LCRH { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
extern crate cc; fn main() { // doesn't work; we need a static lib that only provides `cbor_fprintf`. // println!("cargo:rustc-link-search=native=/Users/perl/Work/tinycbor/lib/"); // println!("cargo:rustc-link-lib=static=tinycbor"); cc::Build::new() .file("../src/cborpretty_stdio_c2rust.c") ...
#[doc = "Reader of register CSR1"] pub type R = crate::R<u32, super::CSR1>; #[doc = "Reader of field `PVDO`"] pub type PVDO_R = crate::R<bool, bool>; #[doc = "Reader of field `ACTVOSRDY`"] pub type ACTVOSRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `ACTVOS`"] pub type ACTVOS_R = crate::R<u8, u8>; #[doc = "Rea...
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let ws: Vec<(u64, u64)> = (0..n) .map(|_| { let w: u64 = rd.get(); let s: u64 = rd.get(); (w, s) }) ...
use crate::thread_pool::ThreadPool; use crate::Result; use std::thread; /// `NaiveThreadPool` is a `ThreadPool` implementation for this naive approach, /// where `ThreadPool::spawn` will create a new thread for each spawned job. pub struct NaiveThreadPool; impl ThreadPool for NaiveThreadPool { fn new(_threads: u3...
use std::collections::HashMap; use std::env; use std::error::Error; use std::fs; use bioinformatics_algorithms::{composition, overlap}; pub fn de_bruijn(k: usize, text: &str) -> HashMap<String, Vec<String>> { let kmers: Vec<&str> = composition(k - 1, text).collect(); let mut dbg = HashMap::default(); fo...
// 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 ...
/* * Given an integer, write a function to determine if it is a power of three. * * Examples: * ---------- * Input: 0 * Output: false * * Input: 27 * Output: true * * Input: 9 * Output: true * * Input: 45 * Output: false */ pub fn is_power_of_three(n: i32) -> bool { let mut num = n.clone(); wh...
use std::sync::{Mutex}; pub trait ThreadSafeIterator: Send + Sync { type Item; fn next(&self) -> Option<Self::Item>; } pub trait RenderingTask: Send + Sync { fn execute(self: Box<Self>); } pub trait RenderingTaskProducer: Send + Sync { fn create_task_iterator(self: Box<Self>) -> Box<ThreadSafeIterat...
use std::error::Error; use regex_automata::{ dfa::{dense, regex::Regex, Automaton, OverlappingState}, nfa::thompson, HalfMatch, MatchError, MatchKind, MultiMatch, }; use crate::util::{BunkPrefilter, SubstringPrefilter}; // Tests that quit bytes in the forward direction work correctly. #[test] fn quit_fwd...
use num_traits::{Float, FromPrimitive}; use std::iter::Sum; use crate::algorithm::area::{get_linestring_area, Area}; use crate::algorithm::euclidean_length::EuclideanLength; use crate::{Line, LineString, MultiPoint, MultiPolygon, Point, Polygon, Rect}; /// Calculation of the centroid. /// The centroid is the arithmet...
use std::env; use std::path::PathBuf; #[derive(Debug, PartialEq, Clone)] pub struct Config { pub port: u16, pub filepath: PathBuf, } impl Config { pub fn new(mut args: env::Args) -> Result<Config, &'static str> { args.next(); // skip the filename let port = match args.next() { ...
// error-pattern:assigning to immutable alias fn f(i: &int) { i += 2; } fn main() { f(1); }
use std::io::Write; use std::{collections::HashMap, io::stdout}; use anyhow::{anyhow, Context, Result}; use termion::raw::IntoRawMode; mod cmd; mod parser; mod view; use cmd::*; use view::{fmt_text, Choice, FixedComplete}; fn main() { match build_cmd() { Ok(Some(cmd)) => { println!("{}", cmd...
use std::collections::HashMap; use std::env; fn main() { let args: Vec<String> = env::args().collect(); let n: i32 = args[1].parse().unwrap_or(100); let reqs = HashMap::from([ (3, "Fizz".into()), (5, "Buzz".into()) ]); println!("{}", do_the_for(n, reqs)); } fn do_the_for<T: IntoI...
use ggez::*; use std; use std::cell::RefCell; use std::rc::Rc; use sop; use state; use world::*; type StoryConstructor = Fn(&mut StoryboardContext) -> Story; pub type StoryState = state::State<StoryboardContext>; pub type StoryTrans = state::Trans<StoryboardContext>; pub enum Story { Setup(Box<StoryConstructor...
use core::ops::{Add, AddAssign, Sub}; use core::time::Duration; use instant::Instant; #[derive(Copy, Clone, Ord, PartialOrd, PartialEq, Eq, Debug)] pub struct GameTime { since_start: Duration, } pub struct GameClock { start_time: Instant, } pub struct PausedClock { orig_start_time: Instant, pause_tim...
use std::sync::{RwLock, Arc}; use std::thread; #[derive(Debug)] struct Config { nightly_enabled: bool, logging_enabled: bool } #[test] fn rwlock_test() { let initial_config = Config { nightly_enabled : true, logging_enabled : false, }; let arc_rwlock = Arc::new(RwLock::new(initi...
//! https://github.com/lumen/otp/tree/lumen/lib/os_mon/src use super::*; test_compiles_lumen_otp!(cpu_sup); test_compiles_lumen_otp!(disksup); test_compiles_lumen_otp!(memsup); test_compiles_lumen_otp!(nteventlog); test_compiles_lumen_otp!(os_mon); test_compiles_lumen_otp!(os_mon_mib); test_compiles_lumen_otp!(os_mon...
// 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 ...
use core::mem; use core::pin::Pin; use core::ptr; use futures_core::future::{FusedFuture, Future}; use futures_core::task::{Context, Poll}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Future for the [`map`](super::FutureExt::map) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or...
use pyo3::prelude::*; use pyo3::types::{IntoPyDict, PyDict}; use n3_program::ast; use super::value::TryToPyObject; #[derive(Debug)] pub struct Outs<'a>(pub &'a ast::Outs); #[derive(Debug)] pub struct OutsExtern<'a>(pub &'a ast::Outs); impl<'a> IntoPyDict for Outs<'a> { fn into_py_dict(self, py: Python) -> &PyD...