text
stringlengths
8
4.13M
use crate::io::BufMut; use crate::postgres::protocol::{StatementId, Write}; use byteorder::{ByteOrder, NetworkEndian}; pub enum Describe<'a> { Statement(StatementId), Portal(&'a str), } impl Write for Describe<'_> { fn write(&self, buf: &mut Vec<u8>) { buf.push(b'D'); let pos = buf.len();...
use std::io::{stdin}; fn factorial(n: i32) -> i32 { if n <= 1 { return 1; } else { return n * factorial(n - 1); } } fn main() { println!("Enter a number for factorial:"); let mut input = String::new(); stdin().read_line(&mut input) .ok() .expect("Couldn't read...
use druid::{AppLauncher, WindowDesc}; use std::error::Error; mod controller; mod state; mod ui; mod widgets; fn main() -> Result<(), Box<dyn Error>> { let window = WindowDesc::new(ui::tracker) .title("Zeitig") .window_size((300.0, 400.0)); use state::backend::Backend; let mut backend = st...
/* * @lc app=leetcode.cn id=257 lang=rust * * [257] 二叉树的所有路径 * * https://leetcode-cn.com/problems/binary-tree-paths/description/ * * algorithms * Easy (60.96%) * Likes: 193 * Dislikes: 0 * Total Accepted: 22.8K * Total Submissions: 36.9K * Testcase Example: '[1,2,3,null,5]' * * 给定一个二叉树,返回所有从根节点到叶子...
use crate::{ error::CreationError, export::Export, import::IsExport, memory::dynamic::DYNAMIC_GUARD_SIZE, memory::static_::{SAFE_STATIC_GUARD_SIZE, SAFE_STATIC_HEAP_SIZE}, types::{MemoryDescriptor, ValueType}, units::Pages, vm, }; use std::{cell::RefCell, fmt, mem, ptr, rc::Rc, slice}; ...
// 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. use crate::view::{ViewAssistantPtr, ViewController, ViewKey}; use failure::{bail, Error, ResultExt}; use fidl::endpoints::{RequestStream, ServiceMarker}; u...
#![no_std] #![no_main] use wio_terminal_probe_run; use wio_terminal as wio; use wio::entry; #[entry] fn main() -> ! { defmt::info!("Hello, world!"); wio_terminal_probe_run::exit() }
//! Types to combine multiple sensors and pools together //! //! If we have two tuples of compatible sensors and pools: //! * `s1` and `p1` //! * `s2` and `p2` //! //! Then we can combine them into a single sensor and pool as follows: //! ``` //! use fuzzcheck::sensors_and_pools::{AndSensor, AndPool, DifferentObservati...
#![feature(test)] extern crate test; #[cfg(test)] mod tests { use test::Bencher; use P34; use P37; #[bench] pub fn bench_p34_totient(b: &mut Bencher) { b.iter(|| P34::totient(123456)); } #[bench] pub fn bench_p37_totient(b: &mut Bencher) { b.iter(|| P37::totient(12345...
// Copyright 2021 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 crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkBufferMemoryBarrier { pub sType: VkStructureType, pub pNext: *const c_void, pub srcAccessMask: VkAccessFlagBits, pub dstAccessMask: VkAccessFlagBits, pub srcQueueFamilyIndex: u32, pub dstQue...
use std::{io, process::ExitStatus}; use thiserror::Error; use tokio::process::{Child, Command}; #[derive(Debug, Error)] pub(crate) enum ForkError { #[error("Failed to fork child program: {0}")] FailedToFork(io::Error), #[cfg(unix)] #[error("Failed to register SIGTERM handler: {0}")] FailedToRegiste...
use super::method::mpf; use super::stat; use super::types::*; use super::weight; pub fn correct(mut xs: &mut Ensemble, truth: &V) { let dev = stat::mean(&xs) - truth; for x in xs.iter_mut() { *x = &*x - &dev; } } pub fn shake(xs: &Ensemble) -> Ensemble { let res = mpf::MergeResampler::default(...
// This file is part of syslog2. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. No part of syslog2, including this file, may be copied, modified, propagated, or distributed except...
#[derive(Clone, Deserialize)] pub struct DebugSettings { pub print_fps: bool, pub print_deaths: bool, pub print_time: bool, }
extern crate math_solver; use std::io::{stdin, BufRead}; fn main() { let stdin = stdin(); let mut stdin = stdin.lock(); loop { let mut line = String::new(); if let Err(e) = stdin.read_line(&mut line) { println!("{:?}", e); return; } let line = line.t...
use float::Float; use int::Int; macro_rules! fp_overflow { (infinity, $fty:ty, $sign: expr) => { return { <$fty as Float>::from_parts( $sign, <$fty as Float>::exponent_max() as <$fty as Float>::Int, 0 as <$fty as Float>::Int) } } } ma...
pub fn roll_over(num : i32) -> f64 { if num > 6 { 0.0 } else if num <= 1 { 1.0 } else { (7 - num) as f64 / 6.0 } } #[test] fn test_roll_over() { assert_eq!(roll_over(0),1.0); assert_eq!(roll_over(1),1.0); assert_eq!(roll_over(4),0.5); assert_eq!(roll_over(6),1.0/...
use super::envelope::Envelope; use serde::{Deserialize, Serialize}; const TIMER_PERIOD: [u16; 16] = [ 4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068, ]; #[derive(Serialize, Deserialize)] pub struct Noise { pub enabled: bool, envelope: Envelope, length_counter_halt: bool, ...
//extern crate regex; //use self::regex::Regex; extern crate serde_json; use self::serde_json::Value; //use std::fs::{self,File}; //use std::io::Read; //use std::path::Path; use super::*; /* static PATH_TO_GRAPHS: &'static str = "./www/graphs"; static IMPORTABLE: &'static str = r"graph(?P<n>(\d+|\d+_\d+_))_(?P<s>\d+...
use crate::error::Error; use crate::WebSocketSink; use std::fmt::{self, Debug, Formatter}; pub struct WebSocketEvent<WebSocketId> { pub id: WebSocketId, pub kind: WebSocketEventKind, } #[derive(Debug)] pub struct CloseFrame { code: u32, reason: String, } pub enum WebSocketEventKind { Connected(We...
// Binary file using a serial communication protocol to the client #![allow(dead_code)] use std::io; use std::io::{BufRead, BufReader, Write}; use std::sync::mpsc::{Receiver, Sender}; use std::thread; mod gui; mod i2c; mod protocol; mod shared; use protocol::{IncomingMsg, OutgoingMsg}; use shared::{Event, SerialEve...
#[inline(always)] pub unsafe fn hlt() { asm!("hlt"); } #[inline(always)] #[allow(dead_code)] pub unsafe fn inb(port: u16) -> u8 { let data: u8; asm!("inb %dx,%al" : "={al}" (data) : "{dx}" (port)); data } #[inline(always)] #[allow(dead_code)] pub unsafe fn inw(port: u16) -> u16 { let data: u16; ...
use crate::process::Pid; use crate::{backend, io}; use bitflags::bitflags; #[cfg(target_os = "linux")] use crate::fd::BorrowedFd; #[cfg(linux_raw)] use crate::backend::process::wait::SiginfoExt; bitflags! { /// Options for modifying the behavior of wait/waitpid #[repr(transparent)] #[derive(Copy, Clone, ...
//! Code generation for `#[graphql_scalar]` macro. use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{parse_quote, spanned::Spanned}; use crate::common::{diagnostic, parse, scalar, SpanContainer}; use super::{derive::parse_derived_methods, Attr, Definition, Methods, ParseToken, TypeOrIdent}; /// [`di...
pub trait YakuAttributes { fn name(&self) -> String; } pub mod situation { use crate::yaku::YakuAttributes; use crate::score::Han; /// 状況役 #[derive(Debug)] pub struct SituationYaku { /// 名前 name: String, /// 飜数 han_value: Han, } impl SituationYaku { ...
// 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 ...
enum SpreadsheetCell { Int(i32), Float(f32), Text(String), } fn main() { let vec: Vec<i32> = Vec::new(); let used_vec = vec![1, 2, 3]; let mut push_vec = Vec::new(); // It return error. if you not push some element. push_vec.push(1); { let vec_scope = vec![1, 2, 3]; ...
// The Look and Say sequence is an interesting sequence of numbers where each term is given by // describing the makeup of the previous term. // // The 1st term is given as 1. The 2nd term is 11 ('one one') because the first term (1) consisted // of a single 1. The 3rd term is then 21 ('two one') because the second ter...
use std::borrow::Cow; use std::cell::Cell; use std::convert::TryFrom; use std::ops::{Deref, Range}; use gccjit::{ BinaryOp, Block, ComparisonOp, Function, LValue, RValue, ToRValue, Type, UnaryOp, }; use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::common::{AtomicOrdering, Ato...
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; fn...
#![feature(async_await)] use lambda::lambda; type Err = Box<dyn std::error::Error + Send + Sync + 'static>; #[lambda] #[runtime::main] async fn main(event: String) -> Result<String, Err> { Ok(event) }
use super::{dynamic_cost::DynamicCostSolver, Item, Problem, Solution, SolverTrait}; #[derive(Debug, Clone)] pub struct FTPASSolver { pub gcd: u32, } impl SolverTrait for FTPASSolver { fn construction(&self, problem: &Problem) -> Solution { let transformed_items = problem .items ...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IProviderSpiConnectionSettings(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IProviderSpiConnectionSettings { ...
use crate::lib::{default_sub_command, file_to_lines, parse_lines, Command}; use anyhow::Error; use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}; use nom::{ branch::alt, bytes::complete::take, character::complete, combinator::{map, map_parser, map_res}, multi::fold_many1, sequence::t...
#![cfg(test)] use crate::headers::{Header, HeaderMapExt, HeaderValue}; pub fn encode<'a, H: Header>(header: H) -> HeaderValue { let mut map = hyper::http::HeaderMap::new(); map.typed_insert(header); map.get(H::name()).unwrap().clone() }
// Copyright 2020, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
use crate::cmp::clamp; use super::flag::Flag; use super::numeric::Inv; static VARINACE_FACTOR: f64 = 2.0; #[derive(Debug)] pub struct Hypothesis { pub inv_depth: Inv, pub variance: f64, valid_min: Inv, valid_max: Inv, } fn range(inv_depth: Inv, variance: f64) -> (f64, f64) { let min = f64::from(i...
use micro_lambda::lambda; fn main() { lambda(handler); } fn handler(event: &str) -> std::result::Result<String, String> { println!("{}", event); if event.contains("fail") { return Err("ERROR".to_string()); } Ok("SUCCESS".to_string()) }
use std::cmp::{max, min}; use std::collections::{HashMap, VecDeque}; use std::iter::FromIterator; use adaptive_radix_tree::u64_art_map::U64ArtMap; use crate::algos::book::*; /// Price-time priority (or FIFO) matching engine implemented using an Adaptive Radix Tree for /// indexing. /// /// Implemented as a state-mac...
use amethyst::{ core::math::Vector2, ecs::prelude::{Component, VecStorage, DenseVecStorage} }; use ncollide2d as nc; pub struct HP { pub value: u32 } impl Component for HP { type Storage = DenseVecStorage<Self>; } pub struct Power { pub value: u32, } impl Component for Power { type Storage =...
// Translated from C++ to Rust. The original C++ code can be found at // https://github.com/jk-jeon/dragonbox and carries the following license: // // Copyright 2020-2021 Junekey Jeon // // The contents of this file may be used under the terms of // the Apache License v2.0 with LLVM Exceptions. // // (See accompanyi...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qeasingcurve.h // dst-file: /src/core/qeasingcurve.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin ...
use std::result; use std::io::Error as IoError; use std::fmt; macro_rules! impl_error { ($from:ty, $to:path) => { impl From<$from> for Error { fn from(e: $from) -> Self { $to(format!("{:?}", e)) } } } } pub type Result<T> = result::Result<T, Error>; #[d...
//! Module for API context management. //! //! This module defines traits and structs that can be used to manage //! contextual data related to a request, as it is passed through a series of //! hyper services. //! //! See the `context_tests` module below for examples of how to use. use crate::XSpanId; use crate::aut...
use proptest::prop_assert_eq; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::binary_to_atom_2::result; use crate::test::strategy; #[test] fn without_binary_errors_badarg() { crate::test::without_binary_with_encoding_is_not_binary(file!(), result); } #[test] fn with_binary_without_atom_encoding_e...
// 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 crate::registry::service_context::GenerateService; use crate::tests::fakes::base::Service; use failure::{format_err, Error}; use fuchsia_zircon as zx; u...
use crate::controller; use crate::editor_transport; use crate::project_root::find_project_root; use crate::thread_worker::Worker; use crate::types::*; use crate::util::*; use crossbeam_channel::{after, never, select, Sender}; use lsp_types::notification::Notification; use lsp_types::*; use std::collections::HashMap; us...
//! service for scheduling compactor tasks. #![deny( rustdoc::broken_intra_doc_links, rust_2018_idioms, missing_debug_implementations, unreachable_pub )] #![warn( missing_docs, clippy::todo, clippy::dbg_macro, clippy::explicit_iter_loop, clippy::clone_on_ref_ptr, // See https://...
#![allow(unused_imports, unused_variables, dead_code)] extern crate futures; #[macro_use] extern crate futures_io; extern crate futures_mio; extern crate trust_dns; mod dns_query; use dns_query::Message; use futures::{Future, Poll, oneshot, Oneshot, Complete}; use futures::stream::Stream; use futures_mio::{Loop, U...
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
// 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. use hyper_rustls; use rustls; use { fuchsia_async::{ net::{TcpConnector, TcpStream}, EHandle, }, futures::{ compat::Co...
use super::ai::AI; use super::grid::Grid; use super::{Coordinates, Direction, InputEvent, Player, Side}; use crossterm::event::{read, Event}; use crossterm::style::{Color, Print, ResetColor, SetBackgroundColor, SetForegroundColor}; use crossterm::{cursor, event, execute}; use std::collections::HashMap; use std::io; us...
use std::collections::HashMap; use std::io::Error; use std::net::Ipv4Addr; use std::net::Ipv6Addr; use std::net::SocketAddr; use std::net::UdpSocket; use std::sync::RwLock; use std::time::Duration; use std::time::Instant; use colored::*; use crossbeam; use crossbeam::channel; use super::config; use super::utils; use ...
#![allow(non_camel_case_types)] use super::access_flags::*; use super::attribute::*; use super::constant_pool::*; use super::field::FieldInfo; use super::instruction::{Instruction, InstructionKind}; use super::method::MethodInfo; use std::fs::File; use std::io::{BufReader, Read}; type u1 = u8; type u2 = u16; type u4 ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use types::U256; pub const BLOCK_TIME_SEC: u32 = 20; pub const BLOCK_WINDOW: u32 = 24; use logger::prelude::*; use traits::ChainReader; pub fn difficult_1_target() -> U256 { U256::max_value() } pub fn current_hash_rate(targe...
//! The module keeping track of the possible game errors. use std::error::Error; use std::fmt; /// All possible error states the game can end up in. #[derive(Debug)] pub(crate) enum GameError { Unknown, } impl Error for GameError { fn source(&self) -> Option<&(dyn Error + 'static)> { use GameError::*...
use super::{NSObject, Object, BOOL, SEL}; use std::{ cmp, ffi::CStr, fmt, hash, ops::Deref, os::raw::{c_char, c_int}, panic::RefUnwindSafe, ptr, }; /// An Objective-C class. /// /// See [documentation](https://developer.apple.com/documentation/objectivec/class). /// /// # Usage /// /// This...
pub struct Solution; impl Solution { pub fn is_additive_number(num: String) -> bool { for i in 1.. { if i + 1 + i > num.len() { break; } for j in 1.. { if i + j + i.max(j) > num.len() { break; } ...
//! libc specifics //! //! These are all re-exports from the [libc crate] and are intended for local //! use w/ APIs that uses a C-like ABI, like [ALSA][crate::alsa]. //! //! [libc crate]: https://crates.io/crates/libc #[doc(inherit)] pub use ::libc::eventfd; #[doc(inherit)] pub use ::libc::free; #[doc(inherit)] pub u...
pub mod crypto; pub mod error; pub mod keystore; pub mod networks; pub mod pkcs8; pub mod store; pub mod wallet;
use smartcore::dataset::breast_cancer; use smartcore::dataset::diabetes; use smartcore::dataset::iris; use std::fs::File; use std::io::prelude::*; // DenseMatrix wrapper around Vec use smartcore::linalg::naive::dense_matrix::DenseMatrix; // Imports for KNN classifier use smartcore::math::distance::*; use smartcore::nei...
use wasm_bindgen::prelude::*; use wasm_bindgen_futures::JsFuture; use js_sys::Promise; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] struct Data<T>{ value: T, } type StrData = Data<String>; #[wasm_bindgen] extern { #[wasm_bindgen(js_namespace = console)] fn log(s: String...
use crate::*; use reqwest::header::HeaderValue; use reqwest::{header, Client, Url}; use std::io::prelude::*; /// Returns the body of the response from a get request to onfido on the endpoint indicated. /// Returns a Box<Error> if it fails to resolve the url, if the request fails to be sent or if its body can't be read...
use std::{mem, ptr, slice, u64, cmp}; #[derive(Debug, Clone, Copy, PartialEq)] pub enum Error { Corrupted, Truncated, } type Result<T> = std::result::Result<T, Error>; fn decode_varint_u32_slow(data: &[u8]) -> Result<(u32, u8)> { let mut res = 0; for i in 0..data.len() { let b = data[i]; ...
use nalgebra::Vector3; use crate::{LumpData, LumpType, PrimitiveRead}; use std::io::{Read, Result as IOResult}; pub struct TextureData { pub reflectivity: Vector3<f32>, pub name_string_table_id: i32, pub width: i32, pub height: i32, pub view_width: i32, pub view_height: i32 } impl LumpData for TextureData...
pub(crate) mod core; pub(crate) mod external; #[cfg(feature = "std")] pub(crate) mod std; pub(crate) mod ty_impls;
// auto generated, do not modify. // created: Wed Jan 20 00:44:03 2016 // src-file: /QtNetwork/qnetworkconfigmanager.h // dst-file: /src/network/qnetworkconfigmanager.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block e...
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_analyze_document( input: &crate::input::AnalyzeDocumentInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonO...
use std::net::TcpStream; use std::io::*; use std::time::Duration; use rustcat::lib; fn connect(host: &String, port: &String) -> TcpStream { let conn_string = format!("{}:{}", host, port); let stream = TcpStream::connect(&conn_string) .expect("Could not connect to address."); println!("Connected to...
use crate::integer::Integer; use core::ops::Sub; // Sub The subtraction operator -. // ['Integer', 'Integer', 'Integer', 'Integer::subtract_assign', 'lhs', // ['ref_mut'], ['ref']] impl Sub<Integer> for Integer { type Output = Integer; fn sub(mut self, rhs: Integer) -> Self::Output { Integer...
mod draw; use libary::polygon_generator; use libary::ghs; use libary::melkmanns; use libary::util::{Point}; fn main() { let polys1 = polygon_generator::gen_polygon(8); draw::draw_aw_stepbystep( &polys1, &[-1, -1]); } fn _draw_ghs_test (){ let a = Point{x:-1.0 ,y: 0.0}; le...
use std::fs::read_to_string; use std::cmp::min; use std::collections::VecDeque; fn read_param(prog: &Vec<i32>, base: i32, pos: usize, i: usize) -> i32 { match prog[pos] / 10_i32.pow(i as u32 + 1) % 10 { 0 => prog[prog[pos + i] as usize], 1 => prog[pos + i], 2 => prog[(base + prog[pos + i]) as usize], ...
use std::ops::{Mul, Add}; fn magic<T: Mul + Add + Copy>(par1: T, par2: T) -> (<T as Mul>::Output, <T as Add>::Output) { (par1 * par2, par1 + par2) } fn main() { println!("{:?}", magic(3, 4)); }
//! Cheesy way to easily wrap text in console colors. //! Example: //! ``` //! use phd::color; //! println!("{}Error: {}{}", color::Red, "Something broke.", color::Reset); //! ``` use std::{ fmt, sync::atomic::{AtomicBool, Ordering as AtomicOrdering}, }; /// Whether to show colors or not. /// Defaults to true...
use nannou::prelude::*; fn main() { nannou::app(model).update(update).simple_window(view).run(); } struct Model {} fn model(_app: &App) -> Model { Model {} } fn update(_app: &App, _model: &mut Model, _update: Update) {} fn view(_app: &App, _model: &Model, frame: Frame) { frame.clear(PURPLE); }
// 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 carnelian::{ set_node_color, App, AppAssistant, Color, Label, Paint, ViewAssistant, ViewAssistantContext, ViewAssistantPtr, ViewKey, }; use fail...
use actix_web::{get, post, web, Error, HttpResponse}; use deadpool_postgres::Pool; use juniper::http::graphiql::graphiql_source; use juniper::http::GraphQLRequest; use std::sync::Arc; use crate::graphql::{Context, Schema}; #[get("/graphql")] pub async fn get_graphql() -> HttpResponse { // Note! if you change this ...
#![warn(unused_imports)] use core::fmt; use core::mem::zeroed; use riscv::register::sstatus::{self, Sstatus, SPP::*}; // 中断处理过程中需要保存的上下文(Context)向量 // 在处理中断之前,必须要保存所有可能被修改的寄存器,并且在处理完成后恢复。 // 保存所有通用寄存器,sepc、scause 和 stval 这三个会被硬件自动写入的 CSR 寄存器,以及 sstatus (因为中断可能会涉及到权限的切换,以及中断的开关,这些都会修改 sstatus。) // scause 以及 stv...
use std::borrow::{Borrow, Cow}; use std::collections::HashMap; use futures::future::Future; use log::{debug, info}; use rusoto_core::credential::AwsCredentials; use rusoto_core::param::{Params, ServiceParams}; use rusoto_core::signature::{SignedRequest, SignedRequestPayload}; use rusoto_core::Region; use rusoto_core::...
#![feature(test)] extern crate test; use test::Bencher; macro_rules! bench { ($name:ident) => { #[bench] #[allow(non_snake_case)] fn $name(b: &mut Bencher) { let src = include_str!(concat!( "../tests/data/", stringify!($name), "....
use rust_client::models; #[allow(unused_imports)] use serde_json::Value; use std::collections::HashMap; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Metadata { #[serde(rename = "operation", skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(rename = "c...
use crate::prelude::*; use super::super::c_char_to_vkstring; use std::os::raw::c_char; #[repr(C)] #[derive(Debug)] pub struct VkDisplayPropertiesKHR { pub display: VkDisplayKHR, pub displayName: *const c_char, pub physicalDimensions: VkExtent2D, pub physicalResolution: VkExtent2D, pub supportedTr...
use std::ffi::CString; use std::io; use std::os; use std::os::raw::{c_char, c_int}; use firefly_util::fs; extern "C" { #[cfg(windows)] pub fn LLVMFireflyLink( argc: c_int, argv: *const *const c_char, stdout: os::windows::io::RawHandle, stderr: os::windows::io::RawHandle, ) ...
/*! An application that load different interfaces using the partial feature. All partials are represented as the same generic struct. Requires the following features: `cargo run --example partials_generic_d --features "listbox frame combobox"` */ extern crate native_windows_gui as nwg; extern crate native...
fn func() -> i32 { // if as a expression and as implicit return statement if true { if false { 1 } else { 2 } } else { 3 } } fn main() { // let a: i32 = 0; let a: i32 = 1; // let a: i32 = 3; // let a: i32 = 4; if a == 0 { ...
// Copyright Jeron A. Lau 2017 - 2018. // Dual-licensed under either the MIT License or the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) //! Render graphics to a computer or phone screen, and get input. Great for //! both video ga...
//! Contains `Scanner`, an on-demand producer of tokens. use crate::runtime::Line; use crate::{ErrorKind, PiccoloError, Token, TokenKind}; use std::collections::VecDeque; /// Converts a piccolo source into a stream of [`Token`]. /// /// Operates in a scan-on-demand fashion. A consumer of tokens calls the [`next_toke...
use diesel::Connection as ConnectionTrait; use diesel::sqlite::SqliteConnection; use dotenv::dotenv; use rocket::http::Status; use rocket::request::{Request, FromRequest, Outcome}; use rocket::outcome::Outcome::*; use r2d2::{Pool, PooledConnection as R2PooledConnection, GetTimeout, Config}; use r2d2_diesel::ConnectionM...
use std::env; use mio::net::{TcpListener, TcpStream}; fn main() { let args: Vec<String> = env::args().collect(); match args[1].as_str() { "server" => { let addr = args[2].parse().unwrap(); println!("listen on {}", addr); let _listener = TcpListener::bind(&addr).unwr...
use svg::node::element::path::{Command, Data}; use svg::node::element::tag::Path; use svg::parser::Event; pub fn parse_path(path_to_svg_file: &str) -> Vec<Point2> { let mut content = String::new(); let mut points = vec![]; let path = vec![]; let mut current_point = pt2(0.0, 0.0); for event in sv...
use rocket::Request; #[catch(404)] pub fn view(req: &Request) -> String { format!("Sorry, '{}' is not a valid path.", req.uri()) }
use super::component_prelude::*; pub struct Player { pub settings: PlayerSettings, pub acceleration: Vector, pub max_velocity: (Option<f32>, Option<f32>), pub jump_data: Option<PlayerJumpSettings>, pub used_dash: bool, } impl Player { pub fn set_normal_speed(&mut self) { self...
#[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::IRQENABLE { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R...
pub mod create_sorted_array_through_instructions; pub mod find_the_most_competitive_subsequence; pub mod rotate_image;
use std::io::{Cursor, Write}; use byteorder::{NetworkEndian, WriteBytesExt}; use super::Packet; impl Packet { pub fn encode(&self) -> Vec<u8> { assert!(self.server_name.as_deref().map(|x| x.len()).unwrap_or(0) < 64); assert!(self.boot_file_name.as_deref().map(|x| x.len()).unwrap_or(0) < 128); ...
extern crate aoc; use std::cmp; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufReader}; use std::str::FromStr; #[derive(Debug, Hash, Eq, PartialEq)] struct Point { x: u16, y: u16, } impl FromStr for Point { type Err = io::Error; fn from_s...
//! # merkle_tree_rust //! `merkle_tree_rust` contains methods to generate string list and the //! merkle tree upon the list use sha2::{Sha256, Digest}; use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; use anyhow::Result; // Redundant, but more readable use anyhow::*; use rayon::prelude::*; /// Par...
// 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 { crate::utils, fuchsia_zircon::sys as zx, wlan_mlme::{ buffer::{BufferProvider, InBuf, OutBuf}, client, common::{f...
use std::hash::Hasher; /// A hasher optimized for hashing component type IDs. #[derive(Default)] pub struct ComponentTypeIdHasher(u64); impl Hasher for ComponentTypeIdHasher { #[inline] fn finish(&self) -> u64 { self.0 } #[inline] fn write_u64(&mut self, seed: u64) { // This must ...