text
stringlengths
8
4.13M
use std::option; use std::vec; use {MAX_QOS}; use error::Result; use mqtt3::{SubscribeTopic, TopicPath, PacketIdentifier, QoS}; #[derive(Debug, Clone)] pub struct Subscription { pub pid: PacketIdentifier, pub topic_path: TopicPath, pub qos: QoS } impl Subscription { pub fn to_subscribe_topic(&self) ->...
use crate::device::Device; use failure::Error; pub trait Visuals { fn setup(&mut self) -> Result<(), Error>; fn done(&mut self, device: &mut Device) -> Result<(), Error>; /// Returns `false` if the debugger should continue running. /// `true` will cause the debugger to exit. fn draw(&mut self, _:...
use super::decode; use serde::{Deserialize, Serialize}; use rmps::Deserializer; use rmps::decode::Error; use std::io::Read; /// Transform List /// /// Instructions on how to transform coordinates for an array /// of chains to create (biological) assemblies. /// The translational component is given in **Å**. #[derive(...
//use std::io::{stdio}; use std::io; use std::thread; use std::rand; fn start_getting_weather() { let mut loop_counter = 0; let delay = 3000; loop { loop_counter += 1; println!("counter: {}", loop_counter); thread::spawn(move || test_fn()); //main_weather_getter(); thre...
use crate::prelude::*; use std::os::raw::c_void; #[repr(C)] #[derive(Debug)] pub struct VkDisplayPresentInfoKHR { pub sType: VkStructureType, pub pNext: *const c_void, pub srcRect: VkRect2D, pub dstRect: VkRect2D, pub persistent: VkBool32, }
// 5 lines of code that converts your JSON string into NBT format. // // This piece of code performs the transcode through `serde_transcode` crate. // It prints NBT transcript for human readbility using `Serializer::transcript`; // if you want NBT bytes, consider using `Serializer::binary` instead. // // Due to the los...
use std::sync::Arc; use async_graphql_parser::types::ExecutableDocument; use async_graphql_value::Variables; use futures_util::{stream::BoxStream, TryFutureExt}; use opentelemetry::{ trace::{FutureExt, SpanKind, TraceContextExt, Tracer}, Context as OpenTelemetryContext, Key, }; use crate::{ extensions::{ ...
use tide_tracing::TraceMiddleware; use { tide::{Error, Response, Result, StatusCode}, tracing::Level, }; #[async_std::main] async fn main() -> tide::Result<()> { let subscriber = tracing_subscriber::fmt() .with_max_level(Level::TRACE) .finish(); tracing::subscriber::set_global_default...
use crate::common::types::{PointVertex, Real, TspResult}; use crate::common::utils::{dist, read_lines, to_points}; use spade::rtree::RTree; use typenum::U2; pub fn solve_for_file(filename: &str) -> TspResult { let file_contents: Vec<Vec<Real>> = read_lines(filename); let points: Vec<PointVertex<Real, U2>> = to...
//https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/ use std::cmp::min; impl Solution { pub fn count_good_rectangles(rectangles: Vec<Vec<i32>>) -> i32 { let mut max_square_count = 0; let mut max_square_size = 0; let mut tmp_square = 0; for ...
// Maybe implement a pallette struct #[derive(Default)] pub struct Color { r: u8, g: u8, b: u8, } #[derive(Default)] pub struct Pallete { colors: [Color; 16], }
//! An actor system where each server exposes a rewritable single-copy register. Servers do not //! provide consensus. use stateright::actor::register::{RegisterActor, RegisterMsg, RegisterMsg::*}; use stateright::actor::{Actor, ActorModel, Id, Network, Out}; use stateright::report::WriteReporter; use stateright::sema...
//! Simple code generator for manual parsing //! //! ## Attributes //! //! ### Struct //! //! There are several attributes that control behaviour of parser //! Each, attached to struct's field //! //! - `starts_with = <prefix>` - Specifies string with which next parse step should start(can be stacked). Errors if prefix...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtGui/qfontinfo.h // dst-file: /src/gui/qfontinfo.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <=...
use bigneon_db::dev::TestProject; use bigneon_db::models::{ TicketPricing, TicketPricingEditableAttributes, TicketType, TicketTypeEditableAttributes, }; use bigneon_db::utils::errors::ErrorCode::ValidationError; use chrono::NaiveDate; use diesel::result::Error; use diesel::Connection; #[test] fn create() { let...
use std::collections::BTreeMap; use crate::{FieldId, IndexedPos}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct PositionMap { pos_to_field: Vec<FieldId>, field_to_pos: BTreeMap<FieldId, IndexedPos>, } impl PositionMap { /// insert `id` at the spe...
#[doc = "Reader of register MMCCTRL"] pub type R = crate::R<u32, super::MMCCTRL>; #[doc = "Writer for register MMCCTRL"] pub type W = crate::W<u32, super::MMCCTRL>; #[doc = "Register MMCCTRL `reset()`'s with value 0"] impl crate::ResetValue for super::MMCCTRL { type Type = u32; #[inline(always)] fn reset_va...
use iron::Handler; use handler::WebHandler; use router::Router; pub struct WebRouter { routes: Vec<Box<WebHandler>>, } impl WebRouter { pub fn new() -> Self { WebRouter { routes: Vec::new() } } pub fn add_route(&mut self, handler: Box<WebHandler>) { self.routes.push(handler); } ...
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; // Test for performance regressions in the *head* revision since the *latest* release. // // ``` // cargo update // cargo bench -- --save-baseline main // critcmp main -g '\w+/(.*)' // ``` criterion_main!(benches); criterion_group!(...
use super::{challenge::Challenge, user_performance_data::UserPerformanceData}; #[derive(Debug)] pub struct ChallengePerformanceData { pub chat_id: i64, pub challenge: Challenge, pub user_performance: Vec<UserPerformanceData>, }
use std::io::{BufReader, BufRead}; use std::fs::File; pub fn solve() -> String { let f = BufReader::new(File::open("resources/day_two.txt").unwrap()); let checksum :u32 = f.lines() .map(|line| line.unwrap()) .map(|line| line_checksum(line)) .sum(); return checksum.to_string() } fn...
use structopt::StructOpt; #[derive(StructOpt)] pub struct CmdOpts { /// Output JSON #[structopt(short, long)] pub json: bool, /// Don't show headers (ignored for JSON output) #[structopt(short = "H", long)] pub no_headers: bool, #[structopt(subcommand)] pub cmd: Command, } #[derive(S...
use super::bus::Busable; use arrayvec::ArrayVec; use num_enum::IntoPrimitive; use crate::gui; pub struct Ppu { background_palette: ArrayVec<Color, 4>, obj_palette0: ArrayVec<Color, 4>, obj_palette1: ArrayVec<Color, 4>, scx: u8, scy: u8, wx: u8, // real_WX - 7 wy: u8, ly: u8, lyc: u...
use std::fmt; #[derive(Debug, PartialEq)] pub enum Token { Eof, Illegal, Identifier(String), Int(i64), Plus, Increment, Minus, Decrement, Assign, Asterisk, Slash, Exclamation, Equal, NotEqual, LessThan, LessThanAndEqual, MoreThan, MoreThanAndEqual, Semicolon, Comma, LeftParanthes...
use tera; use actix_web::http::{ContentEncoding, Method, NormalizePath, StatusCode}; use actix_web::{fs, pred, App, HttpRequest, HttpResponse}; #[cfg(debug_assertions)] use actix_web::middleware::{Middleware, Started}; #[cfg(debug_assertions)] use actix_web::{middleware, Result}; use std::cell::RefCell; pub struct Ap...
use std::collections::HashMap; pub fn part_1(input: &Vec<String>) -> usize { let nr_map = get_counts_per_bit_position(input); let number_length = input[0].len(); let total_numbers = input.len(); let mut gamma_rate = String::new(); for index in 0..number_length { let nr_positive_bits = nr_...
use piston_window::{ Button, Key, MouseButton }; pub struct InputManager; impl InputManager { pub fn new() -> InputManager { InputManager } pub fn get_operation(&self, button: Button) -> Operation { match button { Button::Keyboard(key) => match key { Key::A => ...
use crate::event::{Event, EventState}; use crate::parser::parse_line; use std::error::Error; use std::io::{BufRead, BufReader, Lines, Read}; use std::iter::Enumerate; pub struct Consumer<T> where T: Read, { response: Enumerate<Lines<BufReader<T>>> } impl<'a, T> Consumer<T> where T: Read, { pub fn new(...
//! This module contains minimal stable dummy implementations of NonZero and //! Shared, such that the same code can be used between the nightly and stable //! versions of rust-gc. use std::marker::PhantomData; /// See `::std::ptr::Shared` pub struct Shared<T: ?Sized> { p: *mut T, _pd: PhantomData<T>, } impl...
extern crate gtk; use gtk::prelude::*; use std::cell::Cell; use std::rc::Rc; use std::ops::Deref; use gtk::{Orientation, Window, WindowType}; fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK. Do you have libgtk 3.10+?"); return; } let window = Window::new(WindowType...
fn main() { yew::start_app::<event_bus::Model>(); }
struct Package<'a> { colour: &'a str, shape: &'a str } trait PackageSpecification { fn is_satisfied(&self, package: &Package) -> bool; } struct PackageColourSpecification<'a> { expected_colour: &'a str } impl PackageSpecification for PackageColourSpecification<'_> { fn is_satisfied(&self, package...
use std::collections::HashSet; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::WindowCanvas; pub struct Pellet { rect: Box<Rect>, window_width: i32, window_height: i32, w: u32, h: u32, eaten: bool, } impl Pellet { pub fn new( window_width: i32, window_heig...
use arrow::buffer::{BooleanBuffer, Buffer}; use std::ops::Range; /// An arrow-compatible mutable bitset implementation /// /// Note: This currently operates on individual bytes at a time /// it could be optimised to instead operate on usize blocks #[derive(Debug, Default, Clone)] pub struct BitSet { /// The underl...
#![crate_name = "rspark"] pub mod rspark { use std::error::Error; use std::fmt; /// The Unicode representation of the graph ticks. const TICKS: [char; 8] = [ '\u{2581}', '\u{2582}', '\u{2583}', '\u{2584}', '\u{2585}', '\u{2586}', '\u{2587}', '\u{2588}', ]; /// Renders a graph...
// 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. //! A futures-rs executor design specifically for Fuchsia OS. #![deny(missing_docs)] // Set the system allocator for anything using this crate extern cra...
mod port_bind; mod start; mod stop; pub use port_bind::ProcessPortBindLog; pub use start::ProcessStart; pub use stop::ProcessStop;
::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`*"] fn LdapGetLastError ( ) -> u32 ); #[cfg(feature = "Win32_Foundation")] ::windows_sys::core::link ! ( "wldap32.dll""cdecl" #[doc = "*Required features: `\"Win32_Networking_Ldap\"`, `\"Win32_Foundation\"`*"] fn ...
use std::mem; use futures::{Future, IntoFuture, Poll}; pub(crate) trait Started: Future { fn started(&self) -> bool; } pub(crate) fn lazy<F, R>(func: F) -> Lazy<F, R> where F: FnOnce() -> R, R: IntoFuture, { Lazy { inner: Inner::Init(func), } } // FIXME: allow() required due to `impl Tra...
use proconio::{input, marker::Bytes}; fn main() { input! { s: Bytes, n: u64, }; let mut k = 0; for i in 0..s.len() { if s[i] == b'1' { k += 1 << (s.len() - i - 1); } } if k > n { println!("-1"); return; } for i in 0..s.len() {...
#[doc = "Reader of register AHB3SMENR"] pub type R = crate::R<u32, super::AHB3SMENR>; #[doc = "Writer for register AHB3SMENR"] pub type W = crate::W<u32, super::AHB3SMENR>; #[doc = "Register AHB3SMENR `reset()`'s with value 0x0101"] impl crate::ResetValue for super::AHB3SMENR { type Type = u32; #[inline(always)...
use std::u8; use std::io::{Read, Write}; const DATA_SIZE: usize = 30000; /// A virtual machine to run a program. pub struct VM<I: Read, O: Write> { prog: Vec<u8>, iptr: usize, dptr: usize, data: [u8; DATA_SIZE], input: I, output: O, } /// An action to be taken by the virtual machine after an ...
use serde::Deserialize; use gotham_derive::{StateData, StaticResponseExtender}; #[derive(Deserialize, StateData, StaticResponseExtender)] pub struct PathExtractor { pub key: String, }
mod links; mod config; mod layers; use self::links::Links; use self::config::Config; use self::layers::Layers; pub struct Network { links: Links, layers: Layers, config: Config } impl Network { pub fn new(network_struct: &Vec<u32>, learning_rate: f32, iterations_count: u32) -> Network { let config = Conf...
#[derive(Clone, PartialEq, Debug)] pub enum Token<'input> { // keywords As, Library, Using, Bits, Const, Enum, Protocol, Service, Strict, Struct, Flexible, Table, Union, XUnion, Error, Reserved, Compose, Identifier(&'input str), // litera...
//! `RawDir` and `RawDirEntry`. use core::fmt; use core::mem::{align_of, MaybeUninit}; use linux_raw_sys::general::linux_dirent64; use crate::backend::fs::syscalls::getdents_uninit; use crate::fd::AsFd; use crate::ffi::CStr; use crate::fs::FileType; use crate::io; /// A directory iterator implemented with getdents. ...
#![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_parens)] use num::complex::Complex; use std::ops::{Mul}; use eventual::*; pub fn mandelbrot_point(x: f64, y: f64, iterations: u32) -> u8 { let c = Complex::new(x, y); let mut z = Complex::new(0.0, 0.0); for i in 0..iterations { ...
use std::error::Error; use std::fmt; use std::io; pub fn advanced_types() { type_alias_demo(); never_type_demo(); sized_demo(); } /// 类型别名用来创建类型同义词 type alias fn type_alias_demo() { type Kilometers = i32; let x: i32 = 3; let y: Kilometers = 4; assert_eq!(7, x + y); let f: Box<Fn()...
use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::io::{Error as IOError}; use std::iter; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; use itertools::kmerge; use itertools::Itertools; use regex::Regex; use record_file::RecordFile; use sstable::SSTable; use record::Record; const WA...
// `with_decimals` in integration tests mod with_scientific; use super::*; #[test] fn without_valid_option_errors_badarg() { crate::test::float_to_string::without_valid_option_errors_badarg(file!(), result); }
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn ldexp(x: f64, n: i32) -> f64 { super::scalbn(x, n) }
extern crate rand; extern crate piston_window; mod emulator; use std::env; use std::io::prelude::*; use std::path::Path; use piston_window::*; use emulator::ChipEight; fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 2 { let mut stderr = std::io::stderr(); writeln...
//! The `snow` crate is a straightforward, Hard To Fuck Up™ Noise Protocol implementation. //! //! Read the [Noise Protocol Framework Spec](http://noiseprotocol.org/noise.html) for more //! information. //! //! The typical usage flow is to use `NoiseBuilder` to construct a `Session`, which is main //! state machine you...
// 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 ...
#![recursion_limit = "1024"] use byteorder::{ByteOrder, LittleEndian as LE}; use custom_error::custom_error; use deoptloader::decompressor::{Decompressor, Error as DecompressorError, Op}; use deoptloader::fixup_converter::FixupConverter; use deoptloader::neexe::*; use nom::{do_parse, le_u16, named, named_args, tag, ta...
fn main() { // if is an expression, so it can be used // on the right side of a 'let' statement let condition = true; let number = if condition { 5 } else { 6 // note the lack of semicolon // on this expression }; println!("The value of number is: {}", number...
/* 设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。 注意:本题相对原题做了扩展 示例: 输入:4 输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] 解释: 4 皇后问题存在如下两个不同的解法。 [ [".Q..",  // 解法 1 "...Q", "Q...", "..Q."], ["..Q.",  // 解法 2 "Q...", "...Q", ".Q.."] ] 来源:力扣(LeetCode) 链接...
#[doc = "Reader of register M5FDRH"] pub type R = crate::R<u32, super::M5FDRH>; #[doc = "Reader of field `FEC`"] pub type FEC_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Failing error code"] #[inline(always)] pub fn fec(&self) -> FEC_R { FEC_R::new((self.bits & 0xffff_ffff) as u32) } }...
use nalgebra::{ allocator::Allocator, storage::Storage, DefaultAllocator, Dim, Norm, OVector, RealField, Vector, }; pub fn distance_to_space<X, D, S1, S2, S3>( p1: &Vector<X, D, S1>, min_bounds: &Vector<X, D, S2>, max_bounds: &Vector<X, D, S3>, norm: &impl Norm<X>, ) -> X where X: RealField, ...
/** * @lc app=leetcode.cn id=216 lang=rust * * [216] 组合总和 III * * https://leetcode-cn.com/problems/combination-sum-iii/description/ * * algorithms * Medium (63.45%) * Total Accepted: 3.1K * Total Submissions: 4.9K * Testcase Example: '3\n7' * * 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。...
use crate::{ event::{self, Event}, sinks::util::{ encoding::EncodingConfigWithDefault, http::{Auth, BatchedHttpSink, HttpClient, HttpSink}, service2::TowerRequestConfig, BatchConfig, BatchSettings, BoxedRawValue, JsonArrayBuffer, UriSerde, }, topology::config::{DataType, ...
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use helixdb::Entry; use rand::{thread_rng, Rng}; fn do_benchmark(key_size: usize, value_size: usize, c: &mut Criterion) { let mut rng = thread_rng(); let key = (0..key_size).map(|_| rng.gen()).collect(); let value = (0..value_size).map...
use core::{cmp, mem, ptr, slice}; use orbclient::{Color, Renderer}; use std::fs::find; use std::proto::Protocol; use std::string::String; use std::vec::Vec; use uefi::status::{Error, Result}; use uefi::guid::GuidKind; use uefi::memory::MemoryType; use crate::disk::DiskEfi; use crate::display::{Display, ScaledDisplay, ...
use rust_algorithms::union_find::UnionFind; use rust_algorithms::union_find::quick_find::QuickFind; use crate::union_find::common::*; #[test] #[should_panic] fn quick_find_not_zero() { QuickFind::new(0); } #[test] #[should_panic] fn quick_find_out_of_bounds() { let size = 10; test_out_of_bounds(&mut Quic...
use tree_sitter::Node; use crate::lint::core::{ValidationError, Validator}; use crate::lint::grammar::FIELD_IDENTIFIER; use crate::lint::rule::RULE_EXPECT_CALL; use crate::lint::utils::node_lowercase_eq; pub struct ExpectCallValidator; impl Validator for ExpectCallValidator { fn validate(&self, node: &Node, sour...
// https://github.com/TylerGlaiel/FrameTimingControl/blob/master/frame_timer.cpp use super::*; //these are loaded from Settings in production code const UPDATE_RATE: f64 = 60.; //compute how many ticks one update should be const FIXED_DELTATIME: f64 = 1.0 / UPDATE_RATE; pub(crate) const DESIRED_FRAMETIME: f64 = 1.0 /...
/// /// Creates a retina map that can be used to simulate macular degeneration. /// /// # Arguments /// /// - `res` - resolution of the returned retina map /// - `severity` - the severity of the disease, value between 0 and 100 /// pub fn generate_simple( res: (u32, u32), severity: u8, ) -> image::ImageBuf...
use serde_json::Value; use super::constants::AUTH_RULE; #[allow(non_camel_case_types)] #[derive(Deserialize, Debug, Serialize, PartialEq)] pub enum AuthAction { ADD, EDIT } #[derive(Serialize, Deserialize, PartialEq, Debug)] #[serde(tag = "constraint_id")] pub enum Constraint { #[serde(rename = "OR")] ...
//! Traits for pointers. use std::{mem::ManuallyDrop, ptr::NonNull}; use crate::{ sabi_types::{MovePtr, RMut, RRef}, utils::Transmuter, }; #[allow(unused_imports)] use core_extensions::utils::transmute_ignore_size; #[cfg(test)] mod tests; /// /// Determines whether the referent of a pointer is dropped when...
use super::cstate::*; #[derive(Debug)] pub enum FreeGroup<A> { One(A), And(Box<FreeGroup<A>>, Box<FreeGroup<A>>), Not(Box<FreeGroup<A>>), Empty, } impl<A> FreeGroup<A> { fn empty() -> FreeGroup<A> { FreeGroup::Empty } fn and(self, other: FreeGroup<A>) -> FreeGroup<A> { Fr...
#[cfg(test)] mod tests { //若使用泛型,必须提供类型注解来表明希望使用 Iterator 的哪一个实现 //关联类型更通用 pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; } }
mod file_data; mod file_database; mod file_database_builder; mod recursive_path; mod serde_types; pub use self::file_data::*; pub use self::file_database::*; pub use self::file_database_builder::*; pub use self::recursive_path::*; pub use self::serde_types::*; // ex: noet ts=4 filetype=rust
use solana_program::program_error::ProgramError; use std::mem::size_of; #[repr(C)] #[derive(Debug)] pub enum AuctionInstruction { CreateAuction { start_price: u64 }, Bidding { price: u64, decimals: u8 }, CloseAuction, } impl AuctionInstruction { pub fn unpack(input: &[u8]) -> Result<Self, ProgramError...
#[macro_use] extern crate quote; extern crate proc_macro; extern crate syn; mod native; use syn::{ parse::{Parse, ParseStream}, parse_macro_input, parse_quote, FnArg, ItemFn, Result, Signature, }; #[proc_macro] pub fn export_native(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream { native::exp...
use crate::{ core::{ visitor::{ Visitor, VisitResult, Visit }, math::{ Rect, mat4::Mat4, vec2::Vec2, }, }, scene::base::{ Base, AsBase, BaseBuilder, }, }; #[derive(Clone)] pub...
use rustc_lint::LateLintPass; use rustc_session::{declare_lint, declare_lint_pass}; declare_lint! { /// **What it does:** /// /// **Why is this bad?** /// /// **Known problems:** None. /// /// **Example:** /// /// ```rust /// // example code where a warning is issued /// ```...
//! The `info` subcommand: shows metadata about the git-global installation. use chrono::Duration; use std::path::PathBuf; use std::time::SystemTime; use config::Config; use errors::Result; use report::Report; /// Returns the age of a file in terms of days, hours, minutes, and seconds. fn get_age(filename: PathBuf)...
pub struct Solution; impl Solution { pub fn contains_duplicate(nums: Vec<i32>) -> bool { let mut nums = nums; nums.sort(); for i in 1..nums.len() { if nums[i - 1] == nums[i] { return true; } } return false; } } #[test] fn test0217...
//! types and functions for signing operations on the `secp256r1` curve. use libc::{uint8_t,c_int}; /// size of curve. const BYTES: usize = 32; /// a public ecc key on the `secp256r1` curve. pub struct Public([u8;BYTES+1]); impl_newtype_bytearray_ext!(Public,BYTES+1); impl_serhex_bytearray!(Public,BYTES+1); /// a...
use rust_src::{Dir, DOWN, LEFT, RIGHT, UP}; #[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)] #[repr(C)] pub struct Point { pub x: usize, pub y: usize, } impl Point { pub fn new(x: usize, y: usize) -> Point { Point { x, y } } pub fn dist(&self, other: &Point) -> usize { ((self.x as i32 - other.x as i32).abs...
// Copyright 2013 Google Inc. All Rights Reserved. // Copyright 2017 The Ninja-rs Project Developers. All Rights Reserved. // // 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:/...
use std::cell::RefCell; use std::collections::HashMap; use wasi_common::hostcalls::*; use wasi_common::{WasiCtx, WasiCtxBuilder}; use wasminspect_vm::*; use wasmparser::{FuncType, Type}; pub struct WasiContext { ctx: RefCell<WasiCtx>, } pub fn instantiate_wasi() -> (WasiContext, HashMap<String, HostValue>) { ...
// // https://github.com/rib/jsonwebtokens // use serde_json::json; use serde_json::{Map, Value}; use std::fs; use std::process; use std::str; use std::str::FromStr; use std::time::{SystemTime, UNIX_EPOCH}; use clap::clap_app; use jsonwebtokens as jwt; use jwt::{raw, Algorithm, AlgorithmID, Verifier}; use openssl::...
#[doc = "Reader of register IER1"] pub type R = crate::R<u32, super::IER1>; #[doc = "Writer for register IER1"] pub type W = crate::W<u32, super::IER1>; #[doc = "Register IER1 `reset()`'s with value 0"] impl crate::ResetValue for super::IER1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
use std::fs; use crate::cli; #[cfg(test)] mod test; pub fn run() { let filename = cli::aoc_filename("aoc_2019_08.txt"); let digits = fs::read_to_string(filename).unwrap(); let img = parse(25, 6, digits.trim()); println!("Part One: {}", part_one(&img)); println!("Part Two:\n{}", part_two(&img)); }...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - DBGMCU_IDCODE"] pub idcode: IDCODE, #[doc = "0x04 - Debug MCU configuration register"] pub cr: CR, #[doc = "0x08 - Debug MCU APB1 freeze register1"] pub apb1lfzr: APB1LFZR, #[doc = "0x0c - Debug MCU APB1 freeze ...
// Copyright 2017 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 ...
use super::*; #[derive(Clone)] pub struct NestedClass(pub Row); impl NestedClass { pub fn nested_type(&self) -> TypeDef { Row::new(self.0.u32(0) - 1, TableIndex::TypeDef, self.0.file).into() } pub fn enclosing_type(&self) -> TypeDef { Row::new(self.0.u32(1) - 1, TableIndex::TypeDef, self....
#[cfg(not(feature = "lib"))] use std::{cell::RefCell, collections::{HashMap, HashSet}, convert::TryFrom, mem, ptr, rc::Rc, slice}; mod composition; mod path_builder; mod raster_builder; mod styling; #[cfg(not(feature = "lib"))] use composition::Composition; #[cfg(not(feature = "lib"))] use path_builder::PathBuilder; ...
//TODO : Finish refactoring. // - Move config to it's own module // - Consider moving command out // - Do stuff and things use std::io::*; use std::net::*; use std::sync::mpsc::*; use std::thread; use regex::Regex; use irc::message::*; pub struct Config { pub nick: String, pub server_address: String, pub ...
use std::fs::File; use std::io::Read; struct Param { mode: u8, value: i64, } impl Param { fn new(vec: &Vec<i64>, index: usize, param_index: usize) -> Param { let mode = ((vec[index] / 10i64.pow((param_index + 1) as u32)) % 10) as u8; let value = vec[index + param_index]; assert!(m...
// Export these crates publicly so we can have a single reference pub use tracing; pub use tracing::instrument;
use borsh::{BorshDeserialize, BorshSerialize}; use near_sdk::{ // callback, // callback_vec, env, ext_contract, near_bindgen, Promise, PromiseOrValue, }; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; // Prepaid gas for making a single simple call....
use std::ops::{Deref, DerefMut}; use crate::font::Font; use nannou::wgpu::Texture; use utopia_animations::{ widgets::{animated::Animated as AnimatedWidget, AnimationExt}, CanTween, Linear, }; use utopia_core::{ controllers::TypedController, lens::{Lens, NoLens}, widgets::{ controlled::Contr...
mod extensions; mod language_client; mod language_server_protocol; mod logger; mod rpcclient; mod rpchandler; mod sign; mod types; mod utils; mod viewport; mod vim; mod vimext; mod watcher; use anyhow::Result; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use types::State; #[macro_use] extern crate clap...
use serde::{Deserialize}; use web_view::*; use sdl2::audio::{AudioCallback, AudioSpec, AudioSpecDesired}; use std::sync::{Arc,Mutex}; pub const SAMPLE_FREQUENCY: i32 = 44_100; pub const SAMPLE_COUNT: u16 = 256; pub const CHANNEL_COUNT: u8 = 2; pub const SAMPLE_BUFFER_SIZE: usize = SAMPLE_COUNT as usize * CHANNEL_COUNT...
use super::*; #[test] fn with_different_process_sends_message_when_timer_expires() { run!( |arc_process| { ( Just(arc_process.clone()), milliseconds(), strategy::term(arc_process.clone()), ) }, |(arc_process, millisecon...
/* * NOTE: headers are stored in a BTreeMap. It would be faster to use a HashMap * instead but the order in which they are displayed would become * non-deterministic. */ use std::collections::BTreeMap; use std::collections::btree_map::IntoIter; #[derive(Clone)] pub struct Headers { headers: BTreeMap<String, St...
#[doc = "Reader of register ITLINE26"] pub type R = crate::R<u32, super::ITLINE26>; #[doc = "Reader of field `SPI2`"] pub type SPI2_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - SPI2"] #[inline(always)] pub fn spi2(&self) -> SPI2_R { SPI2_R::new((self.bits & 0x01) != 0) } }
mod systems; mod components; mod models; mod rpops_instance; pub use crate::prelude::*; pub mod prelude { pub use crate::systems::*; pub use crate::components::*; pub use crate::models::*; pub use crate::rpops_instance::*; pub use vermarine_engine::prelude::*; }