text
stringlengths
8
4.13M
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::collections::BTreeMap; use std::fs::create_dir_all; use std::fs::File; use std::io::Seek; use std::io::SeekFrom; use std...
use crate::perm::*; use std::iter::{self, FromIterator}; #[derive(Debug, Clone, Eq)] pub struct WordPermutation<P = DefaultPermutation> where P: Permutation, { word: Vec<P>, } impl<P> WordPermutation<P> where P: Permutation, { /// Custom initialiser that can take a vector capacity. pub(crate) fn i...
#[doc = "Reader of register SCGC4"] pub type R = crate::R<u32, super::SCGC4>; #[doc = "Writer for register SCGC4"] pub type W = crate::W<u32, super::SCGC4>; #[doc = "Register SCGC4 `reset()`'s with value 0xe000_0030"] impl crate::ResetValue for super::SCGC4 { type Type = u32; #[inline(always)] fn reset_valu...
pub fn relative_sort_array(arr1: Vec<i32>, arr2: Vec<i32>) -> Vec<i32> { let mut h1 = std::collections::HashMap::new(); let mut h2 = std::collections::HashSet::new(); let mut rest_arr: Vec<i32> = vec![]; let mut result = vec![]; for v in arr2.clone() { h2.insert(v); } for v in arr...
// Copyright 2023 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use super::{Error, InputSelection, Requirement}; use crate::{ block::output::{AliasTransition, FoundryId, Output}, secret::types::InputSigningData, }; /// Checks if an output is a foundry with a given foundry ID. pub(crate) fn is_foundry_w...
use int::Int; use int::LargeInt; trait UAddSub: LargeInt { fn uadd(self, other: Self) -> Self { let (low, carry) = self.low().overflowing_add(other.low()); let high = self.high().wrapping_add(other.high()); let carry = if carry { Self::HighHalf::ONE } else { ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 pub mod stc; pub mod token_code; pub mod token_info; pub mod token_value; pub const TOKEN_MODULE_NAME: &str = "Token"; #[cfg(test)] mod tests;
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::common::refcell_service::{CalAsyncService, CalService}; use starcoin_service_registry::{RegistryAsyncService, RegistryService}; pub mod common; #[stest::test] async fn test_refcell_cal() { let registry = RegistrySer...
#[doc = "Register `ROUTEPEN` reader"] pub struct R(crate::R<ROUTEPEN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<ROUTEPEN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<ROUTEPEN_SPEC>> for R { #[inline(always)] fn from(reader: ...
#[derive(Debug, PartialEq)] pub struct Template { pub expressions: Vec<TemplateBlock>, } // TODO: Maybe combine unary operators (&, *, !) #[derive(Debug, PartialEq)] pub enum Expression { Ref { on: Box<Expression>, }, Deref { on: Box<Expression>, }, Not { on: Box<Express...
use crate::{ vec3::{Vec3}, ray::{Ray}, material::{Material}, }; #[derive(Copy, Clone)] pub struct HitRecord { pub t: f32, pub p: Vec3, pub normal: Vec3, pub material: Material, } #[derive(Copy, Clone)] pub struct Sphere { pub center: Vec3, pub radius: f32, pub material: Materia...
fn selection_sort(mut nums:Vec<i32>)->Vec<i32>{ if nums.is_empty(){return vec![];} for i in 0..nums.len(){ let mut mini_index=i; for j in i+1..nums.len(){ if nums[j]<nums[mini_index]{ mini_index=j; } } let temp=nums[i]; nums[i]=nums...
//! Configuration of git-global. //! //! Exports the `Config` struct, which defines the base path for finding git //! repos on the machine, path patterns to ignore when scanning for repos, and //! the location of a cache file to prevent scanning the filesystem every time //! the list of known repos is needed. use std:...
use std::collections::HashMap; use std::num::ParseIntError; struct RecitationGame { last_spoken_number: Option<u64>, spoken_numbers: HashMap<u64, u64>, starting_numbers: Vec<u64>, current_turn: u64, } impl RecitationGame { fn new(starting_numbers: Vec<u64>) -> Self { RecitationGame { ...
//! Error types for the domain and aggregate. use std::{error, fmt}; /// The provided reminder time is invalid. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct InvalidReminderTime; impl error::Error for InvalidReminderTime { fn description(&self) -> &str { "reminder time cannot be in the pa...
/// シミュレータ用のストレージ実装. /// /// 全てのデータはメモリ上で保持する. use raftlog::election::Ballot; use raftlog::log::{Log, LogIndex, LogPosition, LogPrefix, LogSuffix}; use raftlog::node::NodeId; use trackable::error::ErrorKindExt; use crate::io::configs::StorageConfig; use crate::io::futures::{DelayedResult, LoadBallot, LoadLog, SaveBall...
fn main() { let p1 = part1("./input"); let p2 = part2("./input"); println!("Part 1: {}", p1); println!("Part 2: {}", p2); } fn part1(path: &str) -> usize { let dat = std::fs::read_to_string(path).unwrap(); let area = dat.split_terminator("\n").map(calc_wrapping).sum(); area } fn part2(pat...
const SERIALIZATION_LENGTH: u32 = 1; struct Metronome { frequency: u32, next: chrono::DateTime<chrono::Utc>, } pub(crate) struct MetronomeAsset { pub frequency: u32, } impl crate::puzzle::PuzzleAsset for MetronomeAsset { fn create( self: Box<Self>, time: &chrono::DateTime<chrono::Utc>, _: &mut std...
use std::cmp::Reverse; use std::collections::VecDeque; use std::marker::PhantomData; pub trait Merge { type Item; fn merge(left: &Self::Item, right: &Self::Item) -> Self::Item; } pub struct MerkleTree<T, M> { nodes: Vec<T>, merge: PhantomData<M>, } pub struct MerkleProof<T, M> { indices: Vec<u3...
// This crate's name conflicts with its dependent but this should work OK. pub fn example_conflicting_symbol() -> String { "[from second_crate]".to_owned() }
//! Advanced Bit Manipulation (ABM) instructions: software fallback. mod popcnt; mod lzcnt; pub use self::popcnt::*; pub use self::lzcnt::*;
//! Miscellaneous utilities. pub trait ToStr { /// Return the value as a `str`. fn to_str(&self) -> &str; fn newline(&self) -> String { format!("{}\n", self.to_str()) } /// Append newline if the string is not empty. fn newline_if_not_empty(&self) -> String { let s = self.to_str...
struct Map<'a>(Vec<&'a str>); struct SlopeIter<'a> { map: &'a Map<'a>, dx: usize, dy: usize, cx: usize, cy: usize, } impl Iterator for SlopeIter<'_> { type Item = char; fn next(&mut self) -> Option<Self::Item> { let char = self.map.xy(self.cx, self.cy); self.cx += self.dx;...
// https://docs.microsoft.com/en-us/windows/desktop/power/power-management-portal mod ffi; mod device; mod iterator; mod manager; pub use self::device::PowerDevice; pub use self::iterator::PowerIterator; pub use self::manager::PowerManager;
use std::cmp; pub fn lsp(number_str: &'static str, window_size: usize) -> Result<u32, &'static str> { if window_size == 0 { return Ok(1); } if window_size > number_str.len() { return Err("Invalid window size"); } let number_vec_char: Vec<char> = number_str.chars().collect(); ...
#[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::LTC0_CW { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w m...
use std::fmt; bitflags!( pub struct Flags: u8 { const Z = 0b1000000; const N = 0b0100000; const H = 0b0010000; const C = 0b0001000; } ); impl Flags { pub fn test(&self, test: bool) -> Flags { if test { *self } else { Flags::empty() ...
use std::fmt::{Debug, Display}; use std::hash::Hash; use crate::Node; /// Types to be used as the `label` of a `Node` needs to implement the `NodeLabel` trait pub trait NodeLabel: Copy + Eq + Ord + Copy + Clone + Hash + Debug + Display + 'static {} impl<L: Copy + Eq + Ord + Copy + Clone + Hash + Debug + Display + 's...
use rocket::outcome::IntoOutcome; use rocket::request::{self, Form, FromRequest, Request}; use rocket::http::{Cookie, Cookies}; use rocket_contrib::{Json}; #[derive(FromForm)] struct Login { username: String, password: String } use mysql as my; #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] struct U...
use heapless_bytes::ArrayLength; pub mod status; pub use status::Status; pub type Data<T> = crate::Bytes<T>; #[derive(Clone, Debug, Eq, PartialEq)] pub enum Response<SIZE> where SIZE: ArrayLength<u8> { Data(Data<SIZE>), Status(Status), } impl<SIZE> Default for Response<SIZE> where SIZE: ArrayLength<u8> { ...
use crate::*; #[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize, Clone)] #[serde(crate = "near_sdk::serde")] pub struct LockedToken { pub token_id: TokenId, pub owner_id: AccountId, pub duration: u64, pub borrowed_money: String, pub apr: u64, pub creditor: Option<AccountId>, ...
// // See Rust Language Specific Instructions // below normal exercise description. // pub fn encode(n: u64) -> String { let units: Vec<String> = get_units(); if n < 1000 { return encode_0_999(n); } let mut batches: Vec<u64> = Vec::new(); let mut working_n = n; while working_n != 0 { ...
use postcode::Postcode; #[async_std::main] async fn main() { let post = Postcode::from_coordinates(53.377476, -2.486197).await.unwrap(); println!("{} ({}, {}) -> ({}, {})", post.postcode, post.region, post.country, post.latitude, post.longitude); }
use std::fs::File; use std::io::ErrorKind; use std::io; use std::io::Read; use std::fs; //RUST_BACKTRACE=1 cargo run fn main() { const file_name: &str = "hello.txt"; // open_file_ugly(file_name); open_file_more_elegant_way(file_name); // File::open("exampleFile.txt").unwrap(); File::open("exampleF...
use syn::ItemFn; use proc_macro::TokenStream; #[proc_macro_attribute] pub fn parse_fn(_attr: TokenStream, item: TokenStream) -> TokenStream { syn::parse_macro_input!(item as ItemFn); TokenStream::new() }
#![allow(non_snake_case)] #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] extern crate libc; /// Structure describes basic parameters of the device. #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct AVDeviceInfo { /// < device name, format depends on device pub device_name: ...
extern crate cgmath; extern crate collision; extern crate rand; extern crate sdl2; #[macro_use] extern crate error_chain; mod assets; mod cookie; mod error; mod state; mod textcache; mod turret; use error::{Error, Result, ResultExt}; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; fn ru...
use crate::config; use crate::node_groups::NodeGroup; use crate::AppConfig; use act_zero::runtimes::tokio::spawn_actor; use act_zero::{upcast, Actor, ActorResult, Addr}; use async_trait::async_trait; pub mod consul; pub mod file; #[async_trait] pub trait NodeGroupDiscoveryProvider: Actor { async fn discover_node_...
use super::util; use super::trie; use std::io; use std::fmt; const WORD_SCORES: [u32; 18] = [ 0, 0, 0, 1, 1, 2, 3, 5, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11 ]; pub const Q: usize = (('q' as i8) - ('a' as i8)) as usize; pub struct Boggler { bd: [[usize; 4]; 4], runs: u32, } const NEIGHBORS_00: [(usize, usize)...
use std::io; use std::io::BufRead; use std::collections::{HashMap, HashSet}; #[derive(Clone)] enum Operand { Const(u16), Gate(String), } #[derive(Clone)] enum Value { And(Operand, Operand), Or(Operand, Operand), Lshift(Operand, u16), Rshift(Operand, u16), Not(Operand), Move(Operand), }...
//! Graph use std::mem; #[derive(Debug, Default)] pub struct Node { pub(crate) outgoing_edges: Option<usize>, } #[derive(Debug)] pub struct Edge { pub(crate) from_node: usize, pub(crate) to_node: usize, pub(crate) next_edge: Option<usize>, } #[derive(Debug)] /// Represents a (directed) graph. pub st...
#[doc = "Register `MODECNF0` reader"] pub struct R(crate::R<MODECNF0_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MODECNF0_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MODECNF0_SPEC>> for R { #[inline(always)] fn from(reader: ...
extern crate md5; mod sqlstate; mod backend; mod frontend; pub use self::sqlstate::{ SqlState, SqlStateClass, }; pub use self::backend::{ PgErrorOrNotice, Oid, FieldDescription, TransactionStatus, }; use self::backend::{ BackendMessage, Row, }; use self::frontend::{ FrontendMessa...
// Copyright 2020 WHTCORPS INC // // 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, sof...
// Copyright (c) <2015> <lummax> // Licensed under MIT (http://opensource.org/licenses/MIT) use ffi; use client::base::{FromRawPtr, AsRawPtr}; pub struct EventQueue { wl_object: *mut ffi::wayland::WLEventQueue, } impl Drop for EventQueue { fn drop(&mut self) { unsafe { ffi::wayland::wl_ev...
use serde_json::json; use tui::backend::Backend; use tui::layout::Rect; // use tui::widgets::Block; // use tui::text::{Span, Spans}; // use tui::widgets::{Paragraph, Wrap}; use tui::Frame; use components::xml; use structs::app::AppState; const DATA: &'static str = r#" <Paragraph styles='{"fg": {"Color": "red"}}...
// This file is part of Substrate. // Copyright (C) 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://www.a...
use core::{ convert::{ AsMut, AsRef, }, fmt, }; // Reexport some often used types pub use iota_streams_core::prelude::{ generic_array::{ ArrayLength, GenericArray, }, hex, typenum::{ marker_traits::Unsigned, U16, U32, U64, ...
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 ...
// This file is part of Substrate. // Copyright (C) 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://www.a...
#![feature(test)] extern crate crossbeam; extern crate simd; extern crate test; use simd::u8x16; use crossbeam::scope; use std::u8; use std::ops::{BitAnd, BitOr}; use test::Bencher; fn main() { const MAP_SIZE: usize = 8; let mut virgin_bits = Box::new([u8x16::splat(u8::MAX); MAP_SIZE]); // let trace_bits...
mod attrs; mod util; pub use self::attrs::*; pub use self::util::*; include!(concat!(env!("OUT_DIR"), "/onnx.rs")); use self::{ tensor_proto::DataType, tensor_shape_proto::{dimension, Dimension}, type_proto::{Tensor, Value}, }; impl From<i64> for dimension::Value { fn from(v: i64) -> Self { ...
struct Solution; impl Solution { fn find_min_arrow_shots(mut points: Vec<Vec<i32>>) -> i32 { let n = points.len(); if n == 0 { return 0; } points.sort_by_key(|p| p[1]); let mut end = points[0][1]; let mut res = 1; for i in 1..n { if po...
use std::cmp; // <summary>Holds the default size for primitive blocks of characters.</summary> const BLOCK_SIZE : i32 = 1 << 6; /// <summary>Holds the mask used to ensure a block boundary cesures.</summary> const BLOCK_MASK : i32 = !(BLOCK_SIZE - 1); trait Node { fn length(&self) -> usize; fn sub_node(&self, start...
use std::env; use std::io; use std::io::Write; use std::path::Path; use std::process; use prelude::*; use config::Config; use ctx::Context; use report::Format; use utils::whatchanged::get_changed_files; use utils::hooks::HookManager; use utils::watch::watch_files; use utils::ui::clear_term; use console::style; use cl...
mod heap; mod merge; mod exercises; fn main() { let a = vec![11, 12, 13, 14]; println!("{:?}", a.split_at(2)); }
mod inp; use inp::Inp; use std::io::Result; fn main() -> Result<()> { let mut inp = Inp::new(); let (n, p) = inp.next_tuple(); let students: Vec<u32> = inp.next_as_iter().collect(); let mut sum = students.iter().sum::<u32>(); let studs = students.len() as u32; let mut add = 0; if p < 100 { ...
// Copyright 2020 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::collections::HashMap; fn solve1((_,b): &(Vec<&str>, Vec<&str>)) -> usize { b.iter().filter(|x| [2,3,4,7].contains(&x.len())).count() } pub fn part1(data: &Vec<(Vec<&str>, Vec<&str>)>) -> usize { data.iter().map(solve1).sum::<usize>() } pub fn solve2((ins, outs): &(Vec<&str>, Vec<&str>)) -> usize { ...
// Copyright 2020 EinsteinDB Project Authors & WHTCORPS INC. Licensed under Apache-2.0. //! A sample Handler for test and micro-benchmark purpose. use crate::*; use std::borrow::Cow; use std::sync::{Arc, Mutex}; use violetabftstore::interlock::::mpsc; /// Message `Runner` can accepts. pub enum Message { /// `Run...
mod asset_volume; mod assets_in_block; mod pools; mod swaps; pub use asset_volume::query_asset_volume; pub use assets_in_block::query_assets_in_block; pub use pools::query_pools; use reqwest::Client as ReqwestClient; pub use swaps::query_swaps; pub struct MyState { client: ReqwestClient, } impl MyState { pub...
use config::{Config, Environment, File}; use serde::Deserialize; /// Configuration values for connecting to the minecraft server #[derive(Debug, Deserialize)] pub struct Settings { /// Minectaft Server URL pub url: String, /// RCON Protocol Port pub port: u16, /// RCON Authentication Password p...
use super::super::error::Error; use super::super::model; use super::Persistence; use chrono::prelude::Utc; use rusqlite::Result as RusqResult; use rusqlite::{params, Connection, ToSql, Transaction}; use sha3::{Digest, Sha3_256}; use std::result::Result; use std::string::String; use std::vec::Vec; pub struct SqlitePers...
// Copyright 2020 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 ...
//! This crate implements memory allocation SDK for SVM. //! Using this crate when writing SVM Templates in Rust isn't mandatory but should be very useful. //! //! The crate is compiled with `![no_std]` (no Rust stdlib) annotation in order to reduce the compiled WASM size. #![no_std] #![allow(missing_docs)] #![allow(u...
#[doc = "Register `CTL` reader"] pub struct R(crate::R<CTL_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CTL_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CTL_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CTL_SPEC>) ...
use std::fs; struct Year { pub year: usize, } impl Year { pub fn is_valid_birth_year(&self) -> bool { 1920 <= self.year && self.year <= 2002 } pub fn is_valid_issue_year(&self) -> bool { 2010 <= self.year && self.year <= 2020 } pub fn is_valid_expiration_year(&self) -> bool { ...
fn collatz(mut n: u64) { while n != 1 { if n % 2 == 0 { n /= 2 } else { n = (3 * n) + 1 } } } fn main() { let mut i: u64 = 11360000000000; let max: u64 = u64::max_value(); while i <= max { if i % 10000000000 == 0 { println!("{}", i); } collatz(i); i += 1; } }...
//pub mod lexer; pub mod lexer; pub mod lexer2; //pub mod interpreter; //pub mod interpreter2; //pub mod interpreter3; pub mod ast; //pub mod parser; pub mod parser; //use std; #[derive(Clone ,Copy, Debug)] pub enum Token { Integer(i32), Plus, Minus, Mult, Div, LParens, RParens, } pub type Tokens<'a> = &'a[Tok...
#![cfg_attr(test, feature(test))] #![warn(rust_2018_idioms)] use std::{env, io, io::prelude::*, process::exit}; mod cpu_time; mod life; mod matmul; mod mergesort; mod nbody; mod noop; mod quicksort; mod sieve; mod tsp; // these are not "full-fledged" benchmarks yet, // they only run with cargo bench #[cfg(test)] mod...
use super::astar::AStar; use super::components::*; use super::cost::Cost; use super::locomotion::*; use super::pathfinder::*; use super::tilemap::*; use crate::grid::Grid; use crate::grid::GridPosition; use crate::pathfinding::path_result::PathResult; use crate::tilemap::Tilemap; use specs::prelude::*; pub struct Path...
use std::mem::transmute; #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub struct Byte(u8); #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub struct Wyde(u16); #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub struct Tetra(u32); #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub struct Octa(u64); macro_rules! type_impl...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use super::*; use crate::{change_set::ChangeSet, state_store::StateStore, LibraDB}; use crypto::HashValue; use std::collections::HashMap; use tempfile::tempdir; use types::{ account_address::{AccountAddress, ADDRESS_LENGTH}, ac...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files // DO NOT EDIT use crate::{Device, Object}; use std::fmt; glib::wrapper! { /// /// /// # Implements /// /// [`DeviceExt`][trait@crate::prelude::DeviceExt], [`ObjectExt`][trait@crate::prelude::ObjectExt], [`trait@gl...
use std::fmt; use std::io; use std::thread; use std::time; use std::io::BufRead; use super::*; use std::sync::{Arc,Mutex}; use slab::*; use itertools::partition; use network::*; // Minkowski stuff: Still ridiculous, but necessary for our purposes. pub struct XYZPoint{ pub x: i64, pub y: i64, pub z: i64 ...
use std::fs::read_dir; use std::path::Path; use config::Config; // List all days with record. pub fn days(config: &Config) { let dir = Path::new(&config.base_filepath); match read_dir(dir) { Ok(dir_iter) => { for dir_item in dir_iter { let entry = match dir_item { ...
///Graphics data formats, for ease of use. use super::gfx::{Slice, PipelineState}; use super::defines::pipe::{Meta, Data}; use Resources; //this is the minimum data necessary to draw to the encoder pub struct Bundle { slice: Slice<Resources>, pso: PipelineState<Resources, Meta>, data: Data<Resources>, } ...
use Number; pub trait Integer: Number /*Not<self> BitAnd<self,self> BitOr<self,self> BitXor<self,self> Shl<self,self> Shr<self,self>*/ // see: https://github.com/mozilla/rust/issues/4183 {...
#[macro_use] extern crate criterion; extern crate totality_sync as sync; use sync::triple_buffer as tb; use std::{time::Duration, thread::sleep, sync::{Arc, atomic::{AtomicU64, Ordering}}}; use criterion::{black_box, Criterion, BatchSize}; fn tb_read(rv: tb::Reader<()>) -> tb::Reader<()>{ rv.grab_always().relea...
struct Solution; use std::i32; impl Solution { fn minimum_abs_difference(mut arr: Vec<i32>) -> Vec<Vec<i32>> { arr.sort_unstable(); let min = arr .windows(2) .fold(i32::MAX, |x, v| i32::min(x, v[1] - v[0])); let mut res: Vec<Vec<i32>> = vec![]; for v in arr....
#![feature(plugin)] #![feature(proc_macro)] #![plugin(rocket_codegen)] extern crate maud; extern crate rocket; use std::path::{Path, PathBuf}; use rocket::response::NamedFile; #[get("/")] fn index() -> Option<NamedFile> { NamedFile::open(Path::new("_build/index.html")).ok() } #[get("/<file..>")] fn files(file: Pa...
fn main() { //悬垂引用报错 let reference_to_nothing: &String = dangle(); } fn dangle() -> &String { let s = String::from("hello"); &s } // 这里 s 离开作用域并被丢弃。其内存被释放。 //修改方法是直接返回String fn no_dangle() -> String { let s = String::from("hello"); s } //这样就没有任何错误了。所有权被移动出去,所以没有值被释放。 /* 让我们概括一下之前对引用的讨论: 在任意给...
pub mod grpc { tonic::include_proto!("notify.fsevent"); } pub type FsNoticeWrite = grpc::NoticeWrite; pub type FsNoticeRemove = grpc::NoticeRemove; pub type FsCreate = grpc::Create; pub type FsWrite = grpc::Write; pub type FsChmod = grpc::Chmod; pub type FsRemove = grpc::Remove; pub type FsRename = grpc::Rename; p...
use dashmap::DashMap; use std::hash::{BuildHasherDefault, Hash}; use std::sync::Arc; use twox_hash::XxHash64; type Map<K, H> = DashMap<K, H, BuildHasherDefault<XxHash64>>; #[derive(Debug)] pub struct Registry<K, H> where K: Eq + Hash + Clone + 'static, H: 'static, { pub map: Arc<Map<K, H>>, } impl<K, H> ...
extern crate encoding_rs; extern crate walkdir; use std::{env::args, fs::{OpenOptions, rename}, io::{Error, ErrorKind, Result, BufReader, BufWriter, prelude::*, stdin}, path::Path, process::exit}; fn showhelp() { println!("Usage: codepage_converter PATH|FILE FROM_CODE(gbk) TO_CODE(shift_jis)"); println!("Check ht...
// vim: tw=80 use crate::{ boxfut, common::{*, label::*} }; use futures::{ Future, IntoFuture, Stream, future, sync::{mpsc, oneshot} }; #[cfg(test)] use mockall::automock; use std::{ ops::Range, rc::Rc, sync::{ atomic::{AtomicU32, AtomicU64, Ordering}, Arc } ...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. #[macro_use] extern crate violetabftstore::interlock::; #[macro_use] pub mod setup; pub mod server; pub mod signal_handler;
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 appl...
extern crate regex; use regex::Regex; use std::io::{self, Write}; use std::process; const COLUMN_NAME_SIZE: usize = 32; const COLUMN_EMAIL_SIZE: usize = 255; struct InputBuffer { buffer: Option<Box<String>>, buffer_length: usize, input_length: usize, } struct Statement { stype: StatementType, row_t...
use c_wrapper::{file::FileDescriptor, fork::{ForkResult::*, fork}, pipe::pipe, wait}; use kennsh_syscall_macro::syscall; use peek_iter::PeekIterator; pub(crate) fn env(command: &[String]) -> crate::Result<u8> { if command.len() == 1 { // Print environment if no argument supplied for (key, value) in std::env::vars...
pub mod error; pub mod metadata; pub mod range; pub mod state_object; pub mod state_update; pub mod transaction; pub use self::metadata::Metadata; pub use self::range::Range; pub use self::state_object::StateObject; pub use self::state_update::StateUpdate; pub use self::transaction::{Transaction, TransactionParams};
use std::{collections::HashMap, mem, rc::Rc, str::FromStr}; use aoc2020::{read_stdin, split_once}; fn main() { let input = read_stdin().unwrap(); let idx = input.find("\n\n").unwrap(); let (rules, cases) = input.split_at(idx); let rules = rules.parse::<RuleSet>().unwrap(); let cases = cases.trim(); let r...
use rusqlite::{Connection, Result}; use serde::{Serialize, Deserialize}; //champion, counter, items, runes #[derive(Debug)] #[derive(Serialize, Deserialize)] pub struct Champion { name: String, win_rate: f64, pick_rate: f64, ban_rate: f64, human_readable_name: String, title: String } impl Cha...
use std::fmt::Debug; use message::Delivery; #[derive(Debug)] pub struct Consumer { tag: String, no_local: bool, no_ack: bool, exclusive: bool, nowait: bool, subscriber: Box<ConsumerSubscriber>, pub current_message: Option<Delivery>, ...
mod lib; extern crate web_view; extern crate types; use std::sync::Mutex; use std::sync::Arc; use web_view::{Content, WebView}; use pleco::Board; fn main() { let html_content = include_str!("../dist/bundle.html"); let mut rt = tokio::runtime::Runtime::new().unwrap(); let board = Arc::new(Mutex::new(Boar...
// fn main() { // let mut toml = String::new(); // let mut deserializer = Deserializer::from_str(r#"{ "kana": {"ent_seq": "1000000"}, "kanji": [] }"#); // let mut serializer = Serializer::pretty(&mut toml); // serde_transcode::transcode(&mut deserializer, &mut serializer).unwrap(); // } fn main() { ...
#![feature(test)] extern crate test; #[macro_use] extern crate chomp; use test::Bencher; use std::iter; use chomp::*; use chomp::buffer::{Stream, IntoStream}; #[bench] fn count_vec_1k(b: &mut Bencher) { let data = iter::repeat(b'a').take(1024).collect::<Vec<u8>>(); fn count_vec<I: Copy>(i: Input<I>) -> Par...
#[derive(Copy, Clone)] pub struct CFFTPlanI { pub packplan: CFFTPPlan, pub blueplan: FFTBluePlan, } pub type FFTBluePlan = *mut FFTBluePlanI; #[derive(Copy, Clone)] pub struct FFTBluePlanI { pub n: usize, pub n2: usize, pub plan: CFFTPPlan, pub mem: *mut f64, pub bk: *mut f64, pub bkf: *...
extern crate ignore; extern crate regex; extern crate rhai; extern crate chrono; extern crate chrono_english; extern crate glob; extern crate lapp; const USAGE: &str = r#" findr 0.1.5: find files and filter with expressions -n, --no-hidden look at hidden files and follow hidden dirs -g, --no-gitignore do not resp...
use std::process::Command; use std::path::Path; use std::fs::remove_dir_all; struct Cleanup; impl Drop for Cleanup { fn drop(&mut self) { remove_dir_all(Path::new(NATORI)).unwrap(); } } const NEW_WITHOUT_NAME: &str = "error: The following required arguments were not provided: <name> USAGE: h...