text
stringlengths
8
4.13M
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorResponse>, }...
// Copyright 2018-2019 Mozilla // // 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...
pub mod file_opener;
#[derive(Clone, Debug)] pub enum Token { LParen, RParen, Plus, Minus, Star, Slash, Name(usize), Print, Num(i64), Assign(usize), Define(usize) } pub enum LexicalError { } pub fn tokenize(s: & [u8]) -> Vec<(usize, Token, usize)> { use Token::*; let mut res :Vec<(usize, Token,...
// 导出与本文件名同名的文件夹下的 b.rs 中的内容 pub mod b; pub use b::*;
#[macro_use] extern crate structopt; extern crate cgmath; #[macro_use] extern crate glium; extern crate aperture; extern crate bincode; extern crate geoprim; extern crate notify; extern crate serde_json; use bincode::deserialize_from; use cgmath::prelude::*; use geoprim::*; use glium::glutin; use glium::Surface; use n...
use crate::Error; pub struct Memory { size: usize, memory: Vec<u8>, } impl Memory { pub fn new(size: usize) -> Self { Memory { size, memory: vec![0; size], } } pub fn load(&self, address: u32) -> Result<u8, Error> { if address > self.size as u32 { ...
use super::token::{Ctrl, FilePos, Kw, Op, Orientation, Position, Span, Token, TokenKind}; use std::path::PathBuf; use std::iter::Iterator; use std::str::Chars; #[derive(Debug, Clone)] pub struct TokenStream<'a> { it: Chars<'a>, source: &'a str, index: usize, line: usize, column: usize, file: P...
// This file is part of Substrate. // Copyright (C) 2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free S...
#[macro_use] extern crate rocket; #[macro_use] extern crate diesel; #[macro_use] extern crate lazy_static; extern crate askama; // for the Template trait and custom derive macro extern crate spongedown; use std::io::Cursor; use rocket::Request; use rocket::Response; use rocket::http::ContentType; use rocket::http::S...
#[macro_use] extern crate serde_derive; extern crate bincode; extern crate bincode_fuzz; use std::env; use bincode_fuzz::random::*; use bincode_fuzz::util::heartbeat; use bincode::{serialize, deserialize, SizeLimit}; include!(concat!(env!("OUT_DIR"), "/type.rs")); fn perform_serializations<R: Rng>(rng: &mut R, n: u...
use std::cmp; struct Item { name: &'static str, weight: usize, value: usize } fn knapsack01_dyn(items: &[Item], max_weight: usize) -> Vec<&Item> { let mut best_value = vec![vec![0; max_weight + 1]; items.len() + 1]; for (i, it) in items.iter().enumerate() { for w in 1 .. max_weight + 1 {...
#[doc = "Register `ETH_DMAMR` reader"] pub type R = crate::R<ETH_DMAMR_SPEC>; #[doc = "Register `ETH_DMAMR` writer"] pub type W = crate::W<ETH_DMAMR_SPEC>; #[doc = "Field `SWR` reader - Software Reset"] pub type SWR_R = crate::BitReader; #[doc = "Field `SWR` writer - Software Reset"] pub type SWR_W<'a, REG, const O: u8...
use std::time::Duration; use std::time::Instant; use perf_monitor::cpu::processor_numbers; use perf_monitor::cpu::ProcessStat; use perf_monitor::cpu::ThreadStat; use perf_monitor::fd::fd_count_cur; use perf_monitor::io::get_process_io_stats; use perf_monitor::mem::get_process_memory_info; fn main() { build_some_t...
use util::mem::read_u16; use crate::memory::{io::IoRegisters, VRAM_SIZE}; use super::line::LineBuffer; /// Render a single line in mode3. /// /// **BG Mode 3 - 240x160 pixels, 32768 colors** /// Two bytes are associated to each pixel, directly defining one of the 32768 colors (without using palette data, /// and thu...
/// The maximum number of results allowed to be returned from `list_executed_transactions`. pub const LIST_TRANSACTIONS_MAX_RESULTS: usize = 1000; /// If no `result_limit` is specified, this value is the limit used by default. pub const LIST_TRANSACTIONS_DEFAULT_RESULT_COUNT: usize = 100;
use crate::spec::hardware_registers::Interrupt; use crate::spec::mmu::{Error as MMUError, MMU}; use std::num::Wrapping; const DIV_ADDR: u16 = 0xFF04; const TIMA_ADDR: u16 = 0xFF05; const TMA_ADDR: u16 = 0xFF06; const TAC_ADDR: u16 = 0xFF07; #[derive(Debug)] pub enum TimerError { MMUError(MMUError), } #[derive(De...
use super::*; pub fn decode_slice(buf: &[u8]) -> Result<Option<Packet<'_>>, Error> { let mut offset = 0; if let Some((header, remaining_len)) = read_header(buf, &mut offset)? { let r = read_packet(header, remaining_len, buf, &mut offset)?; Ok(Some(r)) } else { // Don't have a full p...
// TODO: Temporary redirect pub(crate) use crate::context::CommandRegistry; use crate::evaluate::{evaluate_baseline_expr, Scope}; use crate::parser::{hir, hir::SyntaxShape, parse_command, CallNode}; use crate::prelude::*; use derive_new::new; use indexmap::IndexMap; use log::trace; use serde::{Deserialize, Serialize}; ...
// Copyright (C) 2015-2021 Swift Navigation Inc. // Contact: https://support.swiftnav.com // // This source is subject to the license found in the file 'LICENSE' which must // be be distributed together with this source. All other rights reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ...
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Primitive { Boolean, Number, }
pub fn max_envelopes(mut envelopes: Vec<Vec<i32>>) -> i32 { envelopes.sort(); use std::cmp::max; let n = envelopes.len(); let mut chain = vec![1; n]; let mut longest = 0; for i in 0..n { for j in 0..i { if envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1...
//Find the sum of the only eleven primes that are both truncatable from left to right and right to left. use std::time::Instant; fn main() { let now = Instant::now(); println!("e37:{:?}, {:?} seconds", e(), now.elapsed()); //println!("debug:{:?}", is_left_trunk(3797)); //println!("debug:{:?}", is_right...
pub mod phpipam; use std::error::Error; use reqwest::Url; pub trait Resolver { fn new(url: Url) -> Result<Self, Box<dyn Error>> where Self: Sized; fn get(&self, hostname: &str) -> Result<String, Box<dyn Error>>; }
use std::future::Future; use rand::Rng; const MAX_RETRIES: u64 = 10; async fn sleep(hint: u64) { let delay = std::time::Duration::new( hint * hint as u64, rand::thread_rng().gen_range(0, 1_000_000_000), ); tokio::time::delay_for(delay).await; } pub async fn retry_future_if<F, G, T, E, P>...
enum E { E1, E2 } struct S { a: i32, b: bool } struct TS (f64, char); fn f1() -> E { E::E2 } fn f2() -> S { S { a: 49, b: true } } fn f3() -> TS { TS (4.7, 'w') } fn f4() -> [i16; 4] { [7, -2, 0, 19] } fn f5() -> Vec<i64> { vec![12000] } fn main() { print!("{} ", match f1() { E::E1 => 1, _ => -1 }); print!("{}...
pub trait All<T> { fn all(self) -> T; } impl<'a, A> All<Option<&'a A>> for &'a Option<A> { fn all(self) -> Option<&'a A> { match self { &Some(ref a) => Some(a), _ => None, } } } impl<'a, A> All<Option<&'a mut A>> for &'a mut Option<A> { fn all(self) -> Option<&'...
pub use crate::auth::{ check_session, delete_account, delete_account_admin, login, logout, signup, users, }; pub use crate::logs::logs; pub use crate::songs::{ add_song, artists, edit_song, genres, history, history_all, popular, recognize, songs, };
use std::{io::Write, string::ToString, sync::Arc}; use either::Either; use crate::{ binary::{Encoder, ReadEx}, errors::Result, types::{ column::{ array::ArrayColumnData, list::List, nullable::NullableColumnData, ArcColumnWrapper, ColumnWrapper, StringPool, }, ...
struct Seat { id: u32 } impl From<&str> for Seat { fn from(input: &str) -> Self { let id = input .chars() .fold(0, |total, ch| { (total << 1) + match ch { 'B' | 'R' => 1, _ => 0 } }); S...
extern crate clap; extern crate snarkov; use clap::{App, Arg}; use std::path::Path; use std::str::FromStr; use snarkov::Corpus; fn format_seed(seed: [u32; 4]) -> String { format!("{:x}{:x}{:x}{:x}", seed[0], seed[1], seed[2], seed[3]) } fn parse_seed(seed: &str) -> [u32; 4] { assert!(seed.len() == 32); l...
#[doc = "Register `CFGR` reader"] pub type R = crate::R<CFGR_SPEC>; #[doc = "Register `CFGR` writer"] pub type W = crate::W<CFGR_SPEC>; #[doc = "Field `BKPRW` reader - Backup registers read/write protection offset Protection zone 1 is defined for backup registers from TAMP_BKP0R to TAMP_BKPxR (x = BKPRW-1, from 0 to 12...
#![no_std] #![no_main] #![feature(trait_alias)] #![feature(min_type_alias_impl_trait)] #![feature(impl_trait_in_bindings)] #![feature(type_alias_impl_trait)] #![allow(incomplete_features)] #[path = "../example_common.rs"] mod example_common; use core::fmt::Write; use cortex_m_rt::entry; use embassy::executor::Executor...
extern crate winapi; use std::ptr::null_mut; use winapi::shared::{ minwindef::LPVOID, ntdef::LPCWSTR, windef::HWND, }; type MessageBoxWHook = *const unsafe extern "system" fn(HWND, LPCWSTR, LPCWSTR, u32) -> i32; static mut MESSAGE_BOX_W_HOOK_ADDRESS: u64 = 0; unsafe fn clear_last_error() { use winap...
use std::error; use std::fmt; #[derive(Debug, Clone)] pub struct ResponseContent<T> { pub status: reqwest::StatusCode, pub content: String, pub entity: Option<T>, } #[derive(Debug)] pub enum Error<T> { Reqwest(reqwest::Error), Serde(serde_json::Error), Io(std::io::Error), ResponseError(Res...
use std::cmp; use std::env; use std::fmt::Debug; use std::panic; use crate::{ tester::Status::{Discard, Fail, Pass}, Arbitrary, Gen, }; /// The main QuickCheck type for setting configuration and running QuickCheck. pub struct QuickCheck { tests: u64, max_tests: u64, min_tests_passed: u64, gen:...
use crate::level9::Computer; use std::collections::VecDeque; use std::collections::HashMap; use std::collections::HashSet; use std::error::Error; #[derive(Hash, PartialEq, Eq, Clone, Debug)] struct PaintBot { direction: (i32, i32), // (i, j) position: (i32, i32) // (i, j) } impl PaintBot { pub fn new() ->...
#[derive(Debug, PartialEq, Eq)] // derive auto-implements simple features, like debug printing and comparisons struct Fruit { name: String, amount: u32, } fn convert_to_fruit(line: &str) -> Result<Fruit, &str> { Err("Function not implemented") } #[test] fn test_convert_to_fruit() { let fruit = convert...
use std::fs; fn main() { let right = 3; let down = 1; println!("Sample data hits: {}\n", plot_course("input/sample.input", right, down)); println!("Full data hits: {}\n", plot_course("input/day3.input", right, down)); println!("Sample data product: {}\n", compute_product("input/sample.input"))...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Identity { #[serde(rename = "type")] pub type_: String, #[serde(rename = "identityIds")] pub identi...
use std::time::Instant; const INPUT: &str = include_str!("../input.txt"); fn sums_to_target(nums: &[i64], target: i64) -> bool { for i in 0..nums.len() { for j in i + 1..nums.len() { if nums[i] + nums[j] == target { return true; } } } false } fn pa...
mod level1; mod level2; mod level3; mod level4; mod level5; mod level6; mod level7; mod level8; mod level9; mod level10; mod level11; mod level12; mod level13; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { // let fuel_mass: u32 = level1::part1()?; // println!("{}", fuel_mass); // let fue...
pure fn add(x: u8, y: u8) -> u8 { ret x + y; } pure fn sub(x: u8, y: u8) -> u8 { ret x - y; } pure fn mul(x: u8, y: u8) -> u8 { ret x * y; } pure fn div(x: u8, y: u8) -> u8 { ret x / y; } pure fn rem(x: u8, y: u8) -> u8 { ret x % y; } pure fn lt(x: u8, y: u8) -> bool { ret x < y; } pure fn le(x: u8, y: u8) -> b...
//! Helpers for writing tests. use ContextRef; /// An LLVM context. pub struct Context { pub inner: ContextRef, } impl Context { pub fn new() -> Self { Context { inner: unsafe { ::LLVMRustCreateContext() }, } } } impl Drop for Context { fn drop(&mut self) { unsaf...
use amethyst::ecs::{Component, DenseVecStorage}; #[derive(Clone, Component, Debug)] #[storage(DenseVecStorage)] pub struct CollisionPlatform { pub height: f32, pub width: f32, pub x: f32, pub y: f32, pub is_spike: bool, pub collidee: Option<bool>, } impl Default for CollisionPlatform { fn ...
use std::collections::HashMap; use actix::prelude::*; use gtk::prelude::*; use kosem_webapi::pairing_messages; use kosem_webapi::Uuid; use crate::internal_messages::gui_control::{ MessageFromServer, ShowJoinMenu, UserSelectedProcedure, }; use crate::work_on_procedure::WorkOnProcedureActor; #[derive(woab::Facto...
#[doc = "Reader of register CHAN_RESULT[%s]"] pub type R = crate::R<u32, super::CHAN_RESULT>; #[doc = "Reader of field `RESULT`"] pub type RESULT_R = crate::R<u16, u16>; #[doc = "Reader of field `CHAN_RESULT_NEWVALUE_MIR`"] pub type CHAN_RESULT_NEWVALUE_MIR_R = crate::R<bool, bool>; #[doc = "Reader of field `SATURATE_I...
use std::fmt::Debug; use anyhow::Result; use bevy::{ecs::{component::Component, entity::{Entity, EntityMap}, world::World}, reflect::{Reflect, TypeUuid, Uuid}}; use serde::{Deserialize, Serialize}; use super::BoxedPrefabOverrides; /////////////////////////////////////////////////////////////////////////////// pub t...
fn main() { println!("Hello, world!"); let arr = [1, 2]; another_stuff(&arr); } fn another_stuff (arr: &[i32]) { let index = 2; println!("Exi {}", arr[index]); }
use super::xor_cipher::{SingleCharXorCipher, BlockCipher}; use std::convert::From; use std::string::String; #[test] fn test_xor_cipher() { let plaintext = Vec::from("Super duper secret text"); let key = 'x' as u8; let cipher = SingleCharXorCipher::new(key); let ciphertext = cipher.proc...
use crate::quorum::{AckIndexer, Index}; use crate::{default_logger, HashSet, JointConfig, MajorityConfig}; use datadriven::{run_test, TestData}; fn test_quorum(data: &TestData) -> String { // Two majority configs. The first one is always used (though it may // be empty) and the second one is used iff joint is ...
// use std::path; // use std::fs; use std::io; // use std::process::Command; fn main() -> io::Result<()> { // clear_dir("./pkg")?; // TODO for whatever reasons this does never finish. We'll have to investigate why // Compare: // - https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_wasm ...
mod cell; pub use cell::*; mod color; pub use color::*; mod event; pub use event::*; mod terminal; pub use terminal::*; mod canvas; pub use canvas::*; pub mod geom; use std::io; use std::io::Write; use std::sync::mpsc::{Receiver, TryRecvError}; pub struct TerminalCanvas { term: Terminal, front_buffer: Canvas, back...
use super::super::organism::{ room_modeless, room_modeless_chat::ChatUser, tab_modeless_container::TabModelessList, table_menu::TableMenu, }; use super::{Room, ShowingModal}; use crate::arena::{block, user, Arena, ArenaMut, BlockMut}; use crate::table::Table; use kagura::prelude::*; use std::cell::RefCell; use ...
/// This module contains structures to handle state and index ranges. /// It is used for the extraction of Dyck words from finite state automata. /// A range of integer states. /// This structure is primarily used for two purposes: /// * to represent a range of states of a finite state automaton (similar to /// Bar-...
use std::num::NonZeroI16; /// A non-zero 16-bit error code. /// /// This is the old counterpart to [`OSStatus`](super::OSStatus). /// /// # Usage /// /// In FFI code, this type is meant to be used as [`Option<OSErr>`](Option). /// [`None`] becomes 0 (no error) because this type is /// [`#[repr(transparent)]`]((https:/...
use crate::common::*; test! { name: env, justfile: " foo: echo foo bar: echo bar ", args: ("--choose"), env: { "JUST_CHOOSER": "head -n1", }, stdout: "bar\n", stderr: "echo bar\n", } test! { name: chooser, justfile: " foo: echo foo bar: echo bar ", ...
// hello mod use std::io; pub fn hello() { println!("Hello World!"); let mut guest = String::new(); io::stdin() .read_line(&mut guest) .expect("Failed to read line"); println!("Hello, {}", guest); }
//! Tests that a crate can still build with all warnings enabled. //! //! The code generated by the `cortex-m-rt` macros might need to manually //! `#[allow]` some of them (even though Rust does that by default for a few //! warnings too). #![no_std] #![no_main] #![deny(warnings, missing_docs, rust_2018_idioms)] exte...
use std::str::FromStr; use serde::{Deserialize, Serialize}; // #[derive(Deserialize, Serialize)] // struct SlackIncomingWebhookPayload { // text: String // } // pub async fn post_webhook(url: impl Into<String>, text: impl Into<String>) -> surf::Result<String> { // let body = SlackIncomingWebhookPayload { // ...
use std::fs; fn main() { let data = fs::read_to_string("bootstrap-sm4-cdn-min.js").unwrap(); let mut customized_prefix_data = fs::read_to_string("customized-cdn_prefix.js").unwrap(); let mut customized_data = fs::read_to_string("customized-cdn.js").unwrap(); // remove last ; match customized_prefix_...
fn read_line() -> String { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().to_owned() } fn main() { let stdin = read_line(); let mut iter = stdin.split_whitespace(); let n: u32 = iter.next().unwrap().parse().unwrap(); let w: u32 = iter.next().un...
use bonsaidb_core::{ document::Document, schema::{ view, Collection, CollectionName, InvalidNameError, MapResult, MappedValue, Name, Schematic, View, }, Error, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Shape { pub sides: u32, } impl...
use thiserror::Error; #[derive(Error, Debug, Clone)] pub enum BaguaNetError { #[error("io error")] IOError(String), #[error("tcp error")] TCPError(String), #[error("inner error")] InnerError(String), } #[derive(Debug)] pub struct NCCLNetProperties { pub name: String, pub pci_path: Stri...
extern crate num; use num::integer::gcd; use std::cmp::Ordering; use std::collections; // const INPUT: &str = ".#....#####...#.. // ##...##.#####..## // ##...#...#.#####. // ..#.....#...###.. // ..#.#.....#....##"; // Example // const INPUT: &str = ".#..##.###...####### // ##.############..##. // .#.######.########.# ...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, ...
use super::{AsyncActionHandler, JsonResponse, Request, ResponseHandler, ResponseHeaders, StatusCode, Transport}; use {Error, url}; pub struct JsonResponseBuilder { inner: JsonResponse, } impl JsonResponseBuilder { pub fn new(status_code: StatusCode) -> Self { JsonResponseBuilder { inner: ...
use std::collections::HashMap; #[derive(Debug)] struct MemAction { address: u64, data: u64, } impl From<&str> for MemAction { fn from(input: &str) -> Self { let mut halves = input.split(']'); let before = halves.next().expect("first half").trim(); let after = halves.next().expect("...
#![feature(btree_range)] #![feature(alloc)] #![feature(collections)] #![feature(stmt_expr_attributes)] #![feature(lang_items)] #![feature(const_fn)] #![feature(asm)] #![feature(unwind_attributes)] #![cfg_attr(feature = "freestanding", feature(shared))] #![cfg_attr(feature = "freestanding", feature(unique))] #![cfg_attr...
//! Advanced Vector Extensions 2 (AVX2) use mem::transmute; use simd::*; /// Blend packed 8-bit integers from `a` and `b` using `mask`. #[inline] #[target_feature(enable = "avx2")] pub unsafe fn _mm256_blendv_epi8( a: i8x32, b: i8x32, mask: i8x32, // FIXME: should be m8x32 ) -> i8x32 { transmute(::arc...
// resource - http://silverwingedseraph.net/programming/2016/07/06/rust-using-enums-and-match-expressionsstatements.html enum MachineState { Normal, Comment, Upper, Lower, } fn machine_cycle(state: &MachineState, character: char) -> (Option<char>, MachineState) { use std::ascii::AsciiExt; mat...
#[cfg(target_arch = "x86")] use ::core::arch::x86::*; #[cfg(target_arch = "x86_64")] use ::core::arch::x86_64::*; #[target_feature(enable = "sse2")] pub(crate) unsafe fn quote_mask() -> __m128i { _mm_set1_epi8(b'"' as i8) } #[target_feature(enable = "sse2")] pub(crate) unsafe fn slash_mask() -> __m128i { _mm_...
//! A basic API client for interacting with the Kubernetes API //! //! The [`Client`] uses standard kube error handling. //! //! This client can be used on its own or in conjuction with the [`Api`][crate::api::Api] //! type for more structured interaction with the kubernetes API. //! //! The [`Client`] can also be used...
use syn::{ parse::{self,Parse,ParseBuffer,ParseStream,Peek}, punctuated::Punctuated, }; pub struct ParsePunctuated<T,P>{ pub list:Punctuated<T,P>, } impl<T,P> parse::Parse for ParsePunctuated<T,P> where T:parse::Parse, P:parse::Parse, { fn parse(input: ParseStream) -> parse::Result<Self>{ ...
/* chapter 4 primitive types numeric types */ fn main() { let a = 42; // x has type i32 println!("{}", a); let b = 1.0; // y has type f64 println!("{}", b); } // output should be: /* 42 1 */
#[macro_use] extern crate diesel; extern crate dotenv; use diesel::prelude::*; use dotenv::dotenv; use std::env; use self::models::{Transaction,SavedTransaction}; pub mod models; pub mod schema; pub fn establish_connection() -> PgConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expec...
#[doc = "Reader of register SPINLOCK3"] pub type R = crate::R<u32, super::SPINLOCK3>; impl R {}
use crate::{headers, AddAsHeader}; use http::request::Builder; #[derive(Debug, Clone, Copy)] pub struct Continuation<'a>(&'a str); impl<'a> Continuation<'a> { pub fn new(c: &'a str) -> Self { Self(c) } } impl AddAsHeader for Continuation<'_> { fn add_as_header(&self, builder: Builder) -> Builder ...
#[test] fn type_def() -> Result<(), winmd::Error> { let reader = winmd::Reader::from_os()?; let t: winmd::TypeDef = reader.find("Windows.Foundation.IStringable").unwrap(); let flags = t.flags()?; assert!(flags.windows_runtime()); assert!(flags.interface()); assert!(t.name()? == "IStringable");...
//! Convenience traits for dealing with OSU binary data. use std::io::{Read, Write}; use byteorder::{ReadBytesExt, WriteBytesExt}; /// Result for Error pub type Result<T, E = Error> = std::result::Result<T, E>; /// Errors that could arise from reading binary beatmap data #[derive(Debug, Error)] pub enum Error { ...
pub mod frequency; pub mod hex; pub mod byte_array { pub fn xor(a: &[u8], b: &[u8]) -> Vec<u8> { a.iter().zip(b.iter()).map(|(x, y)| x ^ y).collect() } #[cfg(test)] mod tests { use super::*; use hex; #[test] fn xor_two_equal_length_byte_arrays() { l...
#[derive(Debug)] // 三角形 pub struct Triangle{ bottom: f32, height: f32, } // 长方形 pub struct Rectangle{ width: f32, height: f32, } // 圆形 pub struct Round{ radius: f32, } // 实现一个trait接口 pub trait Area { // 实现一个计算面积的方法 fn getarea(&self) -> f32; } impl Area for Triangle { fn getarea(&s...
use crate::errors::*; use perseus::{HttpRequest, Request}; /// Converts an Actix Web request into an `http::request`. pub fn convert_req(raw: &actix_web::HttpRequest) -> Result<Request, Error> { let mut builder = HttpRequest::builder(); // Add headers one by one for (name, val) in raw.headers() { /...
use std::fmt::Write; use crate::{ custom_client::OsuTrackerModsEntry, embeds::{Author, Footer}, util::numbers::with_comma_int, }; pub struct OsuTrackerModsEmbed { author: Author, description: String, footer: Footer, } impl OsuTrackerModsEmbed { pub fn new(entries: &[OsuTrackerModsEntry], ...
//! Basic BSP accelerometer functions and how they are used are given below. //! //! Requires `cargo install probe-run` //! `cargo run --example accelerometer_usage_i --release` #![no_std] #![no_main] use panic_break as _; use stm32f4xx_hal as hal; use hal::{prelude::*, spi, stm32}; use lis3dsh::{accelerometer::RawA...
#[doc = "Reader of register RPR"] pub type R = crate::R<u32, super::RPR>; #[doc = "Reader of field `PRIORITY`"] pub type PRIORITY_R = crate::R<u8, u8>; impl R { #[doc = "Bits 3:7 - current running priority on the virtual CPU interface"] #[inline(always)] pub fn priority(&self) -> PRIORITY_R { PRIORI...
use crate::output::{ErrorKind, FailureKind, SkipKind, TestCase, TestCaseResult}; use regex::Regex; lazy_static::lazy_static! { static ref TEST_CASE_RE: Regex = Regex::new(r"_* ?[A-Za-z\._]*? \[\w+\] ? _*").expect("Valid regex"); } pub fn process_stdout(content: &str) -> impl Iterator<Item = TestCase> { let fa...
pub mod ref_with_flag { use std::marker::PhantomData; use std::mem::align_of; /// A `&T` and a `bool`, wrapped up in a single word. /// The type `T` must require at least two-byte alignment. pub struct RefWithFlag<'a, T: 'a> { ptr_and_bit: usize, behaves_like: PhantomData<&'a T> // ...
use crate::sqlite::transaction::sqlite_tx::{ version_revision_resolver::VersionRevisionResolverImpl, SqliteTx, }; use apllodb_immutable_schema_engine_domain::{ entity::Entity, row::pk::apparent_pk::ApparentPrimaryKey, version::{active_version::ActiveVersion, id::VersionId, repository::VersionRepository}...
#[cfg(test)] mod tests { use rstate::*; use std::hash::Hash; #[test] fn light_machine() { #[derive(Copy, Clone, Debug)] enum Action { Timer, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum State { Green, Yellow, ...
use std::ops::Add; use std::ops::Sub; // A simple abstraction over a coordinate. Probably redundant. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)] pub struct Point { pub x: i8, pub y: i8, } impl Point { #[inline] pub fn new(x: i8, y: i8) -> Self { Point { x...
use crate::{SBin, StackBin}; const MAX_LEN: usize = StackBin::max_len(); /// Unfortunately `SmallVec` does not implement the size for 23. pub struct StackBinBuilder { vec_excess_capacity: usize, inner: Inner, } enum Inner { Vec(Vec<u8>), Stack { len: usize, array: [u8; MAX_LEN] }, } impl StackBinBui...
macro_rules! c_abort { ($($fmt:expr),*) => {{ let _ = writeln!(&mut ::std::io::stderr(), $($fmt),*); let _ = ::std::io::stderr().flush(); #[allow(unused_unsafe)] unsafe { ::libc::abort(); } }} } macro_rules! c_assert { ($cond:expr) => { if !$cond { c_ab...
pub mod ui_layout; pub mod ui_library; pub mod ui_interaction;
//! Sealed traits use arch::__m64; use mem::transmute; use simd::*; macro_rules! impl_all { ($macro:ident: $($id:ident),*) => { $( $macro!($id); )* } } /// Any 64-bit wide vector type pub trait Any64 { fn as_m64(self) -> __m64; fn from_m64(x: __m64) -> Self; } macro_rules...
use crate::arch::x64::*; pub(super) const PICM_COMMAND: u16 = 0x20; const PICM_DATA: u16 = 0x21; pub(super) const PICS_COMMAND: u16 = 0xa0; const PICS_DATA: u16 = 0xa1; // code to tell pic to send more interrupts pub(super) const PIC_EOI: u8 = 0x20; // from osdev wiki const ICW1_ICW4: u8 = 0x01; /* ICW4 (not) neede...
#![allow(dead_code)] extern crate actix_web; extern crate chrono; extern crate fern; extern crate log; extern crate serde_json; extern crate ikrelln; use std as TheStd; use actix_web::test::TestServer; use ikrelln::api::http_application; pub const DELAY_SPAN_SAVED_MILLISECONDS: u64 = 200; pub const DELAY_RESULT_S...
//! The RFC 959 Rename To (`RNTO`) command use crate::server::ControlChanMsg; use crate::storage::{Metadata, StorageBackend}; use crate::{ auth::UserDetail, server::controlchan::{ error::ControlChanError, handler::{CommandContext, CommandHandler}, Reply, ReplyCode, }, }; use async_t...
use std::mem; use std::ops::{Deref, Index}; pub use lsp_types::{Position, Url}; use lsp_types::{TextDocumentContentChangeEvent}; use crate::util::{Span, FileSpan}; #[derive(Default, Clone)] pub struct LinedString { pub s: String, pub lines: Vec<usize> } impl Index<Span> for LinedString { type Output = str; fn ind...
use crate::fardel_state::get_fardel_owner; use crate::state::{ get_bin_data, set_bin_data, PREFIX_BLOCKED, PREFIX_COMMENTS, PREFIX_DELETED_COMMENTS, PREFIX_DOWNVOTES, PREFIX_FOLLOWERS, PREFIX_FOLLOWER_COUNT, PREFIX_FOLLOWING, PREFIX_LINK, PREFIX_RATED, PREFIX_UPVOTES, PREFIX_VEC, }; use crate::user_state::{...