text
stringlengths
8
4.13M
extern crate piston_window; extern crate find_folder; use self::piston_window::*; fn main(){ const WIDTH: u32 = 600; const HEIGHT: u32 = 420; // Construct the window. let mut window: PistonWindow = WindowSettings::new("All Widgets - Piston Backend", [WIDTH, HEIGHT]) .opengl(OpenGL...
use acid_list::{AcidList, LinkIndex}; use std::io; fn main() -> io::Result<()> { let mut args = std::env::args(); args.next(); // skip program name let path = args.next().ok_or(io::ErrorKind::InvalidInput)?; let from_idx = args .next() .ok_or(io::ErrorKind::InvalidInput)? .par...
fn main() { let start = 353_096; let end = 843_212; println!("{}", (start..=end).filter(|&i| validate(i)).count()) } fn validate(i: i32) -> bool { let mut head = i / 10; let mut tail = i % 10; let mut pair = false; let mut combo = 1; loop { let prev = head % 10; if ta...
use actix::prelude::*; use actix_web_actors::ws; use serde::Deserialize; use kosem_webapi::protocols::{JrpcError, JrpcMessage, JrpcResponse}; use crate::internal_messages::connection::{AddHumanActor, RpcMessage, SetRole}; use crate::role_actors; pub struct WsJrpc { pub state: role_actors::ActorRoleState, } impl...
//! Wrapper module for all the Zoho models. //! Each model (e.g. Tasks) is represented in its own module to maintain separation and allow //! namespacing of similar methods and types, since each model requires (e.g.) a slightly different //! implementation of Filter. pub mod activity; pub mod bug; pub mod category; pu...
use bincode::SizeLimit; use bincode::serde::{serialize_into, deserialize_from}; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::path::Path; use std::io; include!(concat!(env!("OUT_DIR"), "/manage_serde_types.rs")); impl CrateName { fn new(get_name: String) -> CrateName { CrateNa...
mod column_span; mod format_configuration; mod render; mod row_span; mod settings; mod styling;
use std::io::Write; use byteorder::{BE, WriteBytesExt}; use crate::error::{parse_io, TychoStatus}; use crate::Number; use crate::types::ident::NumberIdent; use crate::write::func::write_byte; pub(crate) const NUM_LEN_1: u8 = 0x00; pub(crate) const NUM_LEN_8: u8 = 0x01; pub(crate) const NUM_LEN_16: u8 = 0x02; pub(cra...
use crate::common::{encryption::NetworkedPublicKey, message_type::Peer}; use super::chat_input::ChatInput; pub struct ChatMessage { pub author: Peer, pub msg: String, pub custom_id: Option<u32>, pub received: Option<bool>, pub own: bool } pub struct UIPeer { inner: Peer, pub chat_input: C...
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 n = read_line().parse().unwrap(); let ll = read_line() .split_whitespace() .map(|v| v.parse().unwrap()) .collect(); let ...
#![no_std] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc = include_str!("../README.md")] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" )] #![warn(missing_docs, rust_2018_idioms)]...
use srt_media::{ source::{SrtSource, StreamDescriptor}, NextFrameResult, }; use stainless_ffmpeg::prelude::*; fn main() { pretty_env_logger::init(); let mut srt_source = SrtSource::new("srt://127.0.0.1:3333"); // let mut srt_source = SrtSource::new("srt://194.51.35.43:8998"); let nb_stream = srt_source.f...
mod gauss; mod simpson; extern crate ndarray; use ndarray::prelude::*; use std::f64::consts::PI; use std::io::{self, Read}; static lm: &'static [f64; 4] = &[0.0, PI / 2.0, 0.0, PI / 2.0]; type Iorfn = fn(Box<dyn Fn(f64) -> f64>, f64, f64, usize) -> f64; type Iedfn = Box<dyn Fn(f64, f64) -> f64>; fn Integrated(p: f...
use std::fmt; use std::path::PathBuf; #[derive(Debug)] pub enum Error { EmptyCategory, EmptyHash, EmptyLocationName, EmptySchema, InvalidLatitude(f32), InvalidLongitude(f32), IO(std::io::Error), NotADir(PathBuf), NotAFile(PathBuf), PathConversion, Rusqlite(rusqlite::Error), ...
use super::helpers::{ allocations, fixtures::{get_language, get_language_queries_path}, }; use std::{ ffi::{CStr, CString}, fs, ptr, slice, str, }; use tree_sitter::Point; use tree_sitter_tags::{c_lib as c, Error, TagsConfiguration, TagsContext}; const PYTHON_TAG_QUERY: &str = r#" ( (function_definit...
use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Pathway { target: String, desc: String, inspection: String, is_closed: Option<bool>, is_locked: Option<bool>, } impl Pathway { pub fn target(&self) -> &String { &self.target } pub f...
fn count_red_beads(n: u32) -> u32 { if n < 2 { 0 } else { 2*(n-1) } } #[test] fn test0() { assert_eq!(count_red_beads(0), 0); } #[test] fn test1() { assert_eq!(count_red_beads(1), 0); } #[test] fn test2() { assert_eq!(count_red_beads(2), 2); } #[test] fn test3() { assert_eq!(count_red_beads(3), 4); } #[tes...
use pnet::packet::Packet; use pnet::packet::ipv4::Ipv4Packet; use pnet::packet::ethernet::{EtherTypes, EthernetPacket}; use pnet::packet::ip::IpNextHeaderProtocol; use std::env; use std::io::{self, Write}; use std::process; use std::net::IpAddr; use std::net::Ipv4Addr; use std::collections::VecDeque; use std::collec...
#[derive(PartialEq, Debug, Clone)] pub enum Literal { String(String), Float(f64), Integer(i64), }
use crate::{palette, terminal::SIZE}; use std::{convert::TryFrom, fmt, ops}; #[derive(Clone, Debug, Copy, PartialEq)] pub struct Point { pub x: SIZE, pub y: SIZE, } impl Default for Point { fn default() -> Self { Self { x: Default::default(), y: Default::default(), ...
use actix_web::{web, middleware, App, HttpResponse, HttpServer, Responder}; use std::env; async fn index() -> impl Responder { HttpResponse::Ok().body("<html><h1>Rust sample app is running</h1></html>") } #[actix_rt::main] async fn main() -> std::io::Result<()> { let app_name = env::var("APP_NAME").unwrap_or...
use num_traits::PrimInt; pub fn ceil<T: PrimInt + Copy>(numerator: T, denominator: T) -> T { (numerator + (denominator - T::one())) / denominator } pub fn round_up<T: PrimInt + Copy>(value: T, unit: T) -> T { ceil(value, unit) * unit } pub fn round_down<T: PrimInt + Copy>(value: T, unit: T) -> T { (value...
use graphics::Context; use glutin_window::GlutinWindow; use opengl_graphics::GlGraphics; use piston::input::Button; use piston::input::keyboard::Key; use piston::window::Window; use piston::window::Size as WindowSize; use crate::hover::Hover; use crate::menu::MenuState; use crate::mission::MissionState; use crate::pre...
//! This example demonstrates the flexibility of [`papergrid`] with manual configurations //! of [`Borders`], [`CompactConfig`], and column counts with [`IterRecords`]. //! //! * For an alternative to [`CompactGrid`] and [`CompactGridDimension`] with //! flexible row height, variable intra-column spans, and multiline c...
use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; use std::io::{Error, ErrorKind}; use std::time::{Duration, Instant}; use bitvec::prelude::*; use raidpir::client::RaidPirClient; use raidpir::types::RaidPirData; use sealpir::client::PirClient; use sealpir::{PirQuery, PirReply}; use rayon::prelude::*; use crate::t...
fn walk(maze: &mut Vec<&str>) { println!("{:?}", maze); for y in maze.iter() { for x in y.chars() { print!("{}", x); if x == '@' { println!("Found!"); println!("{},{}", x, y); break } } } } #[test] fn test_...
//! Test suite for the Web and headless browsers. #![cfg(target_arch = "wasm32")] #[path = "../src/lib.rs"] mod lib; #[path = "../src/pcx.rs"] mod pcx; extern crate wasm_bindgen_test; use wasm_bindgen_test::*; use pcx::*; use std::fs::File; use std::io::BufReader; use std::io::Read; wasm_bindgen_test_configure!(run_...
pub fn print_ddd() { println!("print_ddd"); }
fn multiply(first_number_str: &str, second_number_str: &str) -> i32 { let first = first_number_str.parse::<i32>().unwrap(); let second = second_number_str.parse::<i32>().unwrap(); first * second } fn main() { let twenty = multiply("10", "2"); println!("double is {}", twenty); let tt = multiply...
use crate::ani_api::info; use cynic; #[derive(cynic::Enum, Clone, Copy, Debug)] #[cynic(schema_path = "schema.graphql", schema_module = "info")] pub enum MediaType { Anime, Manga, } #[derive(cynic::QueryFragment, Debug)] #[cynic( graphql_type = "Query", argument_struct = "ListQueryArguments", sche...
use ::std::fmt::{Binary, Debug, Formatter}; use ::std::fmt::Result as FmtResult; /// This struct represent 8 bits where the content is dependend on other information. /// Usually, this a flags depending on the dataid. #[derive(Copy, Clone, Serialize, Deserialize)] pub struct Flags8 { /// The field containing the b...
extern crate bio; extern crate debruijn; extern crate debruijn_mapping; extern crate failure; extern crate rayon; use debruijn::dna_string::{DnaString,DnaStringSlice}; use std::env; use failure::Error; use bio::io::{fasta, fastq}; use debruijn_mapping::{config, utils}; use debruijn_mapping::{build_index::build_index, ...
use super::bullet; use crate::engine::element::Element; pub struct BulletPool<'a> { bullets: Vec<&'a Element>, } impl<'a> BulletPool<'a> { pub fn new(bullets: &'a Vec<Element>) -> BulletPool<'a> { let mut bullets_ref = Vec::new(); bullets.iter().for_each(|x| bullets_ref.push(x)); Bullet...
use crate::custom_var::CustomVar; use crate::first; use crate::method::StdMethod; use crate::name::Name; use crate::operator::Operator; use crate::runtime::Runtime; use crate::std_type::Type; use crate::sys::os_do_1; use crate::variable::{FnResult, Variable}; use std::fs::{FileType, Metadata, Permissions}; use std::rc:...
#[macro_use] extern crate log; #[macro_use] extern crate lazy_static; extern crate cc; extern crate itertools; extern crate num_cpus; extern crate pkg_config; extern crate raw_cpuid; mod cargo; mod cpu; mod gcc; mod rte; pub use crate::cargo::{gen_cargo_config, OUT_DIR}; pub use crate::cpu::gen_cpu_features; pub use ...
use crate::relayer::Relayer; use ckb_logger::{debug_target, warn}; use ckb_network::{CKBProtocolContext, PeerIndex}; use ckb_types::{packed, prelude::*}; use failure::{err_msg, Error as FailureError}; use std::sync::Arc; pub struct GetBlockProposalProcess<'a> { message: packed::GetBlockProposalReader<'a>, rela...
#![no_std] extern crate alloc; mod consts; mod edonr224; mod edonr256; mod edonr384; mod edonr512; use core::cmp::Ordering; pub use edonr224::EdonR224; pub use edonr256::EdonR256; pub use edonr384::EdonR384; pub use edonr512::EdonR512; use consts::{q256, q512, P224, P256, P384, P512}; #[cfg(not(feature = "minimal"...
extern crate time; use std::io; use engine::{Input, Event, Registry}; pub struct StdIn<'a> { reader: Box<io::Buffer+'a> } impl<'a> Input for StdIn<'a> { fn next_event(&mut self) -> Event { match self.reader.read_line() { Ok(line) => { debug!("received: {}", line); let x : &[_] = &['\r', '\n']; ...
#![deny(rust_2018_idioms)] //! Load test for pathfinder JSON-RPC endpoints. //! //! This program expects a mainnet pathfinder node synced until block 1800, //! since it contains references to transactions and contract addresses on mainnet. //! //! Running the load test: //! ``` //! cargo run --release -p load-test -- ...
//! //! # `Deploy Section` //! //! +------------------+----------------+---------------+-------------+ //! | | | | | //! | Transaction Id | Layer | Deployer | Template | //! | (32 bytes) | (8 bytes) | (Address) | (Address) | /...
struct Node<T> { data: T, next: Option<Box<Node<T>>>, // The problem is that at compile time the size of next must be known. Since next is recursive ("a node has a node has a node..."), the compiler does not know how much memory is to be allocated. In contrast, Box is a heap pointer with a defined size. } pub...
mod cache_info; pub use self::cache_info::*; use std::mem::size_of; use byteorder::{ByteOrder, NativeEndian}; use failure::ResultExt; use crate::utils::{parse_string, parse_u32}; use crate::{ nla::{DefaultNla, Nla, NlaBuffer}, traits::{Emitable, Parseable}, DecodeError, }; pub const IFA_UNSPEC: u16 = 0;...
use nu_engine::CallExt; use nu_protocol::ast::Call; use nu_protocol::ast::CellPath; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Value}; use std::cmp::Ordering; use std::sync::Arc; #[derive(Clone)] pub struct SubCommand; str...
use wamp_proto::{transport::websocket::WebsocketTransport, uri::Uri, Client, ClientConfig}; use std::time::Duration; use futures::stream::StreamExt as _; use tokio::time::timeout; #[tokio::test] #[ignore] async fn integration_1() { env_logger::init(); let mut client_config = ClientConfig::new("ws://...
// Copyright (C) 2021 Subspace Labs, Inc. // SPDX-License-Identifier: GPL-3.0-or-later // 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 Software Foundation, either version 3 of the License, or // (at your option)...
use nu_protocol::ast::Call; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{Example, IntoPipelineData, PipelineData, ShellError, Signature, Value}; pub mod shadow { include!(concat!(env!("OUT_DIR"), "/shadow.rs")); } #[derive(Clone)] pub struct Version; impl Command for Version { fn...
use std::collections::hash_map::DefaultHasher; use xorf::{Filter, HashProxy, Xor8}; type Title = String; type Url = String; pub type Id = (Title, Url); pub type XorfProxy = HashProxy<String, DefaultHasher, Xor8>; pub type PostFilter = (Id, XorfProxy); pub type PostFilters = Vec<PostFilter>; pub trait Score { fn sc...
use std::fmt; use chrono::{NaiveDate, Datelike}; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct Client { pub id: u32, pub first_name: String, pub last_name: String, pub dob: NaiveDate, pub pronouns: u32, pub foreign_keys: HashMap<String, Vec<u32>>, } impl PartialEq for Client { fn eq...
use crate::elo::calc_elo; use crate::elo::GameResult; use crate::errors::ApiError; use crate::models::{ duels::Duel, games::Game, matches::Match, players::Player, teams::Team, }; use crate::schema::duels::dsl::duels as table_duels; use crate::schema::matches::dsl::matches as table_matches; use diesel::{prelude::*,...
use std::thread::sleep; use std::time::{Duration, SystemTime}; fn main(){ }
extern crate asn1_der; use ::{ std::{ collections::HashMap, u8 }, asn1_der::{ Asn1DerError, DerTag } }; macro_rules! tags { (map: $($key:expr => $value:expr),+) => ({ let mut dict = HashMap::new(); $(dict.insert($key, $value);)+ dict }); () => (tags!(map: 0x01 => DerTag::Boolean, 0x02 => DerTag::Integer...
// Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, lef...
use http::{Request, Response}; use serde_derive::{Deserialize, Serialize}; use serde_json::value::Value; use serde_urlencoded; use yew::{ events::InputData, format::{Json, Nothing}, html, services::{ fetch::{FetchOptions, FetchService, FetchTask}, storage::{Area, StorageService}, }, ...
extern crate rusqlite; use rusqlite::NO_PARAMS; use rusqlite::{named_params, Connection, Result}; #[derive(Debug)] pub struct Account { pub name: String, pub username: String, pub password: String, pub updated_at: Option<String>, } impl Account { pub fn to_string(&self) -> String { let d...
use raylib; pub mod greed_mesher { use crate::base::voxel::ChunkData; use std::ops::Deref; pub fn generate_mesh(chunk_data : ChunkData) -> raylib::models::Mesh { unsafe { std::mem::transmute(generate_chunk_mesh(chunk_data))} } unsafe fn generate_chunk_mesh(chunk_data: ChunkData) -> raylib...
#![allow(unsafe_code)] use destructure_traitobject::data; use std::any::{Any, TypeId}; use std::rc::Rc; pub struct Closure<A, B, C, D, E, F, G, H, RET> { variant: ClosureVariant<A, B, C, D, E, F, G, H, RET>, } fn too_many(a: usize, b: usize) -> String { format!( "Too many arguments provided to closur...
use { std::{ fs, io::prelude::*, path::{Path, PathBuf} }, shaderc::{ Compiler, CompileOptions, IncludeType, IncludeCallbackResult, ResolvedInclude }, convert_case::{Case, Casing}, pathdiff::diff_paths, crate::{ Result, ...
#[doc = "Register `SR` reader"] pub type R = crate::R<SR_SPEC>; #[doc = "Field `CCF` reader - Computation complete flag"] pub type CCF_R = crate::BitReader; #[doc = "Field `RDERR` reader - Read error flag"] pub type RDERR_R = crate::BitReader; #[doc = "Field `WRERR` reader - Write error flag"] pub type WRERR_R = crate:...
use std::str::Utf8Error; /// All the errors that can occur /// when serializing or deserializing /// messages within the airmash protocol. #[derive(Debug, Clone)] pub enum SerError { Utf8Error(Utf8Error), ArrayLengthTooBig, } #[derive(Debug, Clone, Copy)] pub enum DeError { Eof, Utf8Error(Utf8Error), InvalidPack...
pub fn run() { println!("\n====5.28 Vector===="); // https://doc.rust-lang.org/stable/book/ch08-01-vectors.html let mut v = vectors(); println!("{:?}", v); v.push(5); println!("v.push(5); -> {:?}", v); let third: i32 = v[2]; println!("The third element is {}", third); // does not wo...
#[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::ALTPADCFGK { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'...
use crate::Recurse; #[derive(Debug)] pub(crate) struct Config { pub(crate) subcmd: Recurse, } impl Config { pub(crate) fn new(opt: Recurse) -> Self { Self { subcmd: opt } } } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; #[test] fn test_config_instantiation_defau...
//! An `Operation` applies semantics to `Array` and `Scalar` with `Expression`, or emits //! `Raise`. use std::fmt; use il::*; /// An IL Operation updates some state. #[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] pub enum Operation { /// Assign the value given in expression to th...
pub fn mut_ref() { println!("mutable reference == ====== = == = ="); let mut my_number = 8; let num_ref = &mut my_number; *num_ref += 10; println!("{}", my_number); let second_number = 800; let triple_reference = &&&second_number; println!("{}", triple_reference); }
use super::super::super::super::{awesome, btn, modeless, text}; use super::super::super::state::{chat, dicebot, Modal, Modeless}; use super::Msg; use crate::{ block::{self, chat::item::Sender, BlockId}, model::{self}, Color, Resource, }; use kagura::prelude::*; use wasm_bindgen::JsCast; mod common { pu...
#[doc = "Register `MACVIR` reader"] pub type R = crate::R<MACVIR_SPEC>; #[doc = "Register `MACVIR` writer"] pub type W = crate::W<MACVIR_SPEC>; #[doc = "Field `VLT` reader - VLAN Tag for Transmit Packets"] pub type VLT_R = crate::FieldReader<u16>; #[doc = "Field `VLT` writer - VLAN Tag for Transmit Packets"] pub type V...
// Copyright (c) 2017 Anatoly Ikorsky // // 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 http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not be copied, // m...
#[macro_use] extern crate criterion; extern crate dinghy_test; extern crate gazetteer_entity_parser; extern crate rand; extern crate serde_json; use criterion::Criterion; use gazetteer_entity_parser::*; use rand::distributions::Alphanumeric; use rand::rngs::ThreadRng; use rand::seq::IteratorRandom; use rand::thread_rn...
#[derive(Debug,Copy,Clone)] struct Player { rank: u32, score: u32 } fn main() { let mut line = String::new(); std::io::stdin().read_line(&mut line).expect("Read line from stdin"); // let players_num: u32 = line.trim().parse().expect("Parse number"); line.clear(); std::io::stdin().read_line...
use std::io::Write; fn run() { let out = std::io::stdout(); let mut out = std::io::BufWriter::new(out.lock()); input! { t: usize, ask: [(usize, bytes); t], } for (_n, s) in ask { let a = s.iter().filter(|c| **c == b'0').count(); let b = s.iter().filter(|c| **c == b'1...
use bbqueue::BBBuffer; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use std::cmp::min; const DATA_SZ: usize = 128 * 1024 * 1024; pub fn criterion_benchmark(c: &mut Criterion) { let data = vec![0; DATA_SZ].into_boxed_slice(); c.bench_function("bbq 128/4096", |bench| bench.iter(|| ch...
use std::io::Read; use iced_wgpu::wgpu; use rayon::prelude::*; pub use texture::Texture; pub use mipmap::MipmapGenerator; pub use mesh::{Vertex, Mesh}; mod texture; mod mipmap; mod mesh; mod gltf; #[derive(Debug)] pub enum AssetError { IoError(std::io::Error), SerdeJsonError(serde_json::Error), ImageError...
use std::cell::RefCell; use std::{fs, env, io}; use std::rc::Rc; use virtual_machine::interpreter; use virtual_machine::parser; use crate::interpreter::{world, Interpreter}; use std::path::Path; #[derive(Debug)] enum Error { FsError(io::Error), ParseError(String), InterpretError(interpreter::Error), } i...
use maud::{html, Markup, Render}; use crate::posts::{ blog::{BlogPost, LinkTo}, til::TilPost, }; pub(crate) struct TilPostList<'a>(pub(crate) Vec<&'a TilPost>); impl<'a> Render for TilPostList<'a> { fn render(&self) -> Markup { html! { ul { @for post in &self.0 { ...
// // Copyright 2021 The Project Oak Authors // // 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 o...
use std::mem; use cards::{Card, CardSuit, Trick}; use contracts::{ContractType, Contract, Standard, standard_winner_strategy, standard_move_validator}; use player::{Player, PlayerTurn, PlayerId}; #[deriving(Show, PartialEq)] pub enum Success { Next(PlayerId), Last, } #[deriving(Show, PartialEq)] pub enum...
fn main() { let plus_one = |x: i32| x + 1; println!("{}", plus_one(2)); }
use std::process::Command; fn main() { std::env::set_current_dir("highwayhash").unwrap(); let status = Command::new("make") // Rust requires position-independent code for any static library. .args(&["CXXFLAGS=-fPIC", "lib/libhighwayhash.a"]) .status() .expect("Failed to run make...
use parser::Range; use crate::print::{DiffState, Print, PrintState, ValuePrinter}; use crate::Result; pub(crate) fn print_address(range: &Range, w: &mut dyn ValuePrinter) -> Result<()> { if range.end > range.begin { write!(w, "0x{:x}-0x{:x}", range.begin, range.end - 1)?; } else { write!(w, "0...
use crate::mesh::*; use anyhow::*; use byteorder::{LittleEndian, ReadBytesExt}; use scan_fmt::*; use std::fs; use std::io; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; const HEADER_SIZE: u64 = 80; const TRIANGLE_SIZE: u64 = 50; pub enum StlType { Binary, Ascii, } pub struct Parser<T> where T:...
enum Temperature { Celsius(i32), Fahrenheit(i32), } pub fn main() { println!("------{} BEGIN------", file!()); let temperature = Temperature::Celsius(35); // ^ TODO try different values for `temperature` match temperature { Temperature::Celsius(t) if t > 30 => println!("{}C is above 3...
use super::addr::{Ipv4Addr, Ipv6Addr}; use libc::{in_addr, in6_addr, c_uint}; use std::fmt; #[repr(C)] #[derive(Clone, Copy)] pub struct ip_mreq { pub imr_multiaddr: in_addr, pub imr_interface: in_addr, } impl fmt::Debug for ip_mreq { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!...
#[doc = "Register `WRP2R_CUR` reader"] pub type R = crate::R<WRP2R_CUR_SPEC>; #[doc = "Field `WRPSG2` reader - Bank2 sector group protection option status byte Each FLASH_WRP2R_CUR bit reflects the write protection status of the corresponding group of 4 consecutive sectors in bank 2 (0: group is write protected; 1: gro...
pub trait AreaCalculable { fn area(&self) -> f32; }
use std::collections::HashMap; use serde; use chrono::{DateTime, UTC, Timelike}; use byteorder::{WriteBytesExt, BigEndian}; use token::Token; use schema::FieldRef; #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub struct DocRef(u32, u16); impl DocRef { pub fn segment(&self) -> u32 { self.0 } ...
#![cfg(feature = "unstable")] extern crate compiletest_rs as compiletest; use std::fs; use std::result::Result; use compiletest::common::Mode; fn run_mode(mode: Mode) { let config = compiletest::Config { mode: mode, src_base: format!("tests/{}", mode).into(), target_rustcflags: fs::read_...
use super::{chunk_header::*, chunk_type::*, *}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::fmt; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::SystemTime; pub(crate) const PAYLOAD_DATA_ENDING_FRAGMENT_BITMASK: u8 = 1; pub(crate) const PAYLOAD_DATA_BEGINING_FRAGMENT_BITMASK:...
use crate::hittable::{Object}; use crate::vec3::{Point3, Vec3, Color3}; #[derive(Debug, Clone)] pub struct Ray { pub orig: Point3, pub dir: Vec3, } impl Ray { pub fn new(orig: &Point3, dir: &Vec3) -> Self { Self { orig: orig.clone(), dir: dir.clone() } } pub fn at(&self, t: f64) -> Point3...
pub mod armies { pub fn process_command() { loop { println!("Please input an army command or help to see available commands or back to go back!"); let mut input = String::new(); std::io::stdin() .read_line(&mut input) .expect("Error parsing...
#[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::SRAMCTRL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w ...
use crate::ast::{Ast, Range}; use peg; peg::parser! { grammar grammar() for str { rule _ = quiet! { (" " / "\t" / "\n" / "\r")* { } } rule u32() -> u32 = quiet! { n:$(['0'..='9']+) {? n.parse().or(Err("u32")) } } / expected!("number") rule i32() -> ...
use azure_core::errors::AzureError; use http::HeaderMap; use std::borrow::Cow; use url::Url; const HEADER_NEXTPARTITIONKEY: &str = "x-ms-continuation-NextPartitionKey"; const HEADER_NEXTROWKEY: &str = "x-ms-continuation-NextRowKey"; const QUERY_PARAM_NEXTPARTITIONKEY: &str = "NextPartitionKey"; const QUERY_PARAM_NEXTR...
//! Defines the `Celsius` temperature newtype and related trait impls use core::{self, fmt}; use composite::UnitName; use temperature::Fahrenheit; use temperature::Kelvin; /// A newtype that wraps around `f64` and provides convenience functions for unit-aware and type-safe manipulation. #[derive(Clone, Copy)] pub s...
use byteorder::{ReadBytesExt, LittleEndian}; use rwinstructs::timestamp::{DosDateTime}; use errors::{ShellItemError}; use std::io::Read; use std::io::{Seek,SeekFrom}; use std::fmt; use serde::{ser}; use shellitem::{ClassType}; use extension_blocks::{ExtensionBlock}; use utils; pub static mut FLAGS_AS_INT: bool = false...
//! Byte swap intrinsics. pub use arch::_bswap;
//! Endpoint functions relating to albums. use std::fmt::Display; use itertools::Itertools as _; use serde::Deserialize; use super::chunked_sequence; use crate::{Album, Client, Error, Market, Page, Response, TrackSimplified}; /// Album-related endpoints. #[derive(Debug, Clone, Copy)] pub struct Albums<'a>(pub &'a C...
mod modules; use modules::CommandType; use modules::code; use modules::Parser; use modules::SymbolTable; use std::env; fn main() { let mut table = SymbolTable::new(); table.add_entry("SP".to_string(), 0); table.add_entry("LCL".to_string(), 1); table.add_entry("ARG".to_string(), 2); table.add_entry(...
use ui::core::{Widget, ButtonResult}; use std::collections::HashMap; /// Specialized version of a widget that implements an alignment function /// and method for forwarding keys to the parent widgets key map. pub trait Layout: Widget { fn align_elems(&mut self); fn forward_keys(&mut self, key_map: &mut HashMa...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ #![cf...
#![deny(clippy::pedantic)] extern crate proc_macro; #[macro_use] extern crate proc_macro_error; use proc_macro::TokenStream; mod generics; mod lend_to_cuda; mod rust_to_cuda; #[proc_macro_error] #[proc_macro_derive(RustToCuda, attributes(r2cEmbed, r2cBound, r2cEval, r2cPhantom))] pub fn rust_to_cuda_derive(input: ...